2013-03-05 82 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

相关问题