How to make objects in canvas unselectable?

Viewed 16590

I want to make all object in canvas unselectable. I've found selectable method but i didn't find the way to implement it to all objects.

5 Answers

I was looking for an unmovable and uneditable Fabric Text and I finally found a solution combining several SO, hope I can save someone some time.

Using "selectable": false wasn't enough in my case : the text was still editable and the cursor was still the "movable cursor" (even if the object wasn't selectable).

I had to add "evented": false. Here is an example:

this.canvas.add(new fabric.Text("Hello world !", {
            "selectable": false,
            "evented": false
}));

You can play with different control options here : http://fabricjs.com/controls-customization

On a parent HTML element use css property pointer-events:

.locked {
    pointer-events: none;
}

To set this property from javascript:

let canvasElement = document.getElementsByClassName("canvas-container")[0]
canvasElement.classList.add("locked")

To unlock canvas:

canvasElement.classList.remove("locked")
canvas._objects.forEach(obj => {obj.selectable = false;});
canvas.discardActiveObject();

This should do the trick! discardActiveObject should fire events that request a rerender, so you don't need to manually invoke renderAll. In general, you should always use requestRenderAll instead of renderAll.

Related