Question

I need to be able to wait to start a function until the height and width of an image are available. When this code calls start(), it still says the height and width are zero:

var img = new Image();

init = function() {
    img.onload = this.start();
    img.src = "sky.jpg";
    }

start = function() {
    alert("Start called.\nwidth:"+img.width+"\nheight"+img.height);
    }

init();

How can I make it wait until the dimensions are available before calling start()?

Was it helpful?

Solution

var img = new Image();

var start = function() {
    alert("Start called.\nwidth:"+img.width+"\nheight"+img.height);
}

var init = function() {
    img.onload = start;
    img.src = "sky.jpg";
} 

init();

Change this.start() to start.

I also scoped your functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top