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?
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?
Share Improve this question edited Nov 6, 2013 at 10:41 kangax 39.2k13 gold badges100 silver badges135 bronze badges asked Nov 6, 2013 at 9:39 JohnJohn 2,0332 gold badges20 silver badges30 bronze badges 3- Not sure I understand. You lose aspect ratio because you se both width and height to those of canvas (if the canvas has different aspect ratio than an image). – kangax Commented Nov 6, 2013 at 10:42
- 1 I mean autofit an image when loaded onto the canvas with quality. As of now it is skewed,stretched. – John Commented Nov 7, 2013 at 3:16
- I know this is an old thread, but did you find any solution @John, I am running through the same problems?? But I am not trying to set a background with the image, merely adding objects inside the canvas. – mane Commented Jul 28, 2014 at 12:22
1 Answer
Reset to default 15Did 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);