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

math-vectors.mddocs/

Math & Vector Operations

Mathematical functions, trigonometry, random number generation, noise functions, and the comprehensive p5.Vector class for position, velocity, and acceleration calculations in 2D and 3D space.

Capabilities

Basic Mathematical Functions

Core mathematical operations and utilities.

/**
 * Calculate absolute value
 * @param {number} n - Input number
 * @returns {number} Absolute value
 */
function abs(n);

/**
 * Round up to nearest integer
 * @param {number} n - Input number
 * @returns {number} Ceiling value
 */
function ceil(n);

/**
 * Round down to nearest integer
 * @param {number} n - Input number
 * @returns {number} Floor value
 */
function floor(n);

/**
 * Round to nearest integer or specified decimal places
 * @param {number} n - Input number
 * @param {number} [decimals] - Number of decimal places
 * @returns {number} Rounded value
 */
function round(n, decimals);

/**
 * Calculate maximum value
 * @param {...number} args - Numbers to compare
 * @returns {number} Maximum value
 */
function max(...args);

/**
 * Calculate minimum value
 * @param {...number} args - Numbers to compare
 * @returns {number} Minimum value
 */
function min(...args);

/**
 * Constrain a value to a range
 * @param {number} n - Value to constrain
 * @param {number} low - Lower bound
 * @param {number} high - Upper bound
 * @returns {number} Constrained value
 */
function constrain(n, low, high);

/**
 * Calculate distance between two points
 * @param {number} x1 - X coordinate of first point
 * @param {number} y1 - Y coordinate of first point
 * @param {number} x2 - X coordinate of second point
 * @param {number} y2 - Y coordinate of second point
 * @returns {number} Distance between points
 */
function dist(x1, y1, x2, y2);

/**
 * Calculate magnitude of a vector
 * @param {number} a - X or first component
 * @param {number} b - Y or second component
 * @returns {number} Magnitude
 */
function mag(a, b);

/**
 * Square a number
 * @param {number} n - Input number
 * @returns {number} Square of input
 */
function sq(n);

/**
 * Calculate square root
 * @param {number} n - Input number
 * @returns {number} Square root
 */
function sqrt(n);

/**
 * Calculate power (exponentiation)
 * @param {number} n - Base number
 * @param {number} e - Exponent
 * @returns {number} n raised to power e
 */
function pow(n, e);

/**
 * Calculate natural exponential
 * @param {number} n - Input number
 * @returns {number} e raised to power n
 */
function exp(n);

/**
 * Calculate natural logarithm
 * @param {number} n - Input number
 * @returns {number} Natural log of n
 */
function log(n);

Interpolation and Mapping

Functions for value interpolation and range mapping.

/**
 * Linear interpolation between two values
 * @param {number} start - Start value
 * @param {number} stop - End value
 * @param {number} amt - Interpolation amount (0-1)
 * @returns {number} Interpolated value
 */
function lerp(start, stop, amt);

/**
 * Re-map a number from one range to another
 * @param {number} value - Input value
 * @param {number} start1 - Lower bound of input range
 * @param {number} stop1 - Upper bound of input range
 * @param {number} start2 - Lower bound of output range
 * @param {number} stop2 - Upper bound of output range
 * @param {boolean} [withinBounds] - Constrain result to output range
 * @returns {number} Mapped value
 */
function map(value, start1, stop1, start2, stop2, withinBounds);

/**
 * Normalize a value to 0-1 range
 * @param {number} value - Input value
 * @param {number} start - Lower bound of input range
 * @param {number} stop - Upper bound of input range
 * @returns {number} Normalized value (0-1)
 */
function norm(value, start, stop);

Trigonometric Functions

Complete trigonometry functions with angle mode control.

/**
 * Calculate sine
 * @param {number} angle - Angle in current angle mode
 * @returns {number} Sine value
 */
function sin(angle);

/**
 * Calculate cosine
 * @param {number} angle - Angle in current angle mode
 * @returns {number} Cosine value
 */
function cos(angle);

/**
 * Calculate tangent
 * @param {number} angle - Angle in current angle mode
 * @returns {number} Tangent value
 */
function tan(angle);

/**
 * Calculate arcsine
 * @param {number} value - Input value (-1 to 1)
 * @returns {number} Arcsine in current angle mode
 */
function asin(value);

/**
 * Calculate arccosine
 * @param {number} value - Input value (-1 to 1)
 * @returns {number} Arccosine in current angle mode
 */
function acos(value);

/**
 * Calculate arctangent
 * @param {number} value - Input value
 * @returns {number} Arctangent in current angle mode
 */
function atan(value);

/**
 * Calculate two-argument arctangent
 * @param {number} y - Y component
 * @param {number} x - X component
 * @returns {number} Angle from positive x-axis to point (x,y)
 */
function atan2(y, x);

/**
 * Set the angle interpretation mode
 * @param {string} mode - RADIANS or DEGREES
 */
function angleMode(mode);

/**
 * Convert degrees to radians
 * @param {number} degrees - Angle in degrees
 * @returns {number} Angle in radians
 */
function radians(degrees);

/**
 * Convert radians to degrees
 * @param {number} radians - Angle in radians
 * @returns {number} Angle in degrees
 */
function degrees(radians);

Random Number Generation

Functions for generating random numbers and controlling randomness.

/**
 * Generate random number in range
 * @param {number} [min] - Lower bound (or upper bound if max not specified)
 * @param {number} [max] - Upper bound
 * @returns {number} Random number
 */
function random(min, max);

/**
 * Generate random number from Gaussian distribution
 * @param {number} [mean=0] - Mean of distribution
 * @param {number} [sd=1] - Standard deviation
 * @returns {number} Random number from Gaussian distribution
 */
function randomGaussian(mean, sd);

/**
 * Set the seed for random number generation
 * @param {number} seed - Seed value
 */
function randomSeed(seed);

Noise Functions

Perlin noise functions for smooth, natural-looking randomness.

/**
 * Generate Perlin noise value
 * @param {number} x - X coordinate in noise space
 * @param {number} [y] - Y coordinate in noise space
 * @param {number} [z] - Z coordinate in noise space
 * @returns {number} Noise value (0-1)
 */
function noise(x, y, z);

/**
 * Set the detail level of noise
 * @param {number} lod - Level of detail (octaves)
 * @param {number} falloff - Falloff for each octave
 */
function noiseDetail(lod, falloff);

/**
 * Set the seed for noise generation
 * @param {number} seed - Seed value
 */
function noiseSeed(seed);

p5.Vector Class

Comprehensive 2D/3D vector class for position, velocity, and acceleration calculations.

/**
 * 2D/3D vector class
 */
class p5.Vector {
  /**
   * Create a new vector
   * @param {number} [x=0] - X component
   * @param {number} [y=0] - Y component
   * @param {number} [z=0] - Z component
   */
  constructor(x, y, z);
  
  /** X component */
  x;
  /** Y component */
  y;
  /** Z component */
  z;

  /**
   * Set vector components
   * @param {number|p5.Vector} [x] - X component or vector to copy
   * @param {number} [y] - Y component
   * @param {number} [z] - Z component
   * @returns {p5.Vector} This vector for chaining
   */
  set(x, y, z);

  /**
   * Create a copy of this vector
   * @returns {p5.Vector} New vector copy
   */
  copy();

  /**
   * Add to this vector
   * @param {number|p5.Vector} x - X component or vector to add
   * @param {number} [y] - Y component
   * @param {number} [z] - Z component
   * @returns {p5.Vector} This vector for chaining
   */
  add(x, y, z);

  /**
   * Subtract from this vector
   * @param {number|p5.Vector} x - X component or vector to subtract
   * @param {number} [y] - Y component
   * @param {number} [z] - Z component
   * @returns {p5.Vector} This vector for chaining
   */
  sub(x, y, z);

  /**
   * Multiply vector by scalar
   * @param {number} scalar - Multiplier
   * @returns {p5.Vector} This vector for chaining
   */
  mult(scalar);

  /**
   * Divide vector by scalar
   * @param {number} scalar - Divisor
   * @returns {p5.Vector} This vector for chaining
   */
  div(scalar);

  /**
   * Modulo operation on vector components
   * @param {number|p5.Vector} x - X divisor or vector
   * @param {number} [y] - Y divisor
   * @param {number} [z] - Z divisor
   * @returns {p5.Vector} This vector for chaining
   */
  rem(x, y, z);

  /**
   * Calculate magnitude (length) of vector
   * @returns {number} Magnitude
   */
  mag();

  /**
   * Calculate magnitude squared (faster than mag())
   * @returns {number} Magnitude squared
   */
  magSq();

  /**
   * Calculate dot product with another vector
   * @param {p5.Vector} v - Other vector
   * @returns {number} Dot product
   */
  dot(v);

  /**
   * Calculate cross product with another vector
   * @param {p5.Vector} v - Other vector
   * @returns {p5.Vector} Cross product vector
   */
  cross(v);

  /**
   * Calculate distance to another vector
   * @param {p5.Vector} v - Other vector
   * @returns {number} Distance
   */
  dist(v);

  /**
   * Normalize vector to unit length (magnitude 1)
   * @returns {p5.Vector} This vector for chaining
   */
  normalize();

  /**
   * Limit magnitude to maximum value
   * @param {number} max - Maximum magnitude
   * @returns {p5.Vector} This vector for chaining
   */
  limit(max);

  /**
   * Set magnitude to specific value
   * @param {number} n - New magnitude
   * @returns {p5.Vector} This vector for chaining
   */
  setMag(n);

  /**
   * Calculate 2D heading angle
   * @returns {number} Angle in radians
   */
  heading();

  /**
   * Set 2D heading angle
   * @param {number} angle - Angle in radians
   * @returns {p5.Vector} This vector for chaining
   */
  setHeading(angle);

  /**
   * Rotate vector by angle
   * @param {number} angle - Rotation angle in radians
   * @returns {p5.Vector} This vector for chaining
   */
  rotate(angle);

  /**
   * Calculate angle between this and another vector
   * @param {p5.Vector} v - Other vector
   * @returns {number} Angle in radians
   */
  angleBetween(v);

  /**
   * Linear interpolation toward another vector
   * @param {p5.Vector} v - Target vector
   * @param {number} amt - Interpolation amount (0-1)
   * @returns {p5.Vector} This vector for chaining
   */
  lerp(v, amt);

  /**
   * Spherical linear interpolation toward another vector
   * @param {p5.Vector} v - Target vector
   * @param {number} amt - Interpolation amount (0-1)
   * @returns {p5.Vector} This vector for chaining
   */
  slerp(v, amt);

  /**
   * Reflect vector off surface with given normal
   * @param {p5.Vector} normal - Surface normal vector
   * @returns {p5.Vector} This vector for chaining
   */
  reflect(normal);

  /**
   * Convert vector to array
   * @returns {number[]} Array of [x, y, z] components
   */
  array();

  /**
   * Test equality with another vector
   * @param {p5.Vector} v - Other vector
   * @returns {boolean} True if vectors are equal
   */
  equals(v);

  /**
   * String representation
   * @returns {string} String format: "x: 1, y: 2, z: 3"
   */
  toString();

  // Static methods
  /**
   * Create vector from angle and length
   * @param {number} angle - Angle in radians
   * @param {number} [length=1] - Vector length
   * @returns {p5.Vector} New vector
   */
  static fromAngle(angle, length);

  /**
   * Create 3D vector from spherical angles
   * @param {number} theta - Azimuthal angle
   * @param {number} phi - Polar angle
   * @param {number} [length=1] - Vector length
   * @returns {p5.Vector} New vector
   */
  static fromAngles(theta, phi, length);

  /**
   * Create random 2D unit vector
   * @returns {p5.Vector} Random 2D unit vector
   */
  static random2D();

  /**
   * Create random 3D unit vector
   * @returns {p5.Vector} Random 3D unit vector
   */
  static random3D();

  // All instance methods are also available as static methods
  // that take vectors as arguments and return new vectors
}

Constants

// Mathematical constants
const PI = Math.PI;
const HALF_PI = Math.PI / 2;
const QUARTER_PI = Math.PI / 4;
const TWO_PI = Math.PI * 2;
const TAU = Math.PI * 2;

// Angle mode constants
const RADIANS = 'radians';
const DEGREES = 'degrees';

Usage Examples

Basic Math Operations:

function setup() {
  createCanvas(400, 300);
  
  let values = [12.7, 8.3, 15.9, 4.1, 11.2];
  
  let sum = values.reduce((a, b) => a + b);
  let average = sum / values.length;
  let maxVal = max(...values);
  let minVal = min(...values);
  
  console.log(`Sum: ${sum}`);
  console.log(`Average: ${average.toFixed(2)}`);
  console.log(`Max: ${maxVal}, Min: ${minVal}`);
  console.log(`Distance from origin to (3,4): ${dist(0, 0, 3, 4)}`);
}

Value Mapping and Interpolation:

function draw() {
  background(220);
  
  // Map mouse position to circle size
  let size = map(mouseX, 0, width, 20, 200);
  
  // Map mouse Y to color
  let grayValue = map(mouseY, 0, height, 0, 255);
  
  fill(grayValue);
  circle(width/2, height/2, size);
  
  // Lerp between two positions
  let targetX = mouseX;
  let currentX = lerp(width/4, targetX, 0.05);
  
  fill('red');
  circle(currentX, height/4, 30);
}

Trigonometry Example:

function draw() {
  background(220);
  translate(width/2, height/2);
  
  // Create a sine wave
  stroke('blue');
  strokeWeight(2);
  noFill();
  
  beginShape();
  for (let x = -width/2; x < width/2; x += 5) {
    let angle = map(x, -width/2, width/2, 0, TWO_PI * 2);
    let y = sin(angle + frameCount * 0.02) * 50;
    vertex(x, y);
  }
  endShape();
  
  // Rotating line using cos and sin
  let angle = frameCount * 0.02;
  let x = cos(angle) * 80;
  let y = sin(angle) * 80;
  
  stroke('red');
  strokeWeight(3);
  line(0, 0, x, y);
}

Vector Physics Simulation:

let position, velocity, acceleration;

function setup() {
  createCanvas(400, 300);
  
  position = createVector(width/2, height/2);
  velocity = createVector(0, 0);
  acceleration = createVector(0, 0);
}

function draw() {
  background(220);
  
  // Calculate acceleration toward mouse
  let mouse = createVector(mouseX, mouseY);
  acceleration = p5.Vector.sub(mouse, position);
  acceleration.normalize();
  acceleration.mult(0.2);
  
  // Update physics
  velocity.add(acceleration);
  velocity.limit(5); // Limit max speed
  position.add(velocity);
  
  // Bounce off edges
  if (position.x < 0 || position.x > width) velocity.x *= -1;
  if (position.y < 0 || position.y > height) velocity.y *= -1;
  
  // Keep position in bounds
  position.x = constrain(position.x, 0, width);
  position.y = constrain(position.y, 0, height);
  
  // Draw
  fill('red');
  circle(position.x, position.y, 30);
  
  // Show velocity vector
  stroke('blue');
  let vel = p5.Vector.mult(velocity, 10);
  line(position.x, position.y, position.x + vel.x, position.y + vel.y);
}

Noise-based Animation:

let noiseOffset = 0;

function draw() {
  background(220);
  
  // Create organic movement using noise
  for (let x = 0; x < width; x += 20) {
    for (let y = 0; y < height; y += 20) {
      let noiseValue = noise(x * 0.01, y * 0.01, noiseOffset);
      let size = map(noiseValue, 0, 1, 5, 25);
      let gray = map(noiseValue, 0, 1, 100, 255);
      
      fill(gray);
      circle(x, y, size);
    }
  }
  
  noiseOffset += 0.01;
}

Vector Field Visualization:

function draw() {
  background(240);
  
  // Draw vector field
  for (let x = 20; x < width; x += 30) {
    for (let y = 20; y < height; y += 30) {
      // Create vector based on position
      let angle = atan2(y - height/2, x - width/2);
      let magnitude = map(dist(x, y, width/2, height/2), 0, 200, 0, 20);
      
      let vector = p5.Vector.fromAngle(angle, magnitude);
      
      // Draw vector as line
      stroke(0, 100);
      strokeWeight(1);
      line(x, y, x + vector.x, y + vector.y);
      
      // Draw arrowhead
      push();
      translate(x + vector.x, y + vector.y);
      rotate(vector.heading());
      stroke(0, 150);
      line(0, 0, -5, -2);
      line(0, 0, -5, 2);
      pop();
    }
  }
}

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