Phaser

While doing games with Phaser 3 one of the essential thing is loading your local fonts to use in game. When I first try, I was expecting something like loading images/sounds;

// loading image
this.load.image('logo', 'images/logo.png');

// loading font
this.load.font('font', 'fonts/font.woff);

Unfortunately, it’s not working like that 🙂 I look for different solutions, but the easiest way for me using CSS to address the fonts and use in HTML to load them. So for index.html file, I am adding font-face like this;

@font-face {
  font-family: 'font';
  src: url('fonts/font.woff2') format('woff2'),
        url('fonts/font.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

But adding font face is not enough, because browsers not loading the font if you are not using them in your HTML. So we need to create a class to hide our font loader div;

.fontload{
  visibility:hidden;
  position: absolute;
  left: -9999px;
{

The last step is we need to use our font in our HTML, we can add something like this to inside body;

<div class="fontload" style="font-family: 'font';">.</div>

In the end, that “dot” won’t be visible in HTML but our font will be available. And you can define multiple face font and add multiple font loading div, if you want to use multiple fonts. But how do you prepare your fonts to use in web?

I am using https://www.fontsquirrel.com/tools/webfont-generator for that purpose. It allows you to upload any regular font files and gives you optimized for web woff, woff2 fonts to use in browser. Now, how can you create the text at Phaser Scene;

this.add.text(100, 100, 'DEMO TEXT', {fontFamily: 'font'});

Congrats! You have Phaser text with custom local font.