23

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)

1

1 Answer 1

52

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/

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your post. I have edited my post above. Sorry i did not make this more clear when posting before.
let scale = Math.min(300 / img.width, 300 / img.height) img.scale(scale) canvas.add(img) But! This works OK if the angle is 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.