How to Change Sprite Tint Dynamically in Pixi.js

This article explains how to dynamically alter the color tint of an existing Sprite in Pixi.js. You will learn how to modify the tint property, use the correct color formats, and update the sprite’s color in real-time within an animation loop.

The Tint Property

In Pixi.js, every Sprite object has a tint property. By default, this property is set to white (0xFFFFFF), which renders the sprite with its original texture colors. Changing this property multiplies the colors of the sprite’s texture by the tint color.

For the best results, use a grayscale or white base image, as tinting works by multiplying color channels.

Modifying the Tint Value

You can assign a hexadecimal number, a hex string, or a color name to the tint property.

Here is how to set a static tint:

// Using a hexadecimal number (Recommended for performance)
mySprite.tint = 0xFF0000; // Tints the sprite red

// Using a hex string (Supported in Pixi.js v7+)
mySprite.tint = '#00FF00'; // Tints the sprite green

// Using a color name
mySprite.tint = 'blue'; // Tints the sprite blue

To remove a tint and restore the sprite to its original appearance, reset the value to white:

mySprite.tint = 0xFFFFFF;

Changing Tint Dynamically in a Loop

To change the color dynamically over time, you can update the tint property inside the Pixi.js ticker loop.

The following example demonstrates how to oscillate a sprite’s color between red and blue using a sine wave:

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

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

// Create and add the sprite
const mySprite = Sprite.from('path/to/texture.png');
app.stage.addChild(mySprite);

let time = 0;

app.ticker.add((ticker) => {
    time += 0.05 * ticker.deltaTime;

    // Calculate red and blue channels using sine waves (values between 0 and 255)
    const red = Math.floor((Math.sin(time) + 1) * 127.5);
    const blue = Math.floor((Math.cos(time) + 1) * 127.5);
    const green = 0;

    // Combine channels into a single hex number
    mySprite.tint = (red << 16) + (green << 8) + blue;
});

This approach allows you to create smooth transitions, flashing damage effects, or environment-based lighting shifts on any existing sprite in your scene.