three使用精灵图实现标签
最近设计到一个3d项目,需要在模型上添加一个常显的标签,查阅资料后决定采用 canvas 和 精灵图的方式来属性标签
效果图如下
实现步骤:
1,先定义一个canvas的绘制方法
getTextCanvas(text) { var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); var width = ctx.measureText(text).width + 10, // 根据文字数量来决定宽度 height = 30; //固定高度 canvas.width = width; canvas.height = height; ctx.fillStyle = "#cdc73b82"; // 背景颜色 ctx.fillRect(0, 0, width, height); ctx.font = 10 + 'px " bold'; ctx.fillStyle = "yellow"; // 字体颜色 ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText(text, width / 2, height / 2);// 实现边框 ctx.moveTo(0, 0); ctx.lineTo(0, height); ctx.lineWidth = 2; ctx.strokeStyle = "yellow"; ctx.stroke(); ctx.moveTo(0, 0); ctx.lineTo(width, 0); ctx.lineWidth = 2; ctx.strokeStyle = "yellow"; ctx.stroke(); ctx.moveTo(width, height); ctx.lineTo(width, 0); ctx.lineWidth = 2; ctx.strokeStyle = "yellow"; ctx.stroke(); ctx.moveTo(width, height); ctx.lineTo(0, height); ctx.lineWidth = 2; ctx.strokeStyle = "yellow"; ctx.stroke(); return canvas; },
2,定义精灵图,并添加到scene中
var text = "Leo Test Label"; // 目标文字 var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); var width = ctx.measureText(text).width; var scalek = width / 30; // 计算放缩比 var spriteMaterial = new THREE.SpriteMaterial({ map: new THREE.CanvasTexture(_this.getTextCanvas(text)), transparent: true, //开启透明(纹理图片png有透明信息) }); // 创建精灵模型对象,不需要几何体geometry参数 var sprite = new THREE.Sprite(spriteMaterial); sprite.scale.set(scalek, 1, 1); //精灵大小 sprite.position.set( // 设置精灵图位置 -69.7118421042448, 9.677643584477078, 165.00641250371845 ); sprite.translateY(0.8); _this.scene.add(sprite);
搞定
!!!!!!!!!!觉得有用的话,点个赞再走哦!!!! (??????)??