or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

color-system.mdcore-structure.mddom-manipulation.mddrawing-shapes.mdevents-input.mdimage-processing.mdindex.mdio-data.mdmath-vectors.mdtransforms.mdtypography.mdutilities.mdwebgl-3d.md
tile.json

tessl/npm-p5

A free and open-source JavaScript library for accessible creative coding

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/p5@1.11.x

To install, run

npx @tessl/cli install tessl/npm-p5@1.11.0

index.mddocs/

p5.js

p5.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.

Package Information

  • Package Name: p5
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install p5

Core Imports

ES 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>

Basic Usage

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);

Architecture

p5.js is built around several key architectural patterns:

  • Sketch Lifecycle: Three main functions (preload(), setup(), draw()) control execution flow
  • Global vs Instance Mode: Functions can be available globally or bound to a p5 instance
  • Rendering System: Unified API that works with 2D canvas, WebGL, and off-screen graphics
  • Event System: Comprehensive mouse, keyboard, touch, and device motion event handling
  • Vector Math: Complete 2D/3D vector operations through p5.Vector class
  • Color System: Flexible color representation supporting RGB, HSB, HSL color spaces

Capabilities

Core Structure & Environment

Essential 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 position

Core Structure & Environment

2D Drawing & Shapes

Complete 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 */ }

2D Drawing & Shapes

Color System

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 */ }

Color System

Math & Vector Operations

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 */ }

Math & Vector Operations

Transform System

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 */ }

Transform System

Event Handling & Input

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 points

Event Handling & Input

Image Processing

Image 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 */ }

Image Processing

I/O & Data Loading

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 */ }

I/O & Data Loading

Typography

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 */
}

Typography

DOM Manipulation

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 */
}

DOM Manipulation

WebGL & 3D Graphics

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 */ }

WebGL & 3D Graphics

Utility Functions

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 */ }

Utility Functions

Types

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
}