Learn P5JS with Real Code Examples
Updated Nov 26, 2025
Explain
p5.js simplifies drawing shapes, handling events, and creating animations in JavaScript.
It provides a high-level API for 2D and 3D graphics, sound, and video.
The library encourages creative coding and visual experimentation.
It abstracts complex web APIs like Canvas and WebGL for easy use.
p5.js can run directly in a browser without setup.
Core Features
`setup()` and `draw()` loop for initialization and animation
Functions for shapes: `rect()`, `ellipse()`, `line()`
Color and style management: `fill()`, `stroke()`
Mouse and keyboard event callbacks
Integration with DOM and HTML elements
Basic Concepts Overview
Sketch - a p5.js program containing `setup()` and `draw()`
`setup()` - runs once for initialization
`draw()` - runs continuously for animation
Shapes - `rect()`, `ellipse()`, `line()` to draw graphics
Events - `mousePressed()`, `keyPressed()` for interactivity
Project Structure
Single HTML file with embedded JS script
Optional external JS files for modularity
Optional assets folder for images, sounds, etc.
Sketch code usually global in scope
Libraries included as needed
Building Workflow
Create an HTML file and link p5.js
Define `setup()` for canvas and initial setup
Define `draw()` for continuous rendering
Add interactive callbacks as needed
Test and iterate in a web browser
Difficulty Use Cases
Beginner: draw static shapes and colors
Intermediate: animate objects, handle events
Advanced: build interactive multimedia sketches
Expert: integrate with WebGL, ML libraries, or APIs
Architect: design complex interactive experiences or visualizations
Comparisons
p5.js vs Processing -> JavaScript vs Java, both beginner-friendly
p5.js vs Three.js -> p5.js simpler 2D/3D, Three.js more advanced 3D
p5.js vs D3.js -> p5.js creative coding, D3.js data visualization
p5.js vs vanilla Canvas -> p5.js easier, abstracts low-level details
p5.js vs PixiJS -> p5.js general creative coding, PixiJS optimized for WebGL graphics
Versioning Timeline
2014 - p5.js created by Lauren McCarthy
2015 - Initial release and community adoption
2016 - p5.sound library released
2018 - Improved documentation and tutorials
2020–2025 - Active community growth and library updates
Glossary
Sketch - a p5.js program
Canvas - drawing area
draw() - loop function for rendering
setup() - initialization function
Callback - function triggered by an event