Home > database >  Can I get background-image source's size by javascript?
Can I get background-image source's size by javascript?

Time:10-21

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

CodePudding user response:

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.

  • Related