What is the Canvas API?
The Canvas API lets you draw graphics using JavaScript. It works through the <canvas> HTML element — a fixed-size drawing surface that starts completely blank. Nothing appears on it until you write code to draw.
It was introduced as part of HTML5 and first shipped in Safari in 2004. Every modern browser has supported it for years, so it's safe to use everywhere.
The basics
You start by adding a <canvas> element to your HTML. You give it a width and height in pixels — this sets the resolution of the drawing surface (not the CSS display size, which can be different). If you don't set them, the default is 300×150.
Then in JavaScript, you get a reference to the canvas and ask it for a rendering context. The context is the object you actually draw with — think of it as your paintbrush. For 2D graphics you call canvas.getContext('2d'), which gives you a CanvasRenderingContext2D with methods for drawing rectangles, paths, text, images, and more.
In the playground below, we've already set up a canvas (300×150) and its ctx for you. Try hitting Run to see what happens — then change the colour or the coordinates and run it again:
Notice that drawing is immediate-mode: when you call ctx.fillRect(), pixels are painted right away. There's no scene graph like SVG — the canvas doesn't remember what you drew. If you want to change something, you clear the canvas and redraw everything from scratch. This is exactly how animation works: clear, draw, repeat.
Canvas is great for anything that needs pixel-level control and speed: games, data visualisations, image manipulation, generative art, and interactive simulations. For 3D, the same <canvas> element can use a different context — getContext('webgl') — which we'll explore later.