rahulpandharkar
rahulpandharkar

Reputation: 11

Adding 2D Text on a 3D Object in Threejs

I've just started learning threejs, thought of working on a pre-made model. I wanted to work with a Flipper Zero Model.

Here is the link of the model. Flipper's Screen is called "Object_8" in this model, I wanted to add some text as if it were to be displayed on the screen of the model. I tried everything I could but I'm not able to get the text written on the screen. I used the Canvas texture to create something that can have the text but I don't seem to position it rightly to be displayed on the screen.

This is the code (written with AI) that attempts to add a canvas texture on the screen of the model.

loader.load('models/flipper_zero.gltf', (gltf) => {
    const model = gltf.scene;
    const object8 = model.getObjectByName('Object_8');
    if(object8)
    {
      const canvas = document.createElement('canvas');
      canvas.width = 256;
      canvas.height = 128;
      const ctx = canvas.getContext('2d');
    
    
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.fillStyle = 'white';
      ctx.font = 'bold 48px Arial';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillText('Hello', canvas.width / 2, canvas.height / 2);
      const texture = new THREE.CanvasTexture(canvas);
      

      const planeGeometry = new THREE.PlaneGeometry(0.2, 0.1);
      const planeMaterial = new THREE.MeshBasicMaterial({
        map: texture,
        transparent: false,
        opacity: 0.8,
        side: THREE.DoubleSide,
      });
    
      const textPlane = new THREE.Mesh(planeGeometry, planeMaterial);
      
      const screenWorldPos = new THREE.Vector3();
      object8.getWorldPosition(screenWorldPos);
      
      textPlane.position.copy(screenWorldPos);
      
      const normalMatrix = new THREE.Matrix3().getNormalMatrix(object8.matrixWorld);
      const normal = new THREE.Vector3(0, 0, 1).applyMatrix3(normalMatrix).normalize();
      
      textPlane.position.add(normal.multiplyScalar(0.02)); 
      
      textPlane.rotation.copy(object8.rotation);
      
      scene.add(textPlane);
      
      console.log("Found Object 8, i.e. the Screen")
      object8.material.color.set(0xfffff);
    }
    scene.add(model);
  }, undefined, (error) => {
    console.error('Error loading the model:', error);
  });

Can somebody help me position the canvas properly on the screen so that it actually displays the message onto the screen?

Upvotes: 1

Views: 40

Answers (0)

Related Questions