HTML and CSS Reference
In-Depth Information
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 func-
tions 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 onthe same page, so there must be some kind ofsepar-
ation 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() functionisnowlocalto canvasApp() .Anyvariablesorfunctionswecre-
ate 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 ap-
function canvasApp () {
drawScreen ();
function drawScreen () {
Search WWH ::

Custom Search