Prevent Fabric js Objects from scaling out of the canvas boundary

前端 未结 4 1506
[愿得一人]
[愿得一人] 2020-12-06 07:46

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

4条回答
  •  情话喂你
    2020-12-06 08:22

    You can set on object modified listener and check if object is out of bounds. If so, then restore it to its original state.

    this.canvas.on('object:modified', function (options: any) {
        let obj = options.target;
        let boundingRect = obj.getBoundingRect(true);
        if (boundingRect.left < 0
            || boundingRect.top < 0
            || boundingRect.left + boundingRect.width > scope.canvas.getWidth()
            || boundingRect.top + boundingRect.height > scope.canvas.getHeight()) {
            obj.top = obj._stateProperties.top;
            obj.left = obj._stateProperties.left;
            obj.angle = obj._stateProperties.angle;
            obj.scaleX = obj._stateProperties.scaleX;
            obj.scaleY = obj._stateProperties.scaleY;
            obj.setCoords();
            obj.saveState();
        }
    });
    

提交回复
热议问题