HTML5 Canvas [6]
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();
}
or:
window.onload = canvasApp();
We will use the first method throughout this book.
Encapsulating Your JavaScript Code for Canvas
Now that we have created a way to test to see whether the HTML page has loaded, we can start creating our JavaScript application. Because JavaScript runs in an HTML page, it could be running with other JavaScript applications and code simultaneously. Usually, this does not cause any problems. However, there is a chance that your code might have variables or functions that conflict with other JavaScript code on the HTML page.
Canvas applications are a bit different from other apps that run in the web browser. Because Canvas executes its display in a defined region of the screen, its functionality is most likely self-contained, so it should not interfere with the rest of the page, and vice versa. You might also want to put multiple Canvas apps on the same page, so there must be some kind of separation of JavaScript when defining the code.
To avoid this issue, you can encapsulate your variables and functions by placing them inside another function. Functions in JavaScript are objects themselves, and objects in JavaScript can have both properties and methods. By placing a function inside another function, you are making the second function local in scope to the first function.
In our example, we are going to have the canvasApp() function that is called from the window load event contain our entire Canvas application. This “Hello World!” example will have one function named drawScreen(). As soon as canvasApp() is called, we will call drawScreen() immediately to draw our “Hello World!” text.
The drawScreen() function is now local to canvasApp(). Any variables or functions we create in canvasApp() will be local to drawScreen(), but not to the rest of the HTML page or other JavaScript applications that might be running.
Here is the sample code for how we will encapsulate functions and code for our Canvas applications:
function canvasApp() {
drawScreen();
...
function drawScreen() {
...
}
}
Adding Canvas to the HTML Page
In the