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.
jsplatformer1.html
The HTML is very straightforward. There are two important elements here.
<script type="text/javascript" src="jsplatformer1.js"></script>
This line includes the JavaScript source code that will actually modify the canvas element, which will be described later.
<canvas id="canvas" width="600" height="400">
<p>Your browser does not support the canvas element.</p>
</canvas>
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.
The ID attribute of the canvas element is important, as we will need to get a reference to this element using it via JavaScript later on. The width and height attributes simply specify the size of the canvas element, just like any other HTML element like a table or an image.
jsplatformer1.js
The canvas element is quite useless on it's own. JavaScript has to be used to draw anything onto the canvas, and in our case the JavaScript code that will do the drawing is held in the jsplatformer1.js file. As a simple introduction we will load an image, draw it onto the canvas, and move it around.
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();
image.src = "http://javascript-tutorials.googlecode.com/files/jsplatformer1-smiley.jpg";
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.