JS get the height and width of the image method to share

  • 2020-05-30 19:23:41
  • OfStack

1. Get the height and width of the picture as follows:


var img = new Image();
img.src = imgsrc;
var imgWH = CalcImgTiple(img.width, img.height);

But the test in chrome could not get it. img.width, img.height are all 0

Reason: when the picture is not a local picture, but a web picture
The event handler that onload calls when the image is successfully loaded.

In the development of web, there is one requirement: to obtain the size of the image to be loaded by Javascript, so it is natural to think of img's onload method. After the development of firefox is completed, the onload event of img is not called in many cases.

The original code is as follows:


var img = new Image;
img.src = "test.gif";
img.onload = function(){
alert ( img.width );
};

This code looks fine, but why isn't onload called by IE? Because IE will cache the image, the second load of the image, not uploaded from the server, but loaded from the buffer. Does an image loaded from a buffer not trigger the onload event? So I tested the following code and it worked


var img = new Image;
img.onload = function(){
alert ( img.width );     };
img.src = "test.gif";

Write onload first, tell the browser what to do with the image, and then specify the source of the image. So, it's not that IE did not fire the onload event, but rather that the buffer was loaded so fast that it did not run to img.onload when the onload event was fired. This reminds me of Ajax. When writing xmlhttp, I always specify the callback function of onstatechange first, and then send data

That's all for this article, I hope you enjoy it.


Related articles: