Now that we know what the canvas element is, it's time to actually draw something onto the screen. First we need a HTML page to hold and display the canvas element.
The HTML is very straightforward. There are two important elements here.
<canvas id="canvas" width="600" height="400">
<p>Your browser does not support the canvas element.</p>
Here we have created the canvas element. Those browsers that don't support the canvas element, like Internet Explorer (up to version 8), ignore it, displaying the child elements instead. In our case there is a simple paragraph warning the user that their browser doesn't support the canvas element. Those browsers that do support the canvas element, like Chrome, Opera and Firefox ignore any children of the canvas element.
First up some global variables need to be defined.
const FPS = 30;
The FPS variable defines the frequency that the canvas will be redrawn.
var x = 0;
var y = 0;
var xDirection = 1;
var yDirection = 1;
The x, y, xDirection and yDirection variables are used to defined the position of the image (relative to the top left corner of the canvas) and the direction that it is currently moving.
var image = new Image();
In order to draw an image onto the canvas we need to load up an image. For this we create an Image object, and set the src property to the location an image file.
var canvas = null;
var context2D = null;
We also need a reference to the canvas element itself, as well as it's drawing context (more on the context later). We will assign the correct values to these later, so for now they are set to null.
window.onload = init;
Finally we need to be notified when the page has been loaded in order to run the code that will draw to the canvas, so we set the init function to be called on the windows onload event.