1.创建2D文字canvas
makeLabelCanvas(baseWidth, size, name) {
const borderSize = 2;
const ctx = document.createElement('canvas').getContext('2d');
const font = `${size}px bold sans-serif`;
ctx.font = font;
// console.log("ctx",ctx)
// measure how long the name will be
const textWidth = ctx.measureText(name).width;
const doubleBorderSize = borderSize * 2;
const width = baseWidth + doubleBorderSize;
const height = size + doubleBorderSize;
ctx.canvas.width = width;
ctx.canvas.height = height;
// need to set font again after resizing canvas
ctx.font = font;
ctx.textBaseline = 'middle';
ctx.textAlign = 'center';
ctx.fillStyle = '#fffffc';
ctx.fillRect(0, 0, width, height);
// scale to fit but don't stretch
const scaleFactor = Math.min(1, baseWidth / textWidth);
ctx.translate(width / 2, height / 2);
ctx.scale(scaleFactor, 1);
ctx.fillStyle = 'black';
ctx.fillText(name, 0, 0);
return ctx.canvas;
},
2.创建文字精灵
addSpirit(name){
const canvas=this.makeLabelCanvas(300,70,name);
const canvasTexture = new THREE.CanvasTexture(canvas);
canvasTexture.minFilter = THREE.LinearFilter;
canvasTexture.wrapS = THREE.ClampToEdgeWrapping;
canvasTexture.wrapT = THREE.ClampToEdgeWrapping;
const labelMaterial = new THREE.SpriteMaterial({
map: canvasTexture,
transparent: true,
});
const label = new THREE.Sprite(labelMaterial);
label.position.z=this.minY+300;
const labelBaseScale = 1;
label.scale.x = canvas.width * labelBaseScale;
label.scale.y = canvas.height * labelBaseScale;
return label
},
3.给需要的模型添加精灵(精灵图的内容可修改)
//加入显示设备名的精灵图
let label=this.addSpirit(device.name)
// console.log("精灵",canvas)
copyMesh.add(label);