home/ atoms/ p5js-framecount-modulo-animation

frameCount % width produces seamlessly looping horizontal motion in p5.js

p5.js provides the built-in variable frameCount — the number of times draw() has run. Combined with the modulo operator (%), it produces cyclically looping values without conditionals: frameCount % width counts 0 up to width-1 then wraps to 0, resetting an element’s x-coordinate back to the left edge of the canvas. This is more concise than the if (x > width) x = 0 pattern and stays locked to the draw loop’s cadence, so an element sweeps left to right and restarts cleanly.

Examples

function draw() { background(220); let x = frameCount % width; // loops 0..width every width frames circle(x, 200, 30); }

Assessment

What does frameCount % 60 produce after 130 frames? Design a shape whose x-position completes one full sweep every 2 seconds at 60fps.

“When frameCount is equal to width, `frameCount % width` will return 0. This will reset the position of the cloud back to the x-coordinate 0”