JavaScript gets the original size of the image with the width as an example

  • 2020-03-30 02:49:12
  • OfStack

For the img element on the page, if you want to get its original size, the first thing you might think of is the width, as shown below

 
<img src="http://img11.360buyimg.com/da/g14/M07/01/0E/rBEhVlNhh8wIAAAAAADmFBLo1twAAM26gOmCgYAAOYs716.jpg"> 
<script> 
var img = document.getElementsByTagName('img')[0] 
var width = getWH(img, 'width') // 690 
</script> 

The getWH method used here was mentioned in the previous article. The width obtained is the same as the original size of the image.

If you add the width property to img, this method will not work. For example, the actual width of the image is 690, and the width is set to 400
 
<img width="400" src="http://img11.360buyimg.com/da/g14/M07/01/0E/rBEhVlNhh8wIAAAAAADmFBLo1twAAM26gOmCgYAAOYs716.jpg"> 
<script> 
var img = document.getElementsByTagName('img')[0] 
var width = getWH(img, 'width') // 400 
</script> 

Obviously, 400 is not the original width of the image.

One way to get it is to create a new img object, assign the SRC of the old img to the new img, and then get the width of the new img
 
<img width="400" src="http://img11.360buyimg.com/da/g14/M07/01/0E/rBEhVlNhh8wIAAAAAADmFBLo1twAAM26gOmCgYAAOYs716.jpg"> 
<script> 
function getNaturalWidth(img) { 
var image = new Image() 
image.src = img.src 
var naturalWidth = image.width 
return naturalWidth 
} 
var img = document.getElementsByTagName('img')[0] 
getNaturalWidth(img) // 690 
</script> 

It is important to note that the new image created here is in the DOM document that does not need to be added.

HTML 5 provides a new attribute naturalWidth/naturalHeight can directly obtain images of the original width. These two properties in Firefox/Chrome/Safari/Opera and ie 9 has been achieved. Modify the method to get the size of the picture.
 
function getImgNaturalDimensions(img, callback) { 
var nWidth, nHeight 
if (img.naturalWidth) { //Modern browser
nWidth = img.naturalWidth 
nHeight = img.naturalHeight 
} else { // IE6/7/8 
var imgae = new Image() 
image.src = img.src 
image.onload = function() { 
callback(image.width, image.height) 
} 
} 
return [nWidth, nHeight] 
} 

Note the handling of ie6/7/8, a new img is created, only its SRC is set, then the image needs to be fully loaded before the width and height can be obtained. So this is asynchronous, and you can pass a callback that takes the original width and height as an argument.


Related articles: