当前位置:网站首页>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>
边栏推荐
- MySQL - database backup
- Luogu deep foundation part 1 Introduction to language Chapter 7 functions and structures
- Is it safe and reliable to open an account and register for stock speculation? Is there any risk?
- Preliminary understanding of C program design
- 油猴插件
- Advanced technology management - how to examine candidates in the interview and increase the entry probability
- Yyds dry inventory hcie security Day12: concept of supplementary package filtering and security policy
- How PHP gets all method names of objects
- Preliminary analysis of smart microwave radar module
- 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
猜你喜欢
[vulnhub shooting range] impulse: lupinone
The post-90s resigned and started a business, saying they would kill cloud database
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
MySQL——idea连接MySQL
Functions and differences between static and Const
Tidb's initial experience of ticdc6.0
IPhone development swift foundation 09 assets
On my first day at work, this API timeout optimization put me down!
Covariance
What indicators should be paid attention to in current limit monitoring?
随机推荐
Base ring tree Cartesian tree
What should the future of the Internet be like when Silicon Valley employees flee the big factory and rush to Web3| Footprint Analytics
Code in keil5 -- use the code formatting tool astyle (plug-in)
Leetcode problem solving - 230 The k-th smallest element in the binary search tree
QFileDialog
Preliminary analysis of smart microwave radar module
Report on the current situation and development trend of ethoxylated sodium alkyl sulfate industry in the world and China Ⓞ 2022 ~ 2027
How to store null value on the disk of yyds dry inventory?
Tidb's initial experience of ticdc6.0
Collections SQL communes
What is the difference between res.send() and res.end() in the node express framework
2022-02-15 Daily: 2022 AAAI fellow release
Décompiler et modifier un exe ou une DLL non source en utilisant dnspy
Netfilter ARP log
WFC900M-Network_ Card/Qualcomm-Atheros-AR9582-2T-2R-MIMO-802.11-N-900M-high-power-Mini-PCIe-Wi-Fi-Mod
Development trend and market demand analysis report of China's energy storage battery industry Ⓩ 2022 ~ 2028
Correlation
JS Demo calcule combien de jours il reste de l'année
gslb(global server load balance)技术的一点理解
English topic assignment (28)