HTML and CSS Reference
In-Depth Information
An important point to note here is that since the code is drawing or painting the canvas, to produce the
effect of a moving ball, we also need code to erase everything and then redraw everything with the ball in a
new spot. The statement to erase everything is:
ctx.clearRect(box,boxy,boxwidth,boxheight);
It might be possible to erase (clear) just parts of the canvas, but I chose to erase and then redraw
everything. In each situation, you need to decide what makes sense.
Setting up a timing event
Setting up timing events in HTML5 is actually similar to the way its done in the older versions of HTML.
There are two built-in functions: setInterval and setTimeout . Well look at setInterval here and at
setTimeout in the memory game in Chapter 5. Each of these functions takes two arguments. Remember
that arguments are extra pieces of information included in function or method calls. Back in Chapter 1, we
saw that document.write took as its single argument what was to be written out on the screen.
Ill describe the second argument first. The second argument specifies an amount of time, in milliseconds.
There are 1000 milliseconds to a second. This may seem like a very short unit to work with, but it turns out
to be just what we want for games. A second (1000 milliseconds) is quite long for a computer game.
The first argument specifies what is to be done at the intervals specified by the second argument. The first
argument can be the name of a function. For this application, the init function definition contains the
following line:
setInterval(moveball,100);
This tells the JavaScript engine to invoke the function moveball every 100 milliseconds (10 times per
second). moveball is the name of a function that will be defined in this HTML document; it is the event
handler for the timing interval event . Don't be concerned if you write this line of code before writing the
code to define the function. What counts is what exists when the application is run.
JavaScript also provides a way other than a function name for the event handler. You could write
setInterval("moveball();",100);
for the same effect. Putting it another way, for simple cases, when the action is the call of a function
without parameters, the name of the function will do. For more complex cases (as described in the Aside
note), you can write a string to specify code. The string can be a full function call, or something like this:
setInterval("positionx = positionx+speed;",100);
That is, the complete response to the event can be written in the first argument. Using a function is the
way to go in most situations.
Note: Here is a more complex example. Suppose I had a function named slide that itself took one
argument, and I wanted this function to be called with a value 10 times the value of the variable d,
and I wanted this to happen every one and one-half seconds, I would code
setInterval("slide(10*d);",1500);
 
Search WWH ::




Custom Search