Creative Coding · Session c05

Loops + Patterns

Repeat a simple rule millions of times — and get art.

The for loop lets you repeat something many times with a changing number each time. When you put one loop inside another — a nested loop — you can visit every cell of a grid: every row × every column.

A 10 × 7 grid is 70 squares. If each square's colour is a formula using its column, row, and time — you get an animated tapestry.

Live sketch — Living Tapestry

The pattern shifts and breathes on its own. Use the speed slider to control how fast it animates.

1.0×
function setup() { createCanvas(420, 280); noStroke(); } function draw() { let tileSize = 42; // each square is 42 × 42 pixels let t = frameCount * 0.8; // time — controls animation speed // outer loop: columns (left → right) for (let col = 0; col < 10; col++) { // inner loop: rows (top → bottom) for (let row = 0; row < 7; row++) { // colour = formula using col, row, and time let r = (col * 25 + t) % 255; let g = (row * 35 + t * 0.5) % 255; let b = 150; fill(r, g, b); rect(col * tileSize, row * tileSize, tileSize - 2, tileSize - 2); } } }
How nested loops visit a grid:
For col = 0: the inner loop runs rows 0, 1, 2, 3, 4, 5, 6 → 7 squares in column 0.
For col = 1: inner loop runs again → 7 more squares in column 1.
… and so on until col = 9. Total: 10 × 7 = 70 squares, each visited exactly once.
Connection to maths: Try changing the colour formula to col * row * 10 % 255. You just drew the multiplication table as a colour map — the same grid you memorised as times tables!
Challenges
  1. Change tileSize to 20 — how many tiles fit now? What happens to the pattern?
  2. Change the colour formula to (col * row * 10) % 255 for the red channel. You just painted a multiplication table. Can you see the pattern?
  3. Add sin() to the animation: let r = (col * 25 + sin(frameCount * 0.02 + col) * 80) % 255. The wave looks organic.
  4. Replace rect with circle — the grid of circles looks completely different. Try circle(col * tileSize + tileSize/2, row * tileSize + tileSize/2, tileSize - 4).
  5. Open challenge: Design your own colour formula that produces a pattern that means something to you — a flag, a gradient, a wave. Explain in words what your formula does.
Arc 1 complete! 🎉 You've learned: the canvas coordinate system, RGB and HSB colour, variables and motion with sin(), interactive painting with the mouse, and nested loops for grid patterns. The next arc will introduce functions you write yourself, randomness, and building bigger interactive projects. Well done!
← All lessons
Focus 25:00

Ask your tutor