相比于普通气泡窗,Sprite效果拥有一个独特属性,无论场景如何旋转偏移,标签总是正对着相机平面。在日常基础设施、物联设备中精灵标签最为常用。
//精灵标签摄像头
let locatCamera = [new THREE.Vector3(15, 4, 0), new THREE.Vector3(14, 4, -19), new THREE.Vector3(13, 11.5, -9), new THREE.Vector3(85, 11, -45),
new THREE.Vector3(90, 11, 19), new THREE.Vector3(-38, 11, -45), new THREE.Vector3(-45, 11, 20)]
for (let i = 0; i < locatCamera.length; i++) {
let font2 = '摄像头';
let spriteCamera = makeTextSprite(font2 + (i + 1),
{
fontsize: 20,
borderColor: {r: 0, g: 0, b: 0, a: 0.4},/* 边框黑色 */
backgroundColor: {r: 255, g: 255, b: 255, a: 0.9}/* 背景颜色 */
});
spriteCamera.center = new THREE.Vector2(0, 0);
spriteCamera.name = font2 + (i + 1);
spriteCamera.position.set(locatCamera[i].x, locatCamera[i].y - 5, locatCamera[i].z);
Text.add(spriteCamera)
scene.add(Text);
}
精灵标签也可以自己绘制样式,加载图像纹理或canvas纹理
function createSpriteShape(){
/*创建一个画布,设置画布的宽高*/
let canvas = document.createElement("canvas");
canvas.width = 120;
canvas.height = 120;
/*创建图形*/
let ctx = canvas.getContext("2d");
ctx.fillStyle = "#ff0000";
ctx.arc(50,50,50,0,2*Math.PI);
ctx.fill();
/*将canvas作为纹理,创建Sprite*/
let texture = new THREE.Texture(canvas);
texture.needsUpdate = true; //注意
let material = new THREE.SpriteMaterial({map:texture});
let mesh = new THREE.Sprite(material);
/*默认很小的,需要放大*/
mesh.scale.set(100,100,1);
return mesh;
}
标签内容更新,销毁之前的,更新现在的。
function Update(_str, Object) {
var spriteMaterial = getSpriteMaterial(_str);
var msprite = findSprite(Object);
if(msprite){
if(msprite.material) msprite.material.dispose();
msprite.material = null;
msprite.material = spriteMaterial;
}
else{
console.error("sprite_label update text error!");
}
}