Search code examples
javascriptfabricjs

Fabric JS: How to prevent scaling active group


in Fabric JS when an object or multiple objects is/are selected, it's possible to scale them. Either in the corner (with aspects) or only width/height.

Is it possible to allow this only if an object is selected and prevent this if multiple objects are selected?

Thanks in advance!


Solution

  • When you select multiple objects on the canvas, it essentially behaves like a Fabricjs Group. You can disable scaling for a group using lockScalingX and lockScalingY properties.

    Now to access this group formed on selection, you can use the canvas selection:created event. Below is the sample code:

    canvas.on('selection:created',function(ev){
        ev.target.set({
            lockScalingX: true,
            lockScalingY: true
        });
    });
    

    Above code disables scaling specifically for groups formed on user selection and not the groups that might have been added to the canvas by you. If you want to disable scaling globally for any group, then you can do that in following way:

    fabric.Group.prototype.lockScalingX = true;
    fabric.Group.prototype.lockScalingY = true;
    

    You can find a working fiddle here: http://jsfiddle.net/n9z58nuk/2/