当前位置:网站首页>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>
边栏推荐
- Après 90 ans, j'ai démissionné pour démarrer une entreprise et j'ai dit que j'allais détruire la base de données Cloud.
- Exclusive interview with the person in charge of openkruise: to what extent has cloud native application automation developed now?
- 2022 electrician (elementary) examination questions and electrician (elementary) registration examination
- [vulnhub shooting range] impulse: lupinone
- The post-90s resigned and started a business, saying they would kill cloud database
- DR882-Qualcomm-Atheros-QCA9882-2T2R-MIMO-802.11ac-Mini-PCIe-Wi-Fi-Module-5G-high-power
- js demo 计算本年度还剩下多少天
- Global and Chinese market of AC induction motors 2022-2028: Research Report on technology, participants, trends, market size and share
- Cognitive fallacy: what is Fredkin's paradox
- [secretly kill little partner pytorch20 days] - [day3] - [example of text data modeling process]
猜你喜欢

Bluebridge cup Guoxin Changtian single chip microcomputer -- detailed explanation of schematic diagram (IV)

Persistence of Nacos

QFileDialog

Control loop of program (while loop)

Bluebridge cup Guoxin Changtian single chip microcomputer -- hardware environment (I)

JS closure knowledge points essence

Mysql - - Index

Blue Bridge Cup Guoxin Changtian MCU -- program download (III)

gslb(global server load balance)技术的一点理解
![[SRS] build a specified version of SRS](/img/01/0d2d762e01b304220b8924d20277e3.jpg)
[SRS] build a specified version of SRS
随机推荐
Miscellaneous things that don't miss the right business
treevalue——Master Nested Data Like Tensor
Décompiler et modifier un exe ou une DLL non source en utilisant dnspy
2022 electrician (elementary) examination questions and electrician (elementary) registration examination
[vulnhub shooting range] impulse: lupinone
Control loop of program (while loop)
What indicators should be paid attention to in current limit monitoring?
Sed、Awk
Global and Chinese market of gallic acid 2022-2028: Research Report on technology, participants, trends, market size and share
Under the double reduction policy, research travel may become a big winner
Blue Bridge Cup Guoxin Changtian MCU -- program download (III)
DR882-Qualcomm-Atheros-QCA9882-2T2R-MIMO-802.11ac-Mini-PCIe-Wi-Fi-Module-5G-high-power
UC Berkeley proposes a multitask framework slip
Notes on MySQL related knowledge points (startup, index)
Supply and demand situation and market scale calculation report of China's portable energy storage power PES industry Ⓛ 2022 ~ 2028
Rest参考
MySQL -- standardize database design
MySQL——idea连接MySQL
油猴插件
Imitation Netease cloud music applet