How to preserve the aspect ratio of the image loaded onto the canvas? When the image is loaded from local system onto the canvas I'm creating image object with width=canvas.width
and height=canvas.height
.
But the quality is missing. Even if loaded image resolution is higher. Is there any way to preserve the aspect ratio of the loaded image?
Did I get it right: you want to fill the canvas with the image, keep the ratio and hide the overflow?
You should recalculate them:
cw
, ch
- canvas dimensions
iw
, ih
- image dimensions
ih = imgObj.naturalHeight;
iw = imgObj.naturalWidth;
fw
, fh
- final dimensions
width_ratio = cw / iw;
height_ratio = ch / ih;
if (width_ratio > height_ratio) {
fw = iw * width_ratio;
fh = ih*fw/iw;
} else {
fh = ih * height_ratio;
fw = iw*fh/ih;
}
Then just feed options like this
var image = new fabric.Image(imgObj);
image.set({
width:fw,
height:fh
});
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