Javascript calculate image size, after image load

自古美人都是妖i 提交于 2019-12-24 09:58:32

问题


function loader(img) {
        var imgH = img.height;
        var imgW = img.width;
        console.log(imgH, imgW);    
    };

img = new Image();
img.src ='../images/pic1.jpeg';
img.onLoad = loader(img);

So, It is exepeted, that I'll get image's size, but I got "0 0" in console. And size of image is 500X700. What's wrong with this code?


回答1:


This makes no sense:

img.onLoad = loader(img);

you want to pass the actual function to the event:

img.onload = loader;

and use this instead of img within the function.

Also you need to assign the event before changing the image's src property.

Also note that there are numerous problems with the load event on images. From the jQuery manual on load():

Caveats of the load event when used with images

A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:

  • It doesn't work consistently nor reliably cross-browser
  • It doesn't fire correctly in WebKit if the image src is set to the same src as before
  • It doesn't correctly bubble up the DOM tree



回答2:


Try this:

function loader(){
    var imgH = this.height;
    var imgW = this.width;
    console.log(imgH, imgW); 
}
var img = new Image();
img.onload = loader;
img.src ='../images/pic1.jpeg';



回答3:


I used this way:

img.onload = function(){//here wrote everything from loader};

And it was the only working solution I have found.




回答4:


I found the best way is to let the computer do the scaling first.

and declaring the onload = "some_function()" in the body.

<body onload="some_function()">

and then getting the sizing afterward in the script.

some_function(){

var image1 = document.getElementsByClassName('main')[0];
var computedStyle_image1 = window.getComputedStyle(image1);
var image_width = computedStyle_image1.getPropertyValue('width');

}

I noticed with google chrome you need to make sure you call the onload="function" within the body div otherwise the image values arn't set and it pulls in 0px for width and height.



来源:https://stackoverflow.com/questions/7267663/javascript-calculate-image-size-after-image-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!