Here is the jsfiddle.
I want to limit the maximum height/width of the object when you are resizing it.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://raw.github.com/kangax/fabric.js/master/dist/all.js"></script>
</head>
<body>
<canvas id="c" width="300" height="300" style="border:1px solid #ccc"></canvas>
<script>
(function() {
var canvas = new fabric.Canvas('c');
canvas.add(new fabric.Rect({ width: 50, height: 50, fill: 'red', top: 100, left: 100 }));
canvas.add(new fabric.Rect({ width: 30, height: 30, fill: 'green', top: 50, left: 50 }));
})();
</script>
</body>
</html>
When scaling fabric Objects, the scaleX and scaleY properties are updated to reflect the new scaled size of the object. So the actual width of a rect with an initial width of 50 when scaled 2x will be 100.
What you need to do is figure out the maximum scale allowed for your shape given it's maxHeight or maxWidth. That's calculated by dividing the maximum dimension by the initial dimension.
Here's an example of how to implement maximum sizes for objects
var canvas = new fabric.Canvas("c");
var rect1 = new fabric.Rect({ width: 50, height: 50, fill: 'red', top: 100, left: 100});
var rect2 = new fabric.Rect({ width: 30, height: 30, fill: 'green', top: 50, left: 50 });
// add custom properties maxWidth and maxHeight to the rect
rect1.set({maxWidth:100, maxHeight:120});
canvas.observe("object:scaling", function(e){
var shape = e.target
, maxWidth = shape.get("maxWidth")
, maxHeight = shape.get("maxHeight")
, actualWidth = shape.scaleX * shape.width
, actualHeight = shape.scaleY * shape.height;
if(!isNaN(maxWidth) && actualWidth >= maxWidth){
// dividing maxWidth by the shape.width gives us our 'max scale'
shape.set({scaleX: maxWidth/shape.width})
}
if(!isNaN(maxHeight) && actualHeight >= maxHeight){
shape.set({scaleY: maxHeight/shape.height})
}
console.log("width:" + (shape.width * shape.scaleX) + " height:" + (shape.height * shape.scaleY));
});
Works with most fabric objects.. but you want to get the ratio of your object, for maxWidth you can copy this... for maxHeight reverse it.
fabric.Image.fromURL(photo, function(image) {
//console.log(image.width, image.height);
var heightRatio = image.height / image.width;
var maxWidth = 100;
image.set({
left: canvasDimensions.width / 2,//coord.left,
top: canvasDimensions.height / 2, //coord.top,
angle: 0,
width: maxWidth,
height: maxWidth * heightRatio
})
//.scale(getRandomNum(minScale, maxScale))
.setCoords();
canvas.add(image);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With