本学习系列将以Cesium + Vue3+Typescript+elementplus作为主要技术栈展开,后续会循序渐进,持续探索Cesium的高级功能,相关源码全部免费公开。 详情请关注原文Cesium+Vue3学习系列(13)---态势标绘代码封装优化 之前的几篇文章分别介绍了态势标绘(也叫军事标绘)中不同攻击箭头燕尾攻击箭头、钳击箭头等的绘制和编辑方法。写不同箭头类的过程中,发现各个Polygon类型的箭头类写法基本相似。看看下面的钳击箭头类和燕尾箭头类的代码。
可以发现,箭头类中的绘制临时箭头(buildTempEntity)、最终箭头(buildFinalEntity)以及获取鼠标位置(tempCursor)以及onLeftClick判断结束绘制等都基本相似,当箭头类越来越多时,代码就稍显臃肿了。下面给出优化方法。
1、新建BaseArrowArrow,继承BaseDraw。
import { CallbackProperty, Cartesian3, ClassificationType, Color, Entity, PolygonGraphics, Viewer } from "cesium";
import { BaseDraw} from "../BaseDraw";
import EventDispatcher from "@/system/EventDispatcher/EventDispatcher";
export default abstract class BaseArrowArrow extends BaseDraw {
/** 临时点,用来实时跟随鼠标 */
private tempCursor = new Cartesian3();
/** 算法函数,子类注入 */
protected abstract createArrowPoints(pos: Cartesian3[]): Cartesian3[];
/** 达到几个点自动结束(StraightArrow=2,Pincer=5…) */
protected abstract get maxPointCount(): number;
constructor(viewer: Viewer, dispatcher: EventDispatcher) {
super(viewer, dispatcher);
}
protected buildFinalEntity(): Entity {
const geometryPoints = this.createArrowPoints(this.getPositions())
return this.viewer.entities.add({
polygon: new PolygonGraphics({
hierarchy: new CallbackProperty(() => ({
positions: geometryPoints
}), false),
classificationType: ClassificationType.BOTH,
material: Color.BLUE.withAlpha(0.4)
})
});
}
protected buildTempEntity(): Entity | undefined {
if (this.getPositions().length < (this.minPointCount - 1)) return undefined;
return this.viewer.entities.add({
polygon: new PolygonGraphics({
hierarchy: new CallbackProperty(
() => ({
positions: this.createArrowPoints([
...this.getPositions(),
this.tempCursor,
]),
}),
false
),
classificationType: ClassificationType.BOTH,
material: Color.CYAN.withAlpha(0.3),
}),
});
}
protected updateTempEntity(cursor: Cartesian3): void {
this.tempCursor = cursor;
}
/* -------------------- 鼠标事件 -------------------- */
protected onLeftClick(e: any): void {
super.onLeftClick(e);
if (this.getPositions().length === this.maxPointCount) {
this.finish();
}
}
}
2、然后将攻击箭头类(AttackArrow)、钳击箭头类(PincerAttackArrow)、直箭头类(StraightArrow)以及燕尾箭头类(SwallowtailAttackArrow)分别继承BaseArrowArrow类。 3、以上便完成了Polygon类型的箭头的代码优化,由于本学习系列里的Polyline类型的箭头只写了细直线箭头(StraightLineArrow)一种,就暂时不优化了。完成以上操作后,代码是不是精简了许多!
由于代码较多,完整源码请关注原文Cesium+Vue3学习系列(13)---态势标绘代码封装优化