FontLoader and TextGeometry not getting imported properly in threejs

Viewed 32

I am trying to add a 3D text over the BoxGeometry sides for front, right, left and top.

I implmented this code as below :

loadFont = () =>{

const loader = new THREE.FontLoader();
loader.load( 'https://threejs.org/examples/fonts/helvetiker_regular.typeface.json', function ( response ) {

console.log("response "+response);

  return response;

} );}

   
createText = () => {

 let font = this.loadFont();

   this.textGeo = new THREE.TextGeometry( "Hello", {

    font: font,
    size: 70,
    height: 20,
    curveSegments: 4,
    bevelThickness: 2,
    bevelSize: 1.5,
    bevelEnabled: true

  });
  
  const materials = [
    new THREE.MeshPhongMaterial( { color: 0xffffff, flatShading: true } ), // front
    new THREE.MeshPhongMaterial( { color: 0xffffff } ) // side
  ];
  

  this.textMesh1 = new THREE.Mesh(this.textGeo, materials );
  this.textMesh1.position.y = 80;
  this.textMesh1.position.z = 0;
  this.textMesh1.rotation.x = 0;
  this.textMesh1.rotation.y = Math.PI * 2;

  this.scene.add(this.textMesh1);
  this.root.add(this.textMesh1);

I am not able to receive a 3D text in my scene? Getting Error - "THREE.TextGeometry: font parameter is not an instance of THREE.Font."

When I try using

      const loader = new FontLoader(); 
      this.textGeo = new TextGeometry( "Hello", {

    font: font,
    size: 70,
    height: 20,
    curveSegments: 4,
    bevelThickness: 2,
    bevelSize: 1.5,
    bevelEnabled: true

  });

I don't get exact place from where I am required to import these FontLoader and TextGeometry classes.

Any help, guidance or reference would be helpful. Thanks

1 Answers

TextGeometry and FontLoader have been moved out of the core some time ago so you have to import them from three/examples/jsm/geometries/TextGeometry.js and three/examples/jsm/loaders/FontLoader.js.

Next, the following line of code does not work since loadFont() actually works asynchronous:

let font = this.loadFont();

loadFont() will always return undefined since you return the font in the onLoad() callback function of FontLoader.load(). You have to rewrite your listing to account for the asynchronous nature of the code flow.

Related