Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

271
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda