Home > Mobile >  The width of img before appending to DOM?
The width of img before appending to DOM?

Time:07-01

I've done some simple code tasks and I've found that I can get height and width of downloaded img by its img.height and img.width attributes, without appending it to DOM. Is this crossbrowser? Coudn't find any info on this behavior.

CodePudding user response:

You can use the naturalWidth and naturalHeight for that requirement. They represent the original width and height respectively of the image.

naturalWidth - the original width of the image used in tag.

width - the value/default value of width attribute of tag.

naturalHeight - the original height of the image used in tag.

height - the value/default value of height attribute of tag.

For example:

let src = 'http://www.fillmurray.com/g/400/600';
let img = document.createElement('img');
img.onload = () => {
  console.log(`naturalWidth = ${img.naturalWidth}`);
  console.log(`naturalHeight = ${img.naturalHeight }`);
}
img.src = src;

More about naturalHeight - https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/naturalHeight

More about naturalWidth - https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/naturalWidth

  • Related