0

have to find the image natural width, heigth

but image added form css as a background-image

html, body {
    height: 100%;
    margin: 0;
}

.image {
    height: 50%;
    border: 1px solid orange;
    background-repeat: no-repeat;
    background-image: url('https://unsplash.it/200/300?image=0');
}
<div class="image"></div>

demo

2
  • Maybe (img=new Image()).src="sth";img.naturalWidth ... Commented Jul 1, 2017 at 12:56
  • @Jonasw yeah trying that but not going as expected Commented Jul 1, 2017 at 12:58

2 Answers 2

1

See comments:

// Get the image
var img = document.querySelector(".image");
// Get its current style
var style = window.getComputedStyle ? getComputedStyle(img) : img.currentStyle;
// Extract the URL from it
var match = /url\("?([^")]+)"?\)/.exec(style.backgroundImage);
if (match) {
  // Create an `img`
  var x = document.createElement('img');
  // Watch for when it loads (it'll presumably come from cache)
  x.onload = function() {
    // Now we know its natural size
    console.log("width = " + x.width + ", height = " + x.height);
    console.log("naturalWidth = " + x.naturalWidth + ", naturalHeight = " + x.naturalHeight);
  };
  // Set the src (AFTER hooking 'load')
  x.src = match[1];
}
html, body {
    height: 100%;
    margin: 0;
}

.image {
    height: 50%;
    border: 1px solid orange;
    background-repeat: no-repeat;
    background-image: url('https://unsplash.it/200/300?image=0');
}
<div class="image"></div>

Details on the regex here. Basically, it extracts the path within the url(...) omitting "s.

Of course, if you don't have to get the URL from the element's background-image, all the better...

Sign up to request clarification or add additional context in comments.

2 Comments

match = /url\("?([^")]+)"?\)/.exec(style.backgroundImage); is there an other way, i am getting an error like this .. demo
@bhv: That fiddle doesn't use the working code above. My suggestion is...use the working code above instead. ;-) (The reason for the error is that you're not removing the quotes around the value.)
0

You can get the attribute value using jQuery like this

var image_width = $(".image").width()); var image_height = $(".image").height());

I am posting this from my phone so forgive the in formatted code

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.