How to get image size (height & width) using JavaScript?

前端 未结 29 3103
忘了有多久
忘了有多久 2020-11-21 05:23

Are there any JavaScript or jQuery APIs or methods to get the dimensions of an image on the page?

29条回答
  •  后悔当初
    2020-11-21 06:00

    Thought this might be helpful to some who are using Javascript and/or Typescript in 2019.

    I found the following, as some have suggested, to be incorrect:

    let img = new Image();
    img.onload = function() {
      console.log(this.width, this.height) // Error: undefined is not an object
    };
    img.src = "http://example.com/myimage.jpg";
    

    This is correct:

    let img = new Image();
    img.onload = function() {
      console.log(img.width, img.height)
    };
    img.src = "http://example.com/myimage.jpg";
    

    Conclusion:

    Use img, not this, in onload function.

提交回复
热议问题