2013-03-05 58 views
1

我是新的使用JS。我想在一個地方保留所有關於對象的信息。 所以我做了這個功能:image.onload函數 - 爲什麼它不起作用?

function Obiekt(img) { 
this.img = img; 
this.ready = false; 
this.image = new Image(); 
this.image.src = this.img; 
this.image.onload = function() { 
    ready = true; 
}; 
this.x = 0; 
this.y = 0; 
this.rotation = 0; 
} 

然後,我做了我的對象,命名爲英雄。

var hero = new Obiekt("images/hero.png"); 

問題是,hero.ready始終是false,我不能畫出這個。

if (hero.ready) { 
    ctx.drawImage(hero.image, 0, 0); 
} 

你能幫我嗎?

+0

你使用'ready'變量在你的'onload'上沒有引用之前找到的相同的'this.ready'。你必須使用另一種引用(f.i.在'onload'和'that.ready'之外使用'var that = this')。另外,你的'onload'應該在'src'之前定義。 – entonio 2013-03-05 17:22:35

回答

3

兩個問題:

  • ready無法找到
  • 如果圖像緩存(取決於瀏覽器),如圖像不加載後您的使用順序不能工作你設置回調。

這裏有一個解決方案:

var _this = this; 
this.image.onload = function() { 
    _this.ready = true; 
}; 
this.image.src = this.img; 

(我想補充的是,命名是不太好:我寧願imgsrc超過img

相關問題