画布:绘制图像而不是将图像绘制到画布

Canvas: drawImage not drawing image to canvas

本文关键字:图像 绘制 画布      更新时间:2023-09-26

我正在使用画布进行游戏。我有一个将自己绘制到画布上的 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文档中创建的,而我的所有元素都是动态创建的,不知道这是否有任何区别。

干杯

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

您首先在图像对象上设置一个 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 - 保持简单。