Showing Customized Context Menu on clicking shapes(objects of fabric.js) in Canvas

3.6k views Asked by At

I'm using fabric.js to create shapes on canvas . on right click on the shapes i want to show a context menu based on the shape selected. I'm able to capture the right click event and find which object the right click is done. but i don know how to show a context menu from a javascript (something like contextmenu.show). below is the code which im using to find the object. Any one please help.

$('.upper-canvas').bind('contextmenu', function (e) {
    var objectFound = false;
    var clickPoint = new fabric.Point(e.offsetX, e.offsetY);

    e.preventDefault();

    canvas.forEachObject(function (obj) {
        if (!objectFound && obj.containsPoint(clickPoint)) {
            objectFound = true;
             // here need to set a customized context menu and show it
             // but dont now how to do so. 
        }
    });
});
1

There are 1 answers

1
mar10 On BEST ANSWER

Using jquery-ui-contextmenu you could instantiate a context menu on the canvas and modify the menu entries depending on the target.

(Note that the code is untested, but it should show the idea. Have a look at the API docs for details.)

$(document).contextmenu({
    delegate: ".upper-canvas",
    menu: [...],  // default menu
    beforeOpen: function (event, ui) {
        var clickPoint = new fabric.Point(event.offsetX, event.offsetY);
        // find the clicked object and re-define the menu or
        // optionally return false, to prevent opening the menu:
//      return false;
        // En/disable single entries:
        $(document).contextmenu("enableEntry", ...);
        // Show/hide single entries:
        $(document).contextmenu("showEntry", ...);
        // Redefine the whole menu:
        $(document).contextmenu("replaceMenu", ...); 
    },
    select: function(event, ui) {
        // evaluate selected entry...
    }
});