How to Use Custom Bitmap Fonts in Pixi.js

This article provides a straightforward guide on how to generate and load custom bitmap fonts for your Pixi.js projects. You will learn how to create the necessary font sheet assets, load them into your application using the Pixi.js Assets manager, and render high-performance text on the screen.

Step 1: Generate the Bitmap Font Files

Bitmap fonts consist of two files: an image atlas (usually .png) containing the character glyphs and a data file (usually .fnt or .xml) that describes the position and size of each character.

To generate these files, you can use popular tools such as: * SnowB Bitmap Font Generator (Web-based) * BMFont (Windows) * Littera (Web-based) * msdf-bmfont-xml (Command-line)

When exporting your font, choose the XML or text (BMFont) format and export the texture as a PNG. Ensure that both the .fnt (or .xml) file and the .png file are saved in the same directory on your server, as Pixi.js will look for the image relative to the data file.

Step 2: Load the Font in Pixi.js

Pixi.js (version 7 and modern v8) features a built-in Assets utility that automatically parses bitmap font data. You only need to load the configuration file; Pixi.js will automatically detect and load the associated PNG image.

import { Assets } from 'pixi.js';

// Load the bitmap font configuration file
async function loadAssets() {
    await Assets.load('path/to/your-font.fnt');
    console.log('Bitmap font loaded successfully!');
}

Step 3: Render Bitmap Text

Once loaded, the font is registered globally in Pixi’s bitmap font registry. You can render text by creating a BitmapText object. You must reference the exact font name defined inside your .fnt file (the face attribute in the XML), not the filename itself.

import { Application, BitmapText } from 'pixi.js';

const app = new Application();
await app.init({ width: 800, height: 600 });
document.body.appendChild(app.canvas);

// Create the bitmap text object
const myText = new BitmapText({
    text: 'Hello, Pixi.js!',
    style: {
        fontName: 'YourFontNameInsideFnt', // The "face" name from the XML file
        fontSize: 32,
        align: 'left'
    }
});

// Position and add to stage
myText.x = 100;
myText.y = 100;
app.stage.addChild(myText);

Using bitmap fonts instead of standard system fonts prevents layout shifts across different devices and significantly reduces rendering overhead, making it ideal for games and interactive web applications.