将鼠标事件限制为 Pixi.js 个容器

Limit mouse events to Pixi.js Container

我正在使用 Pixi JS 并通过简单的事件处理程序检测鼠标位置:

...

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);

...

但是,当鼠标超出舞台边界(页面上的 <canvas> 元素)时,mouseXmouseY 正在更新。是否可以将 mousemove 事件限制在舞台内?

我试过 stage.hitArea 但没用。

这似乎是预期的行为;即使鼠标指针在容器外也调用 mousemove 回调对于实现某些事情是必要的,例如拖放。

但是您可以使用 mouseovermouseout 事件来跟踪指针是否位于对象上方,如下所示:

...
var graphics = new PIXI.Graphics();
graphics.hitArea = new PIXI.Rectangle(0, 0, 100, 100);
graphics.interactive = true;
stage.addChild(graphics);
...

var mouseIn = false;
graphics.on("mouseover", function(e) {
  console.log("over")
  mouseIn = true;
});

graphics.on("mouseout", function(e) {
  console.log("out");
  mouseIn = false;
});

graphics.on("mousemove",function(e) {
  if (mouseIn) {
    console.log("mouse move inside", e)
  }
});

(注意:我无法在舞台对象上触发 mouseoutmouseover 事件 - 但显然您应该只将子元素添加到舞台并与它们交互。另外, hitArea 是必需的。)

这个 JSFiddle 应该演示这个想法,请看控制台输出: http://jsfiddle.net/qc73ufbh/

这似乎真的是一个功能而不是一个错误,请查看有关此主题的这些已关闭问题: https://github.com/pixijs/pixi.js/issues/2310https://github.com/pixijs/pixi.js/issues/1250

通过设置交互管理器的moveWhenInside属性即可轻松实现

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();