Are there any JavaScript or jQuery APIs or methods to get the dimensions of an image on the page?
Thought this might be helpful to some who are using Javascript and/or Typescript in 2019.
I found the following, as some have suggested, to be incorrect:
let img = new Image();
img.onload = function() {
console.log(this.width, this.height) // Error: undefined is not an object
};
img.src = "http://example.com/myimage.jpg";
This is correct:
let img = new Image();
img.onload = function() {
console.log(img.width, img.height)
};
img.src = "http://example.com/myimage.jpg";
Conclusion:
Use img
, not this
, in onload
function.