当前位置:网站首页>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>
边栏推荐
- China's coal industry investment strategic planning future production and marketing demand forecast report Ⓘ 2022 ~ 2028
- Great gods, I want to send two broadcast streams: 1. Load basic data from MySQL and 2. Load changes in basic data from Kafka
- JS closure knowledge points essence
- Collection | pytoch common loss function disassembly
- MySQL——JDBC
- gslb(global server load balance)技術的一點理解
- Common SQL sets
- Under the double reduction policy, research travel may become a big winner
- 油猴插件
- WFC900M-Network_ Card/Qualcomm-Atheros-AR9582-2T-2R-MIMO-802.11-N-900M-high-power-Mini-PCIe-Wi-Fi-Mod
猜你喜欢

Electronic tube: Literature Research on basic characteristics of 6j1

Control loop of program (while loop)

Collections SQL communes

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

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.

JS closure knowledge points essence

Station B, dark horse programmer, employee management system, access conflict related (there is an unhandled exception at 0x00007ff633a4c54d (in employee management system.Exe): 0xc0000005: read locat
Implementation principle of inheritance, encapsulation and polymorphism

Code in keil5 -- use the code formatting tool astyle (plug-in)
随机推荐
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)
Luogu deep foundation part 1 Introduction to language Chapter 6 string and file operation
The White House held an open source security summit, attended by many technology giants
China's coal industry investment strategic planning future production and marketing demand forecast report Ⓘ 2022 ~ 2028
DR-AP40X9-A-Qualcomm-IPQ-4019-IPQ-4029-5G-4G-LTE-aluminum-body-dual-band-wifi-router-2.4GHZ-5GHz-QSD
Dynamic research and future planning analysis report of China's urban water supply industry Ⓝ 2022 ~ 2028
股票炒股开户注册安全靠谱吗?有没有风险的?
MySQL - index
抓包整理外篇——————autoResponder、composer 、statistics [ 三]
Report on the development strategy of China's engineering bidding agency and suggestions for the 14th five year plan Ⓙ 2022 ~ 2028
2022 electrician (elementary) examination questions and electrician (elementary) registration examination
Redis concludes that the second pipeline publishes / subscribes to bloom filter redis as a database and caches RDB AOF redis configuration files
Exclusive interview with the person in charge of openkruise: to what extent has cloud native application automation developed now?
Are the top ten securities companies safe to open accounts and register? Is there any risk?
flink sql-client 退出,表就会被清空怎么办?
Development trend and market demand analysis report of China's energy storage battery industry Ⓩ 2022 ~ 2028
Global and Chinese market of telematics boxes 2022-2028: Research Report on technology, participants, trends, market size and share
Correlation
What is the difference between res.send() and res.end() in the node express framework
90 後,辭職創業,說要卷死雲數據庫