2

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()?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
cstack
  • 2,152
  • 6
  • 28
  • 47

1 Answers1

2
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.

alex
  • 479,566
  • 201
  • 878
  • 984