Reputation: 438
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;
}
}
Upvotes: 2
Views: 1870
Reputation: 592
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>
Upvotes: 2