0

I'm trying to make a canvas with an image background that fills the entire screen without stretching the background image. To do this, I thought the best method would be to start off with a normal img element with 'object-fit' to make it fill the screen without stretching then I could just apply the same width/height of the img element to a canvas element and make the canvas element replace the img. This also helps make the page load quicker since I don't have to wait for the image to be loaded after the page has loaded since the image is loaded while the page loads. However, while object-fit works as expected for non-img elements, it seems that for img elements it scales the content of the element instead of the element itself meaning, when I try to get the dimensions of the image, I just get the dimensions of the entire window. I have shown this in the below code; if you open inspect element, you can see the img element stretches over the entire screen.

* {
  overflow: hidden;
  margin: 0;
  padding: 0;
}

div {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
<div>
  <img src="https://via.placeholder.com/150">
</div>
Is there something similar to object-fit that scales the element iself or a method to get the width of the contents of an img element?
hopperelec
  • 133
  • 1
  • 2
  • 13
  • 1
    That's how object-fit works, it won't change your img size, it will honor the size of the img element and scale the content based on your configuration. Note that you can also draw the image in a canvas and use object-fit in the canvas element https://stackoverflow.com/questions/54866986/how-does-object-fit-work-with-canvas-element, maybe that helps you – arieljuod Nov 07 '21 at 14:48
  • Keep in mind that `object-fit` has yet to see "full support", and is "partially supported" in some browsers, like Safari and Edge https://caniuse.com/?search=object-fit . In general you can achieve same goals as object-fit through different methods. – Martin Nov 07 '21 at 14:52
  • @Martin Ah, any ideas as to what different methods are available? – hopperelec Nov 07 '21 at 14:55
  • 1
    @Martin I don't really understand your comment as object-fit has been fully supported in all major browsers for several years - though Edge only started fully supporting it at the start of 2020. No IE support of course. – A Haworth Nov 07 '21 at 14:57
  • @AHaworth `object-fit` has partial support in Edge. It's only supported for images for now. – Martin Nov 07 '21 at 16:13
  • 1
    @Martin no, that was older versions, not the situation since start of 2020. It is a footnote, number 2, in the caniuse entry and you'll see which versions have a 2 in them in the colored table above. – A Haworth Nov 07 '21 at 16:41

0 Answers0