2
我使用context.fill方法創建了一個包含文本的sprite對象。但是,我希望更改文字,使其顯示我在3D畫布中計算出的距離。我經常做這個計算,所以這就是爲什麼我不會簡單地創建新的精靈與新的價值裏面..ThreeJS:更新THREE.Sprite內部的文本
例如; 精靈始終顯示,當我在3D世界中計算距離時,精靈內部的文本將更改爲距離值。
我使用:ThreeJS R66
和Stemkoski以下腳本:
function makeTextSprite(message, parameters) {
if (parameters === undefined) parameters = {};
var fontface = parameters.hasOwnProperty("fontface") ?
parameters["fontface"] : "Arial";
var fontsize = parameters.hasOwnProperty("fontsize") ?
parameters["fontsize"] : 18;
var borderThickness = parameters.hasOwnProperty("borderThickness") ?
parameters["borderThickness"] : 4;
var borderColor = parameters.hasOwnProperty("borderColor") ?
parameters["borderColor"] : { r: 0, g: 0, b: 0, a: 1.0 };
var backgroundColor = parameters.hasOwnProperty("backgroundColor") ?
parameters["backgroundColor"] : { r: 255, g: 255, b: 255, a: 1.0 };
//var spriteAlignment = THREE.SpriteAlignment.topLeft;
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.font = "Bold " + fontsize + "px " + fontface;
// get size data (height depends only on font size)
var metrics = context.measureText(message);
var textWidth = metrics.width;
// background color
context.fillStyle = "rgba(" + backgroundColor.r + "," + backgroundColor.g + ","
+ backgroundColor.b + "," + backgroundColor.a + ")";
// border color
context.strokeStyle = "rgba(" + borderColor.r + "," + borderColor.g + ","
+ borderColor.b + "," + borderColor.a + ")";
context.lineWidth = borderThickness;
roundRect(context, borderThickness/2, borderThickness/2, textWidth + borderThickness, fontsize * 1.4 + borderThickness, 6);
// 1.4 is extra height factor for text below baseline: g,j,p,q.
// text color
context.fillStyle = "rgba(0, 0, 0, 1.0)";
context.fillText(message, borderThickness, fontsize + borderThickness);
// canvas contents will be used for a texture
var texture = new THREE.Texture(canvas)
texture.needsUpdate = true;
var spriteMaterial = new THREE.SpriteMaterial(
{ map: texture, useScreenCoordinates: false });
var sprite = new THREE.Sprite(spriteMaterial);
sprite.scale.set(1000, 500, 10);
return sprite;
}
// function for drawing rounded rectangles
function roundRect(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
ctx.lineTo(x + w, y + h - r);
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
ctx.lineTo(x + r, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
謝謝!
不建議直接設置'_needsUpdate'屬性。改爲設置'needsUpdate'。 – WestLangley