Canvas: drawImage not drawing image to canvas

一笑奈何 提交于 2019-11-29 17:24:31

You code is building on synchronous model but you are using asynchronous calls which means this will not work as you might expect.

You first set an url on your image object which means the process of loading is invoked immediately. At the time you then call draw the image may or may not be already loaded (if it exists in the cache this process is usually instant) so when you then set your onload handler (which must be lower case) the image object is perhaps pass that stage and it will never be called (the browser doesn't wait for it to be set).

For this to work you need to use a different model, for example callbacks and/or promises. For simplicity callbacks will do just fine.

An example of this could be:

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());
};

This way when an image has loaded it will call the function you specified as callback, again just for example:

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

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

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

(Personally I would merge setImagePath and setImage - keep it simple.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!