Animating with draw() Loop
index.html
Animating graphics in P5.js relies on the draw() function, which acts as a continuous loop that refreshes the canvas many times per second. Each time draw() runs, the canvas is cleared (if you use background()), shapes are redrawn, and variables can be updated to create motion. This repeated execution is what enables animation and dynamic visual effects.
The frameRate() function determines how many times per second draw() is called. By default, P5.js aims for 60 frames per second, but you can adjust this with frameRate(). A higher frame rate means smoother motion, while a lower frame rate can create a choppier effect.
To animate an object, you store its position and speed in variables. Inside draw(), you update these variables on each frame. For example, a bouncing ball's position is updated by adding its speed to its coordinates, and when it hits the edge of the canvas, the direction is reversed by multiplying the speed by -1. This process of updating variables and redrawing shapes on every frame is the core of time-based art in P5.js.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Can you show me a simple example of animating a shape in P5.js?
How do I control the speed of an animation in P5.js?
What happens if I don't use the `background()` function in `draw()`?
Awesome!
Completion rate improved to 6.67
Animating with draw() Loop
Swipe to show menu
index.html
Animating graphics in P5.js relies on the draw() function, which acts as a continuous loop that refreshes the canvas many times per second. Each time draw() runs, the canvas is cleared (if you use background()), shapes are redrawn, and variables can be updated to create motion. This repeated execution is what enables animation and dynamic visual effects.
The frameRate() function determines how many times per second draw() is called. By default, P5.js aims for 60 frames per second, but you can adjust this with frameRate(). A higher frame rate means smoother motion, while a lower frame rate can create a choppier effect.
To animate an object, you store its position and speed in variables. Inside draw(), you update these variables on each frame. For example, a bouncing ball's position is updated by adding its speed to its coordinates, and when it hits the edge of the canvas, the direction is reversed by multiplying the speed by -1. This process of updating variables and redrawing shapes on every frame is the core of time-based art in P5.js.
Thanks for your feedback!