js determines the method of obtaining the actual width and height of the picture after the picture is loaded

  • 2021-01-06 00:27:46
  • OfStack

This article illustrates how js determines the actual width and height of an image after it is loaded. To share with you for your reference, as follows:

. Normally, we will use jq width () /. height () method to obtain the width/height of the picture or use js. offsetwidth /. offsetheight method to get the width/height of the image, but these methods in our through setting the style image of wide high after the acquisition, it is not the actual width is high, it's not what we want results in some time, then have 1 kind of method to obtain the actual wide high? The answer is yes. The following code can solve such a problem:


<img src="01.jpg" id="test" width="250px">

js code:


// The actual width and height of the picture are obtained after the picture is loaded 
var _test = document.getElementById("test");
test.onload = function(){
  imgSize.call(_test);
}
function imgSize(){
  var imgObj = new Image();
  imgObj.src = this.src;
  alert(imgObj.width + "\n" + imgObj.height);
}

alert(imgObj.width + "\n" + imgObj.height); alert(imgObj.width + "\n" + imgObj.height); Change to return, imgObj, and then the method to be called:


window.onload = function(){
    function a(){
      var real= imgSize.call(_test);
      var realwidth = real.width;
      alert(realwidth);
    }
    a();
}

The above method is too cumbersome, after my refining, abbreviation is as follows:


window.onload = function(){
    var _test = document.getElementById("test"); // if jq , simply replace this code with  var _test = $("#test");  Can. 
    var imgObj = new Image();
    imgObj.src = _test.src; // if jq , simply replace this code with  imgObj.src = _test.attr("src");  Can. 
    alert(imgObj.width);
}

This way, you can call the actual width and height of the image directly from other methods.

More about JavaScript related content interested readers can view the site topic: "JavaScript search algorithm skills summary", "JavaScript animation effects and skills summary", "JavaScript error and debugging skills summary", "JavaScript data structure and algorithm skills summary", "JavaScript eraser calculation method and skills summary" and "JavaScript mathematical operation usage summary"

I hope this article is helpful to JavaScript program design.


Related articles: