HTML and CSS Reference
In-Depth Information
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;
}
erase_circle(ball_x, ball_y);
ball_x += delta;
ball_y += delta;
draw_circle(ball_x, ball_y);
}, 35);
This technique of drawing the entire frame and then erasing it and redrawing it with
some things moved or changed works fine, but in certain circumstances, it's not ideal.
For instance, if you are animating a shape like our red circle on top of a static drawing
(or an image/photo/etc.), it's quite a waste of resources to redraw the unchanging
background image 30 times per second, simply because the foreground shape (the red
circle) has moved and needs to be redrawn.
One solution to this problem is to use two canvas elements, stacked on top of each
other. In the background canvas element, you draw your static scene image, and in the
foreground canvas element you do your animation of the red circle, as above. This way,
the background image is only drawn once, not every time you redraw the layer with
the moving red circle, as shown in Figure 9-17 .
In this example, drawing and redrawing the entire canvas just to show the same red
circle in different positions doesn't seem strictly necessary. However, in practical cases,
you may be animating more than just the position. For instance, you may animate an
object by moving its position and rotating it at the same time. In such cases, the draw/
redraw method of animation is most appropriate.
For this simple case, another option would have been to have a canvas element in the
foreground that was only big enough to contain the red circle (20×20 pixels), and simply
to move that element itself around, using CSS positioning on the page. Especially for
that case, having the red circle separate from the background image is quite helpful, so
that the two elements can be positioned independently.
See Also
Basic canvas animation tutorial at https://developer.mozilla.org/en/Canvas_tutorial/Ba
sic_animations .
 
Search WWH ::




Custom Search