Doug Wolfgram
Doug Wolfgram

Reputation: 2126

Javascript: How do I get the height of unloaded images in a loop?

I am loading a json file and parsing it into an array in Javascript. One of the elements is the path to an image. I am not ready to load the images yet but I need to get the image's height. I know how to do that with code like the following (found on other stackoverflow pages)

function getimageheight(img) {
    var tmpImg = new Image();
    tmpImg.onload = function() {
        var ht = this.height;   
        return ht+0;
    }
    tmpImg.src = img;
}

If I try to call this function in a loop, it returns undefined because the onload for the images is running slower than the loop. My actual code is this:

        var j = 0;
        $.each(cat.placemarks, function(index, mark) {
            markers[cat.name][j] = [];
            markers[cat.name][j].name = mark.name;
            markers[cat.name][j].title = mark.title;
            markers[cat.name][j].markerURL = mark.markerURL;
            markers[cat.name][j].imageURL = mark.imageURL;
            markers[cat.name][j].imageHEIGHT = getimageheight(projpath+mark.imageURL);
            j++;
        }); 

If I call the function once, it works. But calling it in a loop does not. How can I fix this?

Upvotes: 0

Views: 266

Answers (2)

Martin
Martin

Reputation: 1822

If you store reference to data object in Img object used to load it, you can set the value of its properties after the loading is done. Hope that makes sense... Your data will not be ready to use before loading is complete tho. Heres the code

var total=cat.placemarks.length;//if an array, otherwise use another each cycle to get object count
var loaded=0;

$each(cat.placemarks, function(index, mark) {
    markers[cat.name][j] = [];

    var tmpImg = new Image();
    tmpImg.refToObjWithNameOfYourChoice=markers[cat.name][j];
    tmpImg.onload = function() {
        this.refToObjWithNameOfYourChoice.imageHEIGHT=this.heigh;
        loaded++;
        if(loaded==total){
            //markers data is ready to use - add function callback herer or sumthin'
        }
    }
    tmpImg.src=projpath+mark.imageURL;

    markers[cat.name][j].name = mark.name;
    markers[cat.name][j].title = mark.title;
    markers[cat.name][j].markerURL = mark.markerURL;
    markers[cat.name][j].imageURL = mark.imageURL;
    j++;

});

Upvotes: 2

SaganRitual
SaganRitual

Reputation: 3203

markers[cat.name][j].imageHEIGHT is undefined because getImageHeight() isn't returning anything. And naturally, the image load will occur much more slowly than your each() loop, so it won't do you any good to have getImageHeight() return something. You'll have to set up your load() callback to determine which image has been loaded and update the height of the corresponding markers element.

Upvotes: 0

Related Questions