Paddy
Paddy

Reputation: 1175

Canvas - Drawing an image from within a prototype

I am writing some basic code using the prototypal pattern. I am trying to draw an image to canvas but it is not working. I have debugged the code within Chrome and it is because the image.onload is not firing. I don't believe the image is being loaded.

Here are the two functions that control this.

var SimpleGame = function () {
self = this; //Reference to this function

//Canvas 
this.canvas = document.createElement("canvas");
this.ctx = this.canvas.getContext("2d");
this.canvas.width = 251;
this.canvas.height = 217;

//Default objects
this.bgReady = false;
this.bgImage = new Image();

}; 

var simpleProto = SimpleGame.prototype; //Cache the prototype

//Draw the objects on the canvas
simpleProto.draw = function() {

//Draw/ Render the canvas
document.body.appendChild(self.canvas);

//Draw the background
self.bgImage.onload = function() {
    self.bgReady = true;
};

self.bgImage.src = "images/background.png";

    if(self.bgReady) {
    self.ctx.drawImage(self.bgImage, 10, 10);
    };

}

Any idea why?

Upvotes: 2

Views: 486

Answers (1)

markE
markE

Reputation: 105035

Your if(self.bgReady) is being tested before the image has a chance to load.

So naturally it will be false and drawImage will not be executed.

Fix:

Put self.ctx.drawImage in self.bgImage.onload

Good luck with your project!

Upvotes: 1

Related Questions