Thursday, 9 June 2011

Canvas Background Image

In some posts, I use this line to clear the screen before drawing player image:
context2D.clearRect(0, 0, canvas.width, canvas.height);
You can either replace this line, or add a line after it, drawing the background image.
I would personally add the line after clearing, in case at some point we want to do other things with menus or something that could potentially affect it.

You could indeed just use CSS to add a background-image to the canvas element, but that is very bad practice, because many games have a moving background.


Shut up and tell me how to do it...
So, first you need to make the image object. Something like this:
var bgImg = new Image();
bgImg.src = "images/bg.png";
And then in the draw function (if you're not following me, come back to this when you've got to the stage of using a Game Loop), just after the screen is cleared (or instead of clearing the screen), you would want to use this line:
context2D.drawImage(bgImg, 0, 0);
If you want to use a scrolling background, replace the "0, 0" with x and y position variables, and update their values in the relevant place depending on how you want it to work. Remember that position is always relative to the top left corner by default.