HTML Canvas

The HTML <canvas> element acts as a resolution-dependent bitmap canvas, which can be used for rendering graphs, game graphics, art, or other visual images on the fly. Think of it as a blank digital slate where you use JavaScript as your paintbrush. Unlike SVG (Scalable Vector Graphics), which is based on XML shapes, Canvas is pixel-based; once a shape is drawn, the canvas "forgets" what it is and only remembers the pixels.

Developer Tip: Use Canvas for high-performance graphics like games or real-time data visualizations. Use SVG when you need high-quality scaling or want to manipulate individual elements via CSS and the DOM.

Basic Syntax

<canvas id="myCanvas" width="400" height="200" style="border:1px solid #000;"></canvas>

By default, the <canvas> element has no content and no border. It is essential to provide an id so you can reference it in your JavaScript code. You should also define the width and height directly as attributes rather than using CSS.

Watch Out: Setting the canvas size via CSS (e.g., style="width: 500px;") will stretch or squash the drawing area rather than increasing the pixel count. Always use the width and height attributes for the actual drawing resolution.

Setting Up a Canvas

To draw on the canvas, we first need to grab the element from the DOM and then get its rendering context. The 2D context provides the methods and properties we need to manipulate the pixels.

Example: Drawing a Line

<canvas id="lineCanvas" width="400" height="200"></canvas>
<script>
  const canvas = document.getElementById("lineCanvas");
  const ctx = canvas.getContext("2d");

  // Draw a line
  ctx.beginPath();       // Start a new path
  ctx.moveTo(50, 50);    // Move the "pen" to coordinates (x:50, y:50)
  ctx.lineTo(350, 50);   // Draw a line to (x:350, y:50)
  ctx.stroke();          // Actually render the line on the screen
</script>

Output: A straight horizontal line is drawn on the canvas. The coordinate system starts at (0,0) in the top-left corner. Increasing x moves you right, and increasing y moves you down.

Common Mistake: Forgetting to call ctx.stroke() or ctx.fill(). Without these, your path exists in memory but will never appear on the screen.

Drawing Shapes

Canvas provides several built-in methods for drawing rectangles and complex paths (like circles).

1. Rectangles

  • fillRect(x, y, width, height): Draws a solid, colored rectangle.
  • strokeRect(x, y, width, height): Draws just the outline of a rectangle.
  • clearRect(x, y, width, height): Makes a specific area transparent (acts like an eraser).
<canvas id="rectCanvas" width="400" height="200"></canvas>
<script>
  const canvas = document.getElementById("rectCanvas");
  const ctx = canvas.getContext("2d");

  // Filled rectangle (a blue box)
  ctx.fillStyle = "blue";
  ctx.fillRect(50, 50, 100, 50);

  // Rectangle outline (a red border)
  ctx.strokeStyle = "red";
  ctx.lineWidth = 5;
  ctx.strokeRect(200, 50, 100, 50);

  // Clear a part of the canvas (creates a "hole" in the red rectangle)
  ctx.clearRect(210, 60, 80, 30);
</script>
Best Practice: When changing colors or line widths, set the fillStyle or strokeStyle right before you draw that specific shape. This prevents "bleeding" styles where one shape accidentally takes the color of the previous one.

2. Circles and Arcs

To draw a circle, you use the arc() method. This method uses radians instead of degrees. To draw a full circle, you go from 0 to 2 * Math.PI.

  • arc(x, y, radius, startAngle, endAngle, anticlockwise)
<canvas id="circleCanvas" width="400" height="200"></canvas>
<script>
  const canvas = document.getElementById("circleCanvas");
  const ctx = canvas.getContext("2d");

  // Draw a circle
  ctx.beginPath();
  ctx.arc(150, 100, 50, 0, 2 * Math.PI); // Full circle
  ctx.fillStyle = "green";
  ctx.fill();
  ctx.stroke();
</script>

Adding Text

Drawing text on a canvas is useful for labels, HUDs in games, or dynamically generated banners. You can control the font, size, and alignment just like in CSS.

Example: Drawing Text

<canvas id="textCanvas" width="400" height="200"></canvas>
<script>
  const canvas = document.getElementById("textCanvas");
  const ctx = canvas.getContext("2d");

  // Draw solid text
  ctx.font = "bold 24px Segoe UI, Arial";
  ctx.fillStyle = "black";
  ctx.fillText("Hello, Canvas!", 100, 100);

  // Outline text for a "ghost" effect
  ctx.strokeStyle = "blue";
  ctx.strokeText("Hello, Canvas!", 100, 140);
</script>
Watch Out: Canvas text is not accessible to screen readers and cannot be highlighted or searched like normal HTML text. Always provide an alternative (like an aria-label or hidden text) for accessibility.

Adding Images

You can draw external images (JPG, PNG, GIF) onto your canvas. This is the foundation for most 2D web games. However, you must ensure the image is fully loaded before trying to draw it.

Example: Drawing an Image

<canvas id="imageCanvas" width="400" height="200"></canvas>
<script>
  const canvas = document.getElementById("imageCanvas");
  const ctx = canvas.getContext("2d");
  const img = new Image();

  // The image must be loaded before we can draw it!
  img.onload = () => {
    ctx.drawImage(img, 50, 50, 100, 100);
  };
  img.src = "https://via.placeholder.com/100";
</script>
Developer Tip: Use the 5-argument version of drawImage(img, x, y, width, height) to resize images as they are drawn. The 9-argument version allows you to "crop" an image, which is perfect for using sprite sheets.

Animations

Animation in Canvas is created by drawing a frame, clearing the canvas, and then drawing the next frame in a slightly different position. We use requestAnimationFrame because it is optimized for the browser's refresh rate.

Example: Simple Animation

<canvas id="animCanvas" width="400" height="200"></canvas>
<script>
  const canvas = document.getElementById("animCanvas");
  const ctx = canvas.getContext("2d");
  let x = 0;

  function draw() {
    // 1. Clear the canvas (prevents "smearing")
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 2. Draw the object
    ctx.fillStyle = "orange";
    ctx.fillRect(x, 75, 50, 50);

    // 3. Update the position
    x += 2;

    // 4. Repeat
    if (x < canvas.width) {
      requestAnimationFrame(draw);
    }
  }

  draw();
</script>

Output: A moving orange square animates horizontally across the canvas.

Best Practice: Always use requestAnimationFrame() for animations rather than setInterval(). It pauses when the user switches tabs, saving battery and CPU cycles.

 

Summary

The HTML <canvas> element is a high-performance tool for rendering 2D shapes, text, and images. By mastering the 2d context and the coordinate system, you can build everything from simple interactive charts to complex browser-based games. Remember that Canvas is a "draw and forget" system—if you need to change a single object, you'll usually clear the whole screen and redraw everything for the next frame.