Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

270
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda