How to dynamically modify the text of TextGeometry?For example, if I want to get a temperature from the server, how can I make it display on textGeometry in real time .
First solution is dispose old textgeometry and create new if temperature is changed.
Second solution create digits from 0 to 9 and create again digits from 0 to 9.
If temperature 4 then show one textGeometry 4. If 55 then hide 4 and show two textgeometry 5 and 5.
You probably don’t want to use a text geometry for this but render the text on a canvas instead and use it as a sprite. Redrawing the texture with updated text is faster than recreating geometries all over the time. And it might be an easier workflow that composing text from a bunch of digit meshes.
Hello, I did an experiment according to your idea, but I still couldn’t update the text. Could you please help me have a look .
const textureLoader = new TextureLoader().setPath("../../Res/UI/");
textureLoader.load("icon.png", function (_texture) {
const rate = 200;
const width = _texture.image.width / rate;
const height = _texture.image.height / rate;
planeMat = new THREE.SpriteMaterial({ map: _texture, toneMapped: false });
planeMesh = new THREE.Sprite(planeMat);
planeMesh.scale.set(width, height, 1);
planeMesh.position.set(0, 5, 0);
scene.add(planeMesh);
let text = "30.5"
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
ctx.fillStyle = "#ffff00";
ctx.font = "Bold 130px Arial";
ctx.lineWidth = 4;
ctx.fillText(text, 4, 104);
let fontTexture = new THREE.Texture(canvas);
fontTexture.needsUpdate = true;
fontMat = new THREE.SpriteMaterial({ map: fontTexture });
fontMat.needsUpdate=true;
fontMesh = new THREE.Sprite(fontMat);
fontMesh.position.set(0, 0.2, 0);
fontMesh.scale.set(1 / width, 1 / height, 1);
planeMesh.add(fontMesh);
let index = 1;
planeMesh.onBeforeRender = function () {
index += 1;
index%=60;
text=index.toString();
console.log(text);
ctx.fillText(text, 4, 104);
};
});
Why recreate the geometry every time? Geometries can be created once for each letter that will be used.
In the first part of my last post I’ve mentioned that this approach is indeed bad for performance.
In the second part, I’ve highlighted that composing words from a selection of pre-defined letters is potentially an inconvenient workflow (depending on the use case). A label with a texture representing the text is a way more simple solution.