Loading

Animation in Canvas

Canvas also supports animations by repeatedly redrawing shapes at different positions:

Example:

<canvas id="myCanvas" width="500" height="400"></canvas>
  <script>
        const canvas = document.getElementById('myCanvas');
        const context = canvas.getContext('2d');
        let x = 0;
      
        function draw() {
          context.clearRect(0, 0, canvas.width, canvas.height);
          context.fillStyle = 'green';
          context.fillRect(x, 50, 50, 50);
          x += 2;
          requestAnimationFrame(draw);
        }
        
        draw();
  </script>
  • The draw the function is called initially.
  • Inside draw, the canvas is cleared to prepare for the new frame.
  • A green rectangle is drawn at the current position (x, 50).
  • The x the variable is incremented by 2, moving the rectangle to the right.
  • requestAnimationFrame(draw) schedules the draw function to be called again, creating a loop.
  • This loop continues, clearing the canvas and redrawing the rectangle at a slightly shifted position each time, resulting in the animation of the rectangle moving to the right.