Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

269
Views
object-fit changes the width of the image but not the element. How can I get the width of the image in JS?

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!