HTML and CSS Reference
In-Depth Information
Figure 9-16. Animating a red circle in the canvas
Discussion
Depending on the setup of your animation frame, you may need to employ various
methods to get the most efficient drawing (and erasing) of your shapes and/or images.
We'll now cover several different approaches to drawing and erasing to accomplish
animations with the
canvas
element.
If you have a transparent background and one shape (like a circle) bouncing around in
your
canvas
, as in the example code above, you don't need to erase the whole
canvas
element before drawing the next frame; you only need to erase the small portion of the
element that has something drawn in it (i.e., the circle).
That is, all you need to do is erase the part of the
canvas
element that you drew onto
in the previous frame. Especially for larger dimensions, this technique can enhance
performance significantly.
To erase only part of the
canvas
element, use the
canvas
API command
clearRect(...)
:
function draw_circle(x, y) {
mycontext.fillStyle = "#f00";
mycontext.beginPath();
mycontext.arc(x, y, 10, 0, Math.PI * 2, true);
mycontext.fill();
}
function erase_circle(x, y) {
mycontext.
clearRect
(x-10, y-10, 20, 20);
}