HTML and CSS Reference
In-Depth Information
Now that our values have been updated, we simply draw the ball at the
x
and
y
coordinates
specified bythe
x
and
y
properties, andwearedone—that is,until
drawScreen()
iscalled 33
milliseconds later:
context
.
fillStyle
=
"#000000"
;
context
.
beginPath
();
context
.
arc
(
ball
.
x
,
ball
.
y
,
15
,
0
,
Math
.
PI
*
2
,
true
true
);
context
.
closePath
();
context
.
fill
();
Let'strytheexample byexecuting itinawebbrowser.Youcanfinditinthecodedistribution
as
CH5EX2.html
, or you can type in
Example 5-2
.
Watch the ball move from one point to an-
other. If you update the
x
and
y
values of each point, or change the speed, watch the results.
You can do a lot with this very simple example.
Tracing movement: A path of points
For many of the examples in this chapter, we will create a way to trace an object's movement
on the canvas by drawing points to show its path. We have done this to help illustrate how
objectsmove.However,intherealworld,youwouldneedtoremovethisfunctionality sothat
your application will perform to its potential. This is the only place we will discuss this code,
so if you see it listed in any of the later examples in this chapter, refer back to this section to
refresh your memory on its functionality.
First, we create an array in
canvasApp()
to hold the set of points we will draw on the canvas:
var
var
points
=
new
new
Array
();
Next, we load a black 4×4 pixel image,
point.png
, which we will use to display the points on
the canvas:
var
var
pointImage
=
new
new
Image
();
pointImage
.
src
=
"point.png"
;
Wheneverwecalculateapointforanobjectwewillmove,wepushthatpointintothe
points
array:
points
.
push
({
x
:
ball
.
x
,
y
:
ball
.
y
});
On each call to
drawScreen()
, we draw the set of points we have put into the
points
array.
Remember, we have to redraw every point each time because the canvas is an immediate-
mode display surface that does not retain any information about the images drawn onto it:
for
for
(
var
var
i
=
0
;
i
<
points
.
length
;
i
++
) {
context
.
drawImage
(
pointImage
,
points
[
i
].
x
,
points
[
i
].
y
,
1
,
1
);
}