Skip to content

Instantly share code, notes, and snippets.

@kfei
Created October 6, 2015 02:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kfei/6d31bc01e8b3814f4400 to your computer and use it in GitHub Desktop.
Save kfei/6d31bc01e8b3814f4400 to your computer and use it in GitHub Desktop.
Get image dimension
// With naturalWidth, naturalHeight
myImage.addEventListener('onload', function() {
console.log('My width is: ', this.naturalWidth);
console.log('My height is: ', this.naturalHeight);
});
// Without naturalWidth, naturalHeight
function realImgDimension(img) {
var i = new Image();
i.src = img.src;
return {
naturalWidth: i.width,
naturalHeight: i.height
};
}
var myImage = document.getElementById('myImage');
myImage.addEventListener('load', function() {
var realSize = realImgDimension(this);
console.log('My width is: ', realSize.naturalWidth);
console.log('My height is: ', realSize.naturalHeight);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment