Loops & Repetition
Use for loops to repeat things — draw rows, grids, patterns, and animations with just a few lines of code.
A for loop repeats code a set number of times. It has three parts: a starting value (let i = 0), a condition to keep going (i < 8), and a step (i++ means "add 1"). Inside the loop, i is your counter — use it to control position!
Try it!Change the 8 to 20 — how many circles can you fit? Try changing the spacing too!
Put one for loop inside another to make a grid! The outer loop handles rows (y), the inner loop handles columns (x). Multiply the counter by a spacing value to spread things out evenly.
Try it!Change the colors to black and white to make a real checkerboard pattern!
Loops are great for creating lots of objects at once. Combine a loop with random() to scatter shapes across the canvas. Here we create a starfield — each frame redraws the stars at random positions for a twinkling effect.
Try it!Try making the stars NOT twinkle — declare the star positions in setup() using an array instead!
Combine loops with frameCount and math to create mesmerizing animated patterns. Each circle's position depends on both its index in the loop and the current frame — so the whole pattern moves smoothly over time.
Try it!Try changing 0.02 to 0.05 to speed it up, or change 20 to 50 for more circles!
What to try next
- Draw a row of houses using a for loop — each house at a different x position
- Create a grid of emojis using nested loops and the text() function
- Make a spiral pattern using a single loop with increasing radius and angle
- Build an animated rain effect: use a loop and frameCount to make drops fall down the screen