Dynamically create 2D text in three.js

前端 未结 8 2066
醉梦人生
醉梦人生 2020-12-12 19:20

I have 3D model which I have created in three.js. Based on some data, I want to create a set of arrows which is decorated by a small text label. These labels should be in 2D

相关标签:
8条回答
  • 2020-12-12 20:09

    Check out the demo.

    TextGeometry consumes a lot of memory and you need to load a font, which contains a geometry for each letter, you will be using. If I have more than 100 text meshes in a scene, my browser crashes.

    You can draw text on a canvas and include it in your scene via a Sprite. The problem with it is that you need to calculate the font size. If you have a moving camera, then you need to calculate the font size periodically. Otherwise the text will get to blurry, if you get too close to the text with the camera.

    I wrote a class TextSprite which automatically calculates the best possible font size, depending on the distance to the camera and the size of the renderer element. The trick is to use the callback .onBeforeRender of the class Object3D, which receives the camera and the renderer.

    let sprite = new THREE.TextSprite({
      text: 'Hello World!',
      fontFamily: 'Arial, Helvetica, sans-serif',
      fontSize: 12,
      color: '#ffbbff',
    });
    scene.add(sprite);
    

    You can also change the text and the font on the fly.

    sprite.text = 'Hello Stack Overflow!';
    sprite.fontFamily = 'Tahoma, Geneva, sans-serif';
    sprite.fontSize = 24;
    
    0 讨论(0)
  • 2020-12-12 20:13

    You can create a 2d canvas and use css to position it to the top of your webgl canvas. Then you can draw text on it using the ctx.fillText(text,x,y) or ctx.strokeText(text,x,y) methods provided by the 2d canvas context. By using this method you can draw other things besides text, such as arrows and meters.

    You can use the method as suggested by @kronuus to convert a point from 3d to 2d space.

    0 讨论(0)
提交回复
热议问题