HTML and CSS Reference
In-Depth Information
9.10 Animating <canvas> Drawings
Problem
Drawing static shapes into the canvas element is fine, but now you want to make the
shapes move around.
Solution
Animation with the canvas element boils down to drawing a frame of your animation
and then, a few milliseconds later, erasing that drawing and redrawing the next frame,
probably with some elements slightly moved or otherwise changed. If you animate by
showing the frames fast enough—around 20-30 frames per second—it generally looks
like a smooth animation of your shapes.
In this chapter, we've already covered how to draw various things into your canvas
element. We also briefly mentioned one way to clear your canvas element (resetting the
width). To fire up some animation, all we need to do is put those two concepts together.
Here's a basic example of a moving red dot (which is shown in Figure 9-16 ):
function draw_circle(x, y) {
mycontext.fillStyle = "#f00";
mycontext.beginPath();
mycontext.arc(x, y, 10, 0, Math.PI * 2, true);
mycontext.fill();
}
function erase_frame() {
mycanvas.width = mycanvas.width;
}
var ball_x = 50;
var ball_y = 50;
var delta = 3;
draw_circle(ball_x, ball_y);
setInterval(function(){
if (ball_x > 100 || ball_y < 15 || ball_x < 15 || ball_y > 100) {
delta *= −1;
}
ball_x += delta;
ball_y += delta;
erase_frame();
draw_circle(ball_x, ball_y);
}, 35);
 
Search WWH ::




Custom Search