Fabric.js right mouse click

canvas, fabricjs, javascript

Solution

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

Problem

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

Original source