1. 使用entity创建矩形
js
复制代码
var rectangle = viewer.entities.add({
rectangle: {
coordinates: Cesium.Rectangle.fromDegrees(
// 西边的经度
90,
// 南边维度
20,
// 东边经度
110,
// 北边维度
30
),
material: Cesium.Color.GREEN.withAlpha(0.8),
},
2. 使用primivite创建矩形
js
复制代码
// primivite创建矩形
// 01-创建几何体
let rectGeometry = new Cesium.RectangleGeometry({
rectangle: Cesium.Rectangle.fromDegrees(
// 西边的经度
115,
// 南边维度
20,
// 东边经度
135,
// 北边维度
30
),
// 距离表面高度
height: 0,
vertexFormat: Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,
});
// 02-创建几何体实例
let instance = new Cesium.GeometryInstance({
geometry: rectGeometry,
attributes: {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(
Cesium.Color.RED.withAlpha(0.5)
),
},
});
// 03-设置外观
let appearance = new Cesium.PerInstanceColorAppearance({
flat: true,
});
// 04-图元
let primitive = new Cesium.Primitive({
geometryInstances: instance,
appearance: appearance,
});
// 05-添加到viewer
viewer.scene.primitives.add(primitive);
viewer.camera.setView(viewer.entities);
3. 创建多个实体在同一个primitive
js
复制代码
// 04-图元
let primitive = new Cesium.Primitive({
geometryInstances: [instance, instance2],// 在数组geometryInstances 中添加多个实体
appearance: appearance,
});
4. 修改primitive颜色
js
复制代码
// 动态修改图元颜色
setInterval(() => {
let attributes = primitive.getGeometryInstanceAttributes("blueRect");
attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(
// Cesium.Color.YELLOW.withAlpha(0.5)
Cesium.Color.fromRandom({
alpha: 0.5,
})
);
}, 2000);
});
5. primitive和entity物体交互
js
复制代码
// 拾取
var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
handler.setInputAction(function (movement) {
// console.log(movement);
// scene.pick选中物体
var pickedObject = viewer.scene.pick(movement.position);
console.log(pickedObject);
if (Cesium.defined(pickedObject) && typeof pickedObject.id == "string") {
// console.log(pickedObject.id);
let attributes = primitive.getGeometryInstanceAttributes(pickedObject.id);
attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(
Cesium.Color.YELLOW.withAlpha(0.5)
);
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);