开发者

Javascript calculate image size, after image load

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?


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


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';


I used this way:

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

And it was the only working solution I have found.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜