基于cesium和vue繪制多邊形實現地形開挖效果,適合學習Cesium與前端框架結合開發3D可視化項目。
demo源碼運行環境以及配置
運行環境:依賴Node安裝環境,demo本地Node版本:推薦v18+。
運行工具:vscode或者其他工具。
配置方式:下載demo源碼,vscode打開,然后順序執行以下命令:
(1)下載demo環境依賴包命令:npm install
(2)啟動demo命令:npm run dev
(3)打包demo命令: npm run build
技術棧
Vue 3.5.13
Vite 6.2.0
Cesium 1.128.0
示例效果
核心源碼
<template><div id="cesiumContainer" class="cesium-container"><!-- 模型調整控制面板 --><div class="control-panel"><div class="panel-header"><h3>地形開挖</h3></div><div class="panel-body"><div class="control-group"><button @click="startDrawPolygon">繪制多邊形</button></div><div class="control-group"><button @click="clearDrawing">清除繪制</button></div><div class="control-group" v-if="drawingInstructions"><span>{{ drawingInstructions }}</span></div></div></div></div>
</template><script setup>
import { onMounted, onUnmounted, ref } from 'vue';
import * as Cesium from 'cesium';Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxZjhjYjhkYS1jMzA1LTQ1MTEtYWE1Mi0zODc5NDljOGVkMDYiLCJpZCI6MTAzNjEsInNjb3BlcyI6WyJhc2wiLCJhc3IiLCJhc3ciLCJnYyJdLCJpYXQiOjE1NzA2MDY5ODV9.X7tj92tunUvx6PkDpj3LFsMVBs_SBYyKbIL_G9xKESA';
// 聲明Cesium Viewer實例
let viewer = null;
// 聲明變量用于存儲事件處理器和繪制狀態
let handler = null;
let activeShapePoints = [];
let activeShape = null;
let floatingPoint = null;
let excavateInstance = null;// 繪制狀態提示
const drawingInstructions = ref('');// 組件掛載后初始化Cesium
onMounted(async () => {const files = ["./excavateTerrain/excavateTerrain.js"];loadScripts(files, function () {console.log("All scripts loaded");initMap();});
});
const loadScripts = (files, callback) => {// Make Cesium available globally for the scriptswindow.Cesium = Cesium;if (files.length === 0) {callback();return;}const file = files.shift();const script = document.createElement("script");script.onload = function () {loadScripts(files, callback);};script.src = file;document.head.appendChild(script);
};
const initMap = async () => {// 初始化Cesium Viewerviewer = new Cesium.Viewer('cesiumContainer', {// 基礎配置animation: false, // 動畫小部件baseLayerPicker: false, // 底圖選擇器fullscreenButton: false, // 全屏按鈕vrButton: false, // VR按鈕geocoder: false, // 地理編碼搜索框homeButton: false, // 主頁按鈕infoBox: false, // 信息框 - 禁用點擊彈窗sceneModePicker: false, // 場景模式選擇器selectionIndicator: false, // 選擇指示器timeline: false, // 時間軸navigationHelpButton: false, // 導航幫助按鈕navigationInstructionsInitiallyVisible: false, // 導航說明初始可見性scene3DOnly: false, // 僅3D場景terrain: Cesium.Terrain.fromWorldTerrain(), // 使用世界地形});// 隱藏logoviewer.cesiumWidget.creditContainer.style.display = "none";viewer.scene.globe.enableLighting = true;// 禁用大氣層和太陽viewer.scene.skyAtmosphere.show = false;//前提先把場景上的圖層全部移除或者隱藏 // viewer.scene.globe.baseColor = Cesium.Color.BLACK; //修改地圖藍色背景viewer.scene.globe.baseColor = new Cesium.Color(0.0, 0.1, 0.2, 1.0); //修改地圖為暗藍色背景// 設置抗鋸齒viewer.scene.postProcessStages.fxaa.enabled = true;// 清除默認底圖viewer.imageryLayers.remove(viewer.imageryLayers.get(0));// 加載底圖 - 使用更暗的地圖服務const imageryProvider = await Cesium.ArcGisMapServerImageryProvider.fromUrl("https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer");viewer.imageryLayers.addImageryProvider(imageryProvider);// 設置默認視圖位置 - 默認顯示全球視圖viewer.camera.setView({destination: Cesium.Cartesian3.fromDegrees(104.0, 30.0, 10000000.0), // 中國中部上空orientation: {heading: 0.0,pitch: -Cesium.Math.PI_OVER_TWO,roll: 0.0}});// 啟用地形深度測試,確保地形正確渲染viewer.scene.globe.depthTestAgainstTerrain = true;// 清除默認地形// viewer.scene.terrainProvider = new Cesium.EllipsoidTerrainProvider({});// 開啟幀率viewer.scene.debugShowFramesPerSecond = true;
}
// 開始繪制多邊形
const startDrawPolygon = () => {// 清除之前的繪制clearDrawing();// 設置繪制提示drawingInstructions.value = '左鍵點擊添加頂點,右鍵完成繪制';// 創建新的事件處理器handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);// 監聽左鍵點擊事件 - 添加頂點handler.setInputAction((click) => {// 獲取點擊位置的笛卡爾坐標const cartesian = viewer.scene.pickPosition(click.position);if (!Cesium.defined(cartesian)) {return;}// 將點添加到活動形狀點數組activeShapePoints.push(cartesian);// 如果是第一個點,創建浮動點if (activeShapePoints.length === 1) {floatingPoint = createPoint(cartesian);// 創建動態多邊形activeShape = createPolygon(activeShapePoints);}}, Cesium.ScreenSpaceEventType.LEFT_CLICK);// 監聽鼠標移動事件 - 更新動態多邊形handler.setInputAction((movement) => {if (activeShapePoints.length >= 1) {const cartesian = viewer.scene.pickPosition(movement.endPosition);if (!Cesium.defined(cartesian)) {return;}// 更新浮動點位置if (floatingPoint) {floatingPoint.position.setValue(cartesian);}// 更新動態多邊形if (activeShape) {const positions = activeShapePoints.concat([cartesian]);activeShape.polygon.hierarchy = new Cesium.PolygonHierarchy(positions);}}}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);// 監聽右鍵點擊事件 - 完成繪制handler.setInputAction(() => {if (activeShapePoints.length < 3) {// 至少需要3個點才能形成多邊形drawingInstructions.value = '至少需要3個點才能形成多邊形,請繼續繪制';return;}// 完成繪制terminateShape();// 執行地形開挖performExcavation(activeShapePoints);// 清除繪制狀態drawingInstructions.value = '繪制完成,地形已開挖';// 清除事件處理器handler.destroy();handler = null;}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
};// 創建點實體
const createPoint = (position) => {return viewer.entities.add({position: position,point: {color: Cesium.Color.WHITE,pixelSize: 10,heightReference: Cesium.HeightReference.CLAMP_TO_GROUND}});
};// 創建多邊形實體
const createPolygon = (positions) => {return viewer.entities.add({polygon: {hierarchy: new Cesium.PolygonHierarchy(positions),material: new Cesium.ColorMaterialProperty(Cesium.Color.WHITE.withAlpha(0.3)),outline: true,outlineColor: Cesium.Color.WHITE,// heightReference: Cesium.HeightReference.CLAMP_TO_GROUND// 關鍵屬性:貼地模式clampToGround: true,// 禁用擠壓高度// height: 0,// height: 0,// perPositionHeight: false,// classificationType: Cesium.ClassificationType.BOTH,// zIndex: 100}});
};// 完成繪制形狀
const terminateShape = () => {// 移除動態實體if (floatingPoint) {viewer.entities.remove(floatingPoint);floatingPoint = null;}if (activeShape) {viewer.entities.remove(activeShape);activeShape = null;}// 創建最終的多邊形// if (activeShapePoints.length >= 3) {// const finalPolygon = viewer.entities.add({// polygon: {// hierarchy: new Cesium.PolygonHierarchy(activeShapePoints),// material: new Cesium.ColorMaterialProperty(Cesium.Color.GREEN.withAlpha(0.3)),// outline: true,// outlineColor: Cesium.Color.GREEN,// height: 0,// perPositionHeight: false,// classificationType: Cesium.ClassificationType.BOTH,// zIndex: 100// }// });// }
};// 執行地形開挖
const performExcavation = (positions) => {// 如果已有開挖實例,先嘗試清除if (excavateInstance) {try {// 重置地形開挖viewer.scene.globe.clippingPlanes = undefined;viewer.entities.removeById("entityDM");viewer.entities.removeById("entityDMBJ");} catch (error) {console.error("清除之前的開挖失敗", error);}}// 創建新的地形開挖實例excavateInstance = new excavateTerrain(viewer, {positions: positions,height: 50,bottom: "./excavateTerrain/excavationregion_side.jpg",side: "./excavateTerrain/excavationregion_top.jpg",});
};// 清除繪制
const clearDrawing = () => {// 清除事件處理器if (handler) {handler.destroy();handler = null;}// 清除動態實體if (floatingPoint) {viewer.entities.remove(floatingPoint);floatingPoint = null;}if (activeShape) {viewer.entities.remove(activeShape);activeShape = null;}// 清空點數組activeShapePoints = [];viewer.entities.removeAll();// 清除繪制提示drawingInstructions.value = '';// 重置地形開挖if (excavateInstance) {try {viewer.scene.globe.clippingPlanes = undefined;viewer.entities.removeById("entityDM");viewer.entities.removeById("entityDMBJ");excavateInstance = null;} catch (error) {console.error("清除地形開挖失敗", error);}}
};// 組件卸載前清理資源
onUnmounted(() => {clearDrawing();if (viewer) {viewer.destroy();viewer = null;}
});
</script><style scoped>
.cesium-container {width: 100%;height: 100vh;margin: 0;padding: 0;overflow: hidden;position: relative;
}.control-panel {position: absolute;top: 20px;left: 20px;width: 300px;background-color: rgba(38, 38, 38, 0.85);border-radius: 8px;box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);color: white;z-index: 1000;overflow: hidden;transition: all 0.3s ease;
}.panel-header {background-color: rgba(0, 0, 0, 0.5);padding: 10px 15px;border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}.panel-header h3 {margin: 0;font-size: 16px;font-weight: 500;
}.panel-body {padding: 15px;
}.control-group {margin-bottom: 15px;
}.control-group label {display: block;margin-bottom: 5px;font-size: 14px;
}.control-group input[type="range"] {width: 100%;margin-bottom: 5px;background-color: rgba(255, 255, 255, 0.2);border-radius: 4px;
}.control-group span {font-size: 12px;color: rgba(255, 255, 255, 0.7);display: block;margin-top: 5px;line-height: 1.4;
}.control-group span {font-size: 12px;color: rgba(255, 255, 255, 0.7);
}.control-group button {background-color: #4285f4;color: white;border: none;padding: 8px 15px;border-radius: 4px;cursor: pointer;font-size: 14px;width: 100%;transition: background-color 0.3s ease;
}.control-group button:hover {background-color: #3367d6;
}
</style>