Canvas API
The Canvas API provides a drawable area that JavaScript can use to render shapes, text, images, and animations.
What you will learn
- How the canvas element and its drawing context work together
- How coordinates, size, and pixels affect a drawing
- How to keep canvas content understandable and usable
Minimal drawing
<canvas id="scene" width="240" height="120">A rectangle drawing appears here.</canvas>const canvas = document.querySelector('#scene'); const context = canvas.getContext('2d'); context.fillStyle = '#2463eb'; context.fillRect(20, 20, 100, 60);The origin (0, 0) is at the top-left. The first two arguments of fillRect are the x and y position; the next two are width and height.
Important boundaries
- Canvas pixels are not automatically meaningful to screen readers. Provide a text alternative or a nearby accessible explanation.
- Set the drawing buffer size with the canvas attributes; CSS size alone can make drawings blurry.
- Check that a 2D context exists before drawing.
- Do not use canvas when normal HTML provides better semantics or text selection.
Suggested order
- Understand the canvas element.
- Learn
getContext('2d'), coordinates, and rectangles. - Add colors, paths, text, and images one step at a time.
- Test keyboard access and provide an equivalent description.