一般情况下我们使用实体类时,会直接用Entity,但是动态更新实时渲染的不闪烁的话,得使用CallbackProperty回调函数,比较麻烦。可以通过自定义Primitive达到实时渲染效果。
function CustomPolygonPrimtive (options) {
this.positions = options.positions
this.color = options.color
this._positions = undefined
this._color = new Cesium.Color(1, 0, 0, 1)
}
CustomPolygonPrimtive.prototype.getGeometry = function () {
return new Cesium.PolygonGeometry({
polygonHierarchy: new Cesium.PolygonHierarchy(this.positions),
perPositionHeight: true,
vertexFormat: Cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT
})
}
CustomPolygonPrimtive.prototype.getPrimitive = function () {
var geometry = this.getGeometry()
var instances = new Cesium.GeometryInstance({
geometry: geometry
})
return new Primitive({
geometryInstances: instances,
appearance: new Cesium.EllipsoidSurfaceAppearance({
material: Cesium.Material.fromType('Color', {
color: this.color
}),
renderState: {
depthTest: {
enabled: false
}
}
}),
asynchronous: false
})
}
CustomPolygonPrimtive.prototype.update = function (context, frameState, commandList) {
if (!(this.positions !== this._positions || this.color !== this._color)) {
if (this._primitive) {
this._primitive.update(context, frameState, commandList)
}
return;
}
this._positions = this.position;
this._color = this.color;
this._primitive = this._primitive && this._primitive.destroy()
this._primitive = this.getPrimitive()
if (!this._primitive) return;
this._primitive.update(context, frameState, commandList)
}
CustomPolygonPrimtive.prototype.isDestroyed = function () {
return false
}
CustomPolygonPrimtive.prototype.destroy = function () {
this._primitive = this._primitive && this._primitive.destroy()
return Cesium.destroyObject(this)
}
//如何使用
viewer.scene.primitives.add(new CustomPolygonPrimtive(options))
上面代码演示的是自定义Polygon面的实现,只加了坐标positions和颜色color,修改实例化后的CustomPolygonPrimtive两个参数时会实时渲染,不会出现闪烁。上面的代码没做详细的判断,比如positions数组加点或者减少时的判断,数组是引用类型,所以不会变,有需要的可以自己在上面基础上更改代码。