I'm building a 3D environment using ThreeJS in which the camera is at a fixed position, but users can "look around/move the camera" using pointer lock controls.
Objects appear at random places in the 3D environment. I put a certain word next to each object. The word is a 2D sprite since it should always face the user, even if he starts looking around.
This is the code I use for the text sprite:
function makeTextSprite(message, parameters) {
var fontface = parameters.hasOwnProperty("fontface") ? parameters["fontface"] : "Arial";
var fontsize = 65;
var borderThickness = 0;
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.font = fontsize + "px " + fontface;
var metrics = context.measureText(message);
var textWidth = metrics.width;
context.fillStyle = "rgba(" + backgroundColor.r + "," + backgroundColor.g + "," + backgroundColor.b + "," + backgroundColor.a + ")";
context.strokeStyle = "rgba(" + borderColor.r + "," + borderColor.g + "," + borderColor.b + "," + borderColor.a + ")";
context.lineWidth = borderThickness;
roundRect(context, borderThickness / 2, borderThickness / 2, (textWidth + borderThickness) * 1.1, fontsize * 1.4 + borderThickness, 8);
context.fillStyle = "rgba(" + textColor.r + ", " + textColor.g + ", " + textColor.b + ", 1.0)";
context.fillText(message, borderThickness, fontsize + borderThickness);
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(0.5 * fontsize, 0.25 * fontsize, 0.75 * fontsize);
return sprite;
}
This works fine, but I want the text to have the same size, always, as a percentage of the browser width, no matter where the object is. In the code above, the text always has the same size, but it appears smaller when it's put further away from the camera, which I don't want.
Anyone knows how I could achieve this? Thanks in advance!