【问题标题】:Canvas: drawImage not drawing image to canvas画布:drawImage 未将图像绘制到画布
【发布时间】:2013-11-01 23:39:46
【问题描述】:

我正在使用画布进行游戏。我有一个将自身绘制到画布上的 Sprite 对象,在 Sprite 类中,我在创建对象时创建了 Image 成员及其 src 属性。

这是不工作的代码:

Sprite.prototype.draw = function(Context){
    this.Image.onLoad = function(){
    Context.drawImage(this.getImage(),this.getX(),this.getY());
    };
};

在对象构造函数中,我传入了一个字符串参数,它是图像的文件路径 - 这是正确存储的。

我感觉问题出在 setImage 函数上:

Sprite.prototype.setImage = function(){
    this.Image = document.createElement('img');
    this.Image.src = this.getImagePath(); //This just returns the path as a                                                                      
                                            string
};

我在运行时没有收到任何错误...但图像没有绘制到屏幕上?

谁能指出发生了什么?我已经搜索过这个问题的答案,但在每个人中,所有元素都是在 html 文档中创建的,而我的所有元素都是动态创建的,不知道这是否有什么不同。

干杯

【问题讨论】:

  • 首先,它是onload,而不是onLoad。其次,您的 draw 函数仅将侦听器附加到您的图像对象。如果load 事件在您调用draw 时已经触发,那么监听器代码将永远不会运行。

标签: javascript html canvas drawimage


【解决方案1】:

您的代码是在 同步 模型上构建的,但您使用的是 异步 调用,这意味着这不会像您预期的那样工作。

您首先在您的图像对象上设置一个 url,这意味着加载过程会立即被调用。在您调用 draw 时,图像可能已经加载,也可能尚未加载(如果它存在于缓存中,此过程通常是即时的),因此当您设置 onload 处理程序(必须为小写)时,图像对象可能已通过那个阶段,它永远不会被调用(浏览器不会等待它被设置)。

为此,您需要使用不同的模型,例如回调和/或承诺。为简单起见,回调就可以了。

这方面的一个例子可能是:

Sprite.prototype.setImage = function(callback){
    this.Image = document.createElement('img');
    this.Image.onload = function() {
        callback(this); /// just for ex: passing image to callback (or other inf)
    }
    this.Image.src = this.getImagePath();
};
Sprite.prototype.draw = function(Context){
    Context.drawImage(this.getImage(), this.getX(), this.getY());
};

这样,当图片加载完成后,它会调用你指定的回调函数,例如:

var sprite = new Sprite(); /// pseudo as I don't know you real code

sprite.setImagePath('someurl');
sprite.setImage(imageLoaded);

function imageLoaded() {
    sprite.draw(context);
}

(我个人会合并 setImagePathsetImage - 保持简单。)

【讨论】:

  • 干杯!我来自 C# 背景,所以默认情况下 async 让我稍微有点
  • 再次感谢这个答案真的为我连接了很多点
  • @Fendorio 没问题!很高兴我能帮上忙。
  • 谢谢!我来自 Java/Ruby 背景,您在这方面帮助了我很多!我从未想过问题在于对同步模型进行异步调用。这几天我一直在摸不着头脑!
猜你喜欢
  • 2015-11-01
  • 1970-01-01
  • 2013-03-08
  • 2013-03-28
  • 2012-11-09
  • 1970-01-01
  • 1970-01-01
  • 2018-11-30
  • 1970-01-01
相关资源
最近更新 更多