Sometimes CSS isn't enough. You need pixels. Raw, programmable pixels that you control completely. That's what the HTML5 <canvas> element gives you—a blank surface where you can draw anything.

Games, charts, image editors, signature pads, generative art—Canvas makes them all possible. And it's surprisingly easy to get started.

The Basics

Canvas is simple: you create a <canvas> element, get its 2D rendering context, and start drawing. Here's the minimal setup:

The ctx (context) object is your paintbrush. It has methods for rectangles, paths, text, images, and more. Let's build something practical.

Demo 1: Signature Pad

A signature pad is the perfect first Canvas project. It teaches you about mouse/touch events, paths, and real-time drawing. Try it below—draw your signature!

Here's how it works. We track pointer events (which handle both mouse and touch) and draw lines connecting each point:

The key insight: we're not drawing pixels directly. We're drawing paths— lines from one point to another. Canvas connects them smoothly for us.

Demo 2: Simple Bar Chart

Canvas is perfect for data visualization. Here's a bar chart built with just rectangles and text. Hover over the bars to see values.

The code draws rectangles proportional to each value, with labels below:

When to Use Canvas

Canvas is powerful, but it's not always the right choice. Here's a quick guide:

Use Canvas for:

  • Games and animations with many moving objects
  • Data visualization (charts, graphs)
  • Image manipulation and filters
  • Drawing applications and signature capture
  • Generative art and creative coding

Consider SVG instead for:

  • Scalable graphics that need to stay sharp at any size
  • Graphics that need to be accessible (Canvas is just pixels)
  • Fewer elements that need individual event handlers
  • Graphics you want to style with CSS

Consider CSS instead for:

  • Simple shapes and gradients
  • UI animations and transitions
  • Anything that's part of your document flow

Tips for Better Canvas

A few things I've learned:

  • Handle high-DPI displays. Multiply canvas dimensions by devicePixelRatio and scale the context to keep things sharp.
  • Use requestAnimationFrame for animations instead of setInterval. It's smoother and battery-friendly.
  • Clear before redrawing. Use ctx.clearRect() at the start of each frame in animations.
  • Pointer events work everywhere. They handle mouse, touch, and stylus—one API for all input types.

What's Next?

You've seen the basics. From here, you could explore:

  • Animations with requestAnimationFrame
  • Image manipulation with getImageData/putImageData
  • The WebGL API for 3D graphics
  • The OffscreenCanvas API for background rendering

Canvas gives you a blank surface and complete control. What you draw on it is up to you.

Further Reading