Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fabric.js right mouse click

Is there a way to receive right click mouse events on a Fabric.js canvas?

The following code works only with left click:

canvas.observe('mouse:down', function(){console.log('mouse down'));
like image 213
Bastian Avatar asked Oct 28 '12 11:10

Bastian


2 Answers

NOTE: Most answers above are outdated; this answer applies to the latest Fabric version 2.7.0


Simply enable firing right/middle click events for your Fabric canvas

The config for firing right click and middle click events in the canvas can be found here for fireRightClick and here for fireMiddleClick and are set to false by default. This means right and middle click events are by default disabled. The parameter stopContextMenu for stopping context menu to show up on the canvas when right clicking can be found here

You can enable these simply by setting the values when creating your canvas:

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

Now your mousedown event will fire for all clicks and you can distinguish them by using the button identifier on the event:

For canvas:

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

For objects:

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

When clicking on objects you can reach the "real" mouse dom event through event.e:

if(event.button === 3){
  console.log(event.e);
}
like image 120
Wilt Avatar answered Sep 22 '22 05:09

Wilt


I've implemented right click by extending the fabric.Canvas class. Take a look here the _onMouseDown method.

Basically the right mouse down event for an object was disabled in fabricjs by default.

like image 37
Jim Ma Avatar answered Sep 19 '22 05:09

Jim Ma