How do I get alerted in Javascript that an image's dimensions are available?
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()
?
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.
精彩评论