How to Enable Click and Touch on Pixi.js Sprites
To make a specific Sprite responsive to mouse and touch interactions in Pixi.js, you must enable its interactivity properties and bind event listeners to it. This guide quickly explains how to configure a Sprite’s interaction mode, change the cursor style on hover, and handle common pointer events like clicks and taps using the unified pointer event system.
Step 1: Enable Interactivity on the Sprite
By default, Pixi.js disables interaction on sprites to optimize rendering performance. To enable it, you need to set the sprite’s interaction mode.
In Pixi.js v7 and v8, use the eventMode
property:
sprite.eventMode = 'static';'static': Best for buttons and elements that do not move but need to receive click/touch events.'dynamic': Best for moving elements that need to be dragged or continuously hit-tested.
In Pixi.js v6 and older, use the legacy
interactive property:
sprite.interactive = true;Step 2: Show a Button Cursor (Optional)
To improve user experience, you can change the mouse cursor to a pointer when hovering over the interactive sprite:
sprite.cursor = 'pointer';Step 3: Add Event Listeners
Instead of writing separate code for mouse clicks and touch taps,
Pixi.js uses unified pointer events that handle both
inputs simultaneously. Use the .on() method to listen for
these events:
// Triggered on both mouse click and screen touch
sprite.on('pointerdown', (event) => {
console.log('Sprite was clicked or touched!', event);
});Complete Code Example
Here is a complete, minimal example of setting up an interactive sprite in Pixi.js:
import { Application, Sprite } from 'pixi.js';
const app = new Application();
await app.init({ width: 800, height: 600 });
document.body.appendChild(app.canvas);
// Create the sprite
const sprite = Sprite.from('path/to/image.png');
sprite.anchor.set(0.5);
sprite.x = app.screen.width / 2;
sprite.y = app.screen.height / 2;
// Enable interaction
sprite.eventMode = 'static';
sprite.cursor = 'pointer';
// Define the interaction behavior
sprite.on('pointerdown', () => {
// Scale up the sprite when clicked/touched
sprite.scale.set(1.2);
});
sprite.on('pointerup', () => {
// Return to normal scale when released
sprite.scale.set(1.0);
});
app.stage.addChild(sprite);Common Pointer Events
Here are the most useful pointer events you can listen to:
pointerdown: Triggered when the mouse is clicked or the screen is touched.pointerup: Triggered when the click or touch is released.pointerupoutside: Triggered when the click or touch is released outside the boundary of the sprite.pointerover: Triggered when the mouse cursor enters the sprite’s bounds.pointerout: Triggered when the mouse cursor leaves the sprite’s bounds.