A free and open-source JavaScript library for accessible creative coding
npx @tessl/cli install tessl/npm-p5@1.11.0p5.js is a comprehensive JavaScript creative coding library that provides a complete toolkit for interactive web-based art, visualizations, and multimedia experiences. Built as an accessible alternative to the Processing programming language, it offers drawing functionalities, canvas management, interaction handling, animation capabilities, and multimedia support through an intuitive API that emphasizes creative expression and exploratory programming.
npm install p5ES Modules:
import p5 from 'p5';CommonJS:
const p5 = require('p5');For global mode (browser):
<script src="https://cdn.jsdelivr.net/npm/p5@1.11.10/lib/p5.min.js"></script>Global Mode (Browser):
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
circle(mouseX, mouseY, 80);
}Instance Mode:
import p5 from 'p5';
const sketch = (p) => {
p.setup = () => {
p.createCanvas(400, 400);
};
p.draw = () => {
p.background(220);
p.circle(p.mouseX, p.mouseY, 80);
};
};
new p5(sketch);p5.js is built around several key architectural patterns:
preload(), setup(), draw()) control execution flowEssential sketch lifecycle functions, canvas creation, and environment control. This forms the foundation of every p5.js application.
function preload() { /* Called once to load assets before sketch runs */ }
function setup() { /* Called once when sketch begins running */ }
function draw() { /* Called repeatedly while sketch runs */ }
function createCanvas(w, h, renderer) { /* Create main drawing canvas */ }
function background(...args) { /* Set background color */ }
// Environment variables
frameCount; // Number of frames since sketch started
width, height; // Canvas dimensions
mouseX, mouseY; // Current mouse positionComplete 2D drawing capabilities including primitives, curves, custom shapes, and drawing attributes.
function circle(x, y, diameter) { /* Draw circle */ }
function rect(x, y, w, h, tl, tr, br, bl) { /* Draw rectangle */ }
function line(x1, y1, x2, y2) { /* Draw line */ }
function bezier(x1, y1, x2, y2, x3, y3, x4, y4) { /* Draw Bezier curve */ }
function fill(...args) { /* Set fill color */ }
function stroke(...args) { /* Set stroke color */ }
function strokeWeight(weight) { /* Set stroke thickness */ }Comprehensive color handling with multiple color spaces, color manipulation, and advanced features like blending modes.
function color(...args) { /* Create p5.Color object */ }
function colorMode(mode, max1, max2, max3, maxA) { /* Set color interpretation mode */ }
function lerpColor(c1, c2, amt) { /* Interpolate between colors */ }
// Color extraction
function red(color) { /* Extract red component */ }
function green(color) { /* Extract green component */ }
function blue(color) { /* Extract blue component */ }
function alpha(color) { /* Extract alpha component */ }Mathematical functions, trigonometry, random number generation, noise, and the comprehensive p5.Vector class for position/velocity calculations.
class p5.Vector {
constructor(x, y, z) { /* Create vector */ }
add(x, y, z) { /* Add to vector */ }
mult(scalar) { /* Multiply by scalar */ }
mag() { /* Calculate magnitude */ }
normalize() { /* Normalize to unit length */ }
static random2D() { /* Random 2D unit vector */ }
static fromAngle(angle, length) { /* Create from angle */ }
}
function random(min, max) { /* Generate random number */ }
function noise(x, y, z) { /* Perlin noise value */ }
function map(value, start1, stop1, start2, stop2) { /* Re-map number range */ }Coordinate transformations including translation, rotation, scaling, and matrix operations for advanced graphics.
function translate(x, y, z) { /* Translate coordinate system */ }
function rotate(angle) { /* Rotate coordinate system */ }
function scale(s, y, z) { /* Scale coordinate system */ }
function push() { /* Save current transform state */ }
function pop() { /* Restore previous transform state */ }Complete event system for mouse, keyboard, touch, and device motion interactions with both callback functions and polling.
// Event callback functions
function mousePressed() { /* Called when mouse button pressed */ }
function keyPressed() { /* Called when key pressed */ }
function touchStarted() { /* Called when touch begins */ }
// Input state variables
mouseX, mouseY; // Current mouse position
mouseButton; // Current pressed button (LEFT, RIGHT, CENTER)
key; // Most recently pressed key
keyCode; // Numeric code of pressed key
touches; // Array of current touch pointsImage loading, display, manipulation, filtering, and pixel-level operations for creative image effects.
function loadImage(path, successCallback, failureCallback) { /* Load image */ }
function image(img, x, y, width, height) { /* Display image */ }
function tint(...args) { /* Apply color tint to images */ }
function filter(filterType, filterParam) { /* Apply filter to canvas */ }
function get(x, y, w, h) { /* Get pixel/region from canvas */ }
function set(x, y, color) { /* Set pixel color */ }
function loadPixels() { /* Load pixel array for manipulation */ }
function updatePixels() { /* Update canvas from pixel array */ }File loading capabilities for JSON, XML, images, fonts, and other assets, plus data export functionality.
function loadJSON(path, callback, errorCallback) { /* Load JSON data */ }
function loadStrings(filename, callback) { /* Load text file as array */ }
function loadTable(filename, options, callback) { /* Load CSV/TSV data */ }
function loadFont(path, callback) { /* Load font file */ }
function save(objectOrFilename, filename) { /* Save data to file */ }
function saveCanvas(filename, extension) { /* Save canvas as image */ }Text rendering, font loading, text measurement, and typography control for creative text applications.
function text(str, x, y, x2, y2) { /* Draw text to canvas */ }
function textFont(font, size) { /* Set text font */ }
function textSize(size) { /* Set text size */ }
function textAlign(horizAlign, vertAlign) { /* Set text alignment */ }
function textWidth(str) { /* Calculate text width */ }
class p5.Font {
/* Font object with glyph and measurement capabilities */
}Create and control HTML elements, form inputs, and integrate p5.js with web page DOM for interactive applications.
function select(selector, container) { /* Select DOM element */ }
function createElement(tag, content) { /* Create generic element */ }
function createButton(label, value) { /* Create button element */ }
function createSlider(min, max, value, step) { /* Create range slider */ }
function createInput(value, type) { /* Create text input */ }
class p5.Element {
/* DOM element wrapper with p5-specific methods */
}Complete 3D graphics system with primitives, lighting, materials, shaders, cameras, and advanced WebGL features.
function createCanvas(w, h, WEBGL) { /* Create 3D canvas */ }
function box(width, height, depth) { /* Draw 3D box */ }
function sphere(radius, detailX, detailY) { /* Draw sphere */ }
function ambientLight(...args) { /* Create ambient light */ }
function directionalLight(...args) { /* Create directional light */ }
function ambientMaterial(...args) { /* Set ambient material */ }
class p5.Camera { /* 3D camera control */ }
class p5.Shader { /* GLSL shader program wrapper */ }Helpful utility functions for array manipulation, string processing, data conversion, and time/date operations.
function shuffle(array) { /* Randomize array order */ }
function sort(list, count) { /* Sort array */ }
function join(list, separator) { /* Join array into string */ }
function split(value, delim) { /* Split string into array */ }
function int(str, base) { /* Convert to integer */ }
function float(str) { /* Convert to float */ }
function str(n) { /* Convert to string */ }
function millis() { /* Milliseconds since sketch start */ }
function year() { /* Current year */ }class p5 {
constructor(sketch, node);
remove();
}
class p5.Color {
/* Color representation with RGB, HSB, HSL support */
}
class p5.Image {
width, height; // Image dimensions
pixels; // Pixel array
/* Image manipulation methods */
}
class p5.Graphics {
/* Off-screen graphics buffer with same API as main canvas */
}
class p5.StringDict {
/* Dictionary for storing string key-value pairs */
constructor(key, value);
size(); // Number of key-value pairs
hasKey(key); // Check if key exists
get(key); // Get value for key
set(key, value); // Set value for key
create(key, value); // Create new key-value pair
clear(); // Remove all pairs
remove(key); // Remove specific pair
print(); // Log all pairs to console
saveTable(filename); // Save as CSV file
saveJSON(filename); // Save as JSON file
}
class p5.NumberDict {
/* Dictionary for storing number key-value pairs with mathematical operations */
constructor(key, value);
size(); // Number of key-value pairs
hasKey(key); // Check if key exists
get(key); // Get value for key
set(key, value); // Set value for key
create(key, value); // Create new key-value pair
clear(); // Remove all pairs
remove(key); // Remove specific pair
print(); // Log all pairs to console
saveTable(filename); // Save as CSV file
saveJSON(filename); // Save as JSON file
add(key, amount); // Add to value at key
sub(key, amount); // Subtract from value at key
mult(key, amount); // Multiply value at key
div(key, amount); // Divide value at key
minValue(); // Find minimum value
maxValue(); // Find maximum value
minKey(); // Find minimum key
maxKey(); // Find maximum key
}