Week 13: P5js Animations
To Do This Week
Group HTML5 Game DUE Dec 3rdP5js Project (5%) Due November 19th
NOTE: P5js is fun to explore, especially with AI help. It will be too complicated to incorporate into your games - its not great woth physics. This small p5js project won't take long!
Create a generative animation using p5.js that reflects your personal style and curiosity. Your sketch should include animation, randomness or Perlin noise, and pattern logic. You may use AI for assistance, but things will only get really interesting if you dig in and play with the code. Mistakes sometimes reveal interesting results. Ask for good comments in the outputs.
You can use the P5js editor to work out your script, but you should submit to Canvas and HTML page called index.html inside a folder called "p5js."
You will need to link to the p5js library in the head. Use a script tag with link to the p5 js file:
src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.9.0/p5.min.js"
Requirements:
- Include randomness (
random()ornoise()). - Include some kind of animation or interaction.
- Include logic steps and chat logs in the comments at the top of the script.
This is about play, remix, and experimentation!
Generative Art with P5js
Processing Overview
P5js (Processing for JavaScript) is a library that makes it easy to create complex drawings and animations using Canvas and additional built-in Processing methods. Below are resources and examples that show how p5js works.
p5js.org: Processing → JavaScript for fun and art, creative programming.
Here is an example using P5js site editor: Drawing example.
P5js Methods
Animation Loop
- setup(): Runs once at start.
- draw(): Runs repeatedly every frame.
- frameRate(fps): Sets frame rate. [reference]
- noLoop() / loop(): Stops or resumes looping. [noLoop], [loop]
Canvas & Setup
- createCanvas(w, h): Creates a canvas.
- background(val): Sets background color.
- smooth() / noSmooth(): Enables/disables anti-aliasing. [smooth], [noSmooth]
Drawing & Shapes
- line(x1, y1, x2, y2): Draws a line.
- circle(x, y, diameter): Draws a circle.
- ellipse(x, y, w, h): Draws an ellipse.
- arc(x, y, w, h, start, stop, [mode]): Draws part of an ellipse. [arc()]
- rect(x, y, w, h): Draws a rectangle.
- fill(r, g, b, [a]) / noFill(): Sets or disables fill.
- stroke(r, g, b) / noStroke(): Sets or disables stroke.
- strokeWeight(w): Sets stroke thickness.
Input (Mouse & Keyboard)
- mouseX, mouseY: Mouse position.
- mousePressed(), mouseMoved(): Mouse events.
- keyPressed(), key, keyCode: Key events and values.
Math & Vectors
- random(min, max): Random number in range.
- p5.Vector: Class for vector math (position, velocity, direction, or force).
Utilities
- saveCanvas(): Save canvas as image.
- millis(): Time since sketch started (ms).
- text(): Draws text on canvas.
Full reference: p5js.org/reference
P5js Starter
- p5js shapes
- p5js square grid
- p5js animating with framecount
- p5js drawing
- p5js velocity
- p5js bouncing balls
- p5js online editor
- p5js HTML starter template
P5js Resources
- p5js examples
- p5js overview
- p5js reference
- p5js video tutorial
- how to code generative art with p5js
- p5js showcase
Generative Art
- Algorithmic/Rule-Based: Setting up strict rule systems to generate visual outputs.
- Randomness & Noise: Introducing randomness (e.g., Perlin noise) to simulate organic or chaotic patterns.
- Iterative / Recursive Approaches: Fractals and other self-similar patterns, such as recursive subdivisions.
Generative Art Examples
- Game of Life (P5js simulation)
- Tyler Hobbs | Fidenza series
- Emily Xie
- Joshua Davis
- Raven Kwok
- Kjetil Golid
Advanced Generative Art Techniques
Flow Fields
A grid-based technique where each cell contains a vector determining the direction of particle movement. By populating the field with small agents or particles, artists generate organic, undulating patterns that resemble fluid, wind, or magnetic currents. Subtle adjustments to vector generation—often via noise—produce continuously evolving, visually engaging animations.
Example: p5js Flow Fields Example
prompt: “Write a p5.js sketch that creates a flow field using Perlin noise, where 100 particles move according to the flow vectors. The sketch should visualize the paths in real time.”Perlin Noise & Noise-Based Techniques
The random() function in p5.js generates pseudorandom numbers. It can return a floating-point number between 0 and 1, a number within a specified range, or a random element from an array, depending on how it's used. It's useful for introducing unpredictability and variation in sketches.
The noise() function in p5.js uses Perlin noise: a smooth, gradient-based form of randomness that avoids abrupt changes and is often used to add natural variation in movement, color, or shapes. By sampling noise at various scales or “octaves,” artists produce effects of terrains, clouds, or fluid dynamics. Controlled yet unpredictable.
prompt: “Generate p5.js code that draws a 2D Perlin noise field in grayscale, continuously updating over time to look like clouds.”Particle Systems
Particle systems involve numerous small entities (particles) that each follow simple behavioral rules, typically with an emitter releasing new particles over time. By combining forces like gravity, drag, and random variation, these systems can simulate natural phenomena (like fire or smoke) or produce dense, mesmerizing compositions that evolve frame by frame.
prompt: “Create a p5.js sketch of a particle system where new particles are emitted from the bottom center of the screen and rise upwards, fading out over time.”Boids / Flocking
Originating from Craig Reynolds’s model of bird flocking, boids follow rules of separation, alignment, and cohesion to create emergent group movement or murmuration. Even with minimal constraints, the resulting swarming, flocking, or schooling visuals evoke lifelike patterns and make for captivating, dynamic scenes.
prompt: “Write a p5.js sketch implementing boids flocking with 50 boids. The boids should leave a trail of changing random colors so that it makes a pattern in the canvas”Fractals & Recursive Structures
Fractals use recursive functions or iterative processes to reveal self-similar patterns across multiple scales. Techniques like L-systems (Lindenmayer systems), the Mandelbrot set, or tree recursion create visually infinite layers of detail and demonstrate how simple equations can generate hypnotically complex imagery.
prompt: “Generate a p5.js fractal tree sketch that uses recursion to draw multiple branches from each node, with sliders to control branch angle and depth.”Cellular Automata
A grid-based system where each cell transitions between states based on rules involving its neighbors. Conway’s Game of Life is the classic example, showing how seemingly complex organisms can arise from straightforward conditions. Artists extend these concepts to create evolving abstract patterns and even interactive art pieces.
prompt: “Create a p5.js version of Conway’s Game of Life with a grid of 50×50 cells, using random initialization, and animate each generation.”Data Visualization & Sonification
Turning data sets into visual or auditory experiences. This can range from straightforward charts to immersive representations where color, position, shape, or sound encodes underlying information. It blends aesthetic sensibilities with analytical rigor to offer deeper insights into complex data.
prompt: “Create a p5.js data visualization of US debt over 50 years.”Generative Art In-Class Exercise
Play with the advanced techniques above. You can use or alter the sample prompts to get started.
P5.js Advanced Methods for Generative Art
Shape & Path Manipulation
- beginShape() / endShape(): Start and finish a custom shape. beginShape(), endShape()
- vertex(x, y): Define a point in a custom shape. vertex()
- curveVertex(x, y): Creates smooth curves. curveVertex()
- bezierVertex(): Adds Bézier control points. bezierVertex()
Color & Style
- lerpColor(c1, c2, amt): Blend two colors by a value between 0 and 1.
- colorMode(mode, ...): Switch between RGB, HSB, etc.
- blendMode(mode): Set how shapes blend (e.g., ADD, MULTIPLY).
Math & Vectors
- random(min, max): Random float in range.
- map(val, inMin, inMax, outMin, outMax): Map a value to another range.
- dist(x1, y1, x2, y2): Distance between points.
- p5.Vector: Class for vector math.
Transformations
- push() / pop(): Save and restore drawing style and transforms.
- translate(x, y): Move origin to new location.
- rotate(angle): Rotate the drawing context.
- scale(s): Scale the drawing context.
Math & Noise
- noise(x, [y], [z]): Perlin noise (smooth randomness).
- lerp(start, stop, amt): Linearly interpolate between values.
- constrain(val, min, max): Restrict value within a range.
Pixels & Image
- loadPixels() / updatePixels(): Directly access and modify canvas pixels.
- get(x, y): Reads pixel color at position.
- set(x, y, color): Sets pixel at position.