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 or 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, and there is two different way to achieve this. First one is using CSS, the other is using FontFace API.

CSS Method

For example, let’s assume you have index.html file, you need to add 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.

FontFace API Method

This method is much simpler and easy to manage but some of the browsers not supporting it. They are small usage browsers like IE11, Opera mini and big browsers like Chrome, Edge, Safari, Firefox already supporting it. So if you are not have problem with edge cases you can use this method.

For this method we will assume you have preload scene in your phaser game. You need to add these codes to your scene;

export default class Preload extends Phaser.Scene {
    constructor() {
        super("Preload");
    }

    preload() {
        // Load assets and other codes
    }
    
    create() {
        // Load your local font
        const newFontFace = new FontFace('CustomFont', 'url(../assets/CustomFont.ttf)');
        document.fonts.add(newFontFace);
        newFontFace.load().then(() => {
            this.scene.start("Game");
        });
    }
}

We define our font face with FontFace API and waiting until it loads. And after loaded we switch to game scene.

Congrats! Now, you have Phaser local font in your phaser game.