cesium中rectangle是水平垂直于正北方向的,rectangle的属性中有rotation,但是rotation是以矩形的中心点进行旋转的,旋转过程中矩形的形状可能会变形,如果需要以矩形的顶点为原点进行旋转,可以采用primitive的方式添加polygon,并设置polygon的矩阵。
用entity的方式参考cesium 指定点旋转rectangle entity方式 坐标篇-CSDN博客
一、primitive的方式添加polygon
let p1 = [113.389, 38.094669];
let p2 = [113.390968, 38.095338];
// 通过矩形的2个点,得到多边形的四个点
let polygonInstance = new Cesium.GeometryInstance({
geometry: Cesium.PolygonGeometry.fromPositions({
positions: Cesium.Cartesian3.fromDegreesArray([
...p1,
p2[0], p1[1],
...p2,
p1[0], p2[1]
]),
height: 0,
vertexFormat: Cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT
}),
attributes: {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.fromCssColorString('#00ff00').withAlpha(0.5))
}
});
let polygonPrimitive = new Cesium.Primitive({
geometryInstances: [polygonInstance],
undisplayable: true,
appearance: new Cesium.PerInstanceColorAppearance({
flat: true,
translucent: false
})
});
viewer.scene.primitives.add(polygonPrimitive);
二、设置polygon的矩阵,以p1为原点顺时针旋转30度
let center = Cesium.Cartesian3.fromDegrees(...p1);
let localMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(center);
let inverseMatrix = Cesium.Matrix4.inverse(localMatrix, new Cesium.Matrix4);
let rotationZ = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(-30));
let rotationMatrix = Cesium.Matrix4.fromRotation(rotationZ);
let modelMatrix = Cesium.Matrix4.multiply(rotationMatrix, inverseMatrix, new Cesium.Matrix4);
polygonPrimitive.modelMatrix = Cesium.Matrix4.multiply(localMatrix, modelMatrix, new Cesium.Matrix4);
代码解析:Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(-30));
- cesium中z轴是向上的,所以面对着屏幕以p1为原点旋转需要调用用fromRotationZcesium mapboxgl+threebox glb 朝向问题 坐标轴方向_threebox z轴向上-CSDN博客
- fromRotationZ()指向正方向为逆时针方向,所以以p1为原点顺时针旋转30度的时候传入角度是-30