How to Use Custom Fonts in Phaser 3
Using custom fonts in Phaser needs some preparation. In this tutorial, we will look into how to go:
Preload the Custom Font
The first step is to preload your custom font family through the head
of your HTML file:
<!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>
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 thelink
tag.type
: This attribute defines thetype
of content that is linked. It should be a MIME type, in our case, the type of font, eg.:font/ttf
orfont/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:
@font-face {
font-family: CustomFont;
src: url('./Custom-Font.ttf');
}
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:
scene.add.text(x, y, 'Button', { fontFamily: 'CustomFont' });
To summarize, you need three steps in Phaser 3 to use custom fonts:
- Preload the custom font family through your HTML file
- Define a new
font-face
in CSS for the new font - Reference the new font in Phaser
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: