CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-p5

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

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

core-structure.mddocs/

Core Structure & Environment

Essential sketch lifecycle functions, canvas creation, environment control, and system variables that form the foundation of every p5.js application.

Capabilities

Sketch Lifecycle

The three main functions that control p5.js sketch execution flow.

/**
 * Called once to load assets before the sketch runs
 * Functions like loadImage(), loadFont(), etc. called here will block setup()
 * until they complete loading
 */
function preload() {}

/**
 * Called once when the sketch begins running
 * Used to perform setup tasks like creating canvas and initializing variables
 */
function setup() {}

/**
 * Called repeatedly while the sketch runs (draw loop)
 * Default attempts 60 fps, can be controlled with frameRate()
 */
function draw() {}

Draw Loop Control

Functions to control sketch execution and animation loop.

/**
 * Stops the draw loop - draw() will no longer be called
 */
function noLoop();

/**
 * Resumes the draw loop after noLoop() was called
 */
function loop();

/**
 * Returns whether the draw loop is currently active
 * @returns {boolean} True if draw() is being called repeatedly
 */
function isLooping();

/**
 * Executes draw() n times (default 1) even when not looping
 * @param {number} [n=1] - Number of times to call draw()
 */
function redraw(n);

Canvas Creation & Management

Functions for creating and managing the main drawing canvas and off-screen graphics.

/**
 * Creates the main drawing canvas
 * @param {number} w - Width in pixels
 * @param {number} h - Height in pixels  
 * @param {string} [renderer] - P2D (default) or WEBGL for 3D
 * @param {HTMLCanvasElement} [canvas] - Existing canvas element to use
 */
function createCanvas(w, h, renderer, canvas);

/**
 * Resizes the canvas dimensions
 * @param {number} w - New width in pixels
 * @param {number} h - New height in pixels
 * @param {boolean} [noRedraw=false] - If true, don't redraw after resize
 */
function resizeCanvas(w, h, noRedraw);

/**
 * Removes the default canvas (for DOM-only sketches)
 */
function noCanvas();

/**
 * Creates an off-screen graphics buffer with same API as main canvas
 * @param {number} w - Width in pixels
 * @param {number} h - Height in pixels
 * @param {string} [renderer] - P2D (default) or WEBGL
 * @param {HTMLCanvasElement} [canvas] - Existing canvas element
 * @returns {p5.Graphics} Graphics buffer object
 */
function createGraphics(w, h, renderer, canvas);

/**
 * Creates a WebGL framebuffer for off-screen rendering
 * @param {object} [options] - Framebuffer options
 * @returns {p5.Framebuffer} Framebuffer object
 */
function createFramebuffer(options);

Transform State Management

Functions to save and restore drawing states including transforms and styles.

/**
 * Saves current drawing state (transforms, fill, stroke, etc.)
 * Must be paired with pop()
 */
function push();

/**
 * Restores previous drawing state saved with push()
 */
function pop();

System Variables

Key variables that provide information about the sketch state and dimensions.

/**
 * Number of frames since the sketch started
 * Increments by 1 each time draw() is called
 * @type {number}
 */
var frameCount;

/**
 * Time in milliseconds for the last frame
 * Useful for frame-rate independent animation
 * @type {number}
 */
var deltaTime;

/**
 * Current width of the canvas in pixels
 * @type {number}
 */
var width;

/**
 * Current height of the canvas in pixels  
 * @type {number}
 */
var height;

/**
 * Whether the browser window currently has focus
 * @type {boolean}
 */
var focused;

Environment Information

Variables and functions for accessing browser and device information.

/**
 * Browser viewport width in pixels
 * @type {number}
 */
var windowWidth;

/**
 * Browser viewport height in pixels
 * @type {number}
 */
var windowHeight;

/**
 * Screen resolution width in pixels
 * @type {number}
 */
var displayWidth;

/**
 * Screen resolution height in pixels
 * @type {number}
 */
var displayHeight;

/**
 * Current WebGL version being used ('webgl' or 'webgl2')
 * Only set when using WEBGL renderer
 * @type {string}
 */
var webglVersion;

Environment Control Functions

Functions for controlling frame rate, display settings, and getting page information.

/**
 * Set target frame rate or get current frame rate
 * @param {number} [fps] - Target frames per second (default 60)
 * @returns {number} Current frame rate when called without arguments
 */
function frameRate(fps);

/**
 * Set/get pixel density for high DPI displays
 * @param {number} [density] - Pixel density multiplier
 * @returns {number} Current pixel density when called without arguments
 */
function pixelDensity(density);

/**
 * Enter/exit fullscreen mode or get fullscreen state
 * @param {boolean} [val] - True to enter fullscreen, false to exit
 * @returns {boolean} Current fullscreen state when called without arguments
 */
function fullscreen(val);

/**
 * Get the current page URL
 * @returns {string} Current page URL
 */
function getURL();

/**
 * Get URL path as an array of strings
 * @returns {string[]} Array of path segments
 */
function getURLPath();

/**
 * Get URL parameters as an object
 * @returns {object} Object with parameter names as keys
 */
function getURLParams();

Rendering Control

Functions for controlling rendering behavior and accessing the graphics context.

/**
 * Set the pixel blending mode for drawing operations
 * @param {string} mode - Blend mode (BLEND, ADD, MULTIPLY, etc.)
 */
function blendMode(mode);

/**
 * Clear the WebGL depth buffer to specified depth
 * @param {number} [depth=1] - Depth value to clear to (0-1)
 */
function clearDepth(depth);

/**
 * Direct access to the canvas 2D context or WebGL context
 * @type {CanvasRenderingContext2D|WebGLRenderingContext}
 */
var drawingContext;

Cursor Control

Functions for controlling the mouse cursor appearance.

/**
 * Set the cursor appearance
 * @param {string} type - Cursor type (ARROW, CROSS, HAND, MOVE, TEXT, WAIT)
 * @param {number} [x] - Horizontal offset for custom cursor
 * @param {number} [y] - Vertical offset for custom cursor
 */
function cursor(type, x, y);

/**
 * Hide the mouse cursor
 */
function noCursor();

Console Output

Enhanced console output function.

/**
 * Output to console (enhanced console.log)
 * @param {...*} args - Values to print
 */
function print(...args);

Sketch Removal

Function to completely remove the sketch from the page.

/**
 * Removes the sketch from the web page
 * Stops draw loop and removes all HTML elements created by the sketch
 */
function remove();

Usage Examples

Basic Sketch Structure:

let counter = 0;

function setup() {
  createCanvas(400, 300);
  frameRate(30); // Set to 30 fps
}

function draw() {
  background(220);
  
  // Frame-rate independent animation
  counter += deltaTime * 0.001; // Increment by seconds
  
  circle(200 + sin(counter) * 100, 150, 50);
  
  // Display frame info
  text(`Frame: ${frameCount}`, 10, 20);
  text(`FPS: ${frameRate().toFixed(1)}`, 10, 40);
}

State Management with Push/Pop:

function draw() {
  background(220);
  
  // Draw in normal coordinate system
  fill('red');
  rect(10, 10, 50, 50);
  
  push(); // Save current state
  translate(100, 100);
  rotate(PI / 4);
  fill('blue');
  rect(0, 0, 50, 50); // This rectangle is rotated
  pop(); // Restore state
  
  // Back to normal coordinate system
  fill('green');
  rect(200, 10, 50, 50);
}

Off-screen Graphics:

let buffer;

function setup() {
  createCanvas(400, 300);
  buffer = createGraphics(200, 200);
}

function draw() {
  // Draw to off-screen buffer
  buffer.background(100);
  buffer.fill('yellow');
  buffer.circle(mouseX * 0.5, mouseY * 0.5, 50);
  
  // Display buffer on main canvas
  background(220);
  image(buffer, 0, 0);
  image(buffer, 200, 0); // Show twice
}

Install with Tessl CLI

npx tessl i tessl/npm-p5

docs

color-system.md

core-structure.md

dom-manipulation.md

drawing-shapes.md

events-input.md

image-processing.md

index.md

io-data.md

math-vectors.md

transforms.md

typography.md

utilities.md

webgl-3d.md

tile.json