I have added image into canvas and dynamically I want to change image height and width according to the rectangle height and width. I have done calculation of image height and width according to rectangle height and width and original image height and width.
Using below code I have changed image height and width but image quality is getting very low
var image_height = 200; //For now here image height is dummy
var image_width = 150; //For now here image width is dummy
var obj = canvas.getActiveObject();
obj.setHeight(image_height);
obj.setWidth(image_width);
obj.setCoords();
canvas.renderAll();
I ran into the same problem a few days ago. The solution I found is to not try to set width
and height
but rather ask your image to scale up to the canvas dimensions.
Here is how I did it :
var scaleWidth = canvas.getWidth() / img.width;
var scaleHeight = canvas.getHeight() / img.height;
var scale = Math.min(scaleWidth, scaleHeight);
bgImage = new fabric.Image(img, {
[...]
scaleX: scale,
scaleY: scale,
[...]
});
canvas.add(bgImage);
canvas.sendToBack(bgImage); // useful in case you want a background but not **needed**
canvas.renderAll();
In the code above I compute width and height ratios, pick the lower one, and then I apply it on the picture using scaleX
and scaleY
properties.
If it still doesn't work for you, please let me know in the comments.
EDIT : I completed my linked code for more clarity.
2nd EDIT : It appears a method called scale
exists and could be used on your image. Looks cleaner if you want to keep your ratio (aka scaleX
and scaleY
properties would have the same value).