How to Update Text Dynamically in Pixi.js
In Pixi.js, rendering and updating text is a fundamental requirement
for creating interactive applications, games, and dashboards. This
article provides a direct guide on how to dynamically change the string
value of an already rendered Text object. You will learn
the exact property to modify, see a practical code example, and
understand the performance implications of updating text in
real-time.
To dynamically update a rendered text object in Pixi.js, you simply
need to reassign the text property of your
PIXI.Text instance. Pixi.js automatically detects this
change, regenerates the internal canvas texture, and updates the display
on the next render frame.
Step-by-Step Implementation
First, instantiate your text object and add it to the stage:
// Create a text style
const style = new PIXI.TextStyle({
fontFamily: 'Arial',
fontSize: 36,
fill: '#ffffff',
});
// Create the Text object with an initial string
const gameScoreText = new PIXI.Text('Score: 0', style);
// Position and add it to the stage
gameScoreText.x = 50;
gameScoreText.y = 50;
app.stage.addChild(gameScoreText);To update the string value later in your code—such as inside a game
loop, an event listener, or a network callback—directly modify the
.text property:
// Function to update the score
let score = 0;
function increaseScore() {
score += 10;
// Dynamically update the rendered text
gameScoreText.text = `Score: ${score}`;
}Performance Considerations
While updating the .text property is simple, you should
be mindful of how Pixi.js handles text rendering under the hood.
Every time you change the string of a standard PIXI.Text
object, Pixi.js must draw the text onto a hidden HTML5
<canvas>, generate a new WebGL texture, and upload
that texture to the GPU.
- For low-frequency updates (e.g., changing a menu
item, updating a score occasionally, or displaying dialogue), the
standard
PIXI.Textobject is highly efficient and easy to use. - For high-frequency updates (e.g., displaying a
rapidly changing millisecond timer, physics coordinates, or a
fast-updating FPS counter), constantly recreating textures can cause
performance drops and garbage collection spikes. In these scenarios, use
PIXI.BitmapTextinstead, which utilizes a pre-rendered spritesheet of characters and does not require texture regeneration when the string changes.