Skip to content Skip to sidebar Skip to footer

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

Solution 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

Solution 2:

Try this:

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

Solution 3:

I used this way:

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

And it was the only working solution I have found.

Solution 4:

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

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

<bodyonload="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.

Post a Comment for "Javascript Calculate Image Size, After Image Load"