2

I want to prevent objects getting scaled outside of the canvas boundaries, and I kind of got it working. But the issue I'm facing is that when you drag an object to the center and scale it all the way to one of the borders, it gets restricted to to be scaled to the opposite border.

I tried solutions from multiple answers on this matter, but none seems to be working.

I included a fiddle so you can see my problem. https://jsfiddle.net/nkzyaq4b/4/

It has something to do with the way I check if an object crossed a boundary, but I cant figure out how to get it right

let scalingProperties = {
    'left': 0,
    'top': 0,
    'scaleX': 0,
    'scaleY': 0,
}

export function scaling(e) {
    let shape = e.target;
    let maxWidth = shape.canvas.width;
    let maxHeight = shape.canvas.height;

    //left border
    if(shape.left <= 0) {
        shape.left = scalingProperties.left = 0;
        shape.scaleX = scalingProperties.scaleX;
    } else {
        scalingProperties.left = shape.left;
        scalingProperties.scaleX = shape.scaleX;
    }

    //right border
    if((scalingProperties.scaleX * shape.width) + shape.left >= maxWidth) {
        shape.scaleX = (maxWidth - scalingProperties.left) / shape.width;
    } else {
        scalingProperties.scaleX = shape.scaleX;
    }

    //top border
    if(shape.top <= 0) {
        shape.top = scalingProperties.top = 0;
        shape.scaleY = scalingProperties.scaleY;
    } else {
        scalingProperties.top = shape.top;
        scalingProperties.scaleY = shape.scaleY;
    }

    //bottom border
    if((scalingProperties.scaleY * shape.height) + shape.top >= maxHeight) {
        shape.scaleY = (maxHeight - scalingProperties.top) / shape.height;
    } else {
        scalingProperties.scaleY = shape.scaleY;
    }
}
Marcel
  • 398
  • 2
  • 4
  • 22

1 Answers1

2

If you don't mind using an older version, change it to 3.6.6 https://jsfiddle.net/ChrisWong/39ntoe0b/5/

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.6/fabric.js"></script>
Chris Wong
  • 564
  • 4
  • 4
  • What exactly is the difference between those versions? Because I don't see any differences between our jsfiddles, but the older version works – Marcel May 26 '21 at 11:10
  • Dunno why, just found a same problem [here](https://stackoverflow.com/questions/42833142/prevent-fabric-js-objects-from-scaling-out-of-the-canvas-boundary) and be aware of it later. – Chris Wong May 27 '21 at 01:24