How to preloadFont in troika-three-text?

Hi all, this is my first post. I’m just starting to learn three.js and JS (I’ve been coding C# in Unity for 10 years). I have a project coming up that’s going to have a lot of text objects in the 3D space so I’m trying out troika-three-text to see if it’ll work for my needs.

So far so good, I can easily create text in my scene… Now I’d like to preload the font using the method provided by the maker but I can’t figure out how to reference the font after it has been loaded. Here’s what I’ve tried so far. Thanks for any help/guidance on this. -t

import { Text } from 'troika-three-text';
import { preloadFont } from 'troika-three-text';

preloadFont(
  {
    font: 'https://fonts.gstatic.com/s/roboto/v18/KFOmCnqEu92Fr1Mu4mxM.woff',
    characters: 'abcdefghijklmnopqrstuvwxyz',
  },
  () => {
    console.log('preload font complete');
  },
);

// then later after I know the font has been loaded...

function createText() {
  const myText = new Text();

  myText.text = 'hello!!';
  myText.font =  // ???? how do reference the preloaded font?

  myText.sync();

  return myText;
}

export { createText };
  1. Callback is called with this payload - you can pick up the font name from payload.parameters.font.
  2. Preloaded font is stored in a texture atlas - after you preload the font, it should become immediately available for all Troika text instances. You can reference it with the same path you preloaded it with.

Thanks for the reply! I can’t figure out how to get the font name from payload.parameters.font, but in your 2nd point “You can reference it with the same path you preloaded it with” it sounds like your’e saying if I use the same font path in myText.font as I did in preloadFont then that should do it.

I just did some testing and it does seem that the text object is created (almost) immediately if I create it after the preload completes. I think now the slight delay I’m still seeing could be due to the fact that I’m pulling the font via URL rather than locally. I tried to preload a local .woff file in my project but I got some errors in the console so I guess it’s only possible to load fonts via https.