Skip to content
Advertisement

Prevent Fabric js Objects from scaling out of the canvas boundary

I have been trying to keep an object (constructed in fabric js over a canvas) inside the boundaries at all the times. It has been achieved at moving and rotating it. I took help from Move object within canvas boundary limit for achieving this. But when I start to scale the object, it simply keeps on going out of boundary. I do not understand what has to be done to keep it inside the boundary only, even while scaling. Please help me with a code to prevent this behavior. It would be great if you can attach a demo too.

JavaScript

My demo is attached here. : https://jsfiddle.net/3v0cLaLk/

Advertisement

Answer

If you want to perform a real time prevention, you should use object:scaling event, as object:modified is only triggered at the end of the transformation.

1) Add event handler to canvas:

JavaScript

2) In the handler function, get the old and the new object’s bounding rect:

JavaScript

3) For each border, check if object has scaled beyond the canvas boundaries and compute its left, top and scale properties:

JavaScript

4) Similar code for the other borders:

JavaScript

5) If object’s BoundingRect has crossed canvas boundaries, fix its position and scale:

JavaScript

6) Finally, when setting the scaling properties, we have to stick with the smallest scale in case the object has crossed more than one border:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement