This assignment teaches you how to create generative art patterns using p5.js, focusing on loops, grids, and creative coding techniques.
The easiest way to get started is using the p5.js Web Editor:
- Go to the p5.js Web Editor: editor.p5js.org
- Create an account (optional but recommended to save your work)
- Copy and paste the code from any step's
sketch.jsfile into the editor - Click the Play button to see your pattern
- Modify the code and experiment!
The web editor automatically handles all the setup - you just need to focus on the creative coding.
For students who want to work locally and get comfortable with a full development environment:
-
Install Visual Studio Code from code.visualstudio.com
-
Install the p5.vscode extension:
- Open VS Code
- Click the Extensions icon (or press
Cmd+Shift+Xon Mac,Ctrl+Shift+Xon Windows) - Search for "p5.vscode" by Sam Lavigne
- Click Install
-
Clone or download this repository to your local machine
-
Open a step folder in VS Code:
- File → Open Folder
- Select one of the step folders (e.g.,
step1/)
-
Run the sketch:
- Simply open the
index.htmlfile in your web browser, OR - Use the Live Server extension in VS Code:
- Install "Live Server" extension by Ritwick Dey
- Right-click on
index.htmland select "Open with Live Server"
- Your sketch will display in the browser
- Changes will auto-reload when you save (if using Live Server)
- Simply open the
The files are numbered to guide you through increasingly complex patterns:
- Draws a single red circle
- Introduces
setup()anddraw()functions - Basic p5.js canvas creation
- Introduces canvas sizing concepts
- Demonstrates smooth rendering (anti-aliasing)
- Shows how to use
pixelDensity()for high-resolution displays
- Adds nested loops for 4×4 grid
- Introduces helper functions (
drawCircle()) - Uses random RGB colors
- Demonstrates grid-based layouts
- Integrates predefined color palettes (16 colors)
- Creates harmonious color schemes
- Shows how to use color arrays
- Uses
sin()andcos()to arrange circles in circular patterns - Introduces
drawMultipleCircles()function - Adds alpha channel support for transparency
- Implements outline colors with configurable stroke weight
- Enables image saving with keyboard shortcut (press 's')
- Full HD output (1920×1080)
- 16×9 grid layout
- Configurable alpha for fill and outline separately
- Produces high-resolution exports
- Perfect for wallpapers or prints
- Uses golden ratio mathematics (phi ≈ 1.618)
- Creates a spiral with 800 circles
- Positioned using polar coordinates and the golden angle (≈ 137.5°)
- Demonstrates advanced mathematical patterns in generative art
- Interactive animations with dropdown selector
- Four animation modes:
- Rotating: Circles spin around their centers
- Pulsing: Patterns breathe and grow/shrink rhythmically
- Color Shifting: Colors cycle through the palette
- Particles Appearing: Circles appear progressively
- Demonstrates the p5.js
draw()loop for continuous animation - Shows DOM element interaction (dropdown menu)
- Uses
sin()andframeCountfor smooth motion - Press 's' to save a frame
The examples use circles, but you can create many other shapes using p5.js drawing functions:
// Instead of ellipse()
rect(x, y, width, height);
// Or with center mode:
rectMode(CENTER);
rect(x, y, width, height);triangle(x1, y1, x2, y2, x3, y3);// Hexagon example
function drawHexagon(x, y, radius) {
beginShape();
for (let i = 0; i < 6; i++) {
let angle = TWO_PI / 6 * i;
let px = x + radius * cos(angle);
let py = y + radius * sin(angle);
vertex(px, py);
}
endShape(CLOSE);
}strokeWeight(5);
line(x1, y1, x2, y2);// Arc (part of a circle)
arc(x, y, width, height, startAngle, endAngle);
// Example: half circle
arc(100, 100, 80, 80, 0, PI);Here are some ways to create interesting patterns:
-
Mix shapes: Use different shapes in alternating cells
if ((i + j) % 2 === 0) { drawCircle(...); } else { drawRectangle(...); }
-
Vary sizes: Make shapes grow or shrink across the grid
let diameter = 20 + (i * 10); // Gets bigger as i increases
-
Rotate patterns: Use rotation to create dynamic effects
push(); // Save current drawing style translate(x, y); // Move to position rotate(angle + i * PI / 8); // Add rotation per row rect(0, 0, 50, 50); pop(); // Restore drawing style
-
Layer transparency: Use alpha values to create overlapping effects
fill(255, 0, 0, 128); // 50% transparent red
-
Create gradients: Interpolate between colors across the grid
// Fade from first color to last color let amount = i / 4; let c = lerpColor(color1, color2, amount);
-
Combine with math: Try sine waves, spirals, or random variations
let yOffset = sin(i * 0.5) * 50; // Wave pattern
You can create your own color palettes using tools like:
- coolors.co - Color palette generator
- Adobe Color - Color wheel and themes
- Paletton - Color scheme designer
// Create a palette array
let palette = [
[255, 0, 0], // Red
[0, 255, 0], // Green
[0, 0, 255], // Blue
[255, 255, 0] // Yellow
];
// Use colors from the palette
let c = palette[i % palette.length];
fill(c[0], c[1], c[2]);// HSB color mode (Hue, Saturation, Brightness)
colorMode(HSB, 360, 100, 100);
fill(180, 80, 90); // Cyan-ish color
// Lerp between colors
let from = color(255, 0, 0);
let to = color(0, 0, 255);
let between = lerpColor(from, to, 0.5); // PurpleImportant Note: You may notice that the p5.js examples look different from Python versions when using transparency (alpha channel). This is because p5.js and Python/Pillow handle alpha blending differently.
In Python/Pillow (PIL):
- Semi-transparent shapes can use higher alpha values (like 125 out of 255)
- Overlapping areas accumulate gradually, creating subtle layering effects
- The compositing algorithm preserves more translucency
In p5.js:
- You need to use much lower alpha values (like 15-30) to achieve similar translucency
- Alpha accumulates faster, making overlapping areas opaque more quickly
- The rendering creates a different aesthetic - often more glowy/ethereal
Example from step5:
- Python uses:
alpha = 125for semi-transparent fills - p5.js uses:
alpha = 15to achieve a similar translucent effect
Tip for students: Experiment with different alpha values to find what looks best! There's no single "correct" value - it depends on the effect you want to create.
p5.js automatically applies anti-aliasing to make smooth edges. You can control this:
smooth(); // Enable anti-aliasing (default)
noSmooth(); // Disable for pixel-art styleFor high-resolution displays (like Retina), increase pixel density:
pixelDensity(2); // 2x resolution
pixelDensity(displayDensity()); // Match display- p5.js:
ellipse(x, y, width, height)draws from the CENTER by default - You can change this with
ellipseMode(CORNER)to draw from top-left
Press the 's' key in any of the step5, step6, or fibonacci-spiral examples to save your pattern as a PNG image.
You can also add this to any sketch:
function keyPressed() {
if (key === 's' || key === 'S') {
saveCanvas('my-pattern', 'png');
}
}- Start with step1 and modify it incrementally
- Use
console.log()to debug your loop values (check browser console) - Press 's' to save your images (in sketches that have this enabled)
- Increase canvas size for higher resolution, but it may render slower
- Experiment! The best way to learn is to try things and see what happens
ellipse(x, y, w, h)- Draw an ellipse/circlerect(x, y, w, h)- Draw a rectangleline(x1, y1, x2, y2)- Draw a linetriangle(x1, y1, x2, y2, x3, y3)- Draw a trianglepoint(x, y)- Draw a point
fill(r, g, b, a)- Set fill colorstroke(r, g, b, a)- Set stroke/outline colorstrokeWeight(w)- Set stroke thicknessnoFill()- Disable fillnoStroke()- Disable stroke
translate(x, y)- Move the originrotate(angle)- Rotatescale(s)- Scalepush()- Save current style/transformpop()- Restore saved style/transform
random(max)orrandom(min, max)- Random numbersin(angle),cos(angle),tan(angle)- Trigonometrysqrt(n)- Square rootabs(n)- Absolute valuefloor(n),ceil(n),round(n)- Roundingmap(value, start1, stop1, start2, stop2)- Remap a numberlerp(start, stop, amt)- Linear interpolationdist(x1, y1, x2, y2)- Distance between two points
PI- π (3.14159...)TWO_PI- 2π (6.28318...)HALF_PI- π/2 (1.57079...)width- Canvas widthheight- Canvas height
- p5.js Reference - Complete function reference
- p5.js Examples - Learn by example
- The Coding Train - Video tutorials by Daniel Shiffman
- OpenProcessing - Share and explore p5.js sketches
- Creative Coding with p5.js - Beginner tutorial series
If you encounter errors:
- Check the browser console (Right-click → Inspect → Console tab)
- Read the error message - p5.js errors usually indicate the line number and what went wrong
- Compare your code to the working examples
- Try the p5.js Web Editor - it has helpful error messages and autocomplete
- Ask for help - share your code and describe what you're trying to do
Happy coding!