Canvas API

The HTML5 Canvas API is instrumental in rendering the Pac-Man game, allowing us to draw sprites, backgrounds, and manage animations dynamically.

Drawing Primitives

The CanvasRenderingContext2D provides methods for drawing various shapes and images:

  • fillRect(x, y, width, height): Draws a filled rectangle. Source

    // Fill a blue rectangle at position (10, 10) with a width of 50 and height of 30
              context.fillStyle = "blue";
              context.fillRect(10, 10, 50, 30); 
              
  • strokeRect(x, y, width, height): Draws an outline of a rectangle. Source

    // Outline a red rectangle at position (20, 20) with a width of 40 and height of 20
              context.strokeStyle = "red";
              context.strokeRect(20, 20, 40, 20); 
              
  • arc(x, y, radius, startAngle, endAngle, anticlockwise): Draws an arc or circle. Source

    // Draw a green circle at position (50, 50) with a radius of 25
              context.strokeStyle = "green";
              context.beginPath();
              context.arc(50, 50, 25, 0, 2 * Math.PI);
              context.stroke(); 
              
  • drawImage(image, dx, dy): Draws an image onto the canvas. Source

    // Draw an image loaded from a file
              var image = new Image();
              image.src = "myImage.png";
              image.onload = () => {
                  context.drawImage(image, 100, 100); 
              }
              

Animation

The requestAnimationFrame API allows us to perform smooth animation updates on the canvas. Source

// Example animation loop
          function animate() {
            // Clear the canvas
            context.clearRect(0, 0, canvas.width, canvas.height); 
          
            // Update game state and draw elements
            // ...
          
            // Schedule the next frame
            requestAnimationFrame(animate);
          }
          
          // Start the animation loop
          animate();
          

Canvas Element

The canvas element is the container for our drawing operations. Source

<canvas id="gameCanvas" width="400" height="300"></canvas>
          

We access the CanvasRenderingContext2D object using the getContext method:

// Get the 2D rendering context
          var context = canvas.getContext("2d");