How to update text in real time?

I rendered a text with canvas, converted it to Texture, and generated a Sprite, how do I update the text on Sprite in real time, similar to the health in the game.

Update your canvas with the new text, then set the CanvasTexture.needsUpdate property to true

In this example, I update the text with texture.needsUpdate = true;

CPU simulation 8Bit

see CPU-Simulation-8Bit line 3456

function canvasSet( texture, ctx, bgr, w, h, txt ) {
 
    ctx.fillStyle = bgr; 
    ctx.fillRect( 0, 0, w, h );
    ctx.fillStyle = dGray;
    ctx.textAlign = "left";
    ctx.textBaseline = "middle";
    ctx.font = 'bold 80px Courier';     
    ctx.fillText(  txt, 0, h / 2 );    
    texture.needsUpdate = true;
    
}
  planeMesh.userData.update = function () {
            index += 1;
            index %= 60;
            text = index.toString();
            console.log(text);
            ctx.clearRect(0,0,canvas.width,canvas.height);
            canvas.width = canvas.width;
            ctx.fillStyle = "#ffff00";
            ctx.font = "Bold 48px 宋体";
            ctx.textBaseline = "middle";
            ctx.textAlign = "center";
            ctx.fillText(text, canvas.width / 2, canvas.height / 3);
        };

Why is text only updated once?

Why is text only updated once?

Updates then text its changed

It only changed once. I want it to keep changing

For updating every frame

animate(){
requestAnimationFrame(animate);
planeMesh.userData.update();
renderer.render(scene,camera);
}
scene.traverseVisible((obj) => {
    if (obj.userData.update !== undefined) {
        obj.userData.update();
    }
});

That’s what it was written before

animate(){
requestAnimationFrame(animate);
scene.traverseVisible((obj) => {
    if (obj.userData.update !== undefined) {
        obj.userData.update();
    }
});
renderer.render(scene,camera);
}

The function is executed, but the text is updated only once

planeMesh.userData.update = function () {
            index += 1;
            index %= 60;
            text = index.toString();
            console.log(text);
            ctx.clearRect(0,0,canvas.width,canvas.height);
            canvas.width = canvas.width;
            ctx.fillStyle = "#ffff00";
            ctx.font = "Bold 48px 宋体";
            ctx.textBaseline = "middle";
            ctx.textAlign = "center";
            ctx.fillText(text, canvas.width / 2, canvas.height / 3);
texture.needsUpdate = true; // updating
        };

It’s finally running. I thought fontTexture. NeedsUpdate =true would only be called once. Thank you very much

1 Like