HTML and CSS Reference
In-Depth Information
Animation Revisited: Moving Videos
Now we are going to revisit the bouncing balls demo from
Chapter 5
to show you how you
can achieve the same effect with images and videos. Because we covered this in detail in
Example 5-5
(
CH5EX5.html
), we don't need to examine all the codeājust the changes that
make the videos move.
NOTE
Remember that videos are drawn in much the same way as images, so with very few changes, this
application would work just as well with a static image.
While there are a few other changes, the most important is in the
drawScreen()
function
whenwedrawthevideosontothecanvas. Recall thatin
Chapter 5
wecreated anarraynamed
balls
and a dynamic object to hold the properties of each ball that looked like this:
tempBall
=
{
x
:
tempX
,
y
:
tempY
,
radius
:
tempRadius
,
speed
:
tempSpeed
,
angle
:
tempAngle
,
xunits
:
tempXunits
,
yunits
:
tempYunits
}
Forvideos,wewillcreateasimilararray,named
videos
,butwewillalterthedynamicobject:
tempvideo
=
{
x
:
tempX
,
y
:
tempY
,
width
:
180
,
height
:
120
,
speed
:
tempSpeed
,
angle
:
tempAngle
,
xunits
:
tempXunits
,
yunits
:
tempYunits
}
The big difference here is that we no longer need a
radius
that represents the size of the ball;
instead, we need the
width
and
height
so that we can render the video to our desired size in
the
drawScreen()
function.
context
.
beginPath
();
context
.
arc
(
ball
.
x
,
ball
.
y
,
ball
.
radius
,
0
,
Math
.
PI
*
2
,
true
true
);
context
.
closePath
();
context
.
fill
();
To draw videos, we need to change the code:
context
.
drawImage
(
videoElement
,
video
.
x
,
video
.
y
,
video
.
width
,
video
.
height
);
That is pretty much all you need to do! There are some other changes here (for example, we
start all the videos in the center of the screen before they start moving), but the items men-
tioned above are the main things you need to concentrate on to move video, not yellow balls,