HTML and CSS Reference
In-Depth Information
In HTML5 you no longer have to specify the script type.
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 they can do something
based on the event. Some common events that an object in JavaScript might listen for
are key presses, 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
.
Below is the final code we will use to test to see whether the
window
has loaded:
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();
}