Canvas: drawImage not drawing image to canvas

前端 未结 1 1903
日久生厌
日久生厌 2020-12-22 07:19

I\'m using canvas for a game. I have a Sprite object which draws itself to the canvas, in the Sprite class I create the Image member along with it\'s src attribute when i cr

相关标签:
1条回答
  • 2020-12-22 08:21

    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.)

    0 讨论(0)
提交回复
热议问题