Using custom font (in a TypeScript web application)


I am writing a little game in TypeScript that is running on my server and I would like to use a custom font with DynamicTexture, but I cannot understand if and how I can do it.

I don’t know how to import the font to the client machine and make BabylonJS capable to load it. I’ve already tried some tricks with Webpack, but it is not working.

Any suggestion?

Thank you.

Maybe @RaananW or @sebavan will know.

1 Like

The font should be loaded in the browser. Its name should be used when calling the callText to draw the text.

I assume the issue is how to load the font in webpack and attach it to your page. There are a few ways of doing that. The main ones are loading the file directly and referencing it in a style tag, or loading fonts using CSS, which will reference a static (public) local or remote file. I found this tutorial that shows how to deal with fonts - Loading Fonts with webpack. Once the font is loaded and you have its family name, you can use it in babylon.


Thanks @RaananW (and also @Evgeni_Popov)!

Yesterday I tried to follow that tutorial, but I am struggling to make it works, maybe because I am trying to do too much things at the same time :relaxed: I will try to follow it step by step.

The important thing was to have the confirmation that BabylonJS can use custom fonts as they are loaded in the browser! :+1:



I’ve almost fixed, it is working in someway, but I’ve noticed that I have to load the page (at least) twice.

At first load the font is wrong, then after reloading everything is ok. It seems that the font is sent after the script has been loaded, so at the second time that the page is loaded font is cached (not sure if it makes sense). :thinking:

Of course it makes sense. Some would call it a race condition! :wink: (I wouldn’t, for many different reasons).

You will need to be sure the resources load prioir to you initializing the scene (or at least until you create the dynamic texture). Creare a promise the resolves when the resouce is available, and trigger the creation only after this promise fulfills. That’s one way of doing it.