【问题标题】:Limit mouse events to Pixi.js Container将鼠标事件限制在 Pixi.js 容器中
【发布时间】:2017-12-04 18:16:53
【问题描述】:

我正在使用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,但没用。

【问题讨论】:

    标签: javascript canvas pixi.js


    【解决方案1】:

    这似乎是预期的行为;即使鼠标指针位于容器之外,也需要调用 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

    【讨论】:

    • 感谢您的详细回复!这似乎是正确的方法。我猜mouseoutmouseover 不适用于舞台对象,因为它覆盖了整个浏览器视口。再次感谢:-)
    【解决方案2】:

    通过设置交互管理器的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();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      • 1970-01-01
      • 2017-06-25
      • 1970-01-01
      • 2011-05-27
      • 1970-01-01
      相关资源
      最近更新 更多