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

195
Visualizações
Can I get background-image source's size by javascript?

always thanks for everyone of stackoverflow

I made a div and it includes background-image: url(imageURL) such like this codes

HTML >
<div ref={mapRef} className="image-container" style={{ backgroundPosition: '0 0' }} >
    {markersState}
</div>
CSS >
.image-container {
  width: 1024px;
  height: 768px;

  cursor: grab;
  user-select: none;

  background-image: url("/images/map.png");
  background-position: 0 0;
  background-repeat: no-repeat;
}

I want to get background-image source(='/images/map.png')'s size How can I get it? (source's width: 2907px, height: '3460px')

if I need to use instead of background-image, that solution can be good for me Also, is there good library, recommend me please

Thank you, have a nice day

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you want to get the actual width and height of a background image then you can follow these steps

Get the background image's URL like this (https://stackoverflow.com/a/45010803/1391805)

var css = document.getElementById("myElem").style.backgroundImage;
var img = css.replace(/(?:^url\(["']?|["']?\)$)/g, "");

Once you have the image URL do this

var newImg = new Image();
newImg.onload = function(e) {
   console.log( this.naturalWidth ); // This is the width you are looking for
   console.log( this.naturalHeight ); // .. similarly the height.
}
newImg.src = "img.jpg";

Given the fact that this loads an image first you may want to use this carefully, if this is something that does not apply for a lot of images on a single page then this may not be a performance degrade but if the scale is larger then you may consider something better than loading an image on the client side to fetch its actual dimension.

about 4 years ago · Juan Pablo Isaza Relatório
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