three使用精靈圖實現標籤
阿新 • • 發佈:2021-06-15
最近設計到一個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);
搞定
!!!!!!!!!!覺得有用的話,點個贊再走哦!!!! (๑•̀ㅂ•́)و✧