Prevent Fabric js Objects from scaling out of the canvas boundary

前端 未结 4 1497
[愿得一人]
[愿得一人] 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:24

    Below is the code for blocking the coordinates of any object outside the canvas area from all directions

    canvas.on('object:modified', function (data) {
    var currentObject = data.target;
    var tempObject = angular.copy(data.target);
    var canvasMaxWidth = canvas.width - 20,
        canvasMaxHeight = canvas.height - 20;
        var actualWidth = currentObject.getBoundingRect().width,
        actualHeight = currentObject.getBoundingRect().height;
    if (actualHeight > canvasMaxHeight) {
        currentObject.scaleToHeight(canvasMaxHeight);
        currentObject.setCoords();
        canvas.renderAll();
        if (tempObject.scaleX < currentObject.scaleX) {
            currentObject.scaleX = tempObject.scaleX;
            currentObject.setCoords();
            canvas.renderAll();
        }
        if (tempObject.scaleY < currentObject.scaleY) {
            currentObject.scaleY = tempObject.scaleY;
            currentObject.setCoords();
            canvas.renderAll();
        }
            if (currentObject.getBoundingRectHeight() < canvasMaxHeight - 50) {
                currentObject.scaleX = (currentObject.scaleX * canvasMaxHeight) / (currentObject.scaleX * currentObject.width);
                currentObject.setCoords();
                canvas.renderAll();
            }
    
    }
    if (actualWidth > canvasMaxWidth) {
        currentObject.scaleToWidth(canvasMaxWidth);
        obj.setCoords();
        canvas.renderAll();
        if (tempObject.scaleX < currentObject.scaleX) {
            currentObject.scaleX = tempObject.scaleX;
            currentObject.setCoords();
            canvas.renderAll();
        }
        if (tempObject.scaleY < currentObject.scaleY) {
            currentObject.scaleY = tempObject.scaleY;
            currentObject.setCoords();
            canvas.renderAll();
        }
    }
    obj.setCoords();
    canvas.renderAll();
    });
    

提交回复
热议问题