HTML5 Canvas “Hello World!”

As we just mentioned, one of the first things we need to do when putting Canvas on an HTML5 page is test to see whether the entire page has loaded and all HTML elements are present before we start performing any operations. This will become essential when we start working with images and sounds in Canvas.

To do this, you need to work with events in JavaScript. Events are dispatched by objects when a defined event occurs. Other objects listen for events so that they can do something based on the event. Some common events that an object in JavaScript might listen for are keystrokes, mouse movements, and when something has finished loading.

The first event we need to listen for is a window object’s load event, which occurs when the HTML page has finished loading.

To add a listener for an event, use the addEventListener() method that belongs to objects that are part of the DOM. Because window represents the HTML page, it is the top level of the DOM.

The addEventListener() function accepts three arguments:

Event: load

This is the named event for which we are adding a listener. Events for existing objects like window are already defined.

Event handler function: eventWindowLoaded()

Call this function when the event occurs. In our code, we will then call the canvasApp() function, which will start our main application execution.

useCapture: true or false

This sets the function to capture this type of event before it propagates lower in the DOM tree of objects. We will always set this to false.

The final code we will use to test to see whether the window has loaded is as follows:

window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded () {
   canvasApp();
}

Alternatively, you can set up an event listener for the load event in a number of other ways:

window.onload = function()
   {
      canvasApp();
   }

or:

window.onload = canvasApp;

We will use the first method throughout this book.

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.