前言
Cesium点线面绘制是很基本的功能,数据采集类型的系统必须具备此功能。但是Cesium并没有提供相关可以直接使用的绘制方法,只能自己进行封装,虽然实现起来不是很难,但是对Cesium不太熟的同学还是比较麻烦的。
效果图
关键代码
export default class EntityDraw {
constructor(viewer) {
this.viewer = viewer;
this.initEvents();
}
//激活
activate(drawType) {
this.deactivate();
this.drawType = drawType;
this.positions = [];
this.tempPositions = [];
this.registerEvents(); //注册鼠标事件
//设置鼠标状态
this.viewer.enableCursorStyle = false;
this.viewer._element.style.cursor = 'default';
}
//初始化事件
initEvents() {
this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
this.DrawStartEvent = new Cesium.Event(); //开始绘制事件
this.DrawEndEvent = new Cesium.Event(); //结束绘制事件
}
//注册鼠标事件
registerEvents() {
this.leftClickEvent();
this.rightClickEvent();
this.mouseMoveEvent();
}
leftClickEvent() {
//单击鼠标左键画点
this.handler.setInputAction(e => {
this.viewer._element.style.cursor = 'default';
let position = this.viewer.scene.pickPosition(e.position);
if (!position) return;
this.positions.push(position);
if (this.positions.length == 1) {
this.handleFirstPosition();
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
}
mouseMoveEvent() {
this.handler.setInputAction(e => {
this.viewer._element.style.cursor = 'default'; //由于鼠标移动时 Cesium会默认将鼠标样式修改为手柄 所以移动时手动设置回来
let position = this.viewer.scene.pickPosition(e.endPosition);
if (!position) return;
if (!this.drawEntity) return;
this.tempPositions = this.positions.concat([position]);
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
}
//解除鼠标事件
unRegisterEvents() {
this.handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);
this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
this.handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
}
//绘制结束 触发结束事件
drawEnd() {
this.drawEntity.remove = () => {
this.viewer.entities.remove(this.drawEntity);
}
this.DrawEndEvent.raiseEvent(this.drawEntity, this.positions, this.drawType);
this.deactivate();
}
}
详情参见 Cesium实战项目