Reputation: 2033
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?
Upvotes: 7
Views: 6350
Reputation: 1973
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);
Upvotes: 15