Fabric.js 鼠标右键单击

Bas*_*ian 5 javascript canvas fabricjs

有没有办法在 Fabric.js 画布上接收鼠标右键单击事件?

以下代码仅适用于左键单击:

canvas.observe('mouse:down', function(){console.log('mouse down'));
Run Code Online (Sandbox Code Playgroud)

Wil*_*ilt 14

注意: 上面的大多数答案都已过时;此答案适用于最新的 Fabric 版本 2.7.0


只需为您的 Fabric 画布启用触发右/中单击事件

可以在此处为fireRightClick此处为fireMiddleClick在画布中触发右键单击和中键单击事​​件的配置,并且false默认设置为。这意味着右键和中键单击事​​件默认是禁用的。stopContextMenu可以在此处找到右键单击时停止显示在画布上的上下文菜单的参数

您可以通过在创建画布时设置值来启用这些:

var canvas = new fabric.Canvas('canvas', {
  height: height,
  width: width,
  fireRightClick: true,  // <-- enable firing of right click events
  fireMiddleClick: true, // <-- enable firing of middle click events
  stopContextMenu: true, // <--  prevent context menu from showing
});
Run Code Online (Sandbox Code Playgroud)

现在您的mousedown事件将针对所有点击触发,您可以通过使用事件上的按钮标识符来区分它们:

对于画布:

canvas.on('mouse:down', (event) => {
    if(event.button === 1) {
        console.log("left click");
    }
    if(event.button === 2) {
        console.log("middle click");
    }
    if(event.button === 3) {
        console.log("right click");
    }
}
Run Code Online (Sandbox Code Playgroud)

对于对象:

object.on('mousedown', (event) => {
    if(event.button === 1) {
        console.log("left click");
    }
    if(event.button === 2) {
        console.log("middle click");
    }
    if(event.button === 3) {
        console.log("right click");
    }
}
Run Code Online (Sandbox Code Playgroud)

单击对象时,您可以通过 event.e 到达“真正的”鼠标 dom 事件:

if(event.button === 3){
  console.log(event.e);
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ery 3

我这样做的方法是监听整个画布上的右键单击事件,并将单击事件的 x,y 坐标与当前位于给定位置的对象进行匹配。这个解决方案感觉有点像黑客,但是嘿,它有效!

$('#my_canvas').bind('contextmenu', function (env) {
    var x = env.offsetX;
    var y = env.offsetY;
    $.each (canvas._objects, function(i, e) {
        // e.left and e.top are the middle of the object use some "math" to find the outer edges
        var d = e.width / 2;
        var h = e.height / 2;
        if (x >= (e.left - d) && x <= (e.left+d)) {
            if(y >= (e.top - h) && y <= (e.top+h)) {
                console.log("clicked canvas obj #"+i);
                //TODO show custom menu at x, y
                return false; //in case the icons are stacked only take action on one.
            }
        }
    });
    return false; //stops the event propigation
});
Run Code Online (Sandbox Code Playgroud)