using canvis drawImage() when you don't know image dimensions

I am getting images from an API. They are all different sizes and I don’t know ahead of time what dimension they will be.
Both CSS background-image and object-fit offer cover and contain. What I would like is to recreate the cover behaviour in canvas. I want the edges to be cut off from the center so that the image fits into the specified size (but I don’t want to deform/stretch the image).
I couldn’t work out how to do this using drawImage(). Is there a way?

Load the image outside of the canvas beforehand, then you can get it’s dimensions (Image.naturalHeight and Image.naturalWidth) and draw it correctly.

1 Like