πŸ’‘ This page contain affiliate links. By making a purchase through them, we may earn a commission at no extra cost to you.
How to Use Custom Fonts in Phaser 3

How to Use Custom Fonts in Phaser 3

Ferenc Almasi β€’ Last updated 2021 July 13 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

Using custom fonts in Phaser needs some preparation. In this tutorial, we will look into how to go:

Before and after using custom fonts in Phaser3

Preload the Custom Font

The first step is to preload your custom font family through the head of your HTML file:

Copied to clipboard! Playground
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />

        <title>Phaser Game</title>
        <link rel="preload" as="font" href="assets/Custom-Font.ttf" type="font/ttf" />
    </head>
    <body>
        <script src="assets/phaser.js"></script>
    </body>
</html>
index.html

For this to work, you want to use a <link rel="preload"> with two important attributes:

  • as: This specifies the type of content that is being loaded by the link tag.
  • type: This attribute defines the type of content that is linked. It should be a MIME type, in our case, the type of font, eg.: font/ttf or font/woff2

This tells the document to treat the file with high priority and preload it as soon as possible.

Define the new font in CSS

To make it available in Phaser, define the new font family in your CSS that is linked to your document, with the @font-face at-rule:

Copied to clipboard!
@font-face {
    font-family: CustomFont;
    src: url('./Custom-Font.ttf');
}
font.css

Using the Custom Font

To use this font in Phaser, simply reference it in one of your styles, as a fontFamily property. For example, to use it for a button, you can do:

Copied to clipboard!
scene.add.text(x, y, 'Button', { fontFamily: 'CustomFont' });
phaser.js

To summarize, you need three steps in Phaser 3 to use custom fonts:

  1. Preload the custom font family through your HTML file
  2. Define a new font-face in CSS for the new font
  3. Reference the new font in Phaser
Building The Game Breakout Using JavaScript
  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.