NEBians
search Sign In Register

Paint with Code

Lesson 2 of 4 Coding game schedule15 min

Loading simulation…

sports_esportsPlay with the blocks and run your code

flagWhat you'll discover

  • arrow_forwardGet a canvas drawing context with getContext("2d")
  • arrow_forwardDraw circles with beginPath, arc and fill
  • arrow_forwardDrive position, size and colour from a loop variable
  • arrow_forwardUse hsl() colour values to sweep through the rainbow

The canvas: a pixel playground

The <canvas> element is a rectangle of raw pixels that JavaScript paints directly — no tags, no CSS layout, just coordinates. You draw through a context object: ctx = canvas.getContext("2d"). Its coordinate system starts at (0,0) in the TOP-left corner, with y growing downward — the opposite of maths class! ctx.fillRect(x, y, w, h) paints a rectangle; circles take three steps: ctx.beginPath(), ctx.arc(x, y, radius, 0, Math.PI * 2), then ctx.fill(). Games, charts and drawing apps all render through exactly this API.

Loops are paintbrushes

Drawing one circle is a demo; drawing fifty is art — and the difference is a loop. Put your draw calls inside for (let i = 0; i < 50; i++) and use i in the maths: x position 15 + i * 14 marches shapes across the screen, radius 5 + i makes them grow, and Math.sin(i) * 60 makes them wave up and down. One rule, executed many times with a changing input, produces patterns too intricate to draw by hand. That technique has a name — generative art — and galleries exhibit work made exactly this way.

hsl(): colour you can compute

Hex codes like #EC4899 are awkward to vary inside a loop. hsl(hue, saturation%, lightness%) is built for it: hue is an angle around the colour wheel from 0 to 360 — red at 0, green at 120, blue at 240, back to red at 360. Set ctx.fillStyle = "hsl(" + (i * 15) + ", 80%, 60%)" and every pass of the loop paints with the next colour of the rainbow. One multiplication gives you a smooth gradient across all your shapes — colour as arithmetic, not guesswork.

quizCheck your knowledge

1. What does canvas.getContext("2d") give you?
2. On a canvas, where is the point (0, 0)?
3. Inside a loop, ctx.fillStyle = "hsl(" + i * 15 + ", 80%, 60%)" makes the shapes...