Getting Started with p5.js
Summary
This chapter introduces the p5.js library, the primary JavaScript framework used for creating MicroSims. You will learn about the HTML canvas element that serves as the drawing surface, the coordinate system for positioning elements, and the fundamental structure of p5.js programs with the setup() and draw() functions. The chapter covers essential concepts like global and local variables, the animation loop, frame rate control, and the createCanvas() and background() functions.
Concepts Covered
This chapter covers the following 14 concepts from the learning graph:
- p5.js Library
- Canvas Element
- Coordinate System
- Pixels
- RGB Color Model
- setup() Function
- draw() Function
- Global Variables
- Local Variables
- Animation Loop
- Frame Rate
- createCanvas()
- background()
- fill()
Prerequisites
This chapter builds on concepts from:
Welcome to the Creative World of p5.js!
If you've ever wanted to create art with code, build interactive visualizations, or bring mathematical concepts to life through animation, you're about to discover one of the most delightful tools in the creative coding universe. p5.js is a JavaScript library that makes programming accessible, fun, and surprisingly powerful. It transforms the potentially intimidating world of code into a playground where creativity flows as naturally as paint on canvas.
What makes p5.js special isn't just what it can do—it's who it was designed for. Unlike many programming libraries built by engineers for engineers, p5.js was created specifically to help artists, designers, educators, and beginners learn to code. The result is a remarkably intuitive system where you can create something visual in just a few lines of code.
Why p5.js for MicroSims?
p5.js is perfect for educational simulations because it combines visual immediacy with interactivity. Students can see their code come alive instantly, making abstract concepts tangible and engaging.
A Brief History: From Processing to p5.js
Understanding where p5.js comes from helps explain why it's so wonderfully suited for creative coding. The story begins in 2001 at the MIT Media Lab.
Diagram: Processing and p5.js Evolution Timeline
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | |
The Processing Philosophy
In 2001, Ben Fry and Casey Reas were graduate students at the MIT Media Lab when they created Processing—a programming environment designed to teach fundamentals of computer programming within a visual context. Their radical idea was simple yet transformative: programming should be as expressive and immediate as sketching.
Traditional programming languages at the time required hundreds of lines of code just to draw a simple circle on screen. Processing changed that entirely. Suddenly, artists and designers could express visual ideas in code almost as quickly as they could sketch them on paper.
The core principles they established continue to guide p5.js today:
- Immediate visual feedback: See your code's output instantly
- Low barrier to entry: Create something interesting on day one
- High ceiling: The same tools can create sophisticated professional work
- Community-driven: Share, remix, and learn from others
NYU ITP: The Home of p5.js
In 2013, something wonderful happened. Lauren McCarthy, a faculty member and researcher at NYU's Interactive Telecommunications Program (ITP), began developing what would become p5.js. Her vision was to bring Processing's creative philosophy directly into web browsers using JavaScript.
NYU ITP has been instrumental in p5.js's success, providing:
- Institutional support for development and maintenance
- Funding for community programs and accessibility initiatives
- A home for the community through workshops, residencies, and events
- Educational resources including tutorials and curriculum development
- Commitment to diversity and inclusion in the creative coding community
Lauren McCarthy on p5.js
"p5.js is a community and p5.js is a library. I think the community is just as important as the library."
The NYU community's emphasis on accessibility has shaped p5.js into a tool that welcomes everyone. Features like the describe() function for screen reader accessibility, internationalization efforts, and inclusive documentation all reflect this commitment.
The Canvas Element: Your Digital Sketchpad
Every p5.js sketch draws on an HTML canvas element—a special rectangular region on a web page designed specifically for graphics. Think of it as a digital version of an artist's canvas: a defined space where your creative vision comes to life.
| Canvas Property | Description |
|---|---|
| Width | Horizontal size in pixels |
| Height | Vertical size in pixels |
| Background | Base color that clears the canvas |
| Context | The 2D or WebGL drawing context |
The canvas element is part of HTML5 and provides a bitmap drawing surface. Unlike regular HTML elements that contain text and images, the canvas is designed for programmatic drawing—perfect for animations, games, data visualizations, and our MicroSims.
Creating Your First Canvas
In p5.js, you create a canvas using the createCanvas() function. This function takes two required parameters: width and height in pixels.
1 2 3 | |
This single line creates a 400×400 pixel canvas—your digital playground for creative coding. The function also returns a canvas object that you can manipulate further, such as positioning it within a specific HTML container.
Understanding Pixels and the Coordinate System
A pixel (short for "picture element") is the smallest addressable point on your canvas. Each pixel has a specific location defined by its coordinates, and every pixel can display a single color at any given moment.
The p5.js Coordinate System
The p5.js coordinate system might feel a bit unusual at first if you're familiar with standard mathematical graphs. Here's the key difference:
- Origin (0, 0) is at the top-left corner of the canvas
- X values increase as you move right
- Y values increase as you move down
This may seem backwards, but it actually matches how computer displays work—screens refresh from top to bottom, and this coordinate system reflects that underlying technology.
Diagram: p5.js Coordinate System
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | |
Here's a comparison with traditional mathematical coordinates:
| Feature | Math Coordinate System | p5.js Coordinate System |
|---|---|---|
| Origin location | Center or bottom-left | Top-left corner |
| Y-axis direction | Increases upward | Increases downward |
| X-axis direction | Increases rightward | Increases rightward |
| Common use | Graphing functions | Screen graphics |
Colors: The RGB Model
Color in p5.js is specified using the RGB color model, which represents colors as combinations of Red, Green, and Blue light. Each color channel accepts a value from 0 (none) to 255 (maximum intensity).
Common RGB values you'll use frequently:
- Black:
(0, 0, 0)- all channels off - White:
(255, 255, 255)- all channels at maximum - Red:
(255, 0, 0)- only red at maximum - Green:
(0, 255, 0)- only green at maximum - Blue:
(0, 0, 255)- only blue at maximum - Yellow:
(255, 255, 0)- red + green - Cyan:
(0, 255, 255)- green + blue - Magenta:
(255, 0, 255)- red + blue
Using Colors with background() and fill()
The background() function sets the canvas background color, effectively "clearing" the canvas with that color. The fill() function sets the color for shapes drawn afterward.
1 2 3 4 5 6 7 8 9 | |
Color Shorthand
When all three RGB values are the same, you can use a single number: background(220) creates a light gray. You can also add a fourth parameter for transparency (alpha): fill(255, 0, 0, 128) creates a semi-transparent red.
The Magic Two Functions: setup() and draw()
Here's where p5.js reveals its elegant simplicity. Every p5.js program is built around just two core functions:
setup()- Runs once when your program startsdraw()- Runs repeatedly in a loop, creating animation
This pattern is so intuitive that it feels almost natural. You set things up once, then the draw function keeps running, updating your visuals frame by frame. It's like the difference between building a stage (setup) and performing a play on it (draw).
1 2 3 4 5 6 7 8 9 10 | |
Why This Pattern Works
The setup/draw pattern maps beautifully to how animations and simulations actually work:
- Setup: Initialize your world—create the canvas, set initial positions, load resources
- Draw: Update your world—move objects, respond to input, render the current state
This pattern is so fundamental that you'll find variations of it in many other frameworks:
| Framework | Setup Function | Draw/Update Function |
|---|---|---|
| p5.js | setup() |
draw() |
| Processing | setup() |
draw() |
| Arduino | setup() |
loop() |
| Unity | Start() |
Update() |
| Pygame | Initialization code | Main game loop |
Once you master this pattern in p5.js, you'll recognize it everywhere!
Variables: Global vs. Local
Variables in p5.js (and JavaScript generally) come in two flavors based on their scope—where in your code they can be accessed.
Global Variables
Global variables are declared outside of any function, typically at the top of your sketch. They can be accessed and modified from anywhere in your code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
Global variables are essential for MicroSims because they:
- Store state that persists between draw() calls
- Allow values to be shared across multiple functions
- Enable animation by changing values over time
Local Variables
Local variables are declared inside a function and only exist within that function's scope.
1 2 3 4 5 6 7 8 9 | |
Local variables are useful for temporary calculations that don't need to persist between function calls.
| Variable Type | Declaration Location | Accessibility | Lifetime |
|---|---|---|---|
| Global | Outside all functions | Everywhere in sketch | Entire program duration |
| Local | Inside a function | Only within that function | Duration of function call |
The Animation Loop and Frame Rate
The draw() function runs in an animation loop—it executes over and over, creating the illusion of movement just like frames in a movie.
By default, p5.js tries to run draw() approximately 60 times per second. This rate, called the frame rate, determines how smooth your animations appear.
Controlling Frame Rate
You can adjust the frame rate using the frameRate() function:
1 2 3 4 | |
Why would you want to change the frame rate?
- Lower frame rates (15-30 fps): Better for slower animations, educational purposes, or reducing CPU usage
- Higher frame rates (60+ fps): Smoother animations, better for games and interactive experiences
You can also check the current frame rate during execution using the frameRate() function without arguments, and the frameCount variable tells you how many frames have been drawn since the program started.
Diagram: Animation Loop Cycle
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | |
Putting It All Together: Your First Complete Sketch
Let's combine everything we've learned into a complete, working p5.js sketch. This example demonstrates all 14 concepts from this chapter:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | |
This simple bouncing ball animation demonstrates every concept we've covered. The joy of p5.js is that with just these fundamentals, you can create endless variations and increasingly sophisticated simulations!
MicroSim: Sound Visualization with FFT
One of p5.js's most exciting features is its sound library (p5.sound), which includes a powerful FFT (Fast Fourier Transform) analyzer. FFT transforms audio signals into frequency data, letting you visualize sound in real-time.
The following MicroSim demonstrates how just a few lines of code can create a mesmerizing audio visualization using your microphone:
Diagram: FFT Microphone Audio Visualizer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | |
This MicroSim showcases the remarkable power of p5.js—creating a real-time audio visualizer in about 30 lines of code. The p5.FFT object handles all the complex mathematics of frequency analysis, letting you focus on the creative visualization.
MicroSim: 3D Animation Fun
p5.js isn't limited to 2D graphics! By using WebGL mode, you can create stunning 3D graphics right in the browser. Let's explore a playful 3D animation that demonstrates p5.js's versatility:
Diagram: Spinning 3D Shapes MicroSim
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | |
This 3D MicroSim demonstrates that p5.js's elegant simplicity extends into three dimensions. The same setup() and draw() pattern you learned for 2D works identically for 3D—you simply add WEBGL as the third parameter to createCanvas() and suddenly you have access to a whole new dimension of creative possibilities!
Key Takeaways
Let's summarize the essential concepts from this chapter:
-
p5.js is a JavaScript library designed to make creative coding accessible and joyful, with roots in the Processing project and strong institutional support from NYU ITP.
-
The canvas element is your digital drawing surface, created with
createCanvas(width, height). -
The coordinate system places (0,0) at the top-left corner, with X increasing rightward and Y increasing downward.
-
Pixels are the smallest addressable points on the canvas, and colors are specified using the RGB model (0-255 for each channel).
-
The setup() function runs once at program start; the draw() function runs repeatedly as an animation loop.
-
Global variables persist across function calls and enable animation; local variables exist only within their function.
-
The frame rate (default 60 fps) controls how often draw() executes.
-
The background() function clears and colors the canvas; fill() sets the color for shapes.
-
p5.js includes powerful additional libraries like p5.sound for audio visualization.
-
3D graphics are accessible through WEBGL mode using the same simple patterns.
Quick Check: What's the coordinate of a point at the exact center of a 400×300 canvas?
The center would be at (200, 150) — half the width and half the height. Remember, we're measuring from the top-left corner!
Next Steps
Now that you understand the fundamentals of p5.js, you're ready to start building your own MicroSims! In the next chapter, we'll explore how to add interactive controls—sliders, buttons, and input fields—that let users experiment with simulation parameters.
The joy of p5.js is that every concept you learn opens up new creative possibilities. With just the tools from this chapter, you could create:
- Bouncing animations with physics
- Color-changing patterns
- Mouse-following visualizations
- Simple particle systems
- Audio-reactive art
- 3D explorations
The canvas is yours. Go create something wonderful!
References
For further exploration of p5.js:
- p5.js Official Website - Documentation, tutorials, and examples
- p5.js Web Editor - Browser-based coding environment
- The Coding Train - Daniel Shiffman's video tutorials
- Processing Foundation - The non-profit behind Processing and p5.js
- NYU ITP - Academic home of p5.js development