当前位置:网站首页>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>
边栏推荐
- Common SQL sets
- Global and Chinese market of wireless hard disk 2022-2028: Research Report on technology, participants, trends, market size and share
- MySQL - index
- 国泰君安证券开户是安全可靠的么?怎么开国泰君安证券账户
- Development trend and market demand analysis report of China's energy storage battery industry Ⓩ 2022 ~ 2028
- Exclusive interview with the person in charge of openkruise: to what extent has cloud native application automation developed now?
- English topic assignment (28)
- Blue Bridge Cup Guoxin Changtian MCU -- program download (III)
- Notes on MySQL related knowledge points (startup, index)
- Day 9 HomeWrok-ClassHierarchyAnalysis
猜你喜欢

2022 free examination questions for safety management personnel of hazardous chemical business units and reexamination examination for safety management personnel of hazardous chemical business units

How PHP gets all method names of objects

No more! Technical team members resign collectively

On my first day at work, this API timeout optimization put me down!

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

Nacos common configuration

Minio deployment

Awk getting started to proficient series - awk quick start

Day 9 HomeWrok-ClassHierarchyAnalysis

Persistence of Nacos
随机推荐
Global and Chinese market of telematics boxes 2022-2028: Research Report on technology, participants, trends, market size and share
MySQL - idea connects to MySQL
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)
Solve the problem that openocd fails to burn STM32 and cannot connect through SWD
Global and Chinese market of recycled yarn 2022-2028: Research Report on technology, participants, trends, market size and share
Netfilter ARP log
油猴插件
DOM light switch case
Blue Bridge Cup Guoxin Changtian single chip microcomputer -- software environment (II)
pivot ROP Emporium
Covariance
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
使用dnSpy对无源码EXE或DLL进行反编译并且修改
MySQL - SQL injection problem
内存分析器 (MAT)
Code in keil5 -- use the code formatting tool astyle (plug-in)
What is the content of the securities practice examination?
Functions and differences between static and Const
Teach you how to install aidlux (1 installation)
Global and Chinese market of wireless hard disk 2022-2028: Research Report on technology, participants, trends, market size and share