HTML and CSS Reference
In-Depth Information
Moving in a Straight Line
The simplest kinds of animations—moving objects in a straight line up and down the can-
vas—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
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
function gameLoop () {
window . setTimeout ( gameLoop , 20 );
drawScreen ()
gameLoop ();
Inthe drawScreen() function,weupdatethevalueof y byaddingtoitthevalueofthe speed
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
context . fillStyle = "#000000" ;
context . beginPath ();
context . arc ( x , y , 15 , 0 , Math . PI * 2 , true
true );
context . closePath ();
context . fill ();
Search WWH ::

Custom Search