简体   繁体   中英

How to add 2D real time dynamic text to a Three.js scene?

I need a better solution to add 2d text to my three.js scene. I've tried using TextGeometry but I can't update the text in real-time (in a way that won't hurt performance) and I don't want to have to draw triangles. Does anyone know of any libraries or alternative solutions to add 2d text to a scene? I need to be able to easily update the text in realtime. If you know of a library I would greatly appreciate it if you could provide a code example. Thanks.

I did some more research and found this library . I was able to integrate it into my project with no problems. It works exactly as I need it to.

You could use a CanvasTexture , which supports updateable canvases as sources.

var canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 128;
var ctx = canvas.getContext("2d");
var texture = new THREE.CanvasTexture(canvas);
var material = new THREE.MeshBasicMaterial( { map: texture } );

let i = 0;
setInterval(() => {
  ctx.fillStyle = "red";
  ctx.fillRect(0, 0, 128, 128);
  ctx.fillStyle = "black";
  ctx.font = "80px sans-serif";
  ctx.fillText(i, 50, 90);
  texture.needsUpdate = true;
  i++;
}, 1000);

See this pen for the whole thing: https://codepen.io/dawken/pen/YzydEza?editors=1000

You could use a camera-facing plane instead of a cube to make it look 2D.

If you are use webgl(webgl2) context, you must create new canvas, write you're text there (in 2d context) and then turn you canvas to img, and use this img, this is a best solution and all frameworks use it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM