Render Text in Pixi.js Using the Text Class

Rendering text is a fundamental part of creating interactive web applications and games. This article provides a quick, step-by-step guide on how to render standard vector text to the screen using the Text class in Pixi.js. You will learn how to define text styles, initialize a Text object, position it on the screen, and add it to the Pixi.js application stage.

1. Import Pixi.js Classes

To render text, you need the main Application class, the Text class, and optionally the TextStyle class to customize the appearance of your font.

import { Application, Text, TextStyle } from 'pixi.js';

2. Initialize the Application

Create your Pixi.js application instance and mount its canvas to the HTML document.

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

3. Define the Text Style

The TextStyle class allows you to define properties such as font family, size, fill color, alignment, and shadows. Pixi.js renders standard vector text by using the browser’s canvas 2D context to generate a high-quality texture.

const style = new TextStyle({
    fontFamily: 'Arial',
    fontSize: 36,
    fontWeight: 'bold',
    fill: '#ffffff', 
    stroke: { color: '#4a1850', width: 5 },
    dropShadow: {
        color: '#000000',
        blur: 4,
        angle: Math.PI / 6,
        distance: 6,
    },
    wordWrap: true,
    wordWrapWidth: 440,
});

4. Create and Position the Text Object

Instantiate the Text class by passing an options object containing your string and your defined style. Once created, set its coordinates to place it on the screen.

const basicText = new Text({
    text: 'Hello, Pixi.js Vector Text!',
    style: style
});

// Position the text on the screen
basicText.x = 50;
basicText.y = 100;

(Note: If you are using PixiJS v7 or older, the constructor syntax is const basicText = new Text('Hello, Pixi.js Vector Text!', style);)

5. Add the Text to the Stage

To make the text visible on the screen, add the text object to your application’s active stage.

app.stage.addChild(basicText);