Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve the aspect ratio of Image in Fabric.js

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?

like image 708
John Avatar asked Nov 06 '13 09:11

John


1 Answers

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);
like image 156
Edmund Sulzanok Avatar answered Sep 28 '22 07:09

Edmund Sulzanok