HTML5 Canvas Game Programming lesson 1

Initial setup

Here we have the basic structure of a web page with a game-style canvas. It contains a reference to our main JavaScript file, 'Lesson.js' contained inside the folder 'js/'.

This is the HTML file, index.html:

<!DOCTYPE html>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>HTML5 Game Programming Lesson 1</title>
  <script src='js/Lesson.js' />
    #screen { display:block; margin:0 auto; background-color:#F0F; }
  <h3>HTML5 Game Programming lesson 1</h3>
  <canvas id='screen' width='800' height='480'></canvas>

The canvas is given the id 'screen' so that it can be referenced later from the JavaScript code. I gave the canvas a purple background so that if there are any parts of the canvas that the game doesn't render correctly, the purple color will show through. Normally, you'll choose a color like black or white, that doesn't flash so visibly while the page is loading. I also centered the canvas on the page independent of the rest of the page's content.

And this is the JavaScript file, js/Lesson.js:

// ----------------------------------------
// Actual game code goes here.

// Global vars
canvas = null;
ctx = null;

// ----------------------------------------

window.onload = function () {
    canvas = document.getElementById("screen");
    ctx = canvas.getContext("2d");
    ctx.strokeRect(40, 40, 80, 40);
    ctx.fillText("Hello World!", 50, 65);

This JavaScript file contains two global variables to easily reference the canvas and the canvas's context from anywhere. These two objects are initialized when the page receives the window.onload event, i.e. when it's ready to start running and rendering our game. The context is the object through which we can render graphics primitives inside the canvas. I test it by rendering a rectangle and a text string.

That's it for our basic canvas setup!