2014-09-29 79 views
0

我有了一个构造函数的原型雪碧......的drawImage不工作

function Sprite(img) { 
    for (var property in img) this[property] = image[property]; 
} 

...这发生在一个Image对象,使得它的一个副本。现在我想提请雪碧使用的drawImage:

Sprite.prototype.draw = function(ctx, x, y) { 
    ctx.drawImage(this, x, y); 
} 

这给了我一个错误:

Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': No function was found that matched the signature provided. 
然而

如果我用实际Image对象,否则完全相同的代码,即:

Sprite.prototype.draw = function(ctx, x, y) { 
    ctx.drawImage(img, x, y); 
} 

它的工作原理与它应该完全相同(img是Image对象的全局名称)。

这是Sprite原型的完整代码。我不明白是什么差异导致这种情况发生,因为我只将一个函数添加到Sprite中;画。

+0

[drawImage只支持本地对象。](http://stackoverflow.com/questions/14934033/draw-preloaded-image-into-canvas)。 – OrionMelt 2014-09-30 00:27:19

回答

0

我怀疑你的意思是:

this[property] = img[property] 

其他我觉得你的副本比你需要浅。查看这个讨论将原型方法放入副本。 How do I correctly clone a JavaScript object?

最后我会提醒的是,除非您以某种方式更改图像,否则重复使用相同图像效率更高。画布对象引用相同的图像。

+0

是的我的意思是img,这就是我的代码。 – 2014-09-30 00:05:03