Basic Animations

Creating animations on the canvas involves a loop that clears the drawing area, updates the state of objects, and then redraws them for each "frame."

The Animation Loop

A typical animation loop follows these steps:

  1. Clear: Use clearRect() to erase the entire canvas or the parts of the drawing that move.
  2. Update State: Update the position and properties of your shapes (e.g., coordinates, transparency, or color).
  3. Draw: Redraw the objects in their new positions.
  4. Repeat: Use window.requestAnimationFrame() to request the next frame.

requestAnimationFrame()

Modern browsers provide window.requestAnimationFrame() as a performant way to drive animations. This method tells the browser that you want to perform an animation and it ensures that the browser will call a specified function to update the animation before the next repaint.

Method Description
requestAnimationFrame(callback) Specifies a callback function that will be executed before the browser repaints the screen.

Basic Animation Example

In this example, we move a rectangle across the screen and make it bounce off the edges using a persistent animation loop:

View Output

The next lesson explains how to implement pixel manipulation for advanced effects.