Introduction to <canvas>

Introduced in HTML5, the canvas element provides a drawable region in the HTML page. You can use JavaScript to draw anything from simple lines and shapes to complex animations and even 3D games.

What is Canvas?

The canvas element is a bitmap (raster) drawing surface. When you draw on a canvas, you are manipulating pixels.

It provides a "blank slate" where you can programmatically "paint" using JavaScript commands. Unlike a static image file (like a .png or .jpg), a canvas can be updated in real-time, allowing for dynamic data visualization and interactive effects.

SVG vs. Canvas

You might be familiar with SVG (Scalable Vector Graphics), which is another way to create graphics in HTML. Here's how they differ:

Feature Canvas SVG
Rendering Raster-based (pixels). Vector-based (paths).
Drawing Method Scripted (via JavaScript). Declarative (via SVG elements).
Performance High performance with many objects. Performance can drag as the DOM grows.
Scalability Not scalable without losing quality. Perfectly scalable at any resolution.
Accessibility Requires specific techniques. Better accessibility out of the box.

What Can You Do with Canvas?

Common uses for the canvas element include:

The next lesson will show you how to set up your first canvas and prepare it for drawing.