Moving in a Straight Line
The simplest kinds of animations—moving objects in a straight line up and down the
canvas—can take the form of adding a constant value to the x
or y
position of an object every time it is drawn.
So, to animate graphics, we will need to create an interval and then
call a function that will display our updated graphics on every frame.
Each example in this chapter will be built in a similar way. The first
step is to set up the necessary variables in our canvasApp()
function. For this first, basic
example of movement, we will create a variable named speed
. We will apply this value to the y
position of our object on every call to
drawScreen()
. The x
and y
variables set up the initial position of the object (a filled circle) that
we will move down the canvas:
var
speed
=
5
;
var
y
=
10
;
var
x
=
250
;
After we create the variables, we set up an interval to call the
drawScreen()
function every 20
milliseconds. This is the loop we need to update our objects and move them
around the canvas:
function
gameLoop
()
{
window
.
setTimeout
(
gameLoop
,
20
);
drawScreen
()
}
gameLoop
();
In the drawScreen()
function, we
update the value of y
by adding to it
the value of the speed
variable:
y
+=
speed
;
Finally, we draw our circle on the canvas. We position it using the
current values of x
and y
. Because y
is updated every time the function is called, the circle effectively moves
down the canvas:
context
.
fillStyle
=
"#000000"
;
context
.
beginPath
();
context
.
arc
(
x
,
y
,
15
,
0
,
Math
.
PI
*
2
,
true
);
context ...
Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.