If you want to get its original size in the img element on the page, take the width as an example, the first thing you might think of is width, as follows
Copy the codeThe code is as follows:
<img src="http://img11./da/g14/M07/01/0E/">
<script>
var img = ('img')[0]
var width = getWH(img, 'width') // 690
</script>
The getWH method used here is mentioned in the previous article. The width obtained at this time is the same as the original size of the picture.
If you add width attribute to img, this method will not work. For example, the actual width of the image is 690, and the width is set to 400. At this time, the method above will be obtained and the return is 400.
Copy the codeThe code is as follows:
<img width="400" src="http://img11./da/g14/M07/01/0E/">
<script>
var img = ('img')[0]
var width = getWH(img, 'width') // 400
</script>
Obviously, 400 is not the original width of the picture.
There is a way to get it, directly create a new img object, and then assign the src of the old img to the new one, and then get the width of the new img
Copy the codeThe code is as follows:
<img width="400" src="http://img11./da/g14/M07/01/0E/">
<script>
function getNaturalWidth(img) {
var image = new Image()
=
var naturalWidth =
return naturalWidth
}
var img = ('img')[0]
getNaturalWidth(img) // 690
</script>
It should be noted that the newly created image here does not need to be added in the DOM document.
HTML5 provides a new attribute naturalWidth/naturalHeight to directly obtain the original width and height of the image. These two properties have been implemented in Firefox/Chrome/Safari/Opera and IE9. How to get image size under transformation.
Copy the codeThe code is as follows:
function getImgNaturalDimensions(img, callback) {
var nWidth, nHeight
if () { // Modern browser
nWidth =
nHeight =
} else { // IE6/7/8
var imgae = new Image()
=
= function() {
callback(, )
}
}
return [nWidth, nHeight]
}
Pay attention to the processing of IE6/7/8. A new img was created and only its src was set. At this time, the image needs to be fully loaded before it can get its width and height. Therefore, it is asynchronous here. You can pass a callback, and the original width and height are passed in as parameters in the callback.