我正在尝试在three.js中将某些文本显示为sprite,并希望将其与对象一起移动。因此,我使用画布创建用于映射SpriteMaterial的纹理,然后从中创建sprite。然后,当我移动对象时删除精灵,并添加一个带有更新文本的新精灵。但是问题是,即使删除后,删除的精灵仍会显示。我也想知道是否有更好的方法来执行我想做的事情。这是我创建精灵的代码:
function makeTextSprite(theMessage, theParameters) {
if (theParameters === undefined) theParameters = {
};
var fontface = theParameters.hasOwnProperty("fontface") ?
theParameters["fontface"] : "Arial";
var fontsize = theParameters.hasOwnProperty("fontsize") ?
theParameters["fontsize"] : 18;
var borderThickness = theParameters.hasOwnProperty("borderThickness") ?
theParameters["borderThickness"] : 4;
var borderColor = theParameters.hasOwnProperty("borderColor") ?
theParameters["borderColor"] : {
r: 0, g: 0, b: 0, a: 1.0
};
var backgroundColor = theParameters.hasOwnProperty("backgroundColor") ?
theParameters["backgroundColor"] : {
r: 255, g: 255, b: 255, a: 1.0
};
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(theMessage);
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;
// text color
context.fillStyle = "rgba(255, 0, 0, 1.0)";
context.fillText(theMessage, 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: true
});
var sprite = new THREE.Sprite(spriteMaterial);
sprite.scale.set(100, 50, 1.0);
return sprite;
}
这是我的代码,用于更新精灵的文本和位置: 函数setCoordinatePosition()
{
if(scene.getObjectByName('text')!=undefined)
{
scene.remove("text");
}
var sliderValue = document.getElementById("slider").getElementsByTagName("input")[0].value;
var coordinate_info = "(" + (vx/100)*sliderValue + ", " + (vy/100)*sliderValue + ", " + (vz/100)*sliderValue + ")";
text = makeTextSprite(coordinate_info,{ fontsize: 50, borderColor: { r: 0, g: 0, b: 0, a: 1.0 }, backgroundColor: { r: 255, g: 255, b: 255, a: 0.8 } , borderThickness: 5});
text.name = "text";
scene.add(text);
text.position.set(sphere.position.x,sphere.position.y,sphere.position.z);
text.position.y += 5;
render();
}
我希望红色文本显示黄色球的坐标并遵循它。
答案 0 :(得分:0)
Scene.remove需要引用对象,而不是名称
pi@raspberrypi:~ $ sudo apt-get install python-pip
Reading package lists... Done
Building dependency tree
Reading state information... Done
python-pip is already the newest version (9.0.1-2+rpt2).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
代替
scene.remove(scene.getObjectByName('text'));
场景是Object3D的一个实例,因此它使用this方法
如果要实现的目的是将文本与球体一起移动,则可以使用this方法将文本简单地添加为球体的子级。您还必须调整相对位置。
scene.remove("text");