What is the HTML5 Canvas API and how do you draw shapes?

· Category: HTML & CSS

Short answer

The Canvas API provides a resolution-dependent bitmap canvas for rendering graphics, animations, and images dynamically with JavaScript.

How it works

A <canvas> element creates a drawable region. You obtain a 2D rendering context via getContext('2d'), then use methods like fillRect, strokeRect, beginPath, arc, and fill to draw.

Example

<canvas id="myCanvas" width="400" height="300"></canvas>
<script>
  const ctx = document.getElementById('myCanvas').getContext('2d');
  ctx.fillStyle = 'steelblue';
  ctx.fillRect(20, 20, 100, 80);

  ctx.beginPath();
  ctx.arc(200, 150, 50, 0, Math.PI * 2);
  ctx.fillStyle = 'coral';
  ctx.fill();
  ctx.stroke();
</script>

Why it matters

Canvas is ideal for games, image editing, real-time data visualizations, and pixel-level manipulation. For resolution-independent icons and illustrations, SVG is usually the better choice because it scales without blurring and remains accessible.