Reputation: 2387
As per this answer I have built fabricJs version 1.7.18 with all features enabled - Built output file.
I am using the following code to change an object's width and height using scaleToWidth(), but the new width value is not set properly. It is setting the width with some other value.
var obj = canvas.getActiveObject();
obj.scaleX = 1;
obj.scaleY = 1;
obj.scaleToWidth(65);
obj.setCoords();
canvas.renderAll();
//This gives a different width value
console.log(obj.getWidth());
Can anyone help me out to fix this issue?
My actual requirement is: To set the height relatively when I am setting the object width. Example: I have an object with width 50 and height 40. If I am setting the width as 100 using the function setWidth(), then is there any built-in function to set the height as 80?
Upvotes: 2
Views: 3992
Reputation: 15604
As mentioned in scaleToWidth Scales an object to a given width, with respect to bounding box (scaling by x/y equally).
And getWidth
Returns width of an object bounding box counting transformations.
If you just want to set width of an object use obj.width = value
.
You can use scale() or scaleX(),scaleY() to scale an object .
DEMO
(function() {
var canvas = this.__canvas = new fabric.Canvas('c');
var rect = new fabric.Rect({
left:50,top:50,width:50,height:40
})
canvas.add(rect);
rect.scale(2);
rect.setCoords();
console.log(rect.height,rect.scaleY)
})();
canvas{
border-width: 1pz;
border-style: solid;
border-color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.0.0-rc.3/fabric.js"></script>
<canvas id='c' width=300 height=300></canvas>
As you know the width you are setting. calculate the difference how much percentage its changed set the same to height. You will get the result.
Upvotes: 3