It's in the draw function that we actually draw onto the canvas. Lets break this code done to see what is going on.
context2D.clearRect(0, 0, canvas.width, canvas.height);
All drawing is done to the context rather than the canvas element itself. First we clear the context, which gives us a clean slate to work with each frame.
context2D.drawImage(image, x, y);
Next we draw the image to the context using our x and y variables to specify the position to draw the image at.
x += 1 * xDirection;
y += 1 * yDirection;
In order to move the image across the canvas the x and y positions are either incremented or decremented depending on whether xDirection and yDirection are equal to 1 (moving right or down) or -1 (moving up or left).
if (x >= 450)
{
x = 450;
xDirection = -1;
}
else if (x <= 0)
{
x = 0;
xDirection = 1;
}
if (y >= 250)
{
y = 250;
yDirection = -1;
}
else if (y <= 0)
{
y = 0;
yDirection = 1;
}
If the image has moved off the side of the canvas the direction of the image is reversed. We know the dimensions of the image are 150 x 150 pixels, and the dimensions of the canvas are set to 600 x 400 pixels, which gives us the values of 450 (600 - 150) and 250 (400 - 150).
The end result is a smiley face that bounces around inside the canvas. You may be thinking at this point that the same effect could be achieved more easily by modifying the position of an DIV element, and you would be right. However this is just a taste of what can be achieved with the canvas element. The next article will show you some of the advaned effects that can be applied using the canvas element that would be difficult to achieve any other way.
Check out the demo here, and download the source code here.
Read more in the Game Development with JavaScript and the Canvas element series.