← Back to JavaScript
30

Canvas 2D with JavaScript: draw data on a surface

Learn how to use the `canvas` element and its 2D context to clear, draw and repaint shapes from JavaScript-controlled data.

📘 Theory

Canvas is not the DOM

In the DOM you mutate nodes. In canvas you paint on a surface.

If you need independent semantic elements that can be focused and read separately, the DOM is often better. If you need many moving shapes or free drawing, canvas is a stronger fit.

Canvas does not remember a circle as a reusable object. If you want to change the picture, you store the data in JavaScript, clear the surface and draw again.

1

DOM

2

Canvas

3

State

Get the context and draw the first shape

Everything starts with a canvas reference and its 2D context.

1

`getContext('2d')` gives you the object that exposes drawing methods for paths, rectangles, arcs, text and fills.

2

Before drawing a complex shape, `beginPath()` starts a fresh path so previous traces do not leak into the next one.

Repaint from data instead of patching blindly

The stable pattern is clear, draw and repeat from the latest state.

1

When positions, sizes or colors change, it is usually simpler to clear the full canvas and draw the current state than to surgically remove individual traces.

2

That approach keeps each render deterministic and avoids visual leftovers.

🧪 Learn by doing

Example Guided example: draw a simple status badge Paint a circle and a short label on the canvas through the 2D context.

🏁 Challenges

Challenge Challenge: draw bars from an array Turn a list of values into proportional bars inside the canvas.

What is this?

I'm Cristian Eslava and I sometimes build websites so both you and I can learn and experiment. culTest

I made this in February 2026 to make learning easier for my students. The idea is to learn web development by practicing and to keep expanding the project with new topics, tests and challenges.

It draws inspiration from MDN, W3Schools, CodePen, Manz and many other web development references. I wanted to combine useful theory, runnable examples, challenges and the testing system I had already built for culTest. culTest

If you liked it, if you didn't, or if you want to get in touch, write to me at cristianeslava@gmail.com