HTML and CSS Reference
In-Depth Information
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.
Todothis,youneedtoworkwith
events
inJavaScript.Eventsaredispatchedbyobjectswhen
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
thatarepartoftheDOM.Because
window
representstheHTMLpage,itisthetoplevelofthe
DOM.
The
addEventListener()
function accepts three arguments:
Event:
load
load
Thisisthenamedeventforwhichweareaddingalistener.Eventsforexistingobjectslike
window
are already defined.
Event handler function:
eventWindowLoaded()
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
useCapture
:
true
true
or
false
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
false
);
function
function
eventWindowLoaded
() {
canvasApp
();
}
Alternatively, you can set up an event listener for the
load
event in a number of other ways: