Dynamically create 2D text in three.js

前端 未结 8 2093
醉梦人生
醉梦人生 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 19:56

    The response by @LeeStemkoski was quite useful. Yet there is a slight change that needs to be done to the code in order for the text to follow your arrows around i.e. in case the arrow gets moved around, rotated, etc.

    See the next code

                            var canvas1 = document.createElement('canvas');
                            var context1 = canvas1.getContext('2d');
                            context1.font = "Bold 10px Arial";
                            context1.fillStyle = "rgba(255,0,0,1)";
                            context1.fillText('Hello, world!', 0, 60);
    
                            // canvas contents will be used for a texture
                            var texture1 = new THREE.Texture(canvas1)
                            texture1.needsUpdate = true;
    
                            var material1 = new THREE.MeshBasicMaterial({ map: texture1, side: THREE.DoubleSide });
                            material1.transparent = true;
    
                            var mesh1 = new THREE.Mesh(
                                new THREE.PlaneGeometry(50, 10),
                                material1
                              );
                            mesh1.position.set(25, 5, -5);
                            mesh1.rotation.x = -0.9;
                            shape.add(mesh1);
                            // Note that mesh1 gets added to the shape and not to the scene
    
                           scene.add(shape)
    

    As you can see, the trick is to add the text (mesh1) to the shape (your "arrow") instead of adding it to the scene.

    I hope this helps.

提交回复
热议问题