HTML5 Canvas [64]
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 interactions. 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 discussing 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 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) 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);
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 value of x and y. Since 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.closePath();
context.fill();
To move the circle up the screen, we would make speed a negative number. To move it left or right, we would update the x instead of the y variable. To move the circle diagonally, we would update both x and y at the same time.
Example 5-1 shows the complete code needed to create basic movement in a straight line.
Example 5-1. Moving in a straight line
NOTE
The basic structure of the HTML for all of the examples in this chapter will follow these rules. In the interest of saving