Auto Word Wrap Text in Pixi.js

This article provides a quick guide on how to configure and apply automatic word wrapping to text elements in the Pixi.js 2D rendering engine. You will learn which style properties to enable, how to set custom wrapping widths, and how to handle edge cases like breaking exceptionally long words.

In Pixi.js, word wrapping is not enabled by default. To make text automatically wrap when it reaches a certain width, you must configure the text’s style settings using the wordWrap and wordWrapWidth properties.

Step-by-Step Implementation

To apply word wrapping, pass a style configuration object to the Text constructor or define a TextStyle instance.

Here is a complete code example:

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

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

// 1. Define the text style with word wrapping enabled
const style = new TextStyle({
    fontFamily: 'Arial',
    fontSize: 24,
    fill: '#ffffff',
    wordWrap: true,      // Enables automatic word wrapping
    wordWrapWidth: 400,  // Sets the wrap limit to 400 pixels
});

// 2. Create the Text object using the styled configuration
const richText = new Text({
    text: 'This is a long sentence in Pixi.js that will automatically wrap to the next line once it exceeds the specified word wrap width limit.',
    style: style
});

// Position and add the text to the stage
richText.x = 50;
richText.y = 100;
app.stage.addChild(richText);

Key Configuration Properties

To customize how your text wraps, use the following three properties inside your TextStyle configuration:

Dynamic Updates

If you need to change the wrapping width dynamically after the text element has already been rendered, you can update the style property directly on the text object:

// Change the wrapping width dynamically
richText.style.wordWrapWidth = 300;