一、创作思路
1、创建一个自定义CustomPrimitive
2、可动态更新线的点位
3、方便后期绘制线
二、实现代码
1、创建一个CustomPolylinePrimitive类,并加入更新的代码
export default class CustomPolylinePrimitive {
constructor(options) {
this._props = options;
/**
* 渲染列表
* @type {*[]}
* @private
*/
this._primitiveCollection = [];
this._dynamicPrimitive = undefined;
}
updateProperty(options) {
this._props = {
...this._props,
...options,
};
}
/**
* 更新
* @param frameState
*/
update(frameState) {
this._primitiveCollection.forEach((primitive) => {
primitive && !primitive.isDestroyed() && primitive.update(frameState);
});
if (this._dynamicPrimitive) {
this._dynamicPrimitive.update(frameState);
}
}
}
2、编写更新代码
updateProperty(options) {
this._props = {
...this._props,
...options,
};
let positions = this._props.positions;
let complete = this._props.complete;
if (positions.length > 1) {
let dynamicPrimitive = this._dynamicPrimitive;
if (dynamicPrimitive) {
dynamicPrimitive.destroy();
dynamicPrimitive = null;
this._dynamicPrimitive = null;
}
let primitive = this.initPolylinePrimitive(positions);
if (complete) {
this._primitiveCollection.push(primitive);
} else {
this._dynamicPrimitive = primitive;
}
}
}
initPolylinePrimitive(positions) {
let instance = new GeometryInstance({
geometry: new GroundPolylineGeometry({
positions: positions,
width: 4,
}),
});
return new GroundPolylinePrimitive({
geometryInstances: instance,
appearance: new PolylineMaterialAppearance({
material: new Material({
fabric: {
type: "Color",
uniforms: {
color: Color.fromCssColorString("#ff0000"),
},
},
}),
}),
asynchronous: false,
});
}
3、测试代码,自定义动态更新点位
viewer.camera.flyTo({
destination: origin2,
complete: () => {
let primitive = new CustomPolylinePrimitive({});
viewer.scene.primitives.add(primitive);
let count = 0;
let lon = 106;
let lat = 26;
let positions = [];
let interval = setInterval(() => {
let lonTemp = lon + count * 0.00001;
let latTemp = lat + (count % 2) * 0.00001;
positions.push(Cartesian3.fromDegrees(lonTemp, latTemp));
primitive.updateProperty({
positions: positions,
complete: count === 11,
});
if (count > 10) {
clearInterval(interval);
}
count++;
}, 1000);
},
});