PixiJS v7 Drag Example
by Matt Karl
HTML
<script src="https://pixijs.download/dev/pixi.min.js"></script>
CSS
body {
background: #ccc;
margin: 0;
padding: 0;
overflow: hidden;
}
JavaScript
const app = new PIXI.Application({
background: '#999',
resizeTo: window,
});
document.body.appendChild(app.view);
// The stage will handle the move events
app.stage.interactive = true;
app.stage.hitArea = app.screen;
// Create an item we can drag
const sprite = new PIXI.Sprite(PIXI.Texture.WHITE);
sprite.anchor.set(0.5);
sprite.scale.set(5);
sprite.x = app.screen.width / 2;
sprite.y = app.screen.height / 2;
sprite.interactive = true;
sprite.cursor = 'pointer';
app.stage.addChild(sprite);
// Handle the relative offset point
// of the click on the object
let offset = new PIXI.Point();
// Handler for pointermove
function moveDrag(event) {
sprite.x = event.global.x - offset.x;
sprite.y = event.global.y - offset.y;
}
// Sprite handler to start dragging
function startDrag(event) {
app.stage.cursor = 'pointer';
const dragTarget = event.target;
dragTarget.toLocal(event.global, null, offset);
offset.x *= dragTarget.scale.x;
offset.y *= dragTarget.scale.y;
app.stage.on('pointermove', moveDrag);
}
// Sprite handler to stop dragging
function stopDrag() {
app.stage.cursor = null;
app.stage.off('pointermove', moveDrag);
}
// Subscribe listeners for dragging
sprite.on('pointerdown', startDrag);
sprite.on('pointerup', stopDrag);