HTML and CSS Reference
In-Depth Information
CHAPTER 5
Math, Physics, and Animation
Impressing users with animation involves more than knowing how to move objects—
you also need to know how to move them in ways that users expect. That requires
understanding some common algorithms for math-based movement and physics in-
teractions. Simple movement based on points and vectors provides a foundation, and
then it's time to create objects that bounce off walls and one another with a bit of friction
added to the mix. After that, we will step back and talk about movement that goes
beyond straight lines: circles, spirals, and complex Bezier curves. We will then cover
how adding gravity can affect movement. Finally, we will finish this chapter by dis-
cussing easing and how it can have a positive effect on math-based animations.
Moving in a Straight Line
For the simplest kinds of animations—moving objects in a straight line up and down
the canvas—this 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 vari-
able 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) 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 33 milliseconds. This is the loop we need to update our objects and move them
around the canvas:
setInterval(drawScreen, 33);
 
Search WWH ::




Custom Search