描述这样的问题,其实应该说得更加细致一点,我希望绘制一个文本,这个文本是躺在地球平面之上的,而且文本是不会随着我相机的位置而发生变化,虽然cesium 提供了 label 实体,但是那个是经过封装之后的对象,他会随着相机的俯仰角变化而让自己发生变化。同时我们希望我们的字体就像一个图形一样,可以在给定高度的平面内,有的 同学会想设置高度参考为贴地,其实那个和我们实际想要的效果并不同,你可以实际操作一下进行对比。
换句话说,我们的思路就很清晰了,也就是通过canvas画出文本的图片,再将文本的图片作为图元的材质,这时候无论是平面图元还是立体图元都是可以设置的了。
以下是我的一个实现思路:
const canvas = document.createElement ('canvas');
canvas.width = 40;
canvas.height = 20;
const context = canvas.getContext ('2d');
context.fillStyle = 'rgba(240, 240, 240, 0)';
context.fillRect (0, 0, canvas.width, canvas.height);
context.font = '12px sans-serif';
context.fillStyle = '#000';
context.textAlign = 'center';
context.textBaseline = 'middle';
context.fillText (text, canvas.width / 2, canvas.height / 2);
const image = new Image ();
image.src = canvas.toDataURL ();
const rectanglePrimitive = this.viewer.scene.primitives.add (
new Cesium.Primitive ({
geometryInstances: new Cesium.GeometryInstance ({
geometry: new Cesium.RectangleGeometry ({
rectangle: Cesium.Rectangle.fromDegrees (
center.coordinates[0] - 0.00003,
center.coordinates[1] - 0.000015,
center.coordinates[0] + 0.00003,
center.coordinates[1] + 0.000015
),
height: height + 0.5,
}),
}),
appearance: new Cesium.MaterialAppearance ({
material: new Cesium.Material ({
fabric: {
type: 'Image',
uniforms: {
image: image.src,
},
},
}),
})
})
);
this.units.push (rectanglePrimitive)
这是最后的效果: