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
windoware 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:trueorfalseThis sets the function to capture this type of event before it propagates lower in the DOM tree of objects. We will always ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access