How do i scale image to fit the container size correctly? I want a grid of two images and each image to fit the provided size.
https://codepen.io/peteringram0/pen/gebYWo?editors=0010
img.set({
left: 0,
top: 0,
width: 300,
height: 300
// Scale image to fit width / height ?
});
EDIT: Sorry i didn't explain my question very clearly. Im looking to position it within the grid but as a 'cover' type. https://codepen.io/peteringram0/pen/xWwZmy?editors=0011. E.g. in the link there are 4 images in a grid but the images are in the centre and are overflowing. I want to get each of the images vertically centred with no overflow outside the set size. Thanks (x should be in the centre, while keeping the aspect ratio)
If you want to scale image object to given width or height, use scaleToWidth and scaleToHeight respectively.
I've removed the height and width specified inside img.set function from your code. And added a scaeToHeight and scaleToWidth method. Use the code as below.
window.fabric.Image.fromURL(imgUrl, (img) => {
img.set({
left: 300,
top: 0
});
img.scaleToHeight(300);
img.scaleToWidth(300);
canvas.add(img);
})
Check out this fiddle: https://jsfiddle.net/hazeebp/195uan6f/1/