当前位置:网站首页>Cesium terrain clipping draw polygon clipping
Cesium terrain clipping draw polygon clipping
2022-07-03 22:03:00 【Sun batian】
cesium- Terrain clipping - Draw polygon clipping
Introduce
This was covered in the previous article ,cesium Draw polygons and crop terrain , Here I combine the two functions to achieve polygon rendering and terrain clipping
Only convex polygons can be cut here
effect
The first effect
analysis
- Draw polygon
- Storage point array
- Array reversal
- Crop polygon terrain
Complete code
Use here vue Realization ,cesium Initialization is introduced as a module , The specific code has relevant comments
<template>
<div class="home">
<el-row type="flex" :gutter="20">
<el-col :span="24">
<div class="grid-content bg-purple">
<el-breadcrumb separator="/">
<el-breadcrumb-item>cesium</el-breadcrumb-item>
<el-breadcrumb-item> Cutting function </el-breadcrumb-item>
<el-breadcrumb-item> Terrain sheet clipping ( Draw polygon )</el-breadcrumb-item>
</el-breadcrumb>
</div>
</el-col>
</el-row>
<el-row type="flex" :gutter="20">
<el-col :span="24">
<div class="grid-content bg-purple">
<cesiumComponent id="cesium" ref="refCesium"/>
</div>
</el-col>
</el-row>
<el-row type="flex" :gutter="20">
<el-col :span="24">
<div class="grid-content bg-purple">
<el-button type="primary" @click="addDem()"> Reset </el-button>
<el-button type="primary" @click="draw('polygon')"> Draw the section of sanctions </el-button>
<el-button type="primary" @click="clearAll"> Clear all data </el-button>
</div>
</el-col>
</el-row>
</div>
</template>
<script>
import cesiumComponent from '../cesium.vue'
export default {
name: "clipping_single",
data() {
return {
_viewer: undefined,
isClipping: false,
tempEntities: [],
clippingPoints: [],
};
},
components: {
cesiumComponent
},
mounted() {
this.init();
},
methods: {
init() {
this.$refs.refCesium.initMap();
this._viewer = this.$refs.refCesium._viewer;
this.addDem();
},
addDem() {
let that = this;
that._viewer.terrainProvider = new Cesium.CesiumTerrainProvider({
url: '../dem/ASTGTM_N29E087D'
});
that._viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(87.42919921875, 28.700224692776988, 67863.0),
orientation: {
heading: Cesium.Math.toRadians(0.0),
pitch: Cesium.Math.toRadians(-45.0),
roll: 0.0
}
});
},
clippings() {
let that = this;
let clippingPoints = this.clippingPoints;
// Add the first point to the last point , Complete closed loop
clippingPoints.push(clippingPoints[0]);
// Reverse the set of points
let newClippingPoints = clippingPoints.reverse();
// truf Judge whether the polygon coordinates are clockwise ,true: Clockwise ,false: Anti-clockwise
// console.log(turf.booleanClockwise(turf.lineString(clippingPoints)));
let clippingPlanes1 = that.createClippingPlane(newClippingPoints);
that._viewer.scene.globe.depthTestAgainstTerrain = true;
that._viewer.scene.globe.clippingPlanes = new Cesium.ClippingPlaneCollection({
planes: clippingPlanes1,
edgeWidth: 1.0,
edgeColor: Cesium.Color.YELLOW
});
},
draw() {
let that = this;
// Clear polygon data before each cutting
that.clearDrawEntities();
let viewer = this._viewer;
let tempEntities = this.tempEntities;
let position = [];
let tempPoints = [];
let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
// Mouse movement events
handler.setInputAction(function (movement) {
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
// Left click operation
handler.setInputAction(function (click) {
// From the camera position through windowPosition Pixels in world coordinates create a ray . return Cartesian3 Position and direction of rays .
let ray = viewer.camera.getPickRay(click.position);
// Find the intersection between the ray and the rendered earth surface . Rays must be given in world coordinates . return Cartesian3 object
position = viewer.scene.globe.pick(ray, viewer.scene);
// Convert Cartesian coordinates to geographic coordinates
let cartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(position);
// A decimal representation that converts radians into degrees
let longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
let latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
let points = [longitudeString, latitudeString];
// Add point coordinates to the array
that.clippingPoints.push(points);
tempPoints.push(position);
let tempLength = tempPoints.length;
// Call the interface for drawing points
let point = that.drawPoint(position);
tempEntities.push(point);
if (tempLength > 1) {
let pointline = that.drawPolyline([tempPoints[tempPoints.length - 2], tempPoints[tempPoints.length - 1]]);
tempEntities.push(pointline);
} else {
// tooltip.innerHTML = " Please draw the next point , Right click to end ";
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
// Right click operation
handler.setInputAction(function (click) {
let cartesian = viewer.camera.pickEllipsoid(click.position, viewer.scene.globe.ellipsoid);
if (cartesian) {
let tempLength = tempPoints.length;
if (tempLength < 3) {
alert(' Please select 3 Execute the closing operation command after more than one point ');
} else {
// Close last line
let pointline = that.drawPolyline([tempPoints[tempPoints.length - 1], tempPoints[0]]);
tempEntities.push(pointline);
// that.drawPolygon(tempPoints);
tempEntities.push(tempPoints);
that.clippings();
handler.destroy();// Close event handle
handler = null;
}
}
}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
},
drawPoint(position, config) {
let viewer = this._viewer;
let config_ = config ? config : {};
return viewer.entities.add({
name: " Point geometry objects ",
position: position,
point: {
color: Cesium.Color.SKYBLUE,
pixelSize: 10,
outlineColor: Cesium.Color.YELLOW,
outlineWidth: 3,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
}
});
},
drawPolyline(positions, config_) {
let viewer = this._viewer;
if (positions.length < 1) return;
let config = config_ ? config_ : {};
return viewer.entities.add({
name: " Line geometry objects ",
polyline: {
positions: positions,
width: config.width ? config.width : 5.0,
material: new Cesium.PolylineGlowMaterialProperty({
color: config.color ? new Cesium.Color.fromCssColorString(config.color) : Cesium.Color.GOLD,
}),
depthFailMaterial: new Cesium.PolylineGlowMaterialProperty({
color: config.color ? new Cesium.Color.fromCssColorString(config.color) : Cesium.Color.GOLD,
}),
clampToGround: true,
}
});
},
drawPolygon(positions, config_) {
let viewer = this._viewer;
if (positions.length < 2) return;
let config = config_ ? config_ : {};
return viewer.entities.add({
name: " Face geometry objects ",
polygon: {
hierarchy: positions,
material: config.color ? new Cesium.Color.fromCssColorString(config.color).withAlpha(.2) : new Cesium.Color.fromCssColorString("#FFD700").withAlpha(.2),
},
});
},
/**
* Create cut planes from polygon arrays
* @param points_ Polygon array collection
* @returns {[]} Return the cutting plane array
*/
createClippingPlane(points_) {
let points = [];
for (let i = 0; i < points_.length - 1; i++) {
points.push(Cesium.Cartesian3.fromDegrees(points_[i][0], points_[i][1]))
}
let pointsLength = points.length;
let clippingPlanes = []; // Storage ClippingPlane aggregate
for (let i = 0; i < pointsLength; ++i) {
let nextIndex = (i + 1) % pointsLength;
let midpoint = Cesium.Cartesian3.add(points[i], points[nextIndex], new Cesium.Cartesian3());
midpoint = Cesium.Cartesian3.multiplyByScalar(midpoint, 0.5, midpoint);
let up = Cesium.Cartesian3.normalize(midpoint, new Cesium.Cartesian3());
let right = Cesium.Cartesian3.subtract(points[nextIndex], midpoint, new Cesium.Cartesian3());
right = Cesium.Cartesian3.normalize(right, right);
let normal = Cesium.Cartesian3.cross(right, up, new Cesium.Cartesian3());
normal = Cesium.Cartesian3.normalize(normal, normal);
let originCenteredPlane = new Cesium.Plane(normal, 0.0);
let distance = Cesium.Plane.getPointDistance(originCenteredPlane, midpoint);
clippingPlanes.push(new Cesium.ClippingPlane(normal, distance));
}
return clippingPlanes;
},
/**
* Clear entities
*/
clearDrawEntities() {
let viewer = this._viewer;
this.tempEntities = [];
this.clippingPoints = [];
// Clear previous entities
const entitys = viewer.entities._entities._array;
let length = entitys.length
// Flashback traversal prevents entities from decreasing after entitys[f] non-existent
for (let f = length - 1; f >= 0; f--) {
if (entitys[f]._name && (entitys[f]._name === ' Point geometry objects ' || entitys[f]._name === ' Line geometry objects ' || entitys[f]._name === ' Face geometry objects ')) {
viewer.entities.remove(entitys[f]);
}
}
},
clearAll() {
let that = this;
this.clearDrawEntities();
that._viewer.scene.globe.clippingPlanes = null;
}
},
created() {
},
}
</script>
<style scoped>
.home {
height: 100%;
margin: 0;
padding: 0;
overflow-y: auto;
overflow-x: hidden;
}
.el-breadcrumb {
margin: 10px;
font-size: 15px;
}
#cesium {
max-height: 700px;
}
</style>
边栏推荐
- 2022 safety officer-b certificate examination summary and safety officer-b certificate simulation test questions
- regular expression
- Report on the current situation and development trend of ethoxylated sodium alkyl sulfate industry in the world and China Ⓞ 2022 ~ 2027
- What is the content of the securities practice examination?
- MySQL——索引
- [dynamic programming] Jisuan Ke: Jumping stake (variant of the longest increasing subsequence)
- [vulnhub shooting range] impulse: lupinone
- Exclusive interview with the person in charge of openkruise: to what extent has cloud native application automation developed now?
- Miscellaneous things that don't miss the right business
- [dynamic planning] counting garlic customers: the log of garlic King (the longest increasing public subsequence)
猜你喜欢
UC Berkeley proposes a multitask framework slip
Common SQL sets
On my first day at work, this API timeout optimization put me down!
(5) User login - services and processes - History Du touch date stat CP
A little understanding of GSLB (global server load balance) technology
Blue Bridge Cup Guoxin Changtian MCU -- program download (III)
Nacos common configuration
2022 electrician (elementary) examination questions and electrician (elementary) registration examination
The latest analysis of crane driver (limited to bridge crane) in 2022 and the test questions and analysis of crane driver (limited to bridge crane)
Electronic tube: Literature Research on basic characteristics of 6j1
随机推荐
Let me ask you a question. Have you ever used the asynchronous io of Flink SQL to associate dimension tables in MySQL? I set various settings according to the official website
IPhone development swift foundation 08 encryption and security
使用dnSpy对无源码EXE或DLL进行反编译并且修改
Cognitive fallacy: Wittgenstein's ruler
DR882-Qualcomm-Atheros-QCA9882-2T2R-MIMO-802.11ac-Mini-PCIe-Wi-Fi-Module-5G-high-power
Intimacy communication -- [repair relationship] - use communication to heal injuries
How PHP adds two numbers
90 後,辭職創業,說要卷死雲數據庫
WFC900M-Network_ Card/Qualcomm-Atheros-AR9582-2T-2R-MIMO-802.11-N-900M-high-power-Mini-PCIe-Wi-Fi-Mod
How does sentinel, a traffic management artifact, make it easy for business parties to access?
股票炒股开户注册安全靠谱吗?有没有风险的?
pivot ROP Emporium
The 14th five year plan for the construction of Chinese Enterprise Universities and the feasibility study report on investment Ⓓ 2022 ~ 2028
On my first day at work, this API timeout optimization put me down!
Go language slice interview real question 7 consecutive questions
Luogu deep foundation part 1 Introduction to language Chapter 7 functions and structures
Leetcode problem solving - 235 Nearest common ancestor of binary search tree
What if the Flink SQL client exits and the table is emptied?
Blue Bridge Cup Guoxin Changtian MCU -- program download (III)
On my first day at work, this API timeout optimization put me down!