Limit mouse events to Pixi.js Container

Viewed 5253

I'm using Pixi JS and detecting the mouse position via a simple event handler:

...

var stage = new PIXI.Container();
stage.interactive = true;

var handler = function(e){
  mouseX = renderer.plugins.interaction.mouse.global.x;
  mouseY = renderer.plugins.interaction.mouse.global.y;
}

stage.on("pointermove", handler);

...

However mouseX and mouseY are being updated when the mouse is outside of the stage bounds (the <canvas> element on the page). Is it possible to limit the mousemove event to within the stage?

I've tried stage.hitArea but that didn't work.

3 Answers

It can be easily accomplished by setting the moveWhenInside property of interaction manager

app.renderer.plugins.interaction.moveWhenInside = true;

var app = new PIXI.Application({
    width: window.innerWidth,
    height: window.innerHeight,
    backgroundColor: 0x2c3e50
});
document.body.appendChild(app.view);

app.renderer.plugins.interaction.moveWhenInside = true;

 const myGraph = new PIXI.Graphics();
    myGraph.interactive = true;
    myGraph.buttonMode = false;

    myGraph.on('pointermove', (evt) => {
        console.log('pointermove',evt.data.global.x, evt.data.global.y);
    });
    
    
    app.stage.addChild(myGraph);
    myGraph.beginFill(0xFFFFFF);
    myGraph.drawCircle(100, 100, 50);
    myGraph.endFill();

You can check if the event target is the PIXIDisplay.DisplayObject you want to act upon.

So in the OP's example that would be:

var stage = new PIXI.Container();
stage.interactive = true;

var handler = function(e){
  if (e.target === stage) {
    mouseX = renderer.plugins.interaction.mouse.global.x;
    mouseY = renderer.plugins.interaction.mouse.global.y;
  }
}

stage.on("pointermove", handler);
Related