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

192
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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