Search code examples
javascriptcanvashtml5-canvasfabricjs

How to prevent selection of an object after creation on fabricjs canvas


I have an object that on click generates an image on my canvas. How can I disable selection on this generated image object?

I added the following in my code: canvas.selection = false; This disables selection on the object with the click function but for any new image object that is added, it doesn't work.

Example (click the smallest blue dot): https://codepen.io/twan2020/pen/yLVbvGb You can't move the blue dot, but the images that get added can be moved.

I've tried adding the following line: printzelf.selection = false in the function where the image gets created but this still doesn't work. I've also tried adding selection: false alongside the parameters, but no success.

savebtnclick.onclick = function() {
  var imgURL = 'https://printzelf.nl/new/assets/images/logo_gewoon.png';
  var printzelfImg = new Image();
  printzelfImg.onload = function (img) {
    var printzelf = new fabric.Image(printzelfImg, {
    width: 350,
    height: 100,
    left: 450,
    top: 70,
    scaleX: .25,
    scaleY: .25,
    id: 'testimg',
    selection: false
    });
    canvas.add(printzelf);
    printzelf.selection = false;
  };
  printzelfImg.src = imgURL;
}

How can I disable the selection for everything? Including newly added objects? Changing it into a static canvas is not an option because I lose too many functions.


Solution

  • fabric.js offers a property for it's Image class called selectable. If set to false you can't move/rotate/scale an image.

      printzelfImg.onload = function (img) {
        var printzelf = new fabric.Image(printzelfImg, {
        width: 350,
        height: 100,
        left: 450,
        top: 70,
        scaleX: .25,
        scaleY: .25,
        id: 'testimg',
        selectable: false
        });
        canvas.add(printzelf);
        printzelf.selection = false;
      };