p5compat

This module provides compatibility with p5js. Use Include('p5'); on the first line of your script to activate.

Methods

static colorMode()

ignored

static createCanvas()

ignored

static exit()

exit the script after the current Loop().

static imageMode()

ignored

static noSmooth()

ignored

static noTint()

ignored

static settings()

ignored

static size()

ignored

static smooth()

ignored

static strokeWeight()

ignored

static tint()

ignored

inner abs(n) → {Number}

Calculates the absolute value (magnitude) of a number. Maps to Math.abs(). The absolute value of a number is always positive.
Parameters:
Name Type Description
n Number number to compute
Returns:
Number - absolute value of given number
Example
function setup() {
  let x = -3;
  let y = abs(x);

  print(x); // -3
  print(y); // 3
}

inner acos(value) → {Number}

The inverse of cos(), returns the arc cosine of a value. This function expects the values in the range of -1 to 1 and values are returned in the range 0 to PI (3.1415927).
Parameters:
Name Type Description
value Number the value whose arc cosine is to be returned
Returns:
Number - the arc cosine of the given value
Example
let a = PI;
let c = cos(a);
let ac = acos(c);
// Prints: "3.1415927 : -1.0 : 3.1415927"
print(a + ' : ' + c + ' : ' + ac);

let a = PI + PI / 4.0;
let c = cos(a);
let ac = acos(c);
// Prints: "3.926991 : -0.70710665 : 2.3561943"
print(a + ' : ' + c + ' : ' + ac);

inner angleMode(mode)

Sets the current mode of p5 to given mode. Default mode is RADIANS.
Parameters:
Name Type Description
mode Constant either RADIANS or DEGREES
Example
function draw() {
  background(204);
  angleMode(DEGREES); // Change the mode to DEGREES
  let a = atan2(mouseY - height / 2, mouseX - width / 2);
  translate(width / 2, height / 2);
  push();
  rotate(a);
  rect(-20, -5, 40, 10); // Larger rectangle is rotating in degrees
  pop();
  angleMode(RADIANS); // Change the mode to RADIANS
  rotate(a); // variable a stays the same
  rect(-40, -5, 20, 10); // Smaller rectangle is rotating in radians
}

inner append(array, value) → {Array}

Adds a value to the end of an array. Extends the length of the array by one. Maps to Array.push().
Parameters:
Name Type Description
array Array Array to append
value any to be added to the Array
Returns:
Array - the array that was appended to
Example
function setup() {
  var myArray = ['Mango', 'Apple', 'Papaya'];
  print(myArray); // ['Mango', 'Apple', 'Papaya']

  append(myArray, 'Peach');
  print(myArray); // ['Mango', 'Apple', 'Papaya', 'Peach']
}

inner arrayCopy(src, srcPosition, dst, dstPosition, length)

Copies an array (or part of an array) to another array. The src array is copied to the dst array, beginning at the position specified by srcPosition and into the position specified by dstPosition. The number of elements to copy is determined by length. Note that copying values overwrites existing values in the destination array. To append values instead of overwriting them, use concat().

The simplified version with only two arguments, arrayCopy(src, dst), copies an entire array to another of the same size. It is equivalent to arrayCopy(src, 0, dst, 0, src.length).

Using this function is far more efficient for copying array data than iterating through a for() loop and copying each element individually.
Parameters:
Name Type Description
src Array the source Array
srcPosition Integer starting position in the source Array
dst Array the destination Array
dstPosition Integer starting position in the destination Array
length Integer number of Array elements to be copied
Deprecated:
  • Yes
Example
var src = ['A', 'B', 'C'];
var dst = [1, 2, 3];
var srcPosition = 1;
var dstPosition = 0;
var length = 2;

print(src); // ['A', 'B', 'C']
print(dst); // [ 1 ,  2 ,  3 ]

arrayCopy(src, srcPosition, dst, dstPosition, length);
print(dst); // ['B', 'C', 3]

inner asin(value) → {Number}

The inverse of sin(), returns the arc sine of a value. This function expects the values in the range of -1 to 1 and values are returned in the range -PI/2 to PI/2.
Parameters:
Name Type Description
value Number the value whose arc sine is to be returned
Returns:
Number - the arc sine of the given value
Example
let a = PI + PI / 3;
let s = sin(a);
let as = asin(s);
// Prints: "1.0471976 : 0.86602545 : 1.0471976"
print(a + ' : ' + s + ' : ' + as);

let a = PI + PI / 3.0;
let s = sin(a);
let as = asin(s);
// Prints: "4.1887903 : -0.86602545 : -1.0471976"
print(a + ' : ' + s + ' : ' + as);

inner atan(value) → {Number}

The inverse of tan(), returns the arc tangent of a value. This function expects the values in the range of -Infinity to Infinity (exclusive) and values are returned in the range -PI/2 to PI/2.
Parameters:
Name Type Description
value Number the value whose arc tangent is to be returned
Returns:
Number - the arc tangent of the given value
Example
let a = PI + PI / 3;
let t = tan(a);
let at = atan(t);
// Prints: "1.0471976 : 1.7320509 : 1.0471976"
print(a + ' : ' + t + ' : ' + at);

let a = PI + PI / 3.0;
let t = tan(a);
let at = atan(t);
// Prints: "4.1887903 : 1.7320513 : 1.0471977"
print(a + ' : ' + t + ' : ' + at);

inner atan2(y, x) → {Number}

Calculates the angle (in radians) from a specified point to the coordinate origin as measured from the positive x-axis. Values are returned as a float in the range from PI to -PI. The atan2() function is most often used for orienting geometry to the position of the cursor.

Note: The y-coordinate of the point is the first parameter, and the x-coordinate is the second parameter, due the the structure of calculating the tangent.
Parameters:
Name Type Description
y Number y-coordinate of the point
x Number x-coordinate of the point
Returns:
Number - the arc tangent of the given point
Example
function draw() {
  background(204);
  translate(width / 2, height / 2);
  let a = atan2(mouseY - height / 2, mouseX - width / 2);
  rotate(a);
  rect(-30, -5, 60, 10);
}

inner boolean(n) → {Boolean}

Converts a number or string to its boolean representation. For a number, any non-zero value (positive or negative) evaluates to true, while zero evaluates to false. For a string, the value "true" evaluates to true, while any other value evaluates to false. When an array of number or string values is passed in, then a array of booleans of the same length is returned.
Parameters:
Name Type Description
n String | Boolean | Number | Array value to parse
Returns:
Boolean - boolean representation of value
Example
print(boolean(0)); // false
print(boolean(1)); // true
print(boolean('true')); // true
print(boolean('abcd')); // false
print(boolean([0, 12, 'true'])); // [false, true, false]

inner byte(n) → {Number}

Converts a number, string representation of a number, or boolean to its byte representation. A byte can be only a whole number between -128 and 127, so when a value outside of this range is converted, it wraps around to the corresponding byte representation. When an array of number, string or boolean values is passed in, then an array of bytes the same length is returned.
Parameters:
Name Type Description
n String | Boolean | Number value to parse
Returns:
Number - byte representation of value
Example
print(byte(127)); // 127
print(byte(128)); // -128
print(byte(23.4)); // 23
print(byte('23.4')); // 23
print(byte('hello')); // NaN
print(byte(true)); // 1
print(byte([0, 255, '100'])); // [0, -1, 100]

inner ceil(n) → {Integer}

Calculates the closest int value that is greater than or equal to the value of the parameter. Maps to Math.ceil(). For example, ceil(9.03) returns the value 10.
Parameters:
Name Type Description
n Number number to round up
Returns:
Integer - rounded up number
Example
function draw() {
  background(200);
  // map, mouseX between 0 and 5.
  let ax = map(mouseX, 0, 100, 0, 5);
  let ay = 66;

  //Get the ceiling of the mapped number.
  let bx = ceil(map(mouseX, 0, 100, 0, 5));
  let by = 33;

  // Multiply the mapped numbers by 20 to more easily
  // see the changes.
  stroke(0);
  fill(0);
  line(0, ay, ax * 20, ay);
  line(0, by, bx * 20, by);

  // Reformat the float returned by map and draw it.
  noStroke();
  text(nfc(ax, 2), ax, ay - 5);
  text(nfc(bx, 1), bx, by - 5);
}

inner char(n) → {String}

Converts a number or string to its corresponding single-character string representation. If a string parameter is provided, it is first parsed as an integer and then translated into a single-character string. When an array of number or string values is passed in, then an array of single-character strings of the same length is returned.
Parameters:
Name Type Description
n String | Number value to parse
Returns:
String - string representation of value
Example
print(char(65)); // "A"
print(char('65')); // "A"
print(char([65, 66, 67])); // [ "A", "B", "C" ]
print(join(char([65, 66, 67]), '')); // "ABC"

inner concat(a, b) → {Array}

Concatenates two arrays, maps to Array.concat(). Does not modify the input arrays.
Parameters:
Name Type Description
a Array first Array to concatenate
b Array second Array to concatenate
Returns:
Array - concatenated array
Example
function setup() {
  var arr1 = ['A', 'B', 'C'];
  var arr2 = [1, 2, 3];

  print(arr1); // ['A','B','C']
  print(arr2); // [1,2,3]

  var arr3 = concat(arr1, arr2);

  print(arr1); // ['A','B','C']
  print(arr2); // [1, 2, 3]
  print(arr3); // ['A','B','C', 1, 2, 3]
}

inner constrain(n, low, high) → {Number}

Constrains a value between a minimum and maximum value.
Parameters:
Name Type Description
n Number number to constrain
low Number minimum limit
high Number maximum limit
Returns:
Number - constrained number
Example
function draw() {
  background(200);

  let leftWall = 25;
  let rightWall = 75;

  // xm is just the mouseX, while
  // xc is the mouseX, but constrained
  // between the leftWall and rightWall!
  let xm = mouseX;
  let xc = constrain(mouseX, leftWall, rightWall);

  // Draw the walls.
  stroke(150);
  line(leftWall, 0, leftWall, height);
  line(rightWall, 0, rightWall, height);

  // Draw xm and xc as circles.
  noStroke();
  fill(150);
  ellipse(xm, 33, 9, 9); // Not Constrained
  fill(0);
  ellipse(xc, 66, 9, 9); // Constrained
}

inner cos(angle) → {Number}

Calculates the cosine of an angle. This function takes into account the current angleMode. Values are returned in the range -1 to 1.
Parameters:
Name Type Description
angle Number the angle
Returns:
Number - the cosine of the angle
Example
let a = 0.0;
let inc = TWO_PI / 25.0;
for (let i = 0; i < 25; i++) {
  line(i * 4, 50, i * 4, 50 + cos(a) * 40.0);
  a = a + inc;
}

inner createNumberDict(key, value) → {NumberDict}

Creates a new instance of NumberDict using the key-value pair or object you provide.
Parameters:
Name Type Description
key Number
value Number
Returns:
NumberDict
Example
function setup() {
  let myDictionary = createNumberDict(100, 42);
  print(myDictionary.hasKey(100)); // logs true to console

  let anotherDictionary = createNumberDict({ 200: 84 });
  print(anotherDictionary.hasKey(200)); // logs true to console
}

inner createStringDict(key, value) → {StringDict}

Creates a new instance of p5.StringDict using the key-value pair or the object you provide.
Parameters:
Name Type Description
key String
value String
Returns:
StringDict
Example
function setup() {
  let myDictionary = createStringDict('p5', 'js');
  print(myDictionary.hasKey('p5')); // logs true to console

  let anotherDictionary = createStringDict({ happy: 'coding' });
  print(anotherDictionary.hasKey('happy')); // logs true to console
}

inner createVector(xopt, yopt, zopt) → {p5.Vector}

Creates a new PVector (the datatype for storing vectors). This provides a two or three dimensional vector, specifically a Euclidean (also known as geometric) vector. A vector is an entity that has both magnitude and direction.
Parameters:
Name Type Attributes Description
x Number <optional>
x component of the vector
y Number <optional>
y component of the vector
z Number <optional>
z component of the vector
Returns:
p5.Vector
Example
function setup() {
  createCanvas(100, 100, WEBGL);
  noStroke();
  fill(255, 102, 204);
}

function draw() {
  background(255);
  pointLight(color(255), createVector(sin(millis() / 1000) * 20, -40, -10));
  scale(0.75);
  sphere();
}

inner day() → {Integer}

The day() function returns the current day as a value from 1 - 31.
Returns:
Integer - the current day
Example
var d = day();
text('Current day: \n' + d, 5, 50);

inner degrees(radians) → {Number}

Converts a radian measurement to its corresponding value in degrees. Radians and degrees are two ways of measuring the same thing. There are 360 degrees in a circle and 2*PI radians in a circle. For example, 90° = PI/2 = 1.5707964. This function does not take into account the current angleMode.
Parameters:
Name Type Description
radians Number the radians value to convert to degrees
Returns:
Number - the converted angle
Example
let rad = PI / 4;
let deg = degrees(rad);
print(rad + ' radians is ' + deg + ' degrees');
// Prints: 0.7853981633974483 radians is 45 degrees

inner displayDensity() → {Number}

Returns the pixel density of the current display the sketch is running on (always 1 for DOjS).
Returns:
Number - current pixel density of the display
Example
function setup() {
  let density = displayDensity();
  pixelDensity(density);
  createCanvas(100, 100);
  background(200);
  ellipse(width / 2, height / 2, 50, 50);
}

inner dist(x1, y1, x2, y2) → {Number}

Calculates the distance between two points.
Parameters:
Name Type Description
x1 Number x-coordinate of the first point
y1 Number y-coordinate of the first point
x2 Number x-coordinate of the second point
y2 Number y-coordinate of the second point
Returns:
Number - distance between the two points
Example
// Move your mouse inside the canvas to see the
// change in distance between two points!
function draw() {
  background(200);
  fill(0);

  let x1 = 10;
  let y1 = 90;
  let x2 = mouseX;
  let y2 = mouseY;

  line(x1, y1, x2, y2);
  ellipse(x1, y1, 7, 7);
  ellipse(x2, y2, 7, 7);

  // d is the length of the line
  // the distance from point 1 to point 2.
  let d = int(dist(x1, y1, x2, y2));

  // Let's write d along the line we are drawing!
  push();
  translate((x1 + x2) / 2, (y1 + y2) / 2);
  rotate(atan2(y2 - y1, x2 - x1));
  text(nfc(d, 1), 0, -5);
  pop();
  // Fancy!
}

inner exp(n) → {Number}

Returns Euler's number e (2.71828...) raised to the power of the n parameter. Maps to Math.exp().
Parameters:
Name Type Description
n Number exponent to raise
Returns:
Number - e^n
Example
function draw() {
  background(200);

  // Compute the exp() function with a value between 0 and 2
  let xValue = map(mouseX, 0, width, 0, 2);
  let yValue = exp(xValue);

  let y = map(yValue, 0, 8, height, 0);

  let legend = 'exp (' + nfc(xValue, 3) + ')\n= ' + nf(yValue, 1, 4);
  stroke(150);
  line(mouseX, y, mouseX, height);
  fill(0);
  text(legend, 5, 15);
  noStroke();
  ellipse(mouseX, y, 7, 7);

  // Draw the exp(x) curve,
  // over the domain of x from 0 to 2
  noFill();
  stroke(0);
  beginShape();
  for (let x = 0; x < width; x++) {
    xValue = map(x, 0, width, 0, 2);
    yValue = exp(xValue);
    y = map(yValue, 0, 8, height, 0);
    vertex(x, y);
  }

  endShape();
  line(0, 0, 0, height);
  line(0, height - 1, width, height - 1);
}

inner float(str) → {Number}

Converts a string to its floating point representation. The contents of a string must resemble a number, or NaN (not a number) will be returned. For example, float("1234.56") evaluates to 1234.56, but float("giraffe") will return NaN. When an array of values is passed in, then an array of floats of the same length is returned.
Parameters:
Name Type Description
str String float string to parse
Returns:
Number - floating point representation of string
Example
var str = '20';
var diameter = float(str);
ellipse(width / 2, height / 2, diameter, diameter);

inner floor(n) → {Integer}

Calculates the closest int value that is less than or equal to the value of the parameter. Maps to Math.floor().
Parameters:
Name Type Description
n Number number to round down
Returns:
Integer - rounded down number
Example
function draw() {
  background(200);
  //map, mouseX between 0 and 5.
  let ax = map(mouseX, 0, 100, 0, 5);
  let ay = 66;

  //Get the floor of the mapped number.
  let bx = floor(map(mouseX, 0, 100, 0, 5));
  let by = 33;

  // Multiply the mapped numbers by 20 to more easily
  // see the changes.
  stroke(0);
  fill(0);
  line(0, ay, ax * 20, ay);
  line(0, by, bx * 20, by);

  // Reformat the float returned by map and draw it.
  noStroke();
  text(nfc(ax, 2), ax, ay - 5);
  text(nfc(bx, 1), bx, by - 5);
}

inner hex(n, digitsopt) → {String}

Converts a number to a string in its equivalent hexadecimal notation. If a second parameter is passed, it is used to set the number of characters to generate in the hexadecimal notation. When an array is passed in, an array of strings in hexadecimal notation of the same length is returned.
Parameters:
Name Type Attributes Description
n Number value to parse
digits Number <optional>
Returns:
String - hexadecimal string representation of value
Example
print(hex(255)); // "000000FF"
print(hex(255, 6)); // "0000FF"
print(hex([0, 127, 255], 6)); // [ "000000", "00007F", "0000FF" ]

inner hour() → {Integer}

The hour() function returns the current hour as a value from 0 - 23.
Returns:
Integer - the current hour
Example
var h = hour();
text('Current hour:\n' + h, 5, 50);

inner int(n, radixopt) → {Number}

Converts a boolean, string, or float to its integer representation. When an array of values is passed in, then an int array of the same length is returned.
Parameters:
Name Type Attributes Description
n String | Boolean | Number value to parse
radix Integer <optional>
the radix to convert to (default: 10)
Returns:
Number - integer representation of value
Example
print(int('10')); // 10
print(int(10.31)); // 10
print(int(-10)); // -10
print(int(true)); // 1
print(int(false)); // 0
print(int([false, true, '10.3', 9.8])); // [0, 1, 10, 9]

inner join(list, separator) → {String}

Combines an array of Strings into one String, each separated by the character(s) used for the separator parameter. To join arrays of ints or floats, it's necessary to first convert them to Strings using nf() or nfs().
Parameters:
Name Type Description
list Array array of Strings to be joined
separator String String to be placed between each item
Returns:
String - joined String
Example
var array = ['Hello', 'world!'];
var separator = ' ';
var message = join(array, separator);
text(message, 5, 50);

inner lerp(start, stop, amt) → {Number}

Calculates a number between two numbers at a specific increment. The amt parameter is the amount to interpolate between the two values where 0.0 equal to the first point, 0.1 is very near the first point, 0.5 is half-way in between, and 1.0 is equal to the second point. If the value of amt is more than 1.0 or less than 0.0, the number will be calculated accordingly in the ratio of the two given numbers. The lerp function is convenient for creating motion along a straight path and for drawing dotted lines.
Parameters:
Name Type Description
start Number first value
stop Number second value
amt Number number
Returns:
Number - lerped value
Example
function setup() {
  background(200);
  let a = 20;
  let b = 80;
  let c = lerp(a, b, 0.2);
  let d = lerp(a, b, 0.5);
  let e = lerp(a, b, 0.8);

  let y = 50;

  strokeWeight(5);
  stroke(0); // Draw the original points in black
  point(a, y);
  point(b, y);

  stroke(100); // Draw the lerp points in gray
  point(c, y);
  point(d, y);
  point(e, y);
}

inner loadFont(path) → {Font}

Loads a GRX font file (.FNT) from a file Font Object.

Parameters:
Name Type Description
path String name of the file or url to load
Returns:
Font - Font object

inner log(n) → {Number}

Calculates the natural logarithm (the base-e logarithm) of a number. This function expects the n parameter to be a value greater than 0.0. Maps to Math.log().
Parameters:
Name Type Description
n Number number greater than 0
Returns:
Number - natural logarithm of n
Example
function draw() {
  background(200);
  let maxX = 2.8;
  let maxY = 1.5;

  // Compute the natural log of a value between 0 and maxX
  let xValue = map(mouseX, 0, width, 0, maxX);
  let yValue, y;
  if (xValue > 0) {
  // Cannot take the log of a negative number.
    yValue = log(xValue);
    y = map(yValue, -maxY, maxY, height, 0);

    // Display the calculation occurring.
    let legend = 'log(' + nf(xValue, 1, 2) + ')\n= ' + nf(yValue, 1, 3);
    stroke(150);
    line(mouseX, y, mouseX, height);
    fill(0);
    text(legend, 5, 15);
    noStroke();
    ellipse(mouseX, y, 7, 7);
  }

  // Draw the log(x) curve,
  // over the domain of x from 0 to maxX
  noFill();
  stroke(0);
  beginShape();
  for (let x = 0; x < width; x++) {
    xValue = map(x, 0, width, 0, maxX);
    yValue = log(xValue);
    y = map(yValue, -maxY, maxY, height, 0);
    vertex(x, y);
  }
  endShape();
  line(0, 0, 0, height);
  line(0, height / 2, width, height / 2);
}

inner loop()

By default, p5.js loops through draw() continuously, executing the code within it. However, the draw() loop may be stopped by calling noLoop(). In that case, the draw() loop can be resumed with loop(). Avoid calling loop() from inside setup().
Example
let x = 0;
function setup() {
  createCanvas(100, 100);
  noLoop();
}

function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}

function mousePressed() {
  loop();
}

function mouseReleased() {
  noLoop();
}

inner mag(a, b) → {Number}

Calculates the magnitude (or length) of a vector. A vector is a direction in space commonly used in computer graphics and linear algebra. Because it has no "start" position, the magnitude of a vector can be thought of as the distance from the coordinate 0,0 to its x,y value. Therefore, mag() is a shortcut for writing dist(0, 0, x, y).
Parameters:
Name Type Description
a Number first value
b Number second value
Returns:
Number - magnitude of vector from (0,0) to (a,b)
Example
function setup() {
  let x1 = 20;
  let x2 = 80;
  let y1 = 30;
  let y2 = 70;

  line(0, 0, x1, y1);
  print(mag(x1, y1)); // Prints "36.05551275463989"
  line(0, 0, x2, y1);
  print(mag(x2, y1)); // Prints "85.44003745317531"
  line(0, 0, x1, y2);
  print(mag(x1, y2)); // Prints "72.80109889280519"
  line(0, 0, x2, y2);
  print(mag(x2, y2)); // Prints "106.3014581273465"
}

inner map(value, start1, stop1, start2, stop2, withinBoundsopt) → {Number}

Re-maps a number from one range to another.

In the first example above, the number 25 is converted from a value in the range of 0 to 100 into a value that ranges from the left edge of the window (0) to the right edge (width).
Parameters:
Name Type Attributes Description
value Number the incoming value to be converted
start1 Number lower bound of the value's current range
stop1 Number upper bound of the value's current range
start2 Number lower bound of the value's target range
stop2 Number upper bound of the value's target range
withinBounds Boolean <optional>
constrain the value to the newly mapped range
Returns:
Number - remapped number
Example
let value = 25;
let m = map(value, 0, 100, 0, width);
ellipse(m, 50, 10, 10);

function setup() {
  noStroke();
}

function draw() {
  background(204);
  let x1 = map(mouseX, 0, width, 25, 75);
  ellipse(x1, 25, 25, 25);
  //This ellipse is constrained to the 0-100 range
  //after setting withinBounds to true
  let x2 = map(mouseX, 0, width, 0, 100, true);
  ellipse(x2, 75, 25, 25);
}

inner match(str, regexp) → {Array.<String>}

This function is used to apply a regular expression to a piece of text, and return matching groups (elements found inside parentheses) as a String array. If there are no matches, a null value will be returned. If no groups are specified in the regular expression, but the sequence matches, an array of length 1 (with the matched text as the first element of the array) will be returned.

To use the function, first check to see if the result is null. If the result is null, then the sequence did not match at all. If the sequence did match, an array is returned.

If there are groups (specified by sets of parentheses) in the regular expression, then the contents of each will be returned in the array. Element [0] of a regular expression match returns the entire matching string, and the match groups start at element [1] (the first group is [1], the second [2], and so on).
Parameters:
Name Type Description
str String the String to be searched
regexp String the regexp to be used for matching
Returns:
Array.<String> - Array of Strings found
Example
var string = 'Hello p5js*!';
var regexp = 'p5js\\*';
var m = match(string, regexp);
text(m, 5, 50);

inner matchAll(str, regexp) → {Array.<String>}

This function is used to apply a regular expression to a piece of text, and return a list of matching groups (elements found inside parentheses) as a two-dimensional String array. If there are no matches, a null value will be returned. If no groups are specified in the regular expression, but the sequence matches, a two dimensional array is still returned, but the second dimension is only of length one.

To use the function, first check to see if the result is null. If the result is null, then the sequence did not match at all. If the sequence did match, a 2D array is returned.

If there are groups (specified by sets of parentheses) in the regular expression, then the contents of each will be returned in the array. Assuming a loop with counter variable i, element [i][0] of a regular expression match returns the entire matching string, and the match groups start at element [i][1] (the first group is [i][1], the second [i][2], and so on).
Parameters:
Name Type Description
str String the String to be searched
regexp String the regexp to be used for matching
Returns:
Array.<String> - 2d Array of Strings found
Example
var string = 'Hello p5js*! Hello world!';
var regexp = 'Hello';
matchAll(string, regexp);

inner max(n0, n1) → {Number}

Determines the largest value in a sequence of numbers, and then returns that value. max() accepts any number of Number parameters, or an Array of any length.
Parameters:
Name Type Description
n0 Number Number to compare
n1 Number Number to compare
Returns:
Number - maximum Number
Example
function setup() {
  // Change the elements in the array and run the sketch
  // to show how max() works!
  let numArray = [2, 1, 5, 4, 8, 9];
  fill(0);
  noStroke();
  text('Array Elements', 0, 10);
  // Draw all numbers in the array
  let spacing = 15;
  let elemsY = 25;
  for (let i = 0; i < numArray.length; i++) {
    text(numArray[i], i * spacing, elemsY);
  }
  let maxX = 33;
  let maxY = 80;
  // Draw the Maximum value in the array.
  textSize(32);
  text(max(numArray), maxX, maxY);
}

inner millis() → {Number}

Returns the number of milliseconds (thousandths of a second) since starting the program. This information is often used for timing events and animation sequences.
Returns:
Number - the number of milliseconds since starting the program
Example
var millisecond = millis();
text('Milliseconds \nrunning: \n' + millisecond, 5, 40);

inner min(n0, n1) → {Number}

Determines the smallest value in a sequence of numbers, and then returns that value. min() accepts any number of Number parameters, or an Array of any length.
Parameters:
Name Type Description
n0 Number Number to compare
n1 Number Number to compare
Returns:
Number - minimum Number
Example
function setup() {
  // Change the elements in the array and run the sketch
  // to show how min() works!
  let numArray = [2, 1, 5, 4, 8, 9];
  fill(0);
  noStroke();
  text('Array Elements', 0, 10);
  // Draw all numbers in the array
  let spacing = 15;
  let elemsY = 25;
  for (let i = 0; i < numArray.length; i++) {
    text(numArray[i], i * spacing, elemsY);
  }
  let maxX = 33;
  let maxY = 80;
  // Draw the Minimum value in the array.
  textSize(32);
  text(min(numArray), maxX, maxY);
}

inner minute() → {Integer}

The minute() function returns the current minute as a value from 0 - 59.
Returns:
Integer - the current minute
Example
var m = minute();
text('Current minute: \n' + m, 5, 50);

inner month() → {Integer}

The month() function returns the current month as a value from 1 - 12.
Returns:
Integer - the current month
Example
var m = month();
text('Current month: \n' + m, 5, 50);

inner nf(num, leftopt, rightopt) → {String}

Utility function for formatting numbers into strings. There are two versions: one for formatting floats, and one for formatting ints. The values for the digits, left, and right parameters should always be positive integers. (NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter if greater than the current length of the number. For example if number is 123.2 and left parameter passed is 4 which is greater than length of 123 (integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than the result will be 123.200.
Parameters:
Name Type Attributes Description
num Number | String the Number to format
left Integer | String <optional>
number of digits to the left of the decimal point
right Integer | String <optional>
number of digits to the right of the decimal point
Returns:
String - formatted String
Example
var myFont;
function preload() {
  myFont = loadFont('assets/fonts/inconsolata.ttf');
}
function setup() {
  background(200);
  var num1 = 321;
  var num2 = -1321;

  noStroke();
  fill(0);
  textFont(myFont);
  textSize(22);

  text(nf(num1, 4, 2), 10, 30);
  text(nf(num2, 4, 2), 10, 80);
  // Draw dividing line
  stroke(120);
  line(0, 50, width, 50);
}

inner nfc(num, rightopt) → {String}

Utility function for formatting numbers into strings and placing appropriate commas to mark units of 1000. There are two versions: one for formatting ints, and one for formatting an array of ints. The value for the right parameter should always be a positive integer.
Parameters:
Name Type Attributes Description
num Number | String the Number to format
right Integer | String <optional>
number of digits to the right of the decimal point
Returns:
String - formatted String
Example
function setup() {
  background(200);
  var num = 11253106.115;
  var numArr = [1, 1, 2];

  noStroke();
  fill(0);
  textSize(12);

  // Draw formatted numbers
  text(nfc(num, 4), 10, 30);
  text(nfc(numArr, 2), 10, 80);

  // Draw dividing line
  stroke(120);
  line(0, 50, width, 50);
}

inner nfp(num, leftopt, rightopt) → {String}

Utility function for formatting numbers into strings. Similar to nf() but puts a "+" in front of positive numbers and a "-" in front of negative numbers. There are two versions: one for formatting floats, and one for formatting ints. The values for left, and right parameters should always be positive integers.
Parameters:
Name Type Attributes Description
num Number the Number to format
left Integer <optional>
number of digits to the left of the decimal point
right Integer <optional>
number of digits to the right of the decimal point
Returns:
String - formatted String
Example
function setup() {
  background(200);
  var num1 = 11253106.115;
  var num2 = -11253106.115;

  noStroke();
  fill(0);
  textSize(12);

  // Draw formatted numbers
  text(nfp(num1, 4, 2), 10, 30);
  text(nfp(num2, 4, 2), 10, 80);

  // Draw dividing line
  stroke(120);
  line(0, 50, width, 50);
}

inner nfs(num, leftopt, rightopt) → {String}

Utility function for formatting numbers into strings. Similar to nf() but puts an additional "_" (space) in front of positive numbers just in case to align it with negative numbers which includes "-" (minus) sign. The main usecase of nfs() can be seen when one wants to align the digits (place values) of a positive number with some negative number (See the example to get a clear picture). There are two versions: one for formatting float, and one for formatting int. The values for the digits, left, and right parameters should always be positive integers. (IMP): The result on the canvas basically the expected alignment can vary based on the typeface you are using. (NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter if greater than the current length of the number. For example if number is 123.2 and left parameter passed is 4 which is greater than length of 123 (integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than the result will be 123.200.
Parameters:
Name Type Attributes Description
num Number the Number to format
left Integer <optional>
number of digits to the left of the decimal point
right Integer <optional>
number of digits to the right of the decimal point
Returns:
String - formatted String
Example
var myFont;
function preload() {
  myFont = loadFont('assets/fonts/inconsolata.ttf');
}
function setup() {
  background(200);
  var num1 = 321;
  var num2 = -1321;

  noStroke();
  fill(0);
  textFont(myFont);
  textSize(22);

  // nfs() aligns num1 (positive number) with num2 (negative number) by
  // adding a blank space in front of the num1 (positive number)
  // [left = 4] in num1 add one 0 in front, to align the digits with num2
  // [right = 2] in num1 and num2 adds two 0's after both numbers
  // To see the differences check the example of nf() too.
  text(nfs(num1, 4, 2), 10, 30);
  text(nfs(num2, 4, 2), 10, 80);
  // Draw dividing line
  stroke(120);
  line(0, 50, width, 50);
}

inner noCursor()

Hides the cursor from view.
Example
function setup() {
  noCursor();
}

function draw() {
  background(200);
  ellipse(mouseX, mouseY, 10, 10);
}

inner noise(x, yopt, zopt) → {Number}

Returns the Perlin noise value at specified coordinates. Perlin noise is a random sequence generator producing a more natural ordered, harmonic succession of numbers compared to the standard random() function. It was invented by Ken Perlin in the 1980s and been used since in graphical applications to produce procedural textures, natural motion, shapes, terrains etc.

The main difference to the random() function is that Perlin noise is defined in an infinite n-dimensional space where each pair of coordinates corresponds to a fixed semi-random value (fixed only for the lifespan of the program; see the noiseSeed() function). p5.js can compute 1D, 2D and 3D noise, depending on the number of coordinates given. The resulting value will always be between 0.0 and 1.0. The noise value can be animated by moving through the noise space as demonstrated in the example above. The 2nd and 3rd dimension can also be interpreted as time.

The actual noise is structured similar to an audio signal, in respect to the function's use of frequencies. Similar to the concept of harmonics in physics, perlin noise is computed over several octaves which are added together for the final result.

Another way to adjust the character of the resulting sequence is the scale of the input coordinates. As the function works within an infinite space the value of the coordinates doesn't matter as such, only the distance between successive coordinates does (eg. when using noise() within a loop). As a general rule the smaller the difference between coordinates, the smoother the resulting noise sequence will be. Steps of 0.005-0.03 work best for most applications, but this will differ depending on use.
Parameters:
Name Type Attributes Description
x Number x-coordinate in noise space
y Number <optional>
y-coordinate in noise space
z Number <optional>
z-coordinate in noise space
Returns:
Number - Perlin noise value (between 0 and 1) at specified coordinates
Example
let xoff = 0.0;

function draw() {
  background(204);
  xoff = xoff + 0.01;
  let n = noise(xoff) * width;
  line(n, 0, n, height);
}

let noiseScale=0.02;

function draw() {
  background(0);
  for (let x=0; x < width; x++) {
    let noiseVal = noise((mouseX+x)*noiseScale, mouseY*noiseScale);
    stroke(noiseVal*255);
    line(x, mouseY+noiseVal*80, x, height);
  }
}

inner noiseDetail(lod, falloff)

Adjusts the character and level of detail produced by the Perlin noise function. Similar to harmonics in physics, noise is computed over several octaves. Lower octaves contribute more to the output signal and as such define the overall intensity of the noise, whereas higher octaves create finer grained details in the noise sequence.

By default, noise is computed over 4 octaves with each octave contributing exactly half than its predecessor, starting at 50% strength for the 1st octave. This falloff amount can be changed by adding an additional function parameter. Eg. a falloff factor of 0.75 means each octave will now have 75% impact (25% less) of the previous lower octave. Any value between 0.0 and 1.0 is valid, however note that values greater than 0.5 might result in greater than 1.0 values returned by noise().

By changing these parameters, the signal created by the noise() function can be adapted to fit very specific needs and characteristics.
Parameters:
Name Type Description
lod Number number of octaves to be used by the noise
falloff Number falloff factor for each octave
Example
let noiseVal;
let noiseScale = 0.02;

function setup() {
  createCanvas(100, 100);
}

function draw() {
  background(0);
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width / 2; x++) {
      noiseDetail(2, 0.2);
      noiseVal = noise((mouseX + x) * noiseScale, (mouseY + y) * noiseScale);
      stroke(noiseVal * 255);
      point(x, y);
      noiseDetail(8, 0.65);
      noiseVal = noise(
        (mouseX + x + width / 2) * noiseScale,
        (mouseY + y) * noiseScale
      );
      stroke(noiseVal * 255);
      point(x + width / 2, y);
    }
  }
}

inner noLoop()

Stops p5.js from continuously executing the code within draw(). If loop() is called, the code in draw() begins to run continuously again. If using noLoop() in setup(), it should be the last line inside the block.

When noLoop() is used, it's not possible to manipulate or access the screen inside event handling functions such as mousePressed() or keyPressed(). Instead, use those functions to call redraw() or loop(), which will run draw(), which can update the screen properly. This means that when noLoop() has been called, no drawing can happen, and functions like saveFrame() or loadPixels() may not be used.

Note that if the sketch is resized, redraw() will be called to update the sketch, even after noLoop() has been specified. Otherwise, the sketch would enter an odd state until loop() was called.
Example
function setup() {
  createCanvas(100, 100);
  background(200);
  noLoop();
}

function draw() {
  line(10, 10, 90, 90);
}

let x = 0;
function setup() {
  createCanvas(100, 100);
}

function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}

function mousePressed() {
  noLoop();
}

function mouseReleased() {
  loop();
}

inner norm(value, start, stop) → {Number}

Normalizes a number from another range into a value between 0 and 1. Identical to map(value, low, high, 0, 1). Numbers outside of the range are not clamped to 0 and 1, because out-of-range values are often intentional and useful. (See the second example above.)
Parameters:
Name Type Description
value Number incoming value to be normalized
start Number lower bound of the value's current range
stop Number upper bound of the value's current range
Returns:
Number - normalized number
Example
function draw() {
  background(200);
  let currentNum = mouseX;
  let lowerBound = 0;
  let upperBound = width; //100;
  let normalized = norm(currentNum, lowerBound, upperBound);
  let lineY = 70;
  line(0, lineY, width, lineY);
  //Draw an ellipse mapped to the non-normalized value.
  noStroke();
  fill(50);
  let s = 7; // ellipse size
  ellipse(currentNum, lineY, s, s);

  // Draw the guide
  let guideY = lineY + 15;
  text('0', 0, guideY);
  textAlign(RIGHT);
  text('100', width, guideY);

  // Draw the normalized value
  textAlign(LEFT);
  fill(0);
  textSize(32);
  let normalY = 40;
  let normalX = 20;
  text(normalized, normalX, normalY);
}

inner pow(n, e) → {Number}

Facilitates exponential expressions. The pow() function is an efficient way of multiplying numbers by themselves (or their reciprocals) in large quantities. For example, pow(3, 5) is equivalent to the expression 3*3*3*3*3 and pow(3, -5) is equivalent to 1 / 3*3*3*3*3. Maps to Math.pow().
Parameters:
Name Type Description
n Number base of the exponential expression
e Number power by which to raise the base
Returns:
Number - n^e
Example
function setup() {
  //Exponentially increase the size of an ellipse.
  let eSize = 3; // Original Size
  let eLoc = 10; // Original Location

  ellipse(eLoc, eLoc, eSize, eSize);

  ellipse(eLoc * 2, eLoc * 2, pow(eSize, 2), pow(eSize, 2));

  ellipse(eLoc * 4, eLoc * 4, pow(eSize, 3), pow(eSize, 3));

  ellipse(eLoc * 8, eLoc * 8, pow(eSize, 4), pow(eSize, 4));
}

inner radians(degrees) → {Number}

Converts a degree measurement to its corresponding value in radians. Radians and degrees are two ways of measuring the same thing. There are 360 degrees in a circle and 2*PI radians in a circle. For example, 90° = PI/2 = 1.5707964. This function does not take into account the current angleMode.
Parameters:
Name Type Description
degrees Number the degree value to convert to radians
Returns:
Number - the converted angle
Example
let deg = 45.0;
let rad = radians(deg);
print(deg + ' degrees is ' + rad + ' radians');
// Prints: 45 degrees is 0.7853981633974483 radians

inner random(minopt, maxopt) → {Number}

Return a random floating-point number. Takes either 0, 1 or 2 arguments. If no argument is given, returns a random number from 0 up to (but not including) 1. If one argument is given and it is a number, returns a random number from 0 up to (but not including) the number. If one argument is given and it is an array, returns a random element from that array. If two arguments are given, returns a random number from the first argument up to (but not including) the second argument.
Parameters:
Name Type Attributes Description
min Number <optional>
the lower bound (inclusive)
max Number <optional>
the upper bound (exclusive)
Returns:
Number - the random number
Example
for (let i = 0; i < 100; i++) {
  let r = random(50);
  stroke(r * 5);
  line(50, i, 50 + r, i);
}

for (let i = 0; i < 100; i++) {
  let r = random(-50, 50);
  line(50, i, 50 + r, i);
}

// Get a random element from an array using the random(Array) syntax
let words = ['apple', 'bear', 'cat', 'dog'];
let word = random(words); // select random word
text(word, 10, 50); // draw the word

inner randomGaussian(mean, sd) → {Number}

Returns a random number fitting a Gaussian, or normal, distribution. There is theoretically no minimum or maximum value that randomGaussian() might return. Rather, there is just a very low probability that values far from the mean will be returned; and a higher probability that numbers near the mean will be returned.

Takes either 0, 1 or 2 arguments.
If no args, returns a mean of 0 and standard deviation of 1.
If one arg, that arg is the mean (standard deviation is 1).
If two args, first is mean, second is standard deviation.
Parameters:
Name Type Description
mean Number the mean
sd Number the standard deviation
Returns:
Number - the random number
Example
for (let y = 0; y < 100; y++) {
  let x = randomGaussian(50, 15);
  line(50, y, x, y);
}

let distribution = new Array(360);

function setup() {
  createCanvas(100, 100);
  for (let i = 0; i < distribution.length; i++) {
    distribution[i] = floor(randomGaussian(0, 15));
  }
}

function draw() {
  background(204);

  translate(width / 2, width / 2);

  for (let i = 0; i < distribution.length; i++) {
    rotate(TWO_PI / distribution.length);
    stroke(0);
    let dist = abs(distribution[i]);
    line(0, 0, dist, 0);
  }
}

inner randomSeed(seed)

Sets the seed value for random(). By default, random() produces different results each time the program is run. Set the seed parameter to a constant to return the same pseudo-random numbers each time the software is run.
Parameters:
Name Type Description
seed Number the seed value
Example
randomSeed(99);
for (let i = 0; i < 100; i++) {
  let r = random(0, 255);
  stroke(r);
  line(i, 0, i, 100);
}

inner redraw(nopt)

Executes the code within draw() one time. This functions allows the program to update the display window only when necessary, for example when an event registered by mousePressed() or keyPressed() occurs.

In structuring a program, it only makes sense to call redraw() within events such as mousePressed(). This is because redraw() does not run draw() immediately (it only sets a flag that indicates an update is needed).

The redraw() function does not work properly when called inside draw(). To enable/disable animations, use loop() and noLoop().

In addition you can set the number of redraws per method call. Just add an integer as single parameter for the number of redraws.
Parameters:
Name Type Attributes Description
n Integer <optional>
Redraw for n-times. The default value is 1.
Example
let x = 0;

function setup() {
  createCanvas(100, 100);
  noLoop();
}

function draw() {
  background(204);
  line(x, 0, x, height);
}

function mousePressed() {
  x += 1;
  redraw();
}

let x = 0;

function setup() {
  createCanvas(100, 100);
  noLoop();
}

function draw() {
  background(204);
  x += 1;
  line(x, 0, x, height);
}

function mousePressed() {
  redraw(5);
}

inner reverse(list) → {Array}

Reverses the order of an array, maps to Array.reverse()
Parameters:
Name Type Description
list Array Array to reverse
Returns:
Array - the reversed list
Example
function setup() {
  var myArray = ['A', 'B', 'C'];
  print(myArray); // ['A','B','C']

  reverse(myArray);
  print(myArray); // ['C','B','A']
}

inner round(n) → {Integer}

Calculates the integer closest to the n parameter. For example, round(133.8) returns the value 134. Maps to Math.round().
Parameters:
Name Type Description
n Number number to round
Returns:
Integer - rounded number
Example
function draw() {
  background(200);
  //map, mouseX between 0 and 5.
  let ax = map(mouseX, 0, 100, 0, 5);
  let ay = 66;

  // Round the mapped number.
  let bx = round(map(mouseX, 0, 100, 0, 5));
  let by = 33;

  // Multiply the mapped numbers by 20 to more easily
  // see the changes.
  stroke(0);
  fill(0);
  line(0, ay, ax * 20, ay);
  line(0, by, bx * 20, by);

  // Reformat the float returned by map and draw it.
  noStroke();
  text(nfc(ax, 2), ax, ay - 5);
  text(nfc(bx, 1), bx, by - 5);
}

inner second() → {Integer}

The second() function returns the current second as a value from 0 - 59.
Returns:
Integer - the current second
Example
var s = second();
text('Current second: \n' + s, 5, 50);

inner shorten(list) → {Array}

Decreases an array by one element and returns the shortened array, maps to Array.pop().
Parameters:
Name Type Description
list Array Array to shorten
Returns:
Array - shortened Array
Example
function setup() {
  var myArray = ['A', 'B', 'C'];
  print(myArray); // ['A', 'B', 'C']
  var newArray = shorten(myArray);
  print(myArray); // ['A','B','C']
  print(newArray); // ['A','B']
}

inner shuffle(array, boolopt) → {Array}

Randomizes the order of the elements of an array. Implements Fisher-Yates Shuffle Algorithm.
Parameters:
Name Type Attributes Description
array Array Array to shuffle
bool Boolean <optional>
modify passed array
Returns:
Array - shuffled Array
Example
function setup() {
  var regularArr = ['ABC', 'def', createVector(), TAU, Math.E];
  print(regularArr);
  shuffle(regularArr, true); // force modifications to passed array
  print(regularArr);

  // By default shuffle() returns a shuffled cloned array:
  var newArr = shuffle(regularArr);
  print(regularArr);
  print(newArr);
}

inner sin(angle) → {Number}

Calculates the sine of an angle. This function takes into account the current angleMode. Values are returned in the range -1 to 1.
Parameters:
Name Type Description
angle Number the angle
Returns:
Number - the sine of the angle
Example
let a = 0.0;
let inc = TWO_PI / 25.0;
for (let i = 0; i < 25; i++) {
  line(i * 4, 50, i * 4, 50 + sin(a) * 40.0);
  a = a + inc;
}

inner sort(list, countopt) → {Array}

Sorts an array of numbers from smallest to largest, or puts an array of words in alphabetical order. The original array is not modified; a re-ordered array is returned. The count parameter states the number of elements to sort. For example, if there are 12 elements in an array and count is set to 5, only the first 5 elements in the array will be sorted.
Parameters:
Name Type Attributes Description
list Array Array to sort
count Integer <optional>
number of elements to sort, starting from 0
Returns:
Array - the sorted list
Example
function setup() {
  var words = ['banana', 'apple', 'pear', 'lime'];
  print(words); // ['banana', 'apple', 'pear', 'lime']
  var count = 4; // length of array

  words = sort(words, count);
  print(words); // ['apple', 'banana', 'lime', 'pear']
}

function setup() {
  var numbers = [2, 6, 1, 5, 14, 9, 8, 12];
  print(numbers); // [2, 6, 1, 5, 14, 9, 8, 12]
  var count = 5; // Less than the length of the array

  numbers = sort(numbers, count);
  print(numbers); // [1,2,5,6,14,9,8,12]
}

inner splice(list, value, position) → {Array}

Inserts a value or an array of values into an existing array. The first parameter specifies the initial array to be modified, and the second parameter defines the data to be inserted. The third parameter is an index value which specifies the array position from which to insert data. (Remember that array index numbering starts at zero, so the first position is 0, the second position is 1, and so on.)
Parameters:
Name Type Description
list Array Array to splice into
value any value to be spliced in
position Integer in the array from which to insert data
Returns:
Array - the list
Example
function setup() {
  var myArray = [0, 1, 2, 3, 4];
  var insArray = ['A', 'B', 'C'];
  print(myArray); // [0, 1, 2, 3, 4]
  print(insArray); // ['A','B','C']

  splice(myArray, insArray, 3);
  print(myArray); // [0,1,2,'A','B','C',3,4]
}

inner split(value, delim) → {Array.<String>}

The split() function maps to String.split(), it breaks a String into pieces using a character or string as the delimiter. The delim parameter specifies the character or characters that mark the boundaries between each piece. A String[] array is returned that contains each of the pieces. The splitTokens() function works in a similar fashion, except that it splits using a range of characters instead of a specific character or sequence.
Parameters:
Name Type Description
value String the String to be split
delim String the String used to separate the data
Returns:
Array.<String> - Array of Strings
Example
var names = 'Pat,Xio,Alex';
var splitString = split(names, ',');
text(splitString[0], 5, 30);
text(splitString[1], 5, 50);
text(splitString[2], 5, 70);

inner splitTokens(value, delimopt) → {Array.<String>}

The splitTokens() function splits a String at one or many character delimiters or "tokens." The delim parameter specifies the character or characters to be used as a boundary.

If no delim characters are specified, any whitespace character is used to split. Whitespace characters include tab (\t), line feed (\n), carriage return (\r), form feed (\f), and space.
Parameters:
Name Type Attributes Description
value String the String to be split
delim String <optional>
list of individual Strings that will be used as separators
Returns:
Array.<String> - Array of Strings
Example
function setup() {
  var myStr = 'Mango, Banana, Lime';
  var myStrArr = splitTokens(myStr, ',');

  print(myStrArr); // prints : ["Mango"," Banana"," Lime"]
}

inner sq(n) → {Number}

Squares a number (multiplies a number by itself). The result is always a positive number, as multiplying two negative numbers always yields a positive result. For example, -1 * -1 = 1.
Parameters:
Name Type Description
n Number number to square
Returns:
Number - squared number
Example
function draw() {
  background(200);
  let eSize = 7;
  let x1 = map(mouseX, 0, width, 0, 10);
  let y1 = 80;
  let x2 = sq(x1);
  let y2 = 20;

  // Draw the non-squared.
  line(0, y1, width, y1);
  ellipse(x1, y1, eSize, eSize);

  // Draw the squared.
  line(0, y2, width, y2);
  ellipse(x2, y2, eSize, eSize);

  // Draw dividing line.
  stroke(100);
  line(0, height / 2, width, height / 2);

  // Draw text.
  let spacing = 15;
  noStroke();
  fill(0);
  text('x = ' + x1, 0, y1 + spacing);
  text('sq(x) = ' + x2, 0, y2 + spacing);
}

inner sqrt(n) → {Number}

Calculates the square root of a number. The square root of a number is always positive, even though there may be a valid negative root. The square root s of number a is such that s*s = a. It is the opposite of squaring. Maps to Math.sqrt().
Parameters:
Name Type Description
n Number non-negative number to square root
Returns:
Number - square root of number
Example
function draw() {
  background(200);
  let eSize = 7;
  let x1 = mouseX;
  let y1 = 80;
  let x2 = sqrt(x1);
  let y2 = 20;

  // Draw the non-squared.
  line(0, y1, width, y1);
  ellipse(x1, y1, eSize, eSize);

  // Draw the squared.
  line(0, y2, width, y2);
  ellipse(x2, y2, eSize, eSize);

  // Draw dividing line.
  stroke(100);
  line(0, height / 2, width, height / 2);

  // Draw text.
  noStroke();
  fill(0);
  let spacing = 15;
  text('x = ' + x1, 0, y1 + spacing);
  text('sqrt(x) = ' + x2, 0, y2 + spacing);
}

inner str(n) → {String}

Converts a boolean, string or number to its string representation. When an array of values is passed in, then an array of strings of the same length is returned.
Parameters:
Name Type Description
n String | Boolean | Number | Array value to parse
Returns:
String - string representation of value
Example
print(str('10')); // "10"
print(str(10.31)); // "10.31"
print(str(-10)); // "-10"
print(str(true)); // "true"
print(str(false)); // "false"
print(str([true, '10.3', 9.8])); // [ "true", "10.3", "9.8" ]

inner subset(list, start, countopt) → {Array}

Extracts an array of elements from an existing array. The list parameter defines the array from which the elements will be copied, and the start and count parameters specify which elements to extract. If no count is given, elements will be extracted from the start to the end of the array. When specifying the start, remember that the first array element is 0. This function does not change the source array.
Parameters:
Name Type Attributes Description
list Array Array to extract from
start Integer position to begin
count Integer <optional>
number of values to extract
Returns:
Array - Array of extracted elements
Example
function setup() {
  var myArray = [1, 2, 3, 4, 5];
  print(myArray); // [1, 2, 3, 4, 5]

  var sub1 = subset(myArray, 0, 3);
  var sub2 = subset(myArray, 2, 2);
  print(sub1); // [1,2,3]
  print(sub2); // [3,4]
}

inner tan(angle) → {Number}

Calculates the tangent of an angle. This function takes into account the current angleMode. Values are returned in the range -1 to 1.
Parameters:
Name Type Description
angle Number the angle
Returns:
Number - the tangent of the angle
Example
let a = 0.0;
let inc = TWO_PI / 50.0;
for (let i = 0; i < 100; i = i + 2) {
  line(i, 50, i, 50 + tan(a) * 2.0);
  a = a + inc;
}

inner text(str, x, y)

Draws text to the screen. Displays the information specified in the first parameter on the screen in the position specified by the additional parameters. A default font will be used unless a font is set with the textFont() function and a default size will be used unless a font is set with textSize(). Change the color of the text with the fill() function. Change the outline of the text with the stroke() and strokeWeight() functions.

The text displays in relation to the textAlign() function, which gives the option to draw to the left, right, and center of the coordinates.

The x2 and y2 parameters define a rectangular area to display within and may only be used with string data. When these parameters are specified, they are interpreted based on the current rectMode() setting. Text that does not fit completely within the rectangle specified will not be drawn to the screen. If x2 and y2 are not specified, the baseline alignment is the default, which means that the text will be drawn upwards from x and y.

WEBGL: Only opentype/truetype fonts are supported. You must load a font using the loadFont() method (see the example above). stroke() currently has no effect in webgl mode.
Parameters:
Name Type Description
str String | Object | Array | Number | Boolean the alphanumeric symbols to be displayed
x Number x-coordinate of text
y Number y-coordinate of text
Example
text('word', 10, 30);
fill(0, 102, 153);
text('word', 10, 60);
fill(0, 102, 153, 51);
text('word', 10, 90);

let s = 'The quick brown fox jumped over the lazy dog.';
fill(50);
text(s, 10, 10, 70, 80); // Text wraps within text box

avenir;
function setup() {
  avenir = loadFont('assets/Avenir.otf');
  textFont(avenir);
  textSize(width / 3);
  textAlign(CENTER, CENTER);
}
function draw() {
  background(0);
  text('p5.js', 0, 0);
}

inner textAlign(horizAlign, vertAlignopt)

Sets the current alignment for drawing text. Accepts two arguments: horizAlign (LEFT, CENTER, or RIGHT) and vertAlign (TOP, BOTTOM, CENTER, or BASELINE). The horizAlign parameter is in reference to the x value of the text() function, while the vertAlign parameter is in reference to the y value. So if you write textAlign(LEFT), you are aligning the left edge of your text to the x value you give in text(). If you write textAlign(RIGHT, TOP), you are aligning the right edge of your text to the x value and the top of edge of the text to the y value.
Parameters:
Name Type Attributes Description
horizAlign Constant horizontal alignment, either LEFT, CENTER, or RIGHT
vertAlign Constant <optional>
vertical alignment, either TOP, BOTTOM, CENTER, or BASELINE
Example
textSize(16);
textAlign(RIGHT);
text('ABCD', 50, 30);
textAlign(CENTER);
text('EFGH', 50, 50);
textAlign(LEFT);
text('IJKL', 50, 70);

textSize(16);
strokeWeight(0.5);

line(0, 12, width, 12);
textAlign(CENTER, TOP);
text('TOP', 0, 12, width);

line(0, 37, width, 37);
textAlign(CENTER, CENTER);
text('CENTER', 0, 37, width);

line(0, 62, width, 62);
textAlign(CENTER, BASELINE);
text('BASELINE', 0, 62, width);

line(0, 87, width, 87);
textAlign(CENTER, BOTTOM);
text('BOTTOM', 0, 87, width);

inner textFont() → {Object}

Sets the current font that will be drawn with the text() function.

WEBGL: Only fonts loaded via loadFont() are supported.
Returns:
Object - the current font
Example
fill(0);
textSize(12);
textFont('Georgia');
text('Georgia', 12, 30);
textFont('Helvetica');
text('Helvetica', 12, 60);

let fontRegular, fontItalic, fontBold;
function setup() {
  fontRegular = loadFont('assets/Regular.otf');
  fontItalic = loadFont('assets/Italic.ttf');
  fontBold = loadFont('assets/Bold.ttf');
  background(210);
  fill(0);
  textFont(fontRegular);
  text('Font Style Normal', 10, 30);
  textFont(fontItalic);
  text('Font Style Italic', 10, 50);
  textFont(fontBold);
  text('Font Style Bold', 10, 70);
}

inner textSize() → {Number}

Gets the current font size.
Returns:
Number

inner textWidth(theText) → {Number}

Calculates and returns the width of any character or text string.
Parameters:
Name Type Description
theText String the String of characters to measure
Returns:
Number
Example
textSize(28);

let aChar = 'P';
let cWidth = textWidth(aChar);
text(aChar, 0, 40);
line(cWidth, 0, cWidth, 50);

let aString = 'p5.js';
let sWidth = textWidth(aString);
text(aString, 0, 85);
line(sWidth, 50, sWidth, 100);

inner trim(str) → {String}

Removes whitespace characters from the beginning and end of a String. In addition to standard whitespace characters such as space, carriage return, and tab, this function also removes the Unicode "nbsp" character.
Parameters:
Name Type Description
str String a String to be trimmed
Returns:
String - a trimmed String
Example
var string = trim('  No new lines\n   ');
text(string + ' here', 2, 50);

inner unchar(n) → {Number}

Converts a single-character string to its corresponding integer representation. When an array of single-character string values is passed in, then an array of integers of the same length is returned.
Parameters:
Name Type Description
n String value to parse
Returns:
Number - integer representation of value
Example
print(unchar('A')); // 65
print(unchar(['A', 'B', 'C'])); // [ 65, 66, 67 ]
print(unchar(split('ABC', ''))); // [ 65, 66, 67 ]

inner unhex(n) → {Number}

Converts a string representation of a hexadecimal number to its equivalent integer value. When an array of strings in hexadecimal notation is passed in, an array of integers of the same length is returned.
Parameters:
Name Type Description
n String value to parse
Returns:
Number - integer representation of hexadecimal value
Example
print(unhex('A')); // 10
print(unhex('FF')); // 255
print(unhex(['FF', 'AA', '00'])); // [ 255, 170, 0 ]

inner year() → {Integer}

The year() returns the current year as an integer (2014, 2015, 2016, etc).
Returns:
Integer - the current year
Example
var y = year();
text('Current year: \n' + y, 5, 50);

p5compat

Methods

static colorMode()

ignored

static createCanvas()

ignored

static exit()

exit the script after the current Loop().

static imageMode()

ignored

static noSmooth()

ignored

static noTint()

ignored

static settings()

ignored

static size()

ignored

static smooth()

ignored

static strokeWeight()

ignored

static tint()

ignored

inner abs(n) → {Number}

Calculates the absolute value (magnitude) of a number. Maps to Math.abs(). The absolute value of a number is always positive.
Parameters:
Name Type Description
n Number number to compute
Returns:
Number - absolute value of given number
Example
function setup() {
  let x = -3;
  let y = abs(x);

  print(x); // -3
  print(y); // 3
}

inner acos(value) → {Number}

The inverse of cos(), returns the arc cosine of a value. This function expects the values in the range of -1 to 1 and values are returned in the range 0 to PI (3.1415927).
Parameters:
Name Type Description
value Number the value whose arc cosine is to be returned
Returns:
Number - the arc cosine of the given value
Example
let a = PI;
let c = cos(a);
let ac = acos(c);
// Prints: "3.1415927 : -1.0 : 3.1415927"
print(a + ' : ' + c + ' : ' + ac);

let a = PI + PI / 4.0;
let c = cos(a);
let ac = acos(c);
// Prints: "3.926991 : -0.70710665 : 2.3561943"
print(a + ' : ' + c + ' : ' + ac);

inner angleMode(mode)

Sets the current mode of p5 to given mode. Default mode is RADIANS.
Parameters:
Name Type Description
mode Constant either RADIANS or DEGREES
Example
function draw() {
  background(204);
  angleMode(DEGREES); // Change the mode to DEGREES
  let a = atan2(mouseY - height / 2, mouseX - width / 2);
  translate(width / 2, height / 2);
  push();
  rotate(a);
  rect(-20, -5, 40, 10); // Larger rectangle is rotating in degrees
  pop();
  angleMode(RADIANS); // Change the mode to RADIANS
  rotate(a); // variable a stays the same
  rect(-40, -5, 20, 10); // Smaller rectangle is rotating in radians
}

inner append(array, value) → {Array}

Adds a value to the end of an array. Extends the length of the array by one. Maps to Array.push().
Parameters:
Name Type Description
array Array Array to append
value any to be added to the Array
Returns:
Array - the array that was appended to
Example
function setup() {
  var myArray = ['Mango', 'Apple', 'Papaya'];
  print(myArray); // ['Mango', 'Apple', 'Papaya']

  append(myArray, 'Peach');
  print(myArray); // ['Mango', 'Apple', 'Papaya', 'Peach']
}

inner arrayCopy(src, srcPosition, dst, dstPosition, length)

Copies an array (or part of an array) to another array. The src array is copied to the dst array, beginning at the position specified by srcPosition and into the position specified by dstPosition. The number of elements to copy is determined by length. Note that copying values overwrites existing values in the destination array. To append values instead of overwriting them, use concat().

The simplified version with only two arguments, arrayCopy(src, dst), copies an entire array to another of the same size. It is equivalent to arrayCopy(src, 0, dst, 0, src.length).

Using this function is far more efficient for copying array data than iterating through a for() loop and copying each element individually.
Parameters:
Name Type Description
src Array the source Array
srcPosition Integer starting position in the source Array
dst Array the destination Array
dstPosition Integer starting position in the destination Array
length Integer number of Array elements to be copied
Deprecated:
  • Yes
Example
var src = ['A', 'B', 'C'];
var dst = [1, 2, 3];
var srcPosition = 1;
var dstPosition = 0;
var length = 2;

print(src); // ['A', 'B', 'C']
print(dst); // [ 1 ,  2 ,  3 ]

arrayCopy(src, srcPosition, dst, dstPosition, length);
print(dst); // ['B', 'C', 3]

inner asin(value) → {Number}

The inverse of sin(), returns the arc sine of a value. This function expects the values in the range of -1 to 1 and values are returned in the range -PI/2 to PI/2.
Parameters:
Name Type Description
value Number the value whose arc sine is to be returned
Returns:
Number - the arc sine of the given value
Example
let a = PI + PI / 3;
let s = sin(a);
let as = asin(s);
// Prints: "1.0471976 : 0.86602545 : 1.0471976"
print(a + ' : ' + s + ' : ' + as);

let a = PI + PI / 3.0;
let s = sin(a);
let as = asin(s);
// Prints: "4.1887903 : -0.86602545 : -1.0471976"
print(a + ' : ' + s + ' : ' + as);

inner atan(value) → {Number}

The inverse of tan(), returns the arc tangent of a value. This function expects the values in the range of -Infinity to Infinity (exclusive) and values are returned in the range -PI/2 to PI/2.
Parameters:
Name Type Description
value Number the value whose arc tangent is to be returned
Returns:
Number - the arc tangent of the given value
Example
let a = PI + PI / 3;
let t = tan(a);
let at = atan(t);
// Prints: "1.0471976 : 1.7320509 : 1.0471976"
print(a + ' : ' + t + ' : ' + at);

let a = PI + PI / 3.0;
let t = tan(a);
let at = atan(t);
// Prints: "4.1887903 : 1.7320513 : 1.0471977"
print(a + ' : ' + t + ' : ' + at);

inner atan2(y, x) → {Number}

Calculates the angle (in radians) from a specified point to the coordinate origin as measured from the positive x-axis. Values are returned as a float in the range from PI to -PI. The atan2() function is most often used for orienting geometry to the position of the cursor.

Note: The y-coordinate of the point is the first parameter, and the x-coordinate is the second parameter, due the the structure of calculating the tangent.
Parameters:
Name Type Description
y Number y-coordinate of the point
x Number x-coordinate of the point
Returns:
Number - the arc tangent of the given point
Example
function draw() {
  background(204);
  translate(width / 2, height / 2);
  let a = atan2(mouseY - height / 2, mouseX - width / 2);
  rotate(a);
  rect(-30, -5, 60, 10);
}

inner boolean(n) → {Boolean}

Converts a number or string to its boolean representation. For a number, any non-zero value (positive or negative) evaluates to true, while zero evaluates to false. For a string, the value "true" evaluates to true, while any other value evaluates to false. When an array of number or string values is passed in, then a array of booleans of the same length is returned.
Parameters:
Name Type Description
n String | Boolean | Number | Array value to parse
Returns:
Boolean - boolean representation of value
Example
print(boolean(0)); // false
print(boolean(1)); // true
print(boolean('true')); // true
print(boolean('abcd')); // false
print(boolean([0, 12, 'true'])); // [false, true, false]

inner byte(n) → {Number}

Converts a number, string representation of a number, or boolean to its byte representation. A byte can be only a whole number between -128 and 127, so when a value outside of this range is converted, it wraps around to the corresponding byte representation. When an array of number, string or boolean values is passed in, then an array of bytes the same length is returned.
Parameters:
Name Type Description
n String | Boolean | Number value to parse
Returns:
Number - byte representation of value
Example
print(byte(127)); // 127
print(byte(128)); // -128
print(byte(23.4)); // 23
print(byte('23.4')); // 23
print(byte('hello')); // NaN
print(byte(true)); // 1
print(byte([0, 255, '100'])); // [0, -1, 100]

inner ceil(n) → {Integer}

Calculates the closest int value that is greater than or equal to the value of the parameter. Maps to Math.ceil(). For example, ceil(9.03) returns the value 10.
Parameters:
Name Type Description
n Number number to round up
Returns:
Integer - rounded up number
Example
function draw() {
  background(200);
  // map, mouseX between 0 and 5.
  let ax = map(mouseX, 0, 100, 0, 5);
  let ay = 66;

  //Get the ceiling of the mapped number.
  let bx = ceil(map(mouseX, 0, 100, 0, 5));
  let by = 33;

  // Multiply the mapped numbers by 20 to more easily
  // see the changes.
  stroke(0);
  fill(0);
  line(0, ay, ax * 20, ay);
  line(0, by, bx * 20, by);

  // Reformat the float returned by map and draw it.
  noStroke();
  text(nfc(ax, 2), ax, ay - 5);
  text(nfc(bx, 1), bx, by - 5);
}

inner char(n) → {String}

Converts a number or string to its corresponding single-character string representation. If a string parameter is provided, it is first parsed as an integer and then translated into a single-character string. When an array of number or string values is passed in, then an array of single-character strings of the same length is returned.
Parameters:
Name Type Description
n String | Number value to parse
Returns:
String - string representation of value
Example
print(char(65)); // "A"
print(char('65')); // "A"
print(char([65, 66, 67])); // [ "A", "B", "C" ]
print(join(char([65, 66, 67]), '')); // "ABC"

inner concat(a, b) → {Array}

Concatenates two arrays, maps to Array.concat(). Does not modify the input arrays.
Parameters:
Name Type Description
a Array first Array to concatenate
b Array second Array to concatenate
Returns:
Array - concatenated array
Example
function setup() {
  var arr1 = ['A', 'B', 'C'];
  var arr2 = [1, 2, 3];

  print(arr1); // ['A','B','C']
  print(arr2); // [1,2,3]

  var arr3 = concat(arr1, arr2);

  print(arr1); // ['A','B','C']
  print(arr2); // [1, 2, 3]
  print(arr3); // ['A','B','C', 1, 2, 3]
}

inner constrain(n, low, high) → {Number}

Constrains a value between a minimum and maximum value.
Parameters:
Name Type Description
n Number number to constrain
low Number minimum limit
high Number maximum limit
Returns:
Number - constrained number
Example
function draw() {
  background(200);

  let leftWall = 25;
  let rightWall = 75;

  // xm is just the mouseX, while
  // xc is the mouseX, but constrained
  // between the leftWall and rightWall!
  let xm = mouseX;
  let xc = constrain(mouseX, leftWall, rightWall);

  // Draw the walls.
  stroke(150);
  line(leftWall, 0, leftWall, height);
  line(rightWall, 0, rightWall, height);

  // Draw xm and xc as circles.
  noStroke();
  fill(150);
  ellipse(xm, 33, 9, 9); // Not Constrained
  fill(0);
  ellipse(xc, 66, 9, 9); // Constrained
}

inner cos(angle) → {Number}

Calculates the cosine of an angle. This function takes into account the current angleMode. Values are returned in the range -1 to 1.
Parameters:
Name Type Description
angle Number the angle
Returns:
Number - the cosine of the angle
Example
let a = 0.0;
let inc = TWO_PI / 25.0;
for (let i = 0; i < 25; i++) {
  line(i * 4, 50, i * 4, 50 + cos(a) * 40.0);
  a = a + inc;
}

inner createNumberDict(key, value) → {NumberDict}

Creates a new instance of NumberDict using the key-value pair or object you provide.
Parameters:
Name Type Description
key Number
value Number
Returns:
NumberDict
Example
function setup() {
  let myDictionary = createNumberDict(100, 42);
  print(myDictionary.hasKey(100)); // logs true to console

  let anotherDictionary = createNumberDict({ 200: 84 });
  print(anotherDictionary.hasKey(200)); // logs true to console
}

inner createStringDict(key, value) → {StringDict}

Creates a new instance of p5.StringDict using the key-value pair or the object you provide.
Parameters:
Name Type Description
key String
value String
Returns:
StringDict
Example
function setup() {
  let myDictionary = createStringDict('p5', 'js');
  print(myDictionary.hasKey('p5')); // logs true to console

  let anotherDictionary = createStringDict({ happy: 'coding' });
  print(anotherDictionary.hasKey('happy')); // logs true to console
}

inner createVector(xopt, yopt, zopt) → {p5.Vector}

Creates a new PVector (the datatype for storing vectors). This provides a two or three dimensional vector, specifically a Euclidean (also known as geometric) vector. A vector is an entity that has both magnitude and direction.
Parameters:
Name Type Attributes Description
x Number <optional>
x component of the vector
y Number <optional>
y component of the vector
z Number <optional>
z component of the vector
Returns:
p5.Vector
Example
function setup() {
  createCanvas(100, 100, WEBGL);
  noStroke();
  fill(255, 102, 204);
}

function draw() {
  background(255);
  pointLight(color(255), createVector(sin(millis() / 1000) * 20, -40, -10));
  scale(0.75);
  sphere();
}

inner day() → {Integer}

The day() function returns the current day as a value from 1 - 31.
Returns:
Integer - the current day
Example
var d = day();
text('Current day: \n' + d, 5, 50);

inner degrees(radians) → {Number}

Converts a radian measurement to its corresponding value in degrees. Radians and degrees are two ways of measuring the same thing. There are 360 degrees in a circle and 2*PI radians in a circle. For example, 90° = PI/2 = 1.5707964. This function does not take into account the current angleMode.
Parameters:
Name Type Description
radians Number the radians value to convert to degrees
Returns:
Number - the converted angle
Example
let rad = PI / 4;
let deg = degrees(rad);
print(rad + ' radians is ' + deg + ' degrees');
// Prints: 0.7853981633974483 radians is 45 degrees

inner displayDensity() → {Number}

Returns the pixel density of the current display the sketch is running on (always 1 for DOjS).
Returns:
Number - current pixel density of the display
Example
function setup() {
  let density = displayDensity();
  pixelDensity(density);
  createCanvas(100, 100);
  background(200);
  ellipse(width / 2, height / 2, 50, 50);
}

inner dist(x1, y1, x2, y2) → {Number}

Calculates the distance between two points.
Parameters:
Name Type Description
x1 Number x-coordinate of the first point
y1 Number y-coordinate of the first point
x2 Number x-coordinate of the second point
y2 Number y-coordinate of the second point
Returns:
Number - distance between the two points
Example
// Move your mouse inside the canvas to see the
// change in distance between two points!
function draw() {
  background(200);
  fill(0);

  let x1 = 10;
  let y1 = 90;
  let x2 = mouseX;
  let y2 = mouseY;

  line(x1, y1, x2, y2);
  ellipse(x1, y1, 7, 7);
  ellipse(x2, y2, 7, 7);

  // d is the length of the line
  // the distance from point 1 to point 2.
  let d = int(dist(x1, y1, x2, y2));

  // Let's write d along the line we are drawing!
  push();
  translate((x1 + x2) / 2, (y1 + y2) / 2);
  rotate(atan2(y2 - y1, x2 - x1));
  text(nfc(d, 1), 0, -5);
  pop();
  // Fancy!
}

inner exp(n) → {Number}

Returns Euler's number e (2.71828...) raised to the power of the n parameter. Maps to Math.exp().
Parameters:
Name Type Description
n Number exponent to raise
Returns:
Number - e^n
Example
function draw() {
  background(200);

  // Compute the exp() function with a value between 0 and 2
  let xValue = map(mouseX, 0, width, 0, 2);
  let yValue = exp(xValue);

  let y = map(yValue, 0, 8, height, 0);

  let legend = 'exp (' + nfc(xValue, 3) + ')\n= ' + nf(yValue, 1, 4);
  stroke(150);
  line(mouseX, y, mouseX, height);
  fill(0);
  text(legend, 5, 15);
  noStroke();
  ellipse(mouseX, y, 7, 7);

  // Draw the exp(x) curve,
  // over the domain of x from 0 to 2
  noFill();
  stroke(0);
  beginShape();
  for (let x = 0; x < width; x++) {
    xValue = map(x, 0, width, 0, 2);
    yValue = exp(xValue);
    y = map(yValue, 0, 8, height, 0);
    vertex(x, y);
  }

  endShape();
  line(0, 0, 0, height);
  line(0, height - 1, width, height - 1);
}

inner float(str) → {Number}

Converts a string to its floating point representation. The contents of a string must resemble a number, or NaN (not a number) will be returned. For example, float("1234.56") evaluates to 1234.56, but float("giraffe") will return NaN. When an array of values is passed in, then an array of floats of the same length is returned.
Parameters:
Name Type Description
str String float string to parse
Returns:
Number - floating point representation of string
Example
var str = '20';
var diameter = float(str);
ellipse(width / 2, height / 2, diameter, diameter);

inner floor(n) → {Integer}

Calculates the closest int value that is less than or equal to the value of the parameter. Maps to Math.floor().
Parameters:
Name Type Description
n Number number to round down
Returns:
Integer - rounded down number
Example
function draw() {
  background(200);
  //map, mouseX between 0 and 5.
  let ax = map(mouseX, 0, 100, 0, 5);
  let ay = 66;

  //Get the floor of the mapped number.
  let bx = floor(map(mouseX, 0, 100, 0, 5));
  let by = 33;

  // Multiply the mapped numbers by 20 to more easily
  // see the changes.
  stroke(0);
  fill(0);
  line(0, ay, ax * 20, ay);
  line(0, by, bx * 20, by);

  // Reformat the float returned by map and draw it.
  noStroke();
  text(nfc(ax, 2), ax, ay - 5);
  text(nfc(bx, 1), bx, by - 5);
}

inner hex(n, digitsopt) → {String}

Converts a number to a string in its equivalent hexadecimal notation. If a second parameter is passed, it is used to set the number of characters to generate in the hexadecimal notation. When an array is passed in, an array of strings in hexadecimal notation of the same length is returned.
Parameters:
Name Type Attributes Description
n Number value to parse
digits Number <optional>
Returns:
String - hexadecimal string representation of value
Example
print(hex(255)); // "000000FF"
print(hex(255, 6)); // "0000FF"
print(hex([0, 127, 255], 6)); // [ "000000", "00007F", "0000FF" ]

inner hour() → {Integer}

The hour() function returns the current hour as a value from 0 - 23.
Returns:
Integer - the current hour
Example
var h = hour();
text('Current hour:\n' + h, 5, 50);

inner int(n, radixopt) → {Number}

Converts a boolean, string, or float to its integer representation. When an array of values is passed in, then an int array of the same length is returned.
Parameters:
Name Type Attributes Description
n String | Boolean | Number value to parse
radix Integer <optional>
the radix to convert to (default: 10)
Returns:
Number - integer representation of value
Example
print(int('10')); // 10
print(int(10.31)); // 10
print(int(-10)); // -10
print(int(true)); // 1
print(int(false)); // 0
print(int([false, true, '10.3', 9.8])); // [0, 1, 10, 9]

inner join(list, separator) → {String}

Combines an array of Strings into one String, each separated by the character(s) used for the separator parameter. To join arrays of ints or floats, it's necessary to first convert them to Strings using nf() or nfs().
Parameters:
Name Type Description
list Array array of Strings to be joined
separator String String to be placed between each item
Returns:
String - joined String
Example
var array = ['Hello', 'world!'];
var separator = ' ';
var message = join(array, separator);
text(message, 5, 50);

inner lerp(start, stop, amt) → {Number}

Calculates a number between two numbers at a specific increment. The amt parameter is the amount to interpolate between the two values where 0.0 equal to the first point, 0.1 is very near the first point, 0.5 is half-way in between, and 1.0 is equal to the second point. If the value of amt is more than 1.0 or less than 0.0, the number will be calculated accordingly in the ratio of the two given numbers. The lerp function is convenient for creating motion along a straight path and for drawing dotted lines.
Parameters:
Name Type Description
start Number first value
stop Number second value
amt Number number
Returns:
Number - lerped value
Example
function setup() {
  background(200);
  let a = 20;
  let b = 80;
  let c = lerp(a, b, 0.2);
  let d = lerp(a, b, 0.5);
  let e = lerp(a, b, 0.8);

  let y = 50;

  strokeWeight(5);
  stroke(0); // Draw the original points in black
  point(a, y);
  point(b, y);

  stroke(100); // Draw the lerp points in gray
  point(c, y);
  point(d, y);
  point(e, y);
}

inner loadFont(path) → {Font}

Loads a GRX font file (.FNT) from a file Font Object.

Parameters:
Name Type Description
path String name of the file or url to load
Returns:
Font - Font object

inner log(n) → {Number}

Calculates the natural logarithm (the base-e logarithm) of a number. This function expects the n parameter to be a value greater than 0.0. Maps to Math.log().
Parameters:
Name Type Description
n Number number greater than 0
Returns:
Number - natural logarithm of n
Example
function draw() {
  background(200);
  let maxX = 2.8;
  let maxY = 1.5;

  // Compute the natural log of a value between 0 and maxX
  let xValue = map(mouseX, 0, width, 0, maxX);
  let yValue, y;
  if (xValue > 0) {
  // Cannot take the log of a negative number.
    yValue = log(xValue);
    y = map(yValue, -maxY, maxY, height, 0);

    // Display the calculation occurring.
    let legend = 'log(' + nf(xValue, 1, 2) + ')\n= ' + nf(yValue, 1, 3);
    stroke(150);
    line(mouseX, y, mouseX, height);
    fill(0);
    text(legend, 5, 15);
    noStroke();
    ellipse(mouseX, y, 7, 7);
  }

  // Draw the log(x) curve,
  // over the domain of x from 0 to maxX
  noFill();
  stroke(0);
  beginShape();
  for (let x = 0; x < width; x++) {
    xValue = map(x, 0, width, 0, maxX);
    yValue = log(xValue);
    y = map(yValue, -maxY, maxY, height, 0);
    vertex(x, y);
  }
  endShape();
  line(0, 0, 0, height);
  line(0, height / 2, width, height / 2);
}

inner loop()

By default, p5.js loops through draw() continuously, executing the code within it. However, the draw() loop may be stopped by calling noLoop(). In that case, the draw() loop can be resumed with loop(). Avoid calling loop() from inside setup().
Example
let x = 0;
function setup() {
  createCanvas(100, 100);
  noLoop();
}

function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}

function mousePressed() {
  loop();
}

function mouseReleased() {
  noLoop();
}

inner mag(a, b) → {Number}

Calculates the magnitude (or length) of a vector. A vector is a direction in space commonly used in computer graphics and linear algebra. Because it has no "start" position, the magnitude of a vector can be thought of as the distance from the coordinate 0,0 to its x,y value. Therefore, mag() is a shortcut for writing dist(0, 0, x, y).
Parameters:
Name Type Description
a Number first value
b Number second value
Returns:
Number - magnitude of vector from (0,0) to (a,b)
Example
function setup() {
  let x1 = 20;
  let x2 = 80;
  let y1 = 30;
  let y2 = 70;

  line(0, 0, x1, y1);
  print(mag(x1, y1)); // Prints "36.05551275463989"
  line(0, 0, x2, y1);
  print(mag(x2, y1)); // Prints "85.44003745317531"
  line(0, 0, x1, y2);
  print(mag(x1, y2)); // Prints "72.80109889280519"
  line(0, 0, x2, y2);
  print(mag(x2, y2)); // Prints "106.3014581273465"
}

inner map(value, start1, stop1, start2, stop2, withinBoundsopt) → {Number}

Re-maps a number from one range to another.

In the first example above, the number 25 is converted from a value in the range of 0 to 100 into a value that ranges from the left edge of the window (0) to the right edge (width).
Parameters:
Name Type Attributes Description
value Number the incoming value to be converted
start1 Number lower bound of the value's current range
stop1 Number upper bound of the value's current range
start2 Number lower bound of the value's target range
stop2 Number upper bound of the value's target range
withinBounds Boolean <optional>
constrain the value to the newly mapped range
Returns:
Number - remapped number
Example
let value = 25;
let m = map(value, 0, 100, 0, width);
ellipse(m, 50, 10, 10);

function setup() {
  noStroke();
}

function draw() {
  background(204);
  let x1 = map(mouseX, 0, width, 25, 75);
  ellipse(x1, 25, 25, 25);
  //This ellipse is constrained to the 0-100 range
  //after setting withinBounds to true
  let x2 = map(mouseX, 0, width, 0, 100, true);
  ellipse(x2, 75, 25, 25);
}

inner match(str, regexp) → {Array.<String>}

This function is used to apply a regular expression to a piece of text, and return matching groups (elements found inside parentheses) as a String array. If there are no matches, a null value will be returned. If no groups are specified in the regular expression, but the sequence matches, an array of length 1 (with the matched text as the first element of the array) will be returned.

To use the function, first check to see if the result is null. If the result is null, then the sequence did not match at all. If the sequence did match, an array is returned.

If there are groups (specified by sets of parentheses) in the regular expression, then the contents of each will be returned in the array. Element [0] of a regular expression match returns the entire matching string, and the match groups start at element [1] (the first group is [1], the second [2], and so on).
Parameters:
Name Type Description
str String the String to be searched
regexp String the regexp to be used for matching
Returns:
Array.<String> - Array of Strings found
Example
var string = 'Hello p5js*!';
var regexp = 'p5js\\*';
var m = match(string, regexp);
text(m, 5, 50);

inner matchAll(str, regexp) → {Array.<String>}

This function is used to apply a regular expression to a piece of text, and return a list of matching groups (elements found inside parentheses) as a two-dimensional String array. If there are no matches, a null value will be returned. If no groups are specified in the regular expression, but the sequence matches, a two dimensional array is still returned, but the second dimension is only of length one.

To use the function, first check to see if the result is null. If the result is null, then the sequence did not match at all. If the sequence did match, a 2D array is returned.

If there are groups (specified by sets of parentheses) in the regular expression, then the contents of each will be returned in the array. Assuming a loop with counter variable i, element [i][0] of a regular expression match returns the entire matching string, and the match groups start at element [i][1] (the first group is [i][1], the second [i][2], and so on).
Parameters:
Name Type Description
str String the String to be searched
regexp String the regexp to be used for matching
Returns:
Array.<String> - 2d Array of Strings found
Example
var string = 'Hello p5js*! Hello world!';
var regexp = 'Hello';
matchAll(string, regexp);

inner max(n0, n1) → {Number}

Determines the largest value in a sequence of numbers, and then returns that value. max() accepts any number of Number parameters, or an Array of any length.
Parameters:
Name Type Description
n0 Number Number to compare
n1 Number Number to compare
Returns:
Number - maximum Number
Example
function setup() {
  // Change the elements in the array and run the sketch
  // to show how max() works!
  let numArray = [2, 1, 5, 4, 8, 9];
  fill(0);
  noStroke();
  text('Array Elements', 0, 10);
  // Draw all numbers in the array
  let spacing = 15;
  let elemsY = 25;
  for (let i = 0; i < numArray.length; i++) {
    text(numArray[i], i * spacing, elemsY);
  }
  let maxX = 33;
  let maxY = 80;
  // Draw the Maximum value in the array.
  textSize(32);
  text(max(numArray), maxX, maxY);
}

inner millis() → {Number}

Returns the number of milliseconds (thousandths of a second) since starting the program. This information is often used for timing events and animation sequences.
Returns:
Number - the number of milliseconds since starting the program
Example
var millisecond = millis();
text('Milliseconds \nrunning: \n' + millisecond, 5, 40);

inner min(n0, n1) → {Number}

Determines the smallest value in a sequence of numbers, and then returns that value. min() accepts any number of Number parameters, or an Array of any length.
Parameters:
Name Type Description
n0 Number Number to compare
n1 Number Number to compare
Returns:
Number - minimum Number
Example
function setup() {
  // Change the elements in the array and run the sketch
  // to show how min() works!
  let numArray = [2, 1, 5, 4, 8, 9];
  fill(0);
  noStroke();
  text('Array Elements', 0, 10);
  // Draw all numbers in the array
  let spacing = 15;
  let elemsY = 25;
  for (let i = 0; i < numArray.length; i++) {
    text(numArray[i], i * spacing, elemsY);
  }
  let maxX = 33;
  let maxY = 80;
  // Draw the Minimum value in the array.
  textSize(32);
  text(min(numArray), maxX, maxY);
}

inner minute() → {Integer}

The minute() function returns the current minute as a value from 0 - 59.
Returns:
Integer - the current minute
Example
var m = minute();
text('Current minute: \n' + m, 5, 50);

inner month() → {Integer}

The month() function returns the current month as a value from 1 - 12.
Returns:
Integer - the current month
Example
var m = month();
text('Current month: \n' + m, 5, 50);

inner nf(num, leftopt, rightopt) → {String}

Utility function for formatting numbers into strings. There are two versions: one for formatting floats, and one for formatting ints. The values for the digits, left, and right parameters should always be positive integers. (NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter if greater than the current length of the number. For example if number is 123.2 and left parameter passed is 4 which is greater than length of 123 (integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than the result will be 123.200.
Parameters:
Name Type Attributes Description
num Number | String the Number to format
left Integer | String <optional>
number of digits to the left of the decimal point
right Integer | String <optional>
number of digits to the right of the decimal point
Returns:
String - formatted String
Example
var myFont;
function preload() {
  myFont = loadFont('assets/fonts/inconsolata.ttf');
}
function setup() {
  background(200);
  var num1 = 321;
  var num2 = -1321;

  noStroke();
  fill(0);
  textFont(myFont);
  textSize(22);

  text(nf(num1, 4, 2), 10, 30);
  text(nf(num2, 4, 2), 10, 80);
  // Draw dividing line
  stroke(120);
  line(0, 50, width, 50);
}

inner nfc(num, rightopt) → {String}

Utility function for formatting numbers into strings and placing appropriate commas to mark units of 1000. There are two versions: one for formatting ints, and one for formatting an array of ints. The value for the right parameter should always be a positive integer.
Parameters:
Name Type Attributes Description
num Number | String the Number to format
right Integer | String <optional>
number of digits to the right of the decimal point
Returns:
String - formatted String
Example
function setup() {
  background(200);
  var num = 11253106.115;
  var numArr = [1, 1, 2];

  noStroke();
  fill(0);
  textSize(12);

  // Draw formatted numbers
  text(nfc(num, 4), 10, 30);
  text(nfc(numArr, 2), 10, 80);

  // Draw dividing line
  stroke(120);
  line(0, 50, width, 50);
}

inner nfp(num, leftopt, rightopt) → {String}

Utility function for formatting numbers into strings. Similar to nf() but puts a "+" in front of positive numbers and a "-" in front of negative numbers. There are two versions: one for formatting floats, and one for formatting ints. The values for left, and right parameters should always be positive integers.
Parameters:
Name Type Attributes Description
num Number the Number to format
left Integer <optional>
number of digits to the left of the decimal point
right Integer <optional>
number of digits to the right of the decimal point
Returns:
String - formatted String
Example
function setup() {
  background(200);
  var num1 = 11253106.115;
  var num2 = -11253106.115;

  noStroke();
  fill(0);
  textSize(12);

  // Draw formatted numbers
  text(nfp(num1, 4, 2), 10, 30);
  text(nfp(num2, 4, 2), 10, 80);

  // Draw dividing line
  stroke(120);
  line(0, 50, width, 50);
}

inner nfs(num, leftopt, rightopt) → {String}

Utility function for formatting numbers into strings. Similar to nf() but puts an additional "_" (space) in front of positive numbers just in case to align it with negative numbers which includes "-" (minus) sign. The main usecase of nfs() can be seen when one wants to align the digits (place values) of a positive number with some negative number (See the example to get a clear picture). There are two versions: one for formatting float, and one for formatting int. The values for the digits, left, and right parameters should always be positive integers. (IMP): The result on the canvas basically the expected alignment can vary based on the typeface you are using. (NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter if greater than the current length of the number. For example if number is 123.2 and left parameter passed is 4 which is greater than length of 123 (integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than the result will be 123.200.
Parameters:
Name Type Attributes Description
num Number the Number to format
left Integer <optional>
number of digits to the left of the decimal point
right Integer <optional>
number of digits to the right of the decimal point
Returns:
String - formatted String
Example
var myFont;
function preload() {
  myFont = loadFont('assets/fonts/inconsolata.ttf');
}
function setup() {
  background(200);
  var num1 = 321;
  var num2 = -1321;

  noStroke();
  fill(0);
  textFont(myFont);
  textSize(22);

  // nfs() aligns num1 (positive number) with num2 (negative number) by
  // adding a blank space in front of the num1 (positive number)
  // [left = 4] in num1 add one 0 in front, to align the digits with num2
  // [right = 2] in num1 and num2 adds two 0's after both numbers
  // To see the differences check the example of nf() too.
  text(nfs(num1, 4, 2), 10, 30);
  text(nfs(num2, 4, 2), 10, 80);
  // Draw dividing line
  stroke(120);
  line(0, 50, width, 50);
}

inner noCursor()

Hides the cursor from view.
Example
function setup() {
  noCursor();
}

function draw() {
  background(200);
  ellipse(mouseX, mouseY, 10, 10);
}

inner noise(x, yopt, zopt) → {Number}

Returns the Perlin noise value at specified coordinates. Perlin noise is a random sequence generator producing a more natural ordered, harmonic succession of numbers compared to the standard random() function. It was invented by Ken Perlin in the 1980s and been used since in graphical applications to produce procedural textures, natural motion, shapes, terrains etc.

The main difference to the random() function is that Perlin noise is defined in an infinite n-dimensional space where each pair of coordinates corresponds to a fixed semi-random value (fixed only for the lifespan of the program; see the noiseSeed() function). p5.js can compute 1D, 2D and 3D noise, depending on the number of coordinates given. The resulting value will always be between 0.0 and 1.0. The noise value can be animated by moving through the noise space as demonstrated in the example above. The 2nd and 3rd dimension can also be interpreted as time.

The actual noise is structured similar to an audio signal, in respect to the function's use of frequencies. Similar to the concept of harmonics in physics, perlin noise is computed over several octaves which are added together for the final result.

Another way to adjust the character of the resulting sequence is the scale of the input coordinates. As the function works within an infinite space the value of the coordinates doesn't matter as such, only the distance between successive coordinates does (eg. when using noise() within a loop). As a general rule the smaller the difference between coordinates, the smoother the resulting noise sequence will be. Steps of 0.005-0.03 work best for most applications, but this will differ depending on use.
Parameters:
Name Type Attributes Description
x Number x-coordinate in noise space
y Number <optional>
y-coordinate in noise space
z Number <optional>
z-coordinate in noise space
Returns:
Number - Perlin noise value (between 0 and 1) at specified coordinates
Example
let xoff = 0.0;

function draw() {
  background(204);
  xoff = xoff + 0.01;
  let n = noise(xoff) * width;
  line(n, 0, n, height);
}

let noiseScale=0.02;

function draw() {
  background(0);
  for (let x=0; x < width; x++) {
    let noiseVal = noise((mouseX+x)*noiseScale, mouseY*noiseScale);
    stroke(noiseVal*255);
    line(x, mouseY+noiseVal*80, x, height);
  }
}

inner noiseDetail(lod, falloff)

Adjusts the character and level of detail produced by the Perlin noise function. Similar to harmonics in physics, noise is computed over several octaves. Lower octaves contribute more to the output signal and as such define the overall intensity of the noise, whereas higher octaves create finer grained details in the noise sequence.

By default, noise is computed over 4 octaves with each octave contributing exactly half than its predecessor, starting at 50% strength for the 1st octave. This falloff amount can be changed by adding an additional function parameter. Eg. a falloff factor of 0.75 means each octave will now have 75% impact (25% less) of the previous lower octave. Any value between 0.0 and 1.0 is valid, however note that values greater than 0.5 might result in greater than 1.0 values returned by noise().

By changing these parameters, the signal created by the noise() function can be adapted to fit very specific needs and characteristics.
Parameters:
Name Type Description
lod Number number of octaves to be used by the noise
falloff Number falloff factor for each octave
Example
let noiseVal;
let noiseScale = 0.02;

function setup() {
  createCanvas(100, 100);
}

function draw() {
  background(0);
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width / 2; x++) {
      noiseDetail(2, 0.2);
      noiseVal = noise((mouseX + x) * noiseScale, (mouseY + y) * noiseScale);
      stroke(noiseVal * 255);
      point(x, y);
      noiseDetail(8, 0.65);
      noiseVal = noise(
        (mouseX + x + width / 2) * noiseScale,
        (mouseY + y) * noiseScale
      );
      stroke(noiseVal * 255);
      point(x + width / 2, y);
    }
  }
}

inner noLoop()

Stops p5.js from continuously executing the code within draw(). If loop() is called, the code in draw() begins to run continuously again. If using noLoop() in setup(), it should be the last line inside the block.

When noLoop() is used, it's not possible to manipulate or access the screen inside event handling functions such as mousePressed() or keyPressed(). Instead, use those functions to call redraw() or loop(), which will run draw(), which can update the screen properly. This means that when noLoop() has been called, no drawing can happen, and functions like saveFrame() or loadPixels() may not be used.

Note that if the sketch is resized, redraw() will be called to update the sketch, even after noLoop() has been specified. Otherwise, the sketch would enter an odd state until loop() was called.
Example
function setup() {
  createCanvas(100, 100);
  background(200);
  noLoop();
}

function draw() {
  line(10, 10, 90, 90);
}

let x = 0;
function setup() {
  createCanvas(100, 100);
}

function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}

function mousePressed() {
  noLoop();
}

function mouseReleased() {
  loop();
}

inner norm(value, start, stop) → {Number}

Normalizes a number from another range into a value between 0 and 1. Identical to map(value, low, high, 0, 1). Numbers outside of the range are not clamped to 0 and 1, because out-of-range values are often intentional and useful. (See the second example above.)
Parameters:
Name Type Description
value Number incoming value to be normalized
start Number lower bound of the value's current range
stop Number upper bound of the value's current range
Returns:
Number - normalized number
Example
function draw() {
  background(200);
  let currentNum = mouseX;
  let lowerBound = 0;
  let upperBound = width; //100;
  let normalized = norm(currentNum, lowerBound, upperBound);
  let lineY = 70;
  line(0, lineY, width, lineY);
  //Draw an ellipse mapped to the non-normalized value.
  noStroke();
  fill(50);
  let s = 7; // ellipse size
  ellipse(currentNum, lineY, s, s);

  // Draw the guide
  let guideY = lineY + 15;
  text('0', 0, guideY);
  textAlign(RIGHT);
  text('100', width, guideY);

  // Draw the normalized value
  textAlign(LEFT);
  fill(0);
  textSize(32);
  let normalY = 40;
  let normalX = 20;
  text(normalized, normalX, normalY);
}

inner pow(n, e) → {Number}

Facilitates exponential expressions. The pow() function is an efficient way of multiplying numbers by themselves (or their reciprocals) in large quantities. For example, pow(3, 5) is equivalent to the expression 3*3*3*3*3 and pow(3, -5) is equivalent to 1 / 3*3*3*3*3. Maps to Math.pow().
Parameters:
Name Type Description
n Number base of the exponential expression
e Number power by which to raise the base
Returns:
Number - n^e
Example
function setup() {
  //Exponentially increase the size of an ellipse.
  let eSize = 3; // Original Size
  let eLoc = 10; // Original Location

  ellipse(eLoc, eLoc, eSize, eSize);

  ellipse(eLoc * 2, eLoc * 2, pow(eSize, 2), pow(eSize, 2));

  ellipse(eLoc * 4, eLoc * 4, pow(eSize, 3), pow(eSize, 3));

  ellipse(eLoc * 8, eLoc * 8, pow(eSize, 4), pow(eSize, 4));
}

inner radians(degrees) → {Number}

Converts a degree measurement to its corresponding value in radians. Radians and degrees are two ways of measuring the same thing. There are 360 degrees in a circle and 2*PI radians in a circle. For example, 90° = PI/2 = 1.5707964. This function does not take into account the current angleMode.
Parameters:
Name Type Description
degrees Number the degree value to convert to radians
Returns:
Number - the converted angle
Example
let deg = 45.0;
let rad = radians(deg);
print(deg + ' degrees is ' + rad + ' radians');
// Prints: 45 degrees is 0.7853981633974483 radians

inner random(minopt, maxopt) → {Number}

Return a random floating-point number. Takes either 0, 1 or 2 arguments. If no argument is given, returns a random number from 0 up to (but not including) 1. If one argument is given and it is a number, returns a random number from 0 up to (but not including) the number. If one argument is given and it is an array, returns a random element from that array. If two arguments are given, returns a random number from the first argument up to (but not including) the second argument.
Parameters:
Name Type Attributes Description
min Number <optional>
the lower bound (inclusive)
max Number <optional>
the upper bound (exclusive)
Returns:
Number - the random number
Example
for (let i = 0; i < 100; i++) {
  let r = random(50);
  stroke(r * 5);
  line(50, i, 50 + r, i);
}

for (let i = 0; i < 100; i++) {
  let r = random(-50, 50);
  line(50, i, 50 + r, i);
}

// Get a random element from an array using the random(Array) syntax
let words = ['apple', 'bear', 'cat', 'dog'];
let word = random(words); // select random word
text(word, 10, 50); // draw the word

inner randomGaussian(mean, sd) → {Number}

Returns a random number fitting a Gaussian, or normal, distribution. There is theoretically no minimum or maximum value that randomGaussian() might return. Rather, there is just a very low probability that values far from the mean will be returned; and a higher probability that numbers near the mean will be returned.

Takes either 0, 1 or 2 arguments.
If no args, returns a mean of 0 and standard deviation of 1.
If one arg, that arg is the mean (standard deviation is 1).
If two args, first is mean, second is standard deviation.
Parameters:
Name Type Description
mean Number the mean
sd Number the standard deviation
Returns:
Number - the random number
Example
for (let y = 0; y < 100; y++) {
  let x = randomGaussian(50, 15);
  line(50, y, x, y);
}

let distribution = new Array(360);

function setup() {
  createCanvas(100, 100);
  for (let i = 0; i < distribution.length; i++) {
    distribution[i] = floor(randomGaussian(0, 15));
  }
}

function draw() {
  background(204);

  translate(width / 2, width / 2);

  for (let i = 0; i < distribution.length; i++) {
    rotate(TWO_PI / distribution.length);
    stroke(0);
    let dist = abs(distribution[i]);
    line(0, 0, dist, 0);
  }
}

inner randomSeed(seed)

Sets the seed value for random(). By default, random() produces different results each time the program is run. Set the seed parameter to a constant to return the same pseudo-random numbers each time the software is run.
Parameters:
Name Type Description
seed Number the seed value
Example
randomSeed(99);
for (let i = 0; i < 100; i++) {
  let r = random(0, 255);
  stroke(r);
  line(i, 0, i, 100);
}

inner redraw(nopt)

Executes the code within draw() one time. This functions allows the program to update the display window only when necessary, for example when an event registered by mousePressed() or keyPressed() occurs.

In structuring a program, it only makes sense to call redraw() within events such as mousePressed(). This is because redraw() does not run draw() immediately (it only sets a flag that indicates an update is needed).

The redraw() function does not work properly when called inside draw(). To enable/disable animations, use loop() and noLoop().

In addition you can set the number of redraws per method call. Just add an integer as single parameter for the number of redraws.
Parameters:
Name Type Attributes Description
n Integer <optional>
Redraw for n-times. The default value is 1.
Example
let x = 0;

function setup() {
  createCanvas(100, 100);
  noLoop();
}

function draw() {
  background(204);
  line(x, 0, x, height);
}

function mousePressed() {
  x += 1;
  redraw();
}

let x = 0;

function setup() {
  createCanvas(100, 100);
  noLoop();
}

function draw() {
  background(204);
  x += 1;
  line(x, 0, x, height);
}

function mousePressed() {
  redraw(5);
}

inner reverse(list) → {Array}

Reverses the order of an array, maps to Array.reverse()
Parameters:
Name Type Description
list Array Array to reverse
Returns:
Array - the reversed list
Example
function setup() {
  var myArray = ['A', 'B', 'C'];
  print(myArray); // ['A','B','C']

  reverse(myArray);
  print(myArray); // ['C','B','A']
}

inner round(n) → {Integer}

Calculates the integer closest to the n parameter. For example, round(133.8) returns the value 134. Maps to Math.round().
Parameters:
Name Type Description
n Number number to round
Returns:
Integer - rounded number
Example
function draw() {
  background(200);
  //map, mouseX between 0 and 5.
  let ax = map(mouseX, 0, 100, 0, 5);
  let ay = 66;

  // Round the mapped number.
  let bx = round(map(mouseX, 0, 100, 0, 5));
  let by = 33;

  // Multiply the mapped numbers by 20 to more easily
  // see the changes.
  stroke(0);
  fill(0);
  line(0, ay, ax * 20, ay);
  line(0, by, bx * 20, by);

  // Reformat the float returned by map and draw it.
  noStroke();
  text(nfc(ax, 2), ax, ay - 5);
  text(nfc(bx, 1), bx, by - 5);
}

inner second() → {Integer}

The second() function returns the current second as a value from 0 - 59.
Returns:
Integer - the current second
Example
var s = second();
text('Current second: \n' + s, 5, 50);

inner shorten(list) → {Array}

Decreases an array by one element and returns the shortened array, maps to Array.pop().
Parameters:
Name Type Description
list Array Array to shorten
Returns:
Array - shortened Array
Example
function setup() {
  var myArray = ['A', 'B', 'C'];
  print(myArray); // ['A', 'B', 'C']
  var newArray = shorten(myArray);
  print(myArray); // ['A','B','C']
  print(newArray); // ['A','B']
}

inner shuffle(array, boolopt) → {Array}

Randomizes the order of the elements of an array. Implements Fisher-Yates Shuffle Algorithm.
Parameters:
Name Type Attributes Description
array Array Array to shuffle
bool Boolean <optional>
modify passed array
Returns:
Array - shuffled Array
Example
function setup() {
  var regularArr = ['ABC', 'def', createVector(), TAU, Math.E];
  print(regularArr);
  shuffle(regularArr, true); // force modifications to passed array
  print(regularArr);

  // By default shuffle() returns a shuffled cloned array:
  var newArr = shuffle(regularArr);
  print(regularArr);
  print(newArr);
}

inner sin(angle) → {Number}

Calculates the sine of an angle. This function takes into account the current angleMode. Values are returned in the range -1 to 1.
Parameters:
Name Type Description
angle Number the angle
Returns:
Number - the sine of the angle
Example
let a = 0.0;
let inc = TWO_PI / 25.0;
for (let i = 0; i < 25; i++) {
  line(i * 4, 50, i * 4, 50 + sin(a) * 40.0);
  a = a + inc;
}

inner sort(list, countopt) → {Array}

Sorts an array of numbers from smallest to largest, or puts an array of words in alphabetical order. The original array is not modified; a re-ordered array is returned. The count parameter states the number of elements to sort. For example, if there are 12 elements in an array and count is set to 5, only the first 5 elements in the array will be sorted.
Parameters:
Name Type Attributes Description
list Array Array to sort
count Integer <optional>
number of elements to sort, starting from 0
Returns:
Array - the sorted list
Example
function setup() {
  var words = ['banana', 'apple', 'pear', 'lime'];
  print(words); // ['banana', 'apple', 'pear', 'lime']
  var count = 4; // length of array

  words = sort(words, count);
  print(words); // ['apple', 'banana', 'lime', 'pear']
}

function setup() {
  var numbers = [2, 6, 1, 5, 14, 9, 8, 12];
  print(numbers); // [2, 6, 1, 5, 14, 9, 8, 12]
  var count = 5; // Less than the length of the array

  numbers = sort(numbers, count);
  print(numbers); // [1,2,5,6,14,9,8,12]
}

inner splice(list, value, position) → {Array}

Inserts a value or an array of values into an existing array. The first parameter specifies the initial array to be modified, and the second parameter defines the data to be inserted. The third parameter is an index value which specifies the array position from which to insert data. (Remember that array index numbering starts at zero, so the first position is 0, the second position is 1, and so on.)
Parameters:
Name Type Description
list Array Array to splice into
value any value to be spliced in
position Integer in the array from which to insert data
Returns:
Array - the list
Example
function setup() {
  var myArray = [0, 1, 2, 3, 4];
  var insArray = ['A', 'B', 'C'];
  print(myArray); // [0, 1, 2, 3, 4]
  print(insArray); // ['A','B','C']

  splice(myArray, insArray, 3);
  print(myArray); // [0,1,2,'A','B','C',3,4]
}

inner split(value, delim) → {Array.<String>}

The split() function maps to String.split(), it breaks a String into pieces using a character or string as the delimiter. The delim parameter specifies the character or characters that mark the boundaries between each piece. A String[] array is returned that contains each of the pieces. The splitTokens() function works in a similar fashion, except that it splits using a range of characters instead of a specific character or sequence.
Parameters:
Name Type Description
value String the String to be split
delim String the String used to separate the data
Returns:
Array.<String> - Array of Strings
Example
var names = 'Pat,Xio,Alex';
var splitString = split(names, ',');
text(splitString[0], 5, 30);
text(splitString[1], 5, 50);
text(splitString[2], 5, 70);

inner splitTokens(value, delimopt) → {Array.<String>}

The splitTokens() function splits a String at one or many character delimiters or "tokens." The delim parameter specifies the character or characters to be used as a boundary.

If no delim characters are specified, any whitespace character is used to split. Whitespace characters include tab (\t), line feed (\n), carriage return (\r), form feed (\f), and space.
Parameters:
Name Type Attributes Description
value String the String to be split
delim String <optional>
list of individual Strings that will be used as separators
Returns:
Array.<String> - Array of Strings
Example
function setup() {
  var myStr = 'Mango, Banana, Lime';
  var myStrArr = splitTokens(myStr, ',');

  print(myStrArr); // prints : ["Mango"," Banana"," Lime"]
}

inner sq(n) → {Number}

Squares a number (multiplies a number by itself). The result is always a positive number, as multiplying two negative numbers always yields a positive result. For example, -1 * -1 = 1.
Parameters:
Name Type Description
n Number number to square
Returns:
Number - squared number
Example
function draw() {
  background(200);
  let eSize = 7;
  let x1 = map(mouseX, 0, width, 0, 10);
  let y1 = 80;
  let x2 = sq(x1);
  let y2 = 20;

  // Draw the non-squared.
  line(0, y1, width, y1);
  ellipse(x1, y1, eSize, eSize);

  // Draw the squared.
  line(0, y2, width, y2);
  ellipse(x2, y2, eSize, eSize);

  // Draw dividing line.
  stroke(100);
  line(0, height / 2, width, height / 2);

  // Draw text.
  let spacing = 15;
  noStroke();
  fill(0);
  text('x = ' + x1, 0, y1 + spacing);
  text('sq(x) = ' + x2, 0, y2 + spacing);
}

inner sqrt(n) → {Number}

Calculates the square root of a number. The square root of a number is always positive, even though there may be a valid negative root. The square root s of number a is such that s*s = a. It is the opposite of squaring. Maps to Math.sqrt().
Parameters:
Name Type Description
n Number non-negative number to square root
Returns:
Number - square root of number
Example
function draw() {
  background(200);
  let eSize = 7;
  let x1 = mouseX;
  let y1 = 80;
  let x2 = sqrt(x1);
  let y2 = 20;

  // Draw the non-squared.
  line(0, y1, width, y1);
  ellipse(x1, y1, eSize, eSize);

  // Draw the squared.
  line(0, y2, width, y2);
  ellipse(x2, y2, eSize, eSize);

  // Draw dividing line.
  stroke(100);
  line(0, height / 2, width, height / 2);

  // Draw text.
  noStroke();
  fill(0);
  let spacing = 15;
  text('x = ' + x1, 0, y1 + spacing);
  text('sqrt(x) = ' + x2, 0, y2 + spacing);
}

inner str(n) → {String}

Converts a boolean, string or number to its string representation. When an array of values is passed in, then an array of strings of the same length is returned.
Parameters:
Name Type Description
n String | Boolean | Number | Array value to parse
Returns:
String - string representation of value
Example
print(str('10')); // "10"
print(str(10.31)); // "10.31"
print(str(-10)); // "-10"
print(str(true)); // "true"
print(str(false)); // "false"
print(str([true, '10.3', 9.8])); // [ "true", "10.3", "9.8" ]

inner subset(list, start, countopt) → {Array}

Extracts an array of elements from an existing array. The list parameter defines the array from which the elements will be copied, and the start and count parameters specify which elements to extract. If no count is given, elements will be extracted from the start to the end of the array. When specifying the start, remember that the first array element is 0. This function does not change the source array.
Parameters:
Name Type Attributes Description
list Array Array to extract from
start Integer position to begin
count Integer <optional>
number of values to extract
Returns:
Array - Array of extracted elements
Example
function setup() {
  var myArray = [1, 2, 3, 4, 5];
  print(myArray); // [1, 2, 3, 4, 5]

  var sub1 = subset(myArray, 0, 3);
  var sub2 = subset(myArray, 2, 2);
  print(sub1); // [1,2,3]
  print(sub2); // [3,4]
}

inner tan(angle) → {Number}

Calculates the tangent of an angle. This function takes into account the current angleMode. Values are returned in the range -1 to 1.
Parameters:
Name Type Description
angle Number the angle
Returns:
Number - the tangent of the angle
Example
let a = 0.0;
let inc = TWO_PI / 50.0;
for (let i = 0; i < 100; i = i + 2) {
  line(i, 50, i, 50 + tan(a) * 2.0);
  a = a + inc;
}

inner text(str, x, y)

Draws text to the screen. Displays the information specified in the first parameter on the screen in the position specified by the additional parameters. A default font will be used unless a font is set with the textFont() function and a default size will be used unless a font is set with textSize(). Change the color of the text with the fill() function. Change the outline of the text with the stroke() and strokeWeight() functions.

The text displays in relation to the textAlign() function, which gives the option to draw to the left, right, and center of the coordinates.

The x2 and y2 parameters define a rectangular area to display within and may only be used with string data. When these parameters are specified, they are interpreted based on the current rectMode() setting. Text that does not fit completely within the rectangle specified will not be drawn to the screen. If x2 and y2 are not specified, the baseline alignment is the default, which means that the text will be drawn upwards from x and y.

WEBGL: Only opentype/truetype fonts are supported. You must load a font using the loadFont() method (see the example above). stroke() currently has no effect in webgl mode.
Parameters:
Name Type Description
str String | Object | Array | Number | Boolean the alphanumeric symbols to be displayed
x Number x-coordinate of text
y Number y-coordinate of text
Example
text('word', 10, 30);
fill(0, 102, 153);
text('word', 10, 60);
fill(0, 102, 153, 51);
text('word', 10, 90);

let s = 'The quick brown fox jumped over the lazy dog.';
fill(50);
text(s, 10, 10, 70, 80); // Text wraps within text box

avenir;
function setup() {
  avenir = loadFont('assets/Avenir.otf');
  textFont(avenir);
  textSize(width / 3);
  textAlign(CENTER, CENTER);
}
function draw() {
  background(0);
  text('p5.js', 0, 0);
}

inner textAlign(horizAlign, vertAlignopt)

Sets the current alignment for drawing text. Accepts two arguments: horizAlign (LEFT, CENTER, or RIGHT) and vertAlign (TOP, BOTTOM, CENTER, or BASELINE). The horizAlign parameter is in reference to the x value of the text() function, while the vertAlign parameter is in reference to the y value. So if you write textAlign(LEFT), you are aligning the left edge of your text to the x value you give in text(). If you write textAlign(RIGHT, TOP), you are aligning the right edge of your text to the x value and the top of edge of the text to the y value.
Parameters:
Name Type Attributes Description
horizAlign Constant horizontal alignment, either LEFT, CENTER, or RIGHT
vertAlign Constant <optional>
vertical alignment, either TOP, BOTTOM, CENTER, or BASELINE
Example
textSize(16);
textAlign(RIGHT);
text('ABCD', 50, 30);
textAlign(CENTER);
text('EFGH', 50, 50);
textAlign(LEFT);
text('IJKL', 50, 70);

textSize(16);
strokeWeight(0.5);

line(0, 12, width, 12);
textAlign(CENTER, TOP);
text('TOP', 0, 12, width);

line(0, 37, width, 37);
textAlign(CENTER, CENTER);
text('CENTER', 0, 37, width);

line(0, 62, width, 62);
textAlign(CENTER, BASELINE);
text('BASELINE', 0, 62, width);

line(0, 87, width, 87);
textAlign(CENTER, BOTTOM);
text('BOTTOM', 0, 87, width);

inner textFont() → {Object}

Sets the current font that will be drawn with the text() function.

WEBGL: Only fonts loaded via loadFont() are supported.
Returns:
Object - the current font
Example
fill(0);
textSize(12);
textFont('Georgia');
text('Georgia', 12, 30);
textFont('Helvetica');
text('Helvetica', 12, 60);

let fontRegular, fontItalic, fontBold;
function setup() {
  fontRegular = loadFont('assets/Regular.otf');
  fontItalic = loadFont('assets/Italic.ttf');
  fontBold = loadFont('assets/Bold.ttf');
  background(210);
  fill(0);
  textFont(fontRegular);
  text('Font Style Normal', 10, 30);
  textFont(fontItalic);
  text('Font Style Italic', 10, 50);
  textFont(fontBold);
  text('Font Style Bold', 10, 70);
}

inner textSize() → {Number}

Gets the current font size.
Returns:
Number

inner textWidth(theText) → {Number}

Calculates and returns the width of any character or text string.
Parameters:
Name Type Description
theText String the String of characters to measure
Returns:
Number
Example
textSize(28);

let aChar = 'P';
let cWidth = textWidth(aChar);
text(aChar, 0, 40);
line(cWidth, 0, cWidth, 50);

let aString = 'p5.js';
let sWidth = textWidth(aString);
text(aString, 0, 85);
line(sWidth, 50, sWidth, 100);

inner trim(str) → {String}

Removes whitespace characters from the beginning and end of a String. In addition to standard whitespace characters such as space, carriage return, and tab, this function also removes the Unicode "nbsp" character.
Parameters:
Name Type Description
str String a String to be trimmed
Returns:
String - a trimmed String
Example
var string = trim('  No new lines\n   ');
text(string + ' here', 2, 50);

inner unchar(n) → {Number}

Converts a single-character string to its corresponding integer representation. When an array of single-character string values is passed in, then an array of integers of the same length is returned.
Parameters:
Name Type Description
n String value to parse
Returns:
Number - integer representation of value
Example
print(unchar('A')); // 65
print(unchar(['A', 'B', 'C'])); // [ 65, 66, 67 ]
print(unchar(split('ABC', ''))); // [ 65, 66, 67 ]

inner unhex(n) → {Number}

Converts a string representation of a hexadecimal number to its equivalent integer value. When an array of strings in hexadecimal notation is passed in, an array of integers of the same length is returned.
Parameters:
Name Type Description
n String value to parse
Returns:
Number - integer representation of hexadecimal value
Example
print(unhex('A')); // 10
print(unhex('FF')); // 255
print(unhex(['FF', 'AA', '00'])); // [ 255, 170, 0 ]

inner year() → {Integer}

The year() returns the current year as an integer (2014, 2015, 2016, etc).
Returns:
Integer - the current year
Example
var y = year();
text('Current year: \n' + y, 5, 50);

p5compat

Methods

static colorMode()

ignored

static createCanvas()

ignored

static exit()

exit the script after the current Loop().

static imageMode()

ignored

static noSmooth()

ignored

static noTint()

ignored

static settings()

ignored

static size()

ignored

static smooth()

ignored

static strokeWeight()

ignored

static tint()

ignored

inner abs(n) → {Number}

Calculates the absolute value (magnitude) of a number. Maps to Math.abs(). The absolute value of a number is always positive.
Parameters:
Name Type Description
n Number number to compute
Returns:
Number - absolute value of given number
Example
function setup() {
  let x = -3;
  let y = abs(x);

  print(x); // -3
  print(y); // 3
}

inner acos(value) → {Number}

The inverse of cos(), returns the arc cosine of a value. This function expects the values in the range of -1 to 1 and values are returned in the range 0 to PI (3.1415927).
Parameters:
Name Type Description
value Number the value whose arc cosine is to be returned
Returns:
Number - the arc cosine of the given value
Example
let a = PI;
let c = cos(a);
let ac = acos(c);
// Prints: "3.1415927 : -1.0 : 3.1415927"
print(a + ' : ' + c + ' : ' + ac);

let a = PI + PI / 4.0;
let c = cos(a);
let ac = acos(c);
// Prints: "3.926991 : -0.70710665 : 2.3561943"
print(a + ' : ' + c + ' : ' + ac);

inner angleMode(mode)

Sets the current mode of p5 to given mode. Default mode is RADIANS.
Parameters:
Name Type Description
mode Constant either RADIANS or DEGREES
Example
function draw() {
  background(204);
  angleMode(DEGREES); // Change the mode to DEGREES
  let a = atan2(mouseY - height / 2, mouseX - width / 2);
  translate(width / 2, height / 2);
  push();
  rotate(a);
  rect(-20, -5, 40, 10); // Larger rectangle is rotating in degrees
  pop();
  angleMode(RADIANS); // Change the mode to RADIANS
  rotate(a); // variable a stays the same
  rect(-40, -5, 20, 10); // Smaller rectangle is rotating in radians
}

inner append(array, value) → {Array}

Adds a value to the end of an array. Extends the length of the array by one. Maps to Array.push().
Parameters:
Name Type Description
array Array Array to append
value any to be added to the Array
Returns:
Array - the array that was appended to
Example
function setup() {
  var myArray = ['Mango', 'Apple', 'Papaya'];
  print(myArray); // ['Mango', 'Apple', 'Papaya']

  append(myArray, 'Peach');
  print(myArray); // ['Mango', 'Apple', 'Papaya', 'Peach']
}

inner arrayCopy(src, srcPosition, dst, dstPosition, length)

Copies an array (or part of an array) to another array. The src array is copied to the dst array, beginning at the position specified by srcPosition and into the position specified by dstPosition. The number of elements to copy is determined by length. Note that copying values overwrites existing values in the destination array. To append values instead of overwriting them, use concat().

The simplified version with only two arguments, arrayCopy(src, dst), copies an entire array to another of the same size. It is equivalent to arrayCopy(src, 0, dst, 0, src.length).

Using this function is far more efficient for copying array data than iterating through a for() loop and copying each element individually.
Parameters:
Name Type Description
src Array the source Array
srcPosition Integer starting position in the source Array
dst Array the destination Array
dstPosition Integer starting position in the destination Array
length Integer number of Array elements to be copied
Deprecated:
  • Yes
Example
var src = ['A', 'B', 'C'];
var dst = [1, 2, 3];
var srcPosition = 1;
var dstPosition = 0;
var length = 2;

print(src); // ['A', 'B', 'C']
print(dst); // [ 1 ,  2 ,  3 ]

arrayCopy(src, srcPosition, dst, dstPosition, length);
print(dst); // ['B', 'C', 3]

inner asin(value) → {Number}

The inverse of sin(), returns the arc sine of a value. This function expects the values in the range of -1 to 1 and values are returned in the range -PI/2 to PI/2.
Parameters:
Name Type Description
value Number the value whose arc sine is to be returned
Returns:
Number - the arc sine of the given value
Example
let a = PI + PI / 3;
let s = sin(a);
let as = asin(s);
// Prints: "1.0471976 : 0.86602545 : 1.0471976"
print(a + ' : ' + s + ' : ' + as);

let a = PI + PI / 3.0;
let s = sin(a);
let as = asin(s);
// Prints: "4.1887903 : -0.86602545 : -1.0471976"
print(a + ' : ' + s + ' : ' + as);

inner atan(value) → {Number}

The inverse of tan(), returns the arc tangent of a value. This function expects the values in the range of -Infinity to Infinity (exclusive) and values are returned in the range -PI/2 to PI/2.
Parameters:
Name Type Description
value Number the value whose arc tangent is to be returned
Returns:
Number - the arc tangent of the given value
Example
let a = PI + PI / 3;
let t = tan(a);
let at = atan(t);
// Prints: "1.0471976 : 1.7320509 : 1.0471976"
print(a + ' : ' + t + ' : ' + at);

let a = PI + PI / 3.0;
let t = tan(a);
let at = atan(t);
// Prints: "4.1887903 : 1.7320513 : 1.0471977"
print(a + ' : ' + t + ' : ' + at);

inner atan2(y, x) → {Number}

Calculates the angle (in radians) from a specified point to the coordinate origin as measured from the positive x-axis. Values are returned as a float in the range from PI to -PI. The atan2() function is most often used for orienting geometry to the position of the cursor.

Note: The y-coordinate of the point is the first parameter, and the x-coordinate is the second parameter, due the the structure of calculating the tangent.
Parameters:
Name Type Description
y Number y-coordinate of the point
x Number x-coordinate of the point
Returns:
Number - the arc tangent of the given point
Example
function draw() {
  background(204);
  translate(width / 2, height / 2);
  let a = atan2(mouseY - height / 2, mouseX - width / 2);
  rotate(a);
  rect(-30, -5, 60, 10);
}

inner boolean(n) → {Boolean}

Converts a number or string to its boolean representation. For a number, any non-zero value (positive or negative) evaluates to true, while zero evaluates to false. For a string, the value "true" evaluates to true, while any other value evaluates to false. When an array of number or string values is passed in, then a array of booleans of the same length is returned.
Parameters:
Name Type Description
n String | Boolean | Number | Array value to parse
Returns:
Boolean - boolean representation of value
Example
print(boolean(0)); // false
print(boolean(1)); // true
print(boolean('true')); // true
print(boolean('abcd')); // false
print(boolean([0, 12, 'true'])); // [false, true, false]

inner byte(n) → {Number}

Converts a number, string representation of a number, or boolean to its byte representation. A byte can be only a whole number between -128 and 127, so when a value outside of this range is converted, it wraps around to the corresponding byte representation. When an array of number, string or boolean values is passed in, then an array of bytes the same length is returned.
Parameters:
Name Type Description
n String | Boolean | Number value to parse
Returns:
Number - byte representation of value
Example
print(byte(127)); // 127
print(byte(128)); // -128
print(byte(23.4)); // 23
print(byte('23.4')); // 23
print(byte('hello')); // NaN
print(byte(true)); // 1
print(byte([0, 255, '100'])); // [0, -1, 100]

inner ceil(n) → {Integer}

Calculates the closest int value that is greater than or equal to the value of the parameter. Maps to Math.ceil(). For example, ceil(9.03) returns the value 10.
Parameters:
Name Type Description
n Number number to round up
Returns:
Integer - rounded up number
Example
function draw() {
  background(200);
  // map, mouseX between 0 and 5.
  let ax = map(mouseX, 0, 100, 0, 5);
  let ay = 66;

  //Get the ceiling of the mapped number.
  let bx = ceil(map(mouseX, 0, 100, 0, 5));
  let by = 33;

  // Multiply the mapped numbers by 20 to more easily
  // see the changes.
  stroke(0);
  fill(0);
  line(0, ay, ax * 20, ay);
  line(0, by, bx * 20, by);

  // Reformat the float returned by map and draw it.
  noStroke();
  text(nfc(ax, 2), ax, ay - 5);
  text(nfc(bx, 1), bx, by - 5);
}

inner char(n) → {String}

Converts a number or string to its corresponding single-character string representation. If a string parameter is provided, it is first parsed as an integer and then translated into a single-character string. When an array of number or string values is passed in, then an array of single-character strings of the same length is returned.
Parameters:
Name Type Description
n String | Number value to parse
Returns:
String - string representation of value
Example
print(char(65)); // "A"
print(char('65')); // "A"
print(char([65, 66, 67])); // [ "A", "B", "C" ]
print(join(char([65, 66, 67]), '')); // "ABC"

inner concat(a, b) → {Array}

Concatenates two arrays, maps to Array.concat(). Does not modify the input arrays.
Parameters:
Name Type Description
a Array first Array to concatenate
b Array second Array to concatenate
Returns:
Array - concatenated array
Example
function setup() {
  var arr1 = ['A', 'B', 'C'];
  var arr2 = [1, 2, 3];

  print(arr1); // ['A','B','C']
  print(arr2); // [1,2,3]

  var arr3 = concat(arr1, arr2);

  print(arr1); // ['A','B','C']
  print(arr2); // [1, 2, 3]
  print(arr3); // ['A','B','C', 1, 2, 3]
}

inner constrain(n, low, high) → {Number}

Constrains a value between a minimum and maximum value.
Parameters:
Name Type Description
n Number number to constrain
low Number minimum limit
high Number maximum limit
Returns:
Number - constrained number
Example
function draw() {
  background(200);

  let leftWall = 25;
  let rightWall = 75;

  // xm is just the mouseX, while
  // xc is the mouseX, but constrained
  // between the leftWall and rightWall!
  let xm = mouseX;
  let xc = constrain(mouseX, leftWall, rightWall);

  // Draw the walls.
  stroke(150);
  line(leftWall, 0, leftWall, height);
  line(rightWall, 0, rightWall, height);

  // Draw xm and xc as circles.
  noStroke();
  fill(150);
  ellipse(xm, 33, 9, 9); // Not Constrained
  fill(0);
  ellipse(xc, 66, 9, 9); // Constrained
}

inner cos(angle) → {Number}

Calculates the cosine of an angle. This function takes into account the current angleMode. Values are returned in the range -1 to 1.
Parameters:
Name Type Description
angle Number the angle
Returns:
Number - the cosine of the angle
Example
let a = 0.0;
let inc = TWO_PI / 25.0;
for (let i = 0; i < 25; i++) {
  line(i * 4, 50, i * 4, 50 + cos(a) * 40.0);
  a = a + inc;
}

inner createNumberDict(key, value) → {NumberDict}

Creates a new instance of NumberDict using the key-value pair or object you provide.
Parameters:
Name Type Description
key Number
value Number
Returns:
NumberDict
Example
function setup() {
  let myDictionary = createNumberDict(100, 42);
  print(myDictionary.hasKey(100)); // logs true to console

  let anotherDictionary = createNumberDict({ 200: 84 });
  print(anotherDictionary.hasKey(200)); // logs true to console
}

inner createStringDict(key, value) → {StringDict}

Creates a new instance of p5.StringDict using the key-value pair or the object you provide.
Parameters:
Name Type Description
key String
value String
Returns:
StringDict
Example
function setup() {
  let myDictionary = createStringDict('p5', 'js');
  print(myDictionary.hasKey('p5')); // logs true to console

  let anotherDictionary = createStringDict({ happy: 'coding' });
  print(anotherDictionary.hasKey('happy')); // logs true to console
}

inner createVector(xopt, yopt, zopt) → {p5.Vector}

Creates a new PVector (the datatype for storing vectors). This provides a two or three dimensional vector, specifically a Euclidean (also known as geometric) vector. A vector is an entity that has both magnitude and direction.
Parameters:
Name Type Attributes Description
x Number <optional>
x component of the vector
y Number <optional>
y component of the vector
z Number <optional>
z component of the vector
Returns:
p5.Vector
Example
function setup() {
  createCanvas(100, 100, WEBGL);
  noStroke();
  fill(255, 102, 204);
}

function draw() {
  background(255);
  pointLight(color(255), createVector(sin(millis() / 1000) * 20, -40, -10));
  scale(0.75);
  sphere();
}

inner day() → {Integer}

The day() function returns the current day as a value from 1 - 31.
Returns:
Integer - the current day
Example
var d = day();
text('Current day: \n' + d, 5, 50);

inner degrees(radians) → {Number}

Converts a radian measurement to its corresponding value in degrees. Radians and degrees are two ways of measuring the same thing. There are 360 degrees in a circle and 2*PI radians in a circle. For example, 90° = PI/2 = 1.5707964. This function does not take into account the current angleMode.
Parameters:
Name Type Description
radians Number the radians value to convert to degrees
Returns:
Number - the converted angle
Example
let rad = PI / 4;
let deg = degrees(rad);
print(rad + ' radians is ' + deg + ' degrees');
// Prints: 0.7853981633974483 radians is 45 degrees

inner displayDensity() → {Number}

Returns the pixel density of the current display the sketch is running on (always 1 for DOjS).
Returns:
Number - current pixel density of the display
Example
function setup() {
  let density = displayDensity();
  pixelDensity(density);
  createCanvas(100, 100);
  background(200);
  ellipse(width / 2, height / 2, 50, 50);
}

inner dist(x1, y1, x2, y2) → {Number}

Calculates the distance between two points.
Parameters:
Name Type Description
x1 Number x-coordinate of the first point
y1 Number y-coordinate of the first point
x2 Number x-coordinate of the second point
y2 Number y-coordinate of the second point
Returns:
Number - distance between the two points
Example
// Move your mouse inside the canvas to see the
// change in distance between two points!
function draw() {
  background(200);
  fill(0);

  let x1 = 10;
  let y1 = 90;
  let x2 = mouseX;
  let y2 = mouseY;

  line(x1, y1, x2, y2);
  ellipse(x1, y1, 7, 7);
  ellipse(x2, y2, 7, 7);

  // d is the length of the line
  // the distance from point 1 to point 2.
  let d = int(dist(x1, y1, x2, y2));

  // Let's write d along the line we are drawing!
  push();
  translate((x1 + x2) / 2, (y1 + y2) / 2);
  rotate(atan2(y2 - y1, x2 - x1));
  text(nfc(d, 1), 0, -5);
  pop();
  // Fancy!
}

inner exp(n) → {Number}

Returns Euler's number e (2.71828...) raised to the power of the n parameter. Maps to Math.exp().
Parameters:
Name Type Description
n Number exponent to raise
Returns:
Number - e^n
Example
function draw() {
  background(200);

  // Compute the exp() function with a value between 0 and 2
  let xValue = map(mouseX, 0, width, 0, 2);
  let yValue = exp(xValue);

  let y = map(yValue, 0, 8, height, 0);

  let legend = 'exp (' + nfc(xValue, 3) + ')\n= ' + nf(yValue, 1, 4);
  stroke(150);
  line(mouseX, y, mouseX, height);
  fill(0);
  text(legend, 5, 15);
  noStroke();
  ellipse(mouseX, y, 7, 7);

  // Draw the exp(x) curve,
  // over the domain of x from 0 to 2
  noFill();
  stroke(0);
  beginShape();
  for (let x = 0; x < width; x++) {
    xValue = map(x, 0, width, 0, 2);
    yValue = exp(xValue);
    y = map(yValue, 0, 8, height, 0);
    vertex(x, y);
  }

  endShape();
  line(0, 0, 0, height);
  line(0, height - 1, width, height - 1);
}

inner float(str) → {Number}

Converts a string to its floating point representation. The contents of a string must resemble a number, or NaN (not a number) will be returned. For example, float("1234.56") evaluates to 1234.56, but float("giraffe") will return NaN. When an array of values is passed in, then an array of floats of the same length is returned.
Parameters:
Name Type Description
str String float string to parse
Returns:
Number - floating point representation of string
Example
var str = '20';
var diameter = float(str);
ellipse(width / 2, height / 2, diameter, diameter);

inner floor(n) → {Integer}

Calculates the closest int value that is less than or equal to the value of the parameter. Maps to Math.floor().
Parameters:
Name Type Description
n Number number to round down
Returns:
Integer - rounded down number
Example
function draw() {
  background(200);
  //map, mouseX between 0 and 5.
  let ax = map(mouseX, 0, 100, 0, 5);
  let ay = 66;

  //Get the floor of the mapped number.
  let bx = floor(map(mouseX, 0, 100, 0, 5));
  let by = 33;

  // Multiply the mapped numbers by 20 to more easily
  // see the changes.
  stroke(0);
  fill(0);
  line(0, ay, ax * 20, ay);
  line(0, by, bx * 20, by);

  // Reformat the float returned by map and draw it.
  noStroke();
  text(nfc(ax, 2), ax, ay - 5);
  text(nfc(bx, 1), bx, by - 5);
}

inner hex(n, digitsopt) → {String}

Converts a number to a string in its equivalent hexadecimal notation. If a second parameter is passed, it is used to set the number of characters to generate in the hexadecimal notation. When an array is passed in, an array of strings in hexadecimal notation of the same length is returned.
Parameters:
Name Type Attributes Description
n Number value to parse
digits Number <optional>
Returns:
String - hexadecimal string representation of value
Example
print(hex(255)); // "000000FF"
print(hex(255, 6)); // "0000FF"
print(hex([0, 127, 255], 6)); // [ "000000", "00007F", "0000FF" ]

inner hour() → {Integer}

The hour() function returns the current hour as a value from 0 - 23.
Returns:
Integer - the current hour
Example
var h = hour();
text('Current hour:\n' + h, 5, 50);

inner int(n, radixopt) → {Number}

Converts a boolean, string, or float to its integer representation. When an array of values is passed in, then an int array of the same length is returned.
Parameters:
Name Type Attributes Description
n String | Boolean | Number value to parse
radix Integer <optional>
the radix to convert to (default: 10)
Returns:
Number - integer representation of value
Example
print(int('10')); // 10
print(int(10.31)); // 10
print(int(-10)); // -10
print(int(true)); // 1
print(int(false)); // 0
print(int([false, true, '10.3', 9.8])); // [0, 1, 10, 9]

inner join(list, separator) → {String}

Combines an array of Strings into one String, each separated by the character(s) used for the separator parameter. To join arrays of ints or floats, it's necessary to first convert them to Strings using nf() or nfs().
Parameters:
Name Type Description
list Array array of Strings to be joined
separator String String to be placed between each item
Returns:
String - joined String
Example
var array = ['Hello', 'world!'];
var separator = ' ';
var message = join(array, separator);
text(message, 5, 50);

inner lerp(start, stop, amt) → {Number}

Calculates a number between two numbers at a specific increment. The amt parameter is the amount to interpolate between the two values where 0.0 equal to the first point, 0.1 is very near the first point, 0.5 is half-way in between, and 1.0 is equal to the second point. If the value of amt is more than 1.0 or less than 0.0, the number will be calculated accordingly in the ratio of the two given numbers. The lerp function is convenient for creating motion along a straight path and for drawing dotted lines.
Parameters:
Name Type Description
start Number first value
stop Number second value
amt Number number
Returns:
Number - lerped value
Example
function setup() {
  background(200);
  let a = 20;
  let b = 80;
  let c = lerp(a, b, 0.2);
  let d = lerp(a, b, 0.5);
  let e = lerp(a, b, 0.8);

  let y = 50;

  strokeWeight(5);
  stroke(0); // Draw the original points in black
  point(a, y);
  point(b, y);

  stroke(100); // Draw the lerp points in gray
  point(c, y);
  point(d, y);
  point(e, y);
}

inner loadFont(path) → {Font}

Loads a GRX font file (.FNT) from a file Font Object.

Parameters:
Name Type Description
path String name of the file or url to load
Returns:
Font - Font object

inner log(n) → {Number}

Calculates the natural logarithm (the base-e logarithm) of a number. This function expects the n parameter to be a value greater than 0.0. Maps to Math.log().
Parameters:
Name Type Description
n Number number greater than 0
Returns:
Number - natural logarithm of n
Example
function draw() {
  background(200);
  let maxX = 2.8;
  let maxY = 1.5;

  // Compute the natural log of a value between 0 and maxX
  let xValue = map(mouseX, 0, width, 0, maxX);
  let yValue, y;
  if (xValue > 0) {
  // Cannot take the log of a negative number.
    yValue = log(xValue);
    y = map(yValue, -maxY, maxY, height, 0);

    // Display the calculation occurring.
    let legend = 'log(' + nf(xValue, 1, 2) + ')\n= ' + nf(yValue, 1, 3);
    stroke(150);
    line(mouseX, y, mouseX, height);
    fill(0);
    text(legend, 5, 15);
    noStroke();
    ellipse(mouseX, y, 7, 7);
  }

  // Draw the log(x) curve,
  // over the domain of x from 0 to maxX
  noFill();
  stroke(0);
  beginShape();
  for (let x = 0; x < width; x++) {
    xValue = map(x, 0, width, 0, maxX);
    yValue = log(xValue);
    y = map(yValue, -maxY, maxY, height, 0);
    vertex(x, y);
  }
  endShape();
  line(0, 0, 0, height);
  line(0, height / 2, width, height / 2);
}

inner loop()

By default, p5.js loops through draw() continuously, executing the code within it. However, the draw() loop may be stopped by calling noLoop(). In that case, the draw() loop can be resumed with loop(). Avoid calling loop() from inside setup().
Example
let x = 0;
function setup() {
  createCanvas(100, 100);
  noLoop();
}

function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}

function mousePressed() {
  loop();
}

function mouseReleased() {
  noLoop();
}

inner mag(a, b) → {Number}

Calculates the magnitude (or length) of a vector. A vector is a direction in space commonly used in computer graphics and linear algebra. Because it has no "start" position, the magnitude of a vector can be thought of as the distance from the coordinate 0,0 to its x,y value. Therefore, mag() is a shortcut for writing dist(0, 0, x, y).
Parameters:
Name Type Description
a Number first value
b Number second value
Returns:
Number - magnitude of vector from (0,0) to (a,b)
Example
function setup() {
  let x1 = 20;
  let x2 = 80;
  let y1 = 30;
  let y2 = 70;

  line(0, 0, x1, y1);
  print(mag(x1, y1)); // Prints "36.05551275463989"
  line(0, 0, x2, y1);
  print(mag(x2, y1)); // Prints "85.44003745317531"
  line(0, 0, x1, y2);
  print(mag(x1, y2)); // Prints "72.80109889280519"
  line(0, 0, x2, y2);
  print(mag(x2, y2)); // Prints "106.3014581273465"
}

inner map(value, start1, stop1, start2, stop2, withinBoundsopt) → {Number}

Re-maps a number from one range to another.

In the first example above, the number 25 is converted from a value in the range of 0 to 100 into a value that ranges from the left edge of the window (0) to the right edge (width).
Parameters:
Name Type Attributes Description
value Number the incoming value to be converted
start1 Number lower bound of the value's current range
stop1 Number upper bound of the value's current range
start2 Number lower bound of the value's target range
stop2 Number upper bound of the value's target range
withinBounds Boolean <optional>
constrain the value to the newly mapped range
Returns:
Number - remapped number
Example
let value = 25;
let m = map(value, 0, 100, 0, width);
ellipse(m, 50, 10, 10);

function setup() {
  noStroke();
}

function draw() {
  background(204);
  let x1 = map(mouseX, 0, width, 25, 75);
  ellipse(x1, 25, 25, 25);
  //This ellipse is constrained to the 0-100 range
  //after setting withinBounds to true
  let x2 = map(mouseX, 0, width, 0, 100, true);
  ellipse(x2, 75, 25, 25);
}

inner match(str, regexp) → {Array.<String>}

This function is used to apply a regular expression to a piece of text, and return matching groups (elements found inside parentheses) as a String array. If there are no matches, a null value will be returned. If no groups are specified in the regular expression, but the sequence matches, an array of length 1 (with the matched text as the first element of the array) will be returned.

To use the function, first check to see if the result is null. If the result is null, then the sequence did not match at all. If the sequence did match, an array is returned.

If there are groups (specified by sets of parentheses) in the regular expression, then the contents of each will be returned in the array. Element [0] of a regular expression match returns the entire matching string, and the match groups start at element [1] (the first group is [1], the second [2], and so on).
Parameters:
Name Type Description
str String the String to be searched
regexp String the regexp to be used for matching
Returns:
Array.<String> - Array of Strings found
Example
var string = 'Hello p5js*!';
var regexp = 'p5js\\*';
var m = match(string, regexp);
text(m, 5, 50);

inner matchAll(str, regexp) → {Array.<String>}

This function is used to apply a regular expression to a piece of text, and return a list of matching groups (elements found inside parentheses) as a two-dimensional String array. If there are no matches, a null value will be returned. If no groups are specified in the regular expression, but the sequence matches, a two dimensional array is still returned, but the second dimension is only of length one.

To use the function, first check to see if the result is null. If the result is null, then the sequence did not match at all. If the sequence did match, a 2D array is returned.

If there are groups (specified by sets of parentheses) in the regular expression, then the contents of each will be returned in the array. Assuming a loop with counter variable i, element [i][0] of a regular expression match returns the entire matching string, and the match groups start at element [i][1] (the first group is [i][1], the second [i][2], and so on).
Parameters:
Name Type Description
str String the String to be searched
regexp String the regexp to be used for matching
Returns:
Array.<String> - 2d Array of Strings found
Example
var string = 'Hello p5js*! Hello world!';
var regexp = 'Hello';
matchAll(string, regexp);

inner max(n0, n1) → {Number}

Determines the largest value in a sequence of numbers, and then returns that value. max() accepts any number of Number parameters, or an Array of any length.
Parameters:
Name Type Description
n0 Number Number to compare
n1 Number Number to compare
Returns:
Number - maximum Number
Example
function setup() {
  // Change the elements in the array and run the sketch
  // to show how max() works!
  let numArray = [2, 1, 5, 4, 8, 9];
  fill(0);
  noStroke();
  text('Array Elements', 0, 10);
  // Draw all numbers in the array
  let spacing = 15;
  let elemsY = 25;
  for (let i = 0; i < numArray.length; i++) {
    text(numArray[i], i * spacing, elemsY);
  }
  let maxX = 33;
  let maxY = 80;
  // Draw the Maximum value in the array.
  textSize(32);
  text(max(numArray), maxX, maxY);
}

inner millis() → {Number}

Returns the number of milliseconds (thousandths of a second) since starting the program. This information is often used for timing events and animation sequences.
Returns:
Number - the number of milliseconds since starting the program
Example
var millisecond = millis();
text('Milliseconds \nrunning: \n' + millisecond, 5, 40);

inner min(n0, n1) → {Number}

Determines the smallest value in a sequence of numbers, and then returns that value. min() accepts any number of Number parameters, or an Array of any length.
Parameters:
Name Type Description
n0 Number Number to compare
n1 Number Number to compare
Returns:
Number - minimum Number
Example
function setup() {
  // Change the elements in the array and run the sketch
  // to show how min() works!
  let numArray = [2, 1, 5, 4, 8, 9];
  fill(0);
  noStroke();
  text('Array Elements', 0, 10);
  // Draw all numbers in the array
  let spacing = 15;
  let elemsY = 25;
  for (let i = 0; i < numArray.length; i++) {
    text(numArray[i], i * spacing, elemsY);
  }
  let maxX = 33;
  let maxY = 80;
  // Draw the Minimum value in the array.
  textSize(32);
  text(min(numArray), maxX, maxY);
}

inner minute() → {Integer}

The minute() function returns the current minute as a value from 0 - 59.
Returns:
Integer - the current minute
Example
var m = minute();
text('Current minute: \n' + m, 5, 50);

inner month() → {Integer}

The month() function returns the current month as a value from 1 - 12.
Returns:
Integer - the current month
Example
var m = month();
text('Current month: \n' + m, 5, 50);

inner nf(num, leftopt, rightopt) → {String}

Utility function for formatting numbers into strings. There are two versions: one for formatting floats, and one for formatting ints. The values for the digits, left, and right parameters should always be positive integers. (NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter if greater than the current length of the number. For example if number is 123.2 and left parameter passed is 4 which is greater than length of 123 (integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than the result will be 123.200.
Parameters:
Name Type Attributes Description
num Number | String the Number to format
left Integer | String <optional>
number of digits to the left of the decimal point
right Integer | String <optional>
number of digits to the right of the decimal point
Returns:
String - formatted String
Example
var myFont;
function preload() {
  myFont = loadFont('assets/fonts/inconsolata.ttf');
}
function setup() {
  background(200);
  var num1 = 321;
  var num2 = -1321;

  noStroke();
  fill(0);
  textFont(myFont);
  textSize(22);

  text(nf(num1, 4, 2), 10, 30);
  text(nf(num2, 4, 2), 10, 80);
  // Draw dividing line
  stroke(120);
  line(0, 50, width, 50);
}

inner nfc(num, rightopt) → {String}

Utility function for formatting numbers into strings and placing appropriate commas to mark units of 1000. There are two versions: one for formatting ints, and one for formatting an array of ints. The value for the right parameter should always be a positive integer.
Parameters:
Name Type Attributes Description
num Number | String the Number to format
right Integer | String <optional>
number of digits to the right of the decimal point
Returns:
String - formatted String
Example
function setup() {
  background(200);
  var num = 11253106.115;
  var numArr = [1, 1, 2];

  noStroke();
  fill(0);
  textSize(12);

  // Draw formatted numbers
  text(nfc(num, 4), 10, 30);
  text(nfc(numArr, 2), 10, 80);

  // Draw dividing line
  stroke(120);
  line(0, 50, width, 50);
}

inner nfp(num, leftopt, rightopt) → {String}

Utility function for formatting numbers into strings. Similar to nf() but puts a "+" in front of positive numbers and a "-" in front of negative numbers. There are two versions: one for formatting floats, and one for formatting ints. The values for left, and right parameters should always be positive integers.
Parameters:
Name Type Attributes Description
num Number the Number to format
left Integer <optional>
number of digits to the left of the decimal point
right Integer <optional>
number of digits to the right of the decimal point
Returns:
String - formatted String
Example
function setup() {
  background(200);
  var num1 = 11253106.115;
  var num2 = -11253106.115;

  noStroke();
  fill(0);
  textSize(12);

  // Draw formatted numbers
  text(nfp(num1, 4, 2), 10, 30);
  text(nfp(num2, 4, 2), 10, 80);

  // Draw dividing line
  stroke(120);
  line(0, 50, width, 50);
}

inner nfs(num, leftopt, rightopt) → {String}

Utility function for formatting numbers into strings. Similar to nf() but puts an additional "_" (space) in front of positive numbers just in case to align it with negative numbers which includes "-" (minus) sign. The main usecase of nfs() can be seen when one wants to align the digits (place values) of a positive number with some negative number (See the example to get a clear picture). There are two versions: one for formatting float, and one for formatting int. The values for the digits, left, and right parameters should always be positive integers. (IMP): The result on the canvas basically the expected alignment can vary based on the typeface you are using. (NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter if greater than the current length of the number. For example if number is 123.2 and left parameter passed is 4 which is greater than length of 123 (integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than the result will be 123.200.
Parameters:
Name Type Attributes Description
num Number the Number to format
left Integer <optional>
number of digits to the left of the decimal point
right Integer <optional>
number of digits to the right of the decimal point
Returns:
String - formatted String
Example
var myFont;
function preload() {
  myFont = loadFont('assets/fonts/inconsolata.ttf');
}
function setup() {
  background(200);
  var num1 = 321;
  var num2 = -1321;

  noStroke();
  fill(0);
  textFont(myFont);
  textSize(22);

  // nfs() aligns num1 (positive number) with num2 (negative number) by
  // adding a blank space in front of the num1 (positive number)
  // [left = 4] in num1 add one 0 in front, to align the digits with num2
  // [right = 2] in num1 and num2 adds two 0's after both numbers
  // To see the differences check the example of nf() too.
  text(nfs(num1, 4, 2), 10, 30);
  text(nfs(num2, 4, 2), 10, 80);
  // Draw dividing line
  stroke(120);
  line(0, 50, width, 50);
}

inner noCursor()

Hides the cursor from view.
Example
function setup() {
  noCursor();
}

function draw() {
  background(200);
  ellipse(mouseX, mouseY, 10, 10);
}

inner noise(x, yopt, zopt) → {Number}

Returns the Perlin noise value at specified coordinates. Perlin noise is a random sequence generator producing a more natural ordered, harmonic succession of numbers compared to the standard random() function. It was invented by Ken Perlin in the 1980s and been used since in graphical applications to produce procedural textures, natural motion, shapes, terrains etc.

The main difference to the random() function is that Perlin noise is defined in an infinite n-dimensional space where each pair of coordinates corresponds to a fixed semi-random value (fixed only for the lifespan of the program; see the noiseSeed() function). p5.js can compute 1D, 2D and 3D noise, depending on the number of coordinates given. The resulting value will always be between 0.0 and 1.0. The noise value can be animated by moving through the noise space as demonstrated in the example above. The 2nd and 3rd dimension can also be interpreted as time.

The actual noise is structured similar to an audio signal, in respect to the function's use of frequencies. Similar to the concept of harmonics in physics, perlin noise is computed over several octaves which are added together for the final result.

Another way to adjust the character of the resulting sequence is the scale of the input coordinates. As the function works within an infinite space the value of the coordinates doesn't matter as such, only the distance between successive coordinates does (eg. when using noise() within a loop). As a general rule the smaller the difference between coordinates, the smoother the resulting noise sequence will be. Steps of 0.005-0.03 work best for most applications, but this will differ depending on use.
Parameters:
Name Type Attributes Description
x Number x-coordinate in noise space
y Number <optional>
y-coordinate in noise space
z Number <optional>
z-coordinate in noise space
Returns:
Number - Perlin noise value (between 0 and 1) at specified coordinates
Example
let xoff = 0.0;

function draw() {
  background(204);
  xoff = xoff + 0.01;
  let n = noise(xoff) * width;
  line(n, 0, n, height);
}

let noiseScale=0.02;

function draw() {
  background(0);
  for (let x=0; x < width; x++) {
    let noiseVal = noise((mouseX+x)*noiseScale, mouseY*noiseScale);
    stroke(noiseVal*255);
    line(x, mouseY+noiseVal*80, x, height);
  }
}

inner noiseDetail(lod, falloff)

Adjusts the character and level of detail produced by the Perlin noise function. Similar to harmonics in physics, noise is computed over several octaves. Lower octaves contribute more to the output signal and as such define the overall intensity of the noise, whereas higher octaves create finer grained details in the noise sequence.

By default, noise is computed over 4 octaves with each octave contributing exactly half than its predecessor, starting at 50% strength for the 1st octave. This falloff amount can be changed by adding an additional function parameter. Eg. a falloff factor of 0.75 means each octave will now have 75% impact (25% less) of the previous lower octave. Any value between 0.0 and 1.0 is valid, however note that values greater than 0.5 might result in greater than 1.0 values returned by noise().

By changing these parameters, the signal created by the noise() function can be adapted to fit very specific needs and characteristics.
Parameters:
Name Type Description
lod Number number of octaves to be used by the noise
falloff Number falloff factor for each octave
Example
let noiseVal;
let noiseScale = 0.02;

function setup() {
  createCanvas(100, 100);
}

function draw() {
  background(0);
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width / 2; x++) {
      noiseDetail(2, 0.2);
      noiseVal = noise((mouseX + x) * noiseScale, (mouseY + y) * noiseScale);
      stroke(noiseVal * 255);
      point(x, y);
      noiseDetail(8, 0.65);
      noiseVal = noise(
        (mouseX + x + width / 2) * noiseScale,
        (mouseY + y) * noiseScale
      );
      stroke(noiseVal * 255);
      point(x + width / 2, y);
    }
  }
}

inner noLoop()

Stops p5.js from continuously executing the code within draw(). If loop() is called, the code in draw() begins to run continuously again. If using noLoop() in setup(), it should be the last line inside the block.

When noLoop() is used, it's not possible to manipulate or access the screen inside event handling functions such as mousePressed() or keyPressed(). Instead, use those functions to call redraw() or loop(), which will run draw(), which can update the screen properly. This means that when noLoop() has been called, no drawing can happen, and functions like saveFrame() or loadPixels() may not be used.

Note that if the sketch is resized, redraw() will be called to update the sketch, even after noLoop() has been specified. Otherwise, the sketch would enter an odd state until loop() was called.
Example
function setup() {
  createCanvas(100, 100);
  background(200);
  noLoop();
}

function draw() {
  line(10, 10, 90, 90);
}

let x = 0;
function setup() {
  createCanvas(100, 100);
}

function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}

function mousePressed() {
  noLoop();
}

function mouseReleased() {
  loop();
}

inner norm(value, start, stop) → {Number}

Normalizes a number from another range into a value between 0 and 1. Identical to map(value, low, high, 0, 1). Numbers outside of the range are not clamped to 0 and 1, because out-of-range values are often intentional and useful. (See the second example above.)
Parameters:
Name Type Description
value Number incoming value to be normalized
start Number lower bound of the value's current range
stop Number upper bound of the value's current range
Returns:
Number - normalized number
Example
function draw() {
  background(200);
  let currentNum = mouseX;
  let lowerBound = 0;
  let upperBound = width; //100;
  let normalized = norm(currentNum, lowerBound, upperBound);
  let lineY = 70;
  line(0, lineY, width, lineY);
  //Draw an ellipse mapped to the non-normalized value.
  noStroke();
  fill(50);
  let s = 7; // ellipse size
  ellipse(currentNum, lineY, s, s);

  // Draw the guide
  let guideY = lineY + 15;
  text('0', 0, guideY);
  textAlign(RIGHT);
  text('100', width, guideY);

  // Draw the normalized value
  textAlign(LEFT);
  fill(0);
  textSize(32);
  let normalY = 40;
  let normalX = 20;
  text(normalized, normalX, normalY);
}

inner pow(n, e) → {Number}

Facilitates exponential expressions. The pow() function is an efficient way of multiplying numbers by themselves (or their reciprocals) in large quantities. For example, pow(3, 5) is equivalent to the expression 3*3*3*3*3 and pow(3, -5) is equivalent to 1 / 3*3*3*3*3. Maps to Math.pow().
Parameters:
Name Type Description
n Number base of the exponential expression
e Number power by which to raise the base
Returns:
Number - n^e
Example
function setup() {
  //Exponentially increase the size of an ellipse.
  let eSize = 3; // Original Size
  let eLoc = 10; // Original Location

  ellipse(eLoc, eLoc, eSize, eSize);

  ellipse(eLoc * 2, eLoc * 2, pow(eSize, 2), pow(eSize, 2));

  ellipse(eLoc * 4, eLoc * 4, pow(eSize, 3), pow(eSize, 3));

  ellipse(eLoc * 8, eLoc * 8, pow(eSize, 4), pow(eSize, 4));
}

inner radians(degrees) → {Number}

Converts a degree measurement to its corresponding value in radians. Radians and degrees are two ways of measuring the same thing. There are 360 degrees in a circle and 2*PI radians in a circle. For example, 90° = PI/2 = 1.5707964. This function does not take into account the current angleMode.
Parameters:
Name Type Description
degrees Number the degree value to convert to radians
Returns:
Number - the converted angle
Example
let deg = 45.0;
let rad = radians(deg);
print(deg + ' degrees is ' + rad + ' radians');
// Prints: 45 degrees is 0.7853981633974483 radians

inner random(minopt, maxopt) → {Number}

Return a random floating-point number. Takes either 0, 1 or 2 arguments. If no argument is given, returns a random number from 0 up to (but not including) 1. If one argument is given and it is a number, returns a random number from 0 up to (but not including) the number. If one argument is given and it is an array, returns a random element from that array. If two arguments are given, returns a random number from the first argument up to (but not including) the second argument.
Parameters:
Name Type Attributes Description
min Number <optional>
the lower bound (inclusive)
max Number <optional>
the upper bound (exclusive)
Returns:
Number - the random number
Example
for (let i = 0; i < 100; i++) {
  let r = random(50);
  stroke(r * 5);
  line(50, i, 50 + r, i);
}

for (let i = 0; i < 100; i++) {
  let r = random(-50, 50);
  line(50, i, 50 + r, i);
}

// Get a random element from an array using the random(Array) syntax
let words = ['apple', 'bear', 'cat', 'dog'];
let word = random(words); // select random word
text(word, 10, 50); // draw the word

inner randomGaussian(mean, sd) → {Number}

Returns a random number fitting a Gaussian, or normal, distribution. There is theoretically no minimum or maximum value that randomGaussian() might return. Rather, there is just a very low probability that values far from the mean will be returned; and a higher probability that numbers near the mean will be returned.

Takes either 0, 1 or 2 arguments.
If no args, returns a mean of 0 and standard deviation of 1.
If one arg, that arg is the mean (standard deviation is 1).
If two args, first is mean, second is standard deviation.
Parameters:
Name Type Description
mean Number the mean
sd Number the standard deviation
Returns:
Number - the random number
Example
for (let y = 0; y < 100; y++) {
  let x = randomGaussian(50, 15);
  line(50, y, x, y);
}

let distribution = new Array(360);

function setup() {
  createCanvas(100, 100);
  for (let i = 0; i < distribution.length; i++) {
    distribution[i] = floor(randomGaussian(0, 15));
  }
}

function draw() {
  background(204);

  translate(width / 2, width / 2);

  for (let i = 0; i < distribution.length; i++) {
    rotate(TWO_PI / distribution.length);
    stroke(0);
    let dist = abs(distribution[i]);
    line(0, 0, dist, 0);
  }
}

inner randomSeed(seed)

Sets the seed value for random(). By default, random() produces different results each time the program is run. Set the seed parameter to a constant to return the same pseudo-random numbers each time the software is run.
Parameters:
Name Type Description
seed Number the seed value
Example
randomSeed(99);
for (let i = 0; i < 100; i++) {
  let r = random(0, 255);
  stroke(r);
  line(i, 0, i, 100);
}

inner redraw(nopt)

Executes the code within draw() one time. This functions allows the program to update the display window only when necessary, for example when an event registered by mousePressed() or keyPressed() occurs.

In structuring a program, it only makes sense to call redraw() within events such as mousePressed(). This is because redraw() does not run draw() immediately (it only sets a flag that indicates an update is needed).

The redraw() function does not work properly when called inside draw(). To enable/disable animations, use loop() and noLoop().

In addition you can set the number of redraws per method call. Just add an integer as single parameter for the number of redraws.
Parameters:
Name Type Attributes Description
n Integer <optional>
Redraw for n-times. The default value is 1.
Example
let x = 0;

function setup() {
  createCanvas(100, 100);
  noLoop();
}

function draw() {
  background(204);
  line(x, 0, x, height);
}

function mousePressed() {
  x += 1;
  redraw();
}

let x = 0;

function setup() {
  createCanvas(100, 100);
  noLoop();
}

function draw() {
  background(204);
  x += 1;
  line(x, 0, x, height);
}

function mousePressed() {
  redraw(5);
}

inner reverse(list) → {Array}

Reverses the order of an array, maps to Array.reverse()
Parameters:
Name Type Description
list Array Array to reverse
Returns:
Array - the reversed list
Example
function setup() {
  var myArray = ['A', 'B', 'C'];
  print(myArray); // ['A','B','C']

  reverse(myArray);
  print(myArray); // ['C','B','A']
}

inner round(n) → {Integer}

Calculates the integer closest to the n parameter. For example, round(133.8) returns the value 134. Maps to Math.round().
Parameters:
Name Type Description
n Number number to round
Returns:
Integer - rounded number
Example
function draw() {
  background(200);
  //map, mouseX between 0 and 5.
  let ax = map(mouseX, 0, 100, 0, 5);
  let ay = 66;

  // Round the mapped number.
  let bx = round(map(mouseX, 0, 100, 0, 5));
  let by = 33;

  // Multiply the mapped numbers by 20 to more easily
  // see the changes.
  stroke(0);
  fill(0);
  line(0, ay, ax * 20, ay);
  line(0, by, bx * 20, by);

  // Reformat the float returned by map and draw it.
  noStroke();
  text(nfc(ax, 2), ax, ay - 5);
  text(nfc(bx, 1), bx, by - 5);
}

inner second() → {Integer}

The second() function returns the current second as a value from 0 - 59.
Returns:
Integer - the current second
Example
var s = second();
text('Current second: \n' + s, 5, 50);

inner shorten(list) → {Array}

Decreases an array by one element and returns the shortened array, maps to Array.pop().
Parameters:
Name Type Description
list Array Array to shorten
Returns:
Array - shortened Array
Example
function setup() {
  var myArray = ['A', 'B', 'C'];
  print(myArray); // ['A', 'B', 'C']
  var newArray = shorten(myArray);
  print(myArray); // ['A','B','C']
  print(newArray); // ['A','B']
}

inner shuffle(array, boolopt) → {Array}

Randomizes the order of the elements of an array. Implements Fisher-Yates Shuffle Algorithm.
Parameters:
Name Type Attributes Description
array Array Array to shuffle
bool Boolean <optional>
modify passed array
Returns:
Array - shuffled Array
Example
function setup() {
  var regularArr = ['ABC', 'def', createVector(), TAU, Math.E];
  print(regularArr);
  shuffle(regularArr, true); // force modifications to passed array
  print(regularArr);

  // By default shuffle() returns a shuffled cloned array:
  var newArr = shuffle(regularArr);
  print(regularArr);
  print(newArr);
}

inner sin(angle) → {Number}

Calculates the sine of an angle. This function takes into account the current angleMode. Values are returned in the range -1 to 1.
Parameters:
Name Type Description
angle Number the angle
Returns:
Number - the sine of the angle
Example
let a = 0.0;
let inc = TWO_PI / 25.0;
for (let i = 0; i < 25; i++) {
  line(i * 4, 50, i * 4, 50 + sin(a) * 40.0);
  a = a + inc;
}

inner sort(list, countopt) → {Array}

Sorts an array of numbers from smallest to largest, or puts an array of words in alphabetical order. The original array is not modified; a re-ordered array is returned. The count parameter states the number of elements to sort. For example, if there are 12 elements in an array and count is set to 5, only the first 5 elements in the array will be sorted.
Parameters:
Name Type Attributes Description
list Array Array to sort
count Integer <optional>
number of elements to sort, starting from 0
Returns:
Array - the sorted list
Example
function setup() {
  var words = ['banana', 'apple', 'pear', 'lime'];
  print(words); // ['banana', 'apple', 'pear', 'lime']
  var count = 4; // length of array

  words = sort(words, count);
  print(words); // ['apple', 'banana', 'lime', 'pear']
}

function setup() {
  var numbers = [2, 6, 1, 5, 14, 9, 8, 12];
  print(numbers); // [2, 6, 1, 5, 14, 9, 8, 12]
  var count = 5; // Less than the length of the array

  numbers = sort(numbers, count);
  print(numbers); // [1,2,5,6,14,9,8,12]
}

inner splice(list, value, position) → {Array}

Inserts a value or an array of values into an existing array. The first parameter specifies the initial array to be modified, and the second parameter defines the data to be inserted. The third parameter is an index value which specifies the array position from which to insert data. (Remember that array index numbering starts at zero, so the first position is 0, the second position is 1, and so on.)
Parameters:
Name Type Description
list Array Array to splice into
value any value to be spliced in
position Integer in the array from which to insert data
Returns:
Array - the list
Example
function setup() {
  var myArray = [0, 1, 2, 3, 4];
  var insArray = ['A', 'B', 'C'];
  print(myArray); // [0, 1, 2, 3, 4]
  print(insArray); // ['A','B','C']

  splice(myArray, insArray, 3);
  print(myArray); // [0,1,2,'A','B','C',3,4]
}

inner split(value, delim) → {Array.<String>}

The split() function maps to String.split(), it breaks a String into pieces using a character or string as the delimiter. The delim parameter specifies the character or characters that mark the boundaries between each piece. A String[] array is returned that contains each of the pieces. The splitTokens() function works in a similar fashion, except that it splits using a range of characters instead of a specific character or sequence.
Parameters:
Name Type Description
value String the String to be split
delim String the String used to separate the data
Returns:
Array.<String> - Array of Strings
Example
var names = 'Pat,Xio,Alex';
var splitString = split(names, ',');
text(splitString[0], 5, 30);
text(splitString[1], 5, 50);
text(splitString[2], 5, 70);

inner splitTokens(value, delimopt) → {Array.<String>}

The splitTokens() function splits a String at one or many character delimiters or "tokens." The delim parameter specifies the character or characters to be used as a boundary.

If no delim characters are specified, any whitespace character is used to split. Whitespace characters include tab (\t), line feed (\n), carriage return (\r), form feed (\f), and space.
Parameters:
Name Type Attributes Description
value String the String to be split
delim String <optional>
list of individual Strings that will be used as separators
Returns:
Array.<String> - Array of Strings
Example
function setup() {
  var myStr = 'Mango, Banana, Lime';
  var myStrArr = splitTokens(myStr, ',');

  print(myStrArr); // prints : ["Mango"," Banana"," Lime"]
}

inner sq(n) → {Number}

Squares a number (multiplies a number by itself). The result is always a positive number, as multiplying two negative numbers always yields a positive result. For example, -1 * -1 = 1.
Parameters:
Name Type Description
n Number number to square
Returns:
Number - squared number
Example
function draw() {
  background(200);
  let eSize = 7;
  let x1 = map(mouseX, 0, width, 0, 10);
  let y1 = 80;
  let x2 = sq(x1);
  let y2 = 20;

  // Draw the non-squared.
  line(0, y1, width, y1);
  ellipse(x1, y1, eSize, eSize);

  // Draw the squared.
  line(0, y2, width, y2);
  ellipse(x2, y2, eSize, eSize);

  // Draw dividing line.
  stroke(100);
  line(0, height / 2, width, height / 2);

  // Draw text.
  let spacing = 15;
  noStroke();
  fill(0);
  text('x = ' + x1, 0, y1 + spacing);
  text('sq(x) = ' + x2, 0, y2 + spacing);
}

inner sqrt(n) → {Number}

Calculates the square root of a number. The square root of a number is always positive, even though there may be a valid negative root. The square root s of number a is such that s*s = a. It is the opposite of squaring. Maps to Math.sqrt().
Parameters:
Name Type Description
n Number non-negative number to square root
Returns:
Number - square root of number
Example
function draw() {
  background(200);
  let eSize = 7;
  let x1 = mouseX;
  let y1 = 80;
  let x2 = sqrt(x1);
  let y2 = 20;

  // Draw the non-squared.
  line(0, y1, width, y1);
  ellipse(x1, y1, eSize, eSize);

  // Draw the squared.
  line(0, y2, width, y2);
  ellipse(x2, y2, eSize, eSize);

  // Draw dividing line.
  stroke(100);
  line(0, height / 2, width, height / 2);

  // Draw text.
  noStroke();
  fill(0);
  let spacing = 15;
  text('x = ' + x1, 0, y1 + spacing);
  text('sqrt(x) = ' + x2, 0, y2 + spacing);
}

inner str(n) → {String}

Converts a boolean, string or number to its string representation. When an array of values is passed in, then an array of strings of the same length is returned.
Parameters:
Name Type Description
n String | Boolean | Number | Array value to parse
Returns:
String - string representation of value
Example
print(str('10')); // "10"
print(str(10.31)); // "10.31"
print(str(-10)); // "-10"
print(str(true)); // "true"
print(str(false)); // "false"
print(str([true, '10.3', 9.8])); // [ "true", "10.3", "9.8" ]

inner subset(list, start, countopt) → {Array}

Extracts an array of elements from an existing array. The list parameter defines the array from which the elements will be copied, and the start and count parameters specify which elements to extract. If no count is given, elements will be extracted from the start to the end of the array. When specifying the start, remember that the first array element is 0. This function does not change the source array.
Parameters:
Name Type Attributes Description
list Array Array to extract from
start Integer position to begin
count Integer <optional>
number of values to extract
Returns:
Array - Array of extracted elements
Example
function setup() {
  var myArray = [1, 2, 3, 4, 5];
  print(myArray); // [1, 2, 3, 4, 5]

  var sub1 = subset(myArray, 0, 3);
  var sub2 = subset(myArray, 2, 2);
  print(sub1); // [1,2,3]
  print(sub2); // [3,4]
}

inner tan(angle) → {Number}

Calculates the tangent of an angle. This function takes into account the current angleMode. Values are returned in the range -1 to 1.
Parameters:
Name Type Description
angle Number the angle
Returns:
Number - the tangent of the angle
Example
let a = 0.0;
let inc = TWO_PI / 50.0;
for (let i = 0; i < 100; i = i + 2) {
  line(i, 50, i, 50 + tan(a) * 2.0);
  a = a + inc;
}

inner text(str, x, y)

Draws text to the screen. Displays the information specified in the first parameter on the screen in the position specified by the additional parameters. A default font will be used unless a font is set with the textFont() function and a default size will be used unless a font is set with textSize(). Change the color of the text with the fill() function. Change the outline of the text with the stroke() and strokeWeight() functions.

The text displays in relation to the textAlign() function, which gives the option to draw to the left, right, and center of the coordinates.

The x2 and y2 parameters define a rectangular area to display within and may only be used with string data. When these parameters are specified, they are interpreted based on the current rectMode() setting. Text that does not fit completely within the rectangle specified will not be drawn to the screen. If x2 and y2 are not specified, the baseline alignment is the default, which means that the text will be drawn upwards from x and y.

WEBGL: Only opentype/truetype fonts are supported. You must load a font using the loadFont() method (see the example above). stroke() currently has no effect in webgl mode.
Parameters:
Name Type Description
str String | Object | Array | Number | Boolean the alphanumeric symbols to be displayed
x Number x-coordinate of text
y Number y-coordinate of text
Example
text('word', 10, 30);
fill(0, 102, 153);
text('word', 10, 60);
fill(0, 102, 153, 51);
text('word', 10, 90);

let s = 'The quick brown fox jumped over the lazy dog.';
fill(50);
text(s, 10, 10, 70, 80); // Text wraps within text box

avenir;
function setup() {
  avenir = loadFont('assets/Avenir.otf');
  textFont(avenir);
  textSize(width / 3);
  textAlign(CENTER, CENTER);
}
function draw() {
  background(0);
  text('p5.js', 0, 0);
}

inner textAlign(horizAlign, vertAlignopt)

Sets the current alignment for drawing text. Accepts two arguments: horizAlign (LEFT, CENTER, or RIGHT) and vertAlign (TOP, BOTTOM, CENTER, or BASELINE). The horizAlign parameter is in reference to the x value of the text() function, while the vertAlign parameter is in reference to the y value. So if you write textAlign(LEFT), you are aligning the left edge of your text to the x value you give in text(). If you write textAlign(RIGHT, TOP), you are aligning the right edge of your text to the x value and the top of edge of the text to the y value.
Parameters:
Name Type Attributes Description
horizAlign Constant horizontal alignment, either LEFT, CENTER, or RIGHT
vertAlign Constant <optional>
vertical alignment, either TOP, BOTTOM, CENTER, or BASELINE
Example
textSize(16);
textAlign(RIGHT);
text('ABCD', 50, 30);
textAlign(CENTER);
text('EFGH', 50, 50);
textAlign(LEFT);
text('IJKL', 50, 70);

textSize(16);
strokeWeight(0.5);

line(0, 12, width, 12);
textAlign(CENTER, TOP);
text('TOP', 0, 12, width);

line(0, 37, width, 37);
textAlign(CENTER, CENTER);
text('CENTER', 0, 37, width);

line(0, 62, width, 62);
textAlign(CENTER, BASELINE);
text('BASELINE', 0, 62, width);

line(0, 87, width, 87);
textAlign(CENTER, BOTTOM);
text('BOTTOM', 0, 87, width);

inner textFont() → {Object}

Sets the current font that will be drawn with the text() function.

WEBGL: Only fonts loaded via loadFont() are supported.
Returns:
Object - the current font
Example
fill(0);
textSize(12);
textFont('Georgia');
text('Georgia', 12, 30);
textFont('Helvetica');
text('Helvetica', 12, 60);

let fontRegular, fontItalic, fontBold;
function setup() {
  fontRegular = loadFont('assets/Regular.otf');
  fontItalic = loadFont('assets/Italic.ttf');
  fontBold = loadFont('assets/Bold.ttf');
  background(210);
  fill(0);
  textFont(fontRegular);
  text('Font Style Normal', 10, 30);
  textFont(fontItalic);
  text('Font Style Italic', 10, 50);
  textFont(fontBold);
  text('Font Style Bold', 10, 70);
}

inner textSize() → {Number}

Gets the current font size.
Returns:
Number

inner textWidth(theText) → {Number}

Calculates and returns the width of any character or text string.
Parameters:
Name Type Description
theText String the String of characters to measure
Returns:
Number
Example
textSize(28);

let aChar = 'P';
let cWidth = textWidth(aChar);
text(aChar, 0, 40);
line(cWidth, 0, cWidth, 50);

let aString = 'p5.js';
let sWidth = textWidth(aString);
text(aString, 0, 85);
line(sWidth, 50, sWidth, 100);

inner trim(str) → {String}

Removes whitespace characters from the beginning and end of a String. In addition to standard whitespace characters such as space, carriage return, and tab, this function also removes the Unicode "nbsp" character.
Parameters:
Name Type Description
str String a String to be trimmed
Returns:
String - a trimmed String
Example
var string = trim('  No new lines\n   ');
text(string + ' here', 2, 50);

inner unchar(n) → {Number}

Converts a single-character string to its corresponding integer representation. When an array of single-character string values is passed in, then an array of integers of the same length is returned.
Parameters:
Name Type Description
n String value to parse
Returns:
Number - integer representation of value
Example
print(unchar('A')); // 65
print(unchar(['A', 'B', 'C'])); // [ 65, 66, 67 ]
print(unchar(split('ABC', ''))); // [ 65, 66, 67 ]

inner unhex(n) → {Number}

Converts a string representation of a hexadecimal number to its equivalent integer value. When an array of strings in hexadecimal notation is passed in, an array of integers of the same length is returned.
Parameters:
Name Type Description
n String value to parse
Returns:
Number - integer representation of hexadecimal value
Example
print(unhex('A')); // 10
print(unhex('FF')); // 255
print(unhex(['FF', 'AA', '00'])); // [ 255, 170, 0 ]

inner year() → {Integer}

The year() returns the current year as an integer (2014, 2015, 2016, etc).
Returns:
Integer - the current year
Example
var y = year();
text('Current year: \n' + y, 5, 50);

p5compat

Methods

static colorMode()

ignored

static createCanvas()

ignored

static exit()

exit the script after the current Loop().

static imageMode()

ignored

static noSmooth()

ignored

static noTint()

ignored

static settings()

ignored

static size()

ignored

static smooth()

ignored

static strokeWeight()

ignored

static tint()

ignored

inner abs(n) → {Number}

Calculates the absolute value (magnitude) of a number. Maps to Math.abs(). The absolute value of a number is always positive.
Parameters:
Name Type Description
n Number number to compute
Returns:
Number - absolute value of given number
Example
function setup() {
  let x = -3;
  let y = abs(x);

  print(x); // -3
  print(y); // 3
}

inner acos(value) → {Number}

The inverse of cos(), returns the arc cosine of a value. This function expects the values in the range of -1 to 1 and values are returned in the range 0 to PI (3.1415927).
Parameters:
Name Type Description
value Number the value whose arc cosine is to be returned
Returns:
Number - the arc cosine of the given value
Example
let a = PI;
let c = cos(a);
let ac = acos(c);
// Prints: "3.1415927 : -1.0 : 3.1415927"
print(a + ' : ' + c + ' : ' + ac);

let a = PI + PI / 4.0;
let c = cos(a);
let ac = acos(c);
// Prints: "3.926991 : -0.70710665 : 2.3561943"
print(a + ' : ' + c + ' : ' + ac);

inner angleMode(mode)

Sets the current mode of p5 to given mode. Default mode is RADIANS.
Parameters:
Name Type Description
mode Constant either RADIANS or DEGREES
Example
function draw() {
  background(204);
  angleMode(DEGREES); // Change the mode to DEGREES
  let a = atan2(mouseY - height / 2, mouseX - width / 2);
  translate(width / 2, height / 2);
  push();
  rotate(a);
  rect(-20, -5, 40, 10); // Larger rectangle is rotating in degrees
  pop();
  angleMode(RADIANS); // Change the mode to RADIANS
  rotate(a); // variable a stays the same
  rect(-40, -5, 20, 10); // Smaller rectangle is rotating in radians
}

inner append(array, value) → {Array}

Adds a value to the end of an array. Extends the length of the array by one. Maps to Array.push().
Parameters:
Name Type Description
array Array Array to append
value any to be added to the Array
Returns:
Array - the array that was appended to
Example
function setup() {
  var myArray = ['Mango', 'Apple', 'Papaya'];
  print(myArray); // ['Mango', 'Apple', 'Papaya']

  append(myArray, 'Peach');
  print(myArray); // ['Mango', 'Apple', 'Papaya', 'Peach']
}

inner arrayCopy(src, srcPosition, dst, dstPosition, length)

Copies an array (or part of an array) to another array. The src array is copied to the dst array, beginning at the position specified by srcPosition and into the position specified by dstPosition. The number of elements to copy is determined by length. Note that copying values overwrites existing values in the destination array. To append values instead of overwriting them, use concat().

The simplified version with only two arguments, arrayCopy(src, dst), copies an entire array to another of the same size. It is equivalent to arrayCopy(src, 0, dst, 0, src.length).

Using this function is far more efficient for copying array data than iterating through a for() loop and copying each element individually.
Parameters:
Name Type Description
src Array the source Array
srcPosition Integer starting position in the source Array
dst Array the destination Array
dstPosition Integer starting position in the destination Array
length Integer number of Array elements to be copied
Deprecated:
  • Yes
Example
var src = ['A', 'B', 'C'];
var dst = [1, 2, 3];
var srcPosition = 1;
var dstPosition = 0;
var length = 2;

print(src); // ['A', 'B', 'C']
print(dst); // [ 1 ,  2 ,  3 ]

arrayCopy(src, srcPosition, dst, dstPosition, length);
print(dst); // ['B', 'C', 3]

inner asin(value) → {Number}

The inverse of sin(), returns the arc sine of a value. This function expects the values in the range of -1 to 1 and values are returned in the range -PI/2 to PI/2.
Parameters:
Name Type Description
value Number the value whose arc sine is to be returned
Returns:
Number - the arc sine of the given value
Example
let a = PI + PI / 3;
let s = sin(a);
let as = asin(s);
// Prints: "1.0471976 : 0.86602545 : 1.0471976"
print(a + ' : ' + s + ' : ' + as);

let a = PI + PI / 3.0;
let s = sin(a);
let as = asin(s);
// Prints: "4.1887903 : -0.86602545 : -1.0471976"
print(a + ' : ' + s + ' : ' + as);

inner atan(value) → {Number}

The inverse of tan(), returns the arc tangent of a value. This function expects the values in the range of -Infinity to Infinity (exclusive) and values are returned in the range -PI/2 to PI/2.
Parameters:
Name Type Description
value Number the value whose arc tangent is to be returned
Returns:
Number - the arc tangent of the given value
Example
let a = PI + PI / 3;
let t = tan(a);
let at = atan(t);
// Prints: "1.0471976 : 1.7320509 : 1.0471976"
print(a + ' : ' + t + ' : ' + at);

let a = PI + PI / 3.0;
let t = tan(a);
let at = atan(t);
// Prints: "4.1887903 : 1.7320513 : 1.0471977"
print(a + ' : ' + t + ' : ' + at);

inner atan2(y, x) → {Number}

Calculates the angle (in radians) from a specified point to the coordinate origin as measured from the positive x-axis. Values are returned as a float in the range from PI to -PI. The atan2() function is most often used for orienting geometry to the position of the cursor.

Note: The y-coordinate of the point is the first parameter, and the x-coordinate is the second parameter, due the the structure of calculating the tangent.
Parameters:
Name Type Description
y Number y-coordinate of the point
x Number x-coordinate of the point
Returns:
Number - the arc tangent of the given point
Example
function draw() {
  background(204);
  translate(width / 2, height / 2);
  let a = atan2(mouseY - height / 2, mouseX - width / 2);
  rotate(a);
  rect(-30, -5, 60, 10);
}

inner boolean(n) → {Boolean}

Converts a number or string to its boolean representation. For a number, any non-zero value (positive or negative) evaluates to true, while zero evaluates to false. For a string, the value "true" evaluates to true, while any other value evaluates to false. When an array of number or string values is passed in, then a array of booleans of the same length is returned.
Parameters:
Name Type Description
n String | Boolean | Number | Array value to parse
Returns:
Boolean - boolean representation of value
Example
print(boolean(0)); // false
print(boolean(1)); // true
print(boolean('true')); // true
print(boolean('abcd')); // false
print(boolean([0, 12, 'true'])); // [false, true, false]

inner byte(n) → {Number}

Converts a number, string representation of a number, or boolean to its byte representation. A byte can be only a whole number between -128 and 127, so when a value outside of this range is converted, it wraps around to the corresponding byte representation. When an array of number, string or boolean values is passed in, then an array of bytes the same length is returned.
Parameters:
Name Type Description
n String | Boolean | Number value to parse
Returns:
Number - byte representation of value
Example
print(byte(127)); // 127
print(byte(128)); // -128
print(byte(23.4)); // 23
print(byte('23.4')); // 23
print(byte('hello')); // NaN
print(byte(true)); // 1
print(byte([0, 255, '100'])); // [0, -1, 100]

inner ceil(n) → {Integer}

Calculates the closest int value that is greater than or equal to the value of the parameter. Maps to Math.ceil(). For example, ceil(9.03) returns the value 10.
Parameters:
Name Type Description
n Number number to round up
Returns:
Integer - rounded up number
Example
function draw() {
  background(200);
  // map, mouseX between 0 and 5.
  let ax = map(mouseX, 0, 100, 0, 5);
  let ay = 66;

  //Get the ceiling of the mapped number.
  let bx = ceil(map(mouseX, 0, 100, 0, 5));
  let by = 33;

  // Multiply the mapped numbers by 20 to more easily
  // see the changes.
  stroke(0);
  fill(0);
  line(0, ay, ax * 20, ay);
  line(0, by, bx * 20, by);

  // Reformat the float returned by map and draw it.
  noStroke();
  text(nfc(ax, 2), ax, ay - 5);
  text(nfc(bx, 1), bx, by - 5);
}

inner char(n) → {String}

Converts a number or string to its corresponding single-character string representation. If a string parameter is provided, it is first parsed as an integer and then translated into a single-character string. When an array of number or string values is passed in, then an array of single-character strings of the same length is returned.
Parameters:
Name Type Description
n String | Number value to parse
Returns:
String - string representation of value
Example
print(char(65)); // "A"
print(char('65')); // "A"
print(char([65, 66, 67])); // [ "A", "B", "C" ]
print(join(char([65, 66, 67]), '')); // "ABC"

inner concat(a, b) → {Array}

Concatenates two arrays, maps to Array.concat(). Does not modify the input arrays.
Parameters:
Name Type Description
a Array first Array to concatenate
b Array second Array to concatenate
Returns:
Array - concatenated array
Example
function setup() {
  var arr1 = ['A', 'B', 'C'];
  var arr2 = [1, 2, 3];

  print(arr1); // ['A','B','C']
  print(arr2); // [1,2,3]

  var arr3 = concat(arr1, arr2);

  print(arr1); // ['A','B','C']
  print(arr2); // [1, 2, 3]
  print(arr3); // ['A','B','C', 1, 2, 3]
}

inner constrain(n, low, high) → {Number}

Constrains a value between a minimum and maximum value.
Parameters:
Name Type Description
n Number number to constrain
low Number minimum limit
high Number maximum limit
Returns:
Number - constrained number
Example
function draw() {
  background(200);

  let leftWall = 25;
  let rightWall = 75;

  // xm is just the mouseX, while
  // xc is the mouseX, but constrained
  // between the leftWall and rightWall!
  let xm = mouseX;
  let xc = constrain(mouseX, leftWall, rightWall);

  // Draw the walls.
  stroke(150);
  line(leftWall, 0, leftWall, height);
  line(rightWall, 0, rightWall, height);

  // Draw xm and xc as circles.
  noStroke();
  fill(150);
  ellipse(xm, 33, 9, 9); // Not Constrained
  fill(0);
  ellipse(xc, 66, 9, 9); // Constrained
}

inner cos(angle) → {Number}

Calculates the cosine of an angle. This function takes into account the current angleMode. Values are returned in the range -1 to 1.
Parameters:
Name Type Description
angle Number the angle
Returns:
Number - the cosine of the angle
Example
let a = 0.0;
let inc = TWO_PI / 25.0;
for (let i = 0; i < 25; i++) {
  line(i * 4, 50, i * 4, 50 + cos(a) * 40.0);
  a = a + inc;
}

inner createNumberDict(key, value) → {NumberDict}

Creates a new instance of NumberDict using the key-value pair or object you provide.
Parameters:
Name Type Description
key Number
value Number
Returns:
NumberDict
Example
function setup() {
  let myDictionary = createNumberDict(100, 42);
  print(myDictionary.hasKey(100)); // logs true to console

  let anotherDictionary = createNumberDict({ 200: 84 });
  print(anotherDictionary.hasKey(200)); // logs true to console
}

inner createStringDict(key, value) → {StringDict}

Creates a new instance of p5.StringDict using the key-value pair or the object you provide.
Parameters:
Name Type Description
key String
value String
Returns:
StringDict
Example
function setup() {
  let myDictionary = createStringDict('p5', 'js');
  print(myDictionary.hasKey('p5')); // logs true to console

  let anotherDictionary = createStringDict({ happy: 'coding' });
  print(anotherDictionary.hasKey('happy')); // logs true to console
}

inner createVector(xopt, yopt, zopt) → {p5.Vector}

Creates a new PVector (the datatype for storing vectors). This provides a two or three dimensional vector, specifically a Euclidean (also known as geometric) vector. A vector is an entity that has both magnitude and direction.
Parameters:
Name Type Attributes Description
x Number <optional>
x component of the vector
y Number <optional>
y component of the vector
z Number <optional>
z component of the vector
Returns:
p5.Vector
Example
function setup() {
  createCanvas(100, 100, WEBGL);
  noStroke();
  fill(255, 102, 204);
}

function draw() {
  background(255);
  pointLight(color(255), createVector(sin(millis() / 1000) * 20, -40, -10));
  scale(0.75);
  sphere();
}

inner day() → {Integer}

The day() function returns the current day as a value from 1 - 31.
Returns:
Integer - the current day
Example
var d = day();
text('Current day: \n' + d, 5, 50);

inner degrees(radians) → {Number}

Converts a radian measurement to its corresponding value in degrees. Radians and degrees are two ways of measuring the same thing. There are 360 degrees in a circle and 2*PI radians in a circle. For example, 90° = PI/2 = 1.5707964. This function does not take into account the current angleMode.
Parameters:
Name Type Description
radians Number the radians value to convert to degrees
Returns:
Number - the converted angle
Example
let rad = PI / 4;
let deg = degrees(rad);
print(rad + ' radians is ' + deg + ' degrees');
// Prints: 0.7853981633974483 radians is 45 degrees

inner displayDensity() → {Number}

Returns the pixel density of the current display the sketch is running on (always 1 for DOjS).
Returns:
Number - current pixel density of the display
Example
function setup() {
  let density = displayDensity();
  pixelDensity(density);
  createCanvas(100, 100);
  background(200);
  ellipse(width / 2, height / 2, 50, 50);
}

inner dist(x1, y1, x2, y2) → {Number}

Calculates the distance between two points.
Parameters:
Name Type Description
x1 Number x-coordinate of the first point
y1 Number y-coordinate of the first point
x2 Number x-coordinate of the second point
y2 Number y-coordinate of the second point
Returns:
Number - distance between the two points
Example
// Move your mouse inside the canvas to see the
// change in distance between two points!
function draw() {
  background(200);
  fill(0);

  let x1 = 10;
  let y1 = 90;
  let x2 = mouseX;
  let y2 = mouseY;

  line(x1, y1, x2, y2);
  ellipse(x1, y1, 7, 7);
  ellipse(x2, y2, 7, 7);

  // d is the length of the line
  // the distance from point 1 to point 2.
  let d = int(dist(x1, y1, x2, y2));

  // Let's write d along the line we are drawing!
  push();
  translate((x1 + x2) / 2, (y1 + y2) / 2);
  rotate(atan2(y2 - y1, x2 - x1));
  text(nfc(d, 1), 0, -5);
  pop();
  // Fancy!
}

inner exp(n) → {Number}

Returns Euler's number e (2.71828...) raised to the power of the n parameter. Maps to Math.exp().
Parameters:
Name Type Description
n Number exponent to raise
Returns:
Number - e^n
Example
function draw() {
  background(200);

  // Compute the exp() function with a value between 0 and 2
  let xValue = map(mouseX, 0, width, 0, 2);
  let yValue = exp(xValue);

  let y = map(yValue, 0, 8, height, 0);

  let legend = 'exp (' + nfc(xValue, 3) + ')\n= ' + nf(yValue, 1, 4);
  stroke(150);
  line(mouseX, y, mouseX, height);
  fill(0);
  text(legend, 5, 15);
  noStroke();
  ellipse(mouseX, y, 7, 7);

  // Draw the exp(x) curve,
  // over the domain of x from 0 to 2
  noFill();
  stroke(0);
  beginShape();
  for (let x = 0; x < width; x++) {
    xValue = map(x, 0, width, 0, 2);
    yValue = exp(xValue);
    y = map(yValue, 0, 8, height, 0);
    vertex(x, y);
  }

  endShape();
  line(0, 0, 0, height);
  line(0, height - 1, width, height - 1);
}

inner float(str) → {Number}

Converts a string to its floating point representation. The contents of a string must resemble a number, or NaN (not a number) will be returned. For example, float("1234.56") evaluates to 1234.56, but float("giraffe") will return NaN. When an array of values is passed in, then an array of floats of the same length is returned.
Parameters:
Name Type Description
str String float string to parse
Returns:
Number - floating point representation of string
Example
var str = '20';
var diameter = float(str);
ellipse(width / 2, height / 2, diameter, diameter);

inner floor(n) → {Integer}

Calculates the closest int value that is less than or equal to the value of the parameter. Maps to Math.floor().
Parameters:
Name Type Description
n Number number to round down
Returns:
Integer - rounded down number
Example
function draw() {
  background(200);
  //map, mouseX between 0 and 5.
  let ax = map(mouseX, 0, 100, 0, 5);
  let ay = 66;

  //Get the floor of the mapped number.
  let bx = floor(map(mouseX, 0, 100, 0, 5));
  let by = 33;

  // Multiply the mapped numbers by 20 to more easily
  // see the changes.
  stroke(0);
  fill(0);
  line(0, ay, ax * 20, ay);
  line(0, by, bx * 20, by);

  // Reformat the float returned by map and draw it.
  noStroke();
  text(nfc(ax, 2), ax, ay - 5);
  text(nfc(bx, 1), bx, by - 5);
}

inner hex(n, digitsopt) → {String}

Converts a number to a string in its equivalent hexadecimal notation. If a second parameter is passed, it is used to set the number of characters to generate in the hexadecimal notation. When an array is passed in, an array of strings in hexadecimal notation of the same length is returned.
Parameters:
Name Type Attributes Description
n Number value to parse
digits Number <optional>
Returns:
String - hexadecimal string representation of value
Example
print(hex(255)); // "000000FF"
print(hex(255, 6)); // "0000FF"
print(hex([0, 127, 255], 6)); // [ "000000", "00007F", "0000FF" ]

inner hour() → {Integer}

The hour() function returns the current hour as a value from 0 - 23.
Returns:
Integer - the current hour
Example
var h = hour();
text('Current hour:\n' + h, 5, 50);

inner int(n, radixopt) → {Number}

Converts a boolean, string, or float to its integer representation. When an array of values is passed in, then an int array of the same length is returned.
Parameters:
Name Type Attributes Description
n String | Boolean | Number value to parse
radix Integer <optional>
the radix to convert to (default: 10)
Returns:
Number - integer representation of value
Example
print(int('10')); // 10
print(int(10.31)); // 10
print(int(-10)); // -10
print(int(true)); // 1
print(int(false)); // 0
print(int([false, true, '10.3', 9.8])); // [0, 1, 10, 9]

inner join(list, separator) → {String}

Combines an array of Strings into one String, each separated by the character(s) used for the separator parameter. To join arrays of ints or floats, it's necessary to first convert them to Strings using nf() or nfs().
Parameters:
Name Type Description
list Array array of Strings to be joined
separator String String to be placed between each item
Returns:
String - joined String
Example
var array = ['Hello', 'world!'];
var separator = ' ';
var message = join(array, separator);
text(message, 5, 50);

inner lerp(start, stop, amt) → {Number}

Calculates a number between two numbers at a specific increment. The amt parameter is the amount to interpolate between the two values where 0.0 equal to the first point, 0.1 is very near the first point, 0.5 is half-way in between, and 1.0 is equal to the second point. If the value of amt is more than 1.0 or less than 0.0, the number will be calculated accordingly in the ratio of the two given numbers. The lerp function is convenient for creating motion along a straight path and for drawing dotted lines.
Parameters:
Name Type Description
start Number first value
stop Number second value
amt Number number
Returns:
Number - lerped value
Example
function setup() {
  background(200);
  let a = 20;
  let b = 80;
  let c = lerp(a, b, 0.2);
  let d = lerp(a, b, 0.5);
  let e = lerp(a, b, 0.8);

  let y = 50;

  strokeWeight(5);
  stroke(0); // Draw the original points in black
  point(a, y);
  point(b, y);

  stroke(100); // Draw the lerp points in gray
  point(c, y);
  point(d, y);
  point(e, y);
}

inner loadFont(path) → {Font}

Loads a GRX font file (.FNT) from a file Font Object.

Parameters:
Name Type Description
path String name of the file or url to load
Returns:
Font - Font object

inner log(n) → {Number}

Calculates the natural logarithm (the base-e logarithm) of a number. This function expects the n parameter to be a value greater than 0.0. Maps to Math.log().
Parameters:
Name Type Description
n Number number greater than 0
Returns:
Number - natural logarithm of n
Example
function draw() {
  background(200);
  let maxX = 2.8;
  let maxY = 1.5;

  // Compute the natural log of a value between 0 and maxX
  let xValue = map(mouseX, 0, width, 0, maxX);
  let yValue, y;
  if (xValue > 0) {
  // Cannot take the log of a negative number.
    yValue = log(xValue);
    y = map(yValue, -maxY, maxY, height, 0);

    // Display the calculation occurring.
    let legend = 'log(' + nf(xValue, 1, 2) + ')\n= ' + nf(yValue, 1, 3);
    stroke(150);
    line(mouseX, y, mouseX, height);
    fill(0);
    text(legend, 5, 15);
    noStroke();
    ellipse(mouseX, y, 7, 7);
  }

  // Draw the log(x) curve,
  // over the domain of x from 0 to maxX
  noFill();
  stroke(0);
  beginShape();
  for (let x = 0; x < width; x++) {
    xValue = map(x, 0, width, 0, maxX);
    yValue = log(xValue);
    y = map(yValue, -maxY, maxY, height, 0);
    vertex(x, y);
  }
  endShape();
  line(0, 0, 0, height);
  line(0, height / 2, width, height / 2);
}

inner loop()

By default, p5.js loops through draw() continuously, executing the code within it. However, the draw() loop may be stopped by calling noLoop(). In that case, the draw() loop can be resumed with loop(). Avoid calling loop() from inside setup().
Example
let x = 0;
function setup() {
  createCanvas(100, 100);
  noLoop();
}

function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}

function mousePressed() {
  loop();
}

function mouseReleased() {
  noLoop();
}

inner mag(a, b) → {Number}

Calculates the magnitude (or length) of a vector. A vector is a direction in space commonly used in computer graphics and linear algebra. Because it has no "start" position, the magnitude of a vector can be thought of as the distance from the coordinate 0,0 to its x,y value. Therefore, mag() is a shortcut for writing dist(0, 0, x, y).
Parameters:
Name Type Description
a Number first value
b Number second value
Returns:
Number - magnitude of vector from (0,0) to (a,b)
Example
function setup() {
  let x1 = 20;
  let x2 = 80;
  let y1 = 30;
  let y2 = 70;

  line(0, 0, x1, y1);
  print(mag(x1, y1)); // Prints "36.05551275463989"
  line(0, 0, x2, y1);
  print(mag(x2, y1)); // Prints "85.44003745317531"
  line(0, 0, x1, y2);
  print(mag(x1, y2)); // Prints "72.80109889280519"
  line(0, 0, x2, y2);
  print(mag(x2, y2)); // Prints "106.3014581273465"
}

inner map(value, start1, stop1, start2, stop2, withinBoundsopt) → {Number}

Re-maps a number from one range to another.

In the first example above, the number 25 is converted from a value in the range of 0 to 100 into a value that ranges from the left edge of the window (0) to the right edge (width).
Parameters:
Name Type Attributes Description
value Number the incoming value to be converted
start1 Number lower bound of the value's current range
stop1 Number upper bound of the value's current range
start2 Number lower bound of the value's target range
stop2 Number upper bound of the value's target range
withinBounds Boolean <optional>
constrain the value to the newly mapped range
Returns:
Number - remapped number
Example
let value = 25;
let m = map(value, 0, 100, 0, width);
ellipse(m, 50, 10, 10);

function setup() {
  noStroke();
}

function draw() {
  background(204);
  let x1 = map(mouseX, 0, width, 25, 75);
  ellipse(x1, 25, 25, 25);
  //This ellipse is constrained to the 0-100 range
  //after setting withinBounds to true
  let x2 = map(mouseX, 0, width, 0, 100, true);
  ellipse(x2, 75, 25, 25);
}

inner match(str, regexp) → {Array.<String>}

This function is used to apply a regular expression to a piece of text, and return matching groups (elements found inside parentheses) as a String array. If there are no matches, a null value will be returned. If no groups are specified in the regular expression, but the sequence matches, an array of length 1 (with the matched text as the first element of the array) will be returned.

To use the function, first check to see if the result is null. If the result is null, then the sequence did not match at all. If the sequence did match, an array is returned.

If there are groups (specified by sets of parentheses) in the regular expression, then the contents of each will be returned in the array. Element [0] of a regular expression match returns the entire matching string, and the match groups start at element [1] (the first group is [1], the second [2], and so on).
Parameters:
Name Type Description
str String the String to be searched
regexp String the regexp to be used for matching
Returns:
Array.<String> - Array of Strings found
Example
var string = 'Hello p5js*!';
var regexp = 'p5js\\*';
var m = match(string, regexp);
text(m, 5, 50);

inner matchAll(str, regexp) → {Array.<String>}

This function is used to apply a regular expression to a piece of text, and return a list of matching groups (elements found inside parentheses) as a two-dimensional String array. If there are no matches, a null value will be returned. If no groups are specified in the regular expression, but the sequence matches, a two dimensional array is still returned, but the second dimension is only of length one.

To use the function, first check to see if the result is null. If the result is null, then the sequence did not match at all. If the sequence did match, a 2D array is returned.

If there are groups (specified by sets of parentheses) in the regular expression, then the contents of each will be returned in the array. Assuming a loop with counter variable i, element [i][0] of a regular expression match returns the entire matching string, and the match groups start at element [i][1] (the first group is [i][1], the second [i][2], and so on).
Parameters:
Name Type Description
str String the String to be searched
regexp String the regexp to be used for matching
Returns:
Array.<String> - 2d Array of Strings found
Example
var string = 'Hello p5js*! Hello world!';
var regexp = 'Hello';
matchAll(string, regexp);

inner max(n0, n1) → {Number}

Determines the largest value in a sequence of numbers, and then returns that value. max() accepts any number of Number parameters, or an Array of any length.
Parameters:
Name Type Description
n0 Number Number to compare
n1 Number Number to compare
Returns:
Number - maximum Number
Example
function setup() {
  // Change the elements in the array and run the sketch
  // to show how max() works!
  let numArray = [2, 1, 5, 4, 8, 9];
  fill(0);
  noStroke();
  text('Array Elements', 0, 10);
  // Draw all numbers in the array
  let spacing = 15;
  let elemsY = 25;
  for (let i = 0; i < numArray.length; i++) {
    text(numArray[i], i * spacing, elemsY);
  }
  let maxX = 33;
  let maxY = 80;
  // Draw the Maximum value in the array.
  textSize(32);
  text(max(numArray), maxX, maxY);
}

inner millis() → {Number}

Returns the number of milliseconds (thousandths of a second) since starting the program. This information is often used for timing events and animation sequences.
Returns:
Number - the number of milliseconds since starting the program
Example
var millisecond = millis();
text('Milliseconds \nrunning: \n' + millisecond, 5, 40);

inner min(n0, n1) → {Number}

Determines the smallest value in a sequence of numbers, and then returns that value. min() accepts any number of Number parameters, or an Array of any length.
Parameters:
Name Type Description
n0 Number Number to compare
n1 Number Number to compare
Returns:
Number - minimum Number
Example
function setup() {
  // Change the elements in the array and run the sketch
  // to show how min() works!
  let numArray = [2, 1, 5, 4, 8, 9];
  fill(0);
  noStroke();
  text('Array Elements', 0, 10);
  // Draw all numbers in the array
  let spacing = 15;
  let elemsY = 25;
  for (let i = 0; i < numArray.length; i++) {
    text(numArray[i], i * spacing, elemsY);
  }
  let maxX = 33;
  let maxY = 80;
  // Draw the Minimum value in the array.
  textSize(32);
  text(min(numArray), maxX, maxY);
}

inner minute() → {Integer}

The minute() function returns the current minute as a value from 0 - 59.
Returns:
Integer - the current minute
Example
var m = minute();
text('Current minute: \n' + m, 5, 50);

inner month() → {Integer}

The month() function returns the current month as a value from 1 - 12.
Returns:
Integer - the current month
Example
var m = month();
text('Current month: \n' + m, 5, 50);

inner nf(num, leftopt, rightopt) → {String}

Utility function for formatting numbers into strings. There are two versions: one for formatting floats, and one for formatting ints. The values for the digits, left, and right parameters should always be positive integers. (NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter if greater than the current length of the number. For example if number is 123.2 and left parameter passed is 4 which is greater than length of 123 (integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than the result will be 123.200.
Parameters:
Name Type Attributes Description
num Number | String the Number to format
left Integer | String <optional>
number of digits to the left of the decimal point
right Integer | String <optional>
number of digits to the right of the decimal point
Returns:
String - formatted String
Example
var myFont;
function preload() {
  myFont = loadFont('assets/fonts/inconsolata.ttf');
}
function setup() {
  background(200);
  var num1 = 321;
  var num2 = -1321;

  noStroke();
  fill(0);
  textFont(myFont);
  textSize(22);

  text(nf(num1, 4, 2), 10, 30);
  text(nf(num2, 4, 2), 10, 80);
  // Draw dividing line
  stroke(120);
  line(0, 50, width, 50);
}

inner nfc(num, rightopt) → {String}

Utility function for formatting numbers into strings and placing appropriate commas to mark units of 1000. There are two versions: one for formatting ints, and one for formatting an array of ints. The value for the right parameter should always be a positive integer.
Parameters:
Name Type Attributes Description
num Number | String the Number to format
right Integer | String <optional>
number of digits to the right of the decimal point
Returns:
String - formatted String
Example
function setup() {
  background(200);
  var num = 11253106.115;
  var numArr = [1, 1, 2];

  noStroke();
  fill(0);
  textSize(12);

  // Draw formatted numbers
  text(nfc(num, 4), 10, 30);
  text(nfc(numArr, 2), 10, 80);

  // Draw dividing line
  stroke(120);
  line(0, 50, width, 50);
}

inner nfp(num, leftopt, rightopt) → {String}

Utility function for formatting numbers into strings. Similar to nf() but puts a "+" in front of positive numbers and a "-" in front of negative numbers. There are two versions: one for formatting floats, and one for formatting ints. The values for left, and right parameters should always be positive integers.
Parameters:
Name Type Attributes Description
num Number the Number to format
left Integer <optional>
number of digits to the left of the decimal point
right Integer <optional>
number of digits to the right of the decimal point
Returns:
String - formatted String
Example
function setup() {
  background(200);
  var num1 = 11253106.115;
  var num2 = -11253106.115;

  noStroke();
  fill(0);
  textSize(12);

  // Draw formatted numbers
  text(nfp(num1, 4, 2), 10, 30);
  text(nfp(num2, 4, 2), 10, 80);

  // Draw dividing line
  stroke(120);
  line(0, 50, width, 50);
}

inner nfs(num, leftopt, rightopt) → {String}

Utility function for formatting numbers into strings. Similar to nf() but puts an additional "_" (space) in front of positive numbers just in case to align it with negative numbers which includes "-" (minus) sign. The main usecase of nfs() can be seen when one wants to align the digits (place values) of a positive number with some negative number (See the example to get a clear picture). There are two versions: one for formatting float, and one for formatting int. The values for the digits, left, and right parameters should always be positive integers. (IMP): The result on the canvas basically the expected alignment can vary based on the typeface you are using. (NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter if greater than the current length of the number. For example if number is 123.2 and left parameter passed is 4 which is greater than length of 123 (integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than the result will be 123.200.
Parameters:
Name Type Attributes Description
num Number the Number to format
left Integer <optional>
number of digits to the left of the decimal point
right Integer <optional>
number of digits to the right of the decimal point
Returns:
String - formatted String
Example
var myFont;
function preload() {
  myFont = loadFont('assets/fonts/inconsolata.ttf');
}
function setup() {
  background(200);
  var num1 = 321;
  var num2 = -1321;

  noStroke();
  fill(0);
  textFont(myFont);
  textSize(22);

  // nfs() aligns num1 (positive number) with num2 (negative number) by
  // adding a blank space in front of the num1 (positive number)
  // [left = 4] in num1 add one 0 in front, to align the digits with num2
  // [right = 2] in num1 and num2 adds two 0's after both numbers
  // To see the differences check the example of nf() too.
  text(nfs(num1, 4, 2), 10, 30);
  text(nfs(num2, 4, 2), 10, 80);
  // Draw dividing line
  stroke(120);
  line(0, 50, width, 50);
}

inner noCursor()

Hides the cursor from view.
Example
function setup() {
  noCursor();
}

function draw() {
  background(200);
  ellipse(mouseX, mouseY, 10, 10);
}

inner noise(x, yopt, zopt) → {Number}

Returns the Perlin noise value at specified coordinates. Perlin noise is a random sequence generator producing a more natural ordered, harmonic succession of numbers compared to the standard random() function. It was invented by Ken Perlin in the 1980s and been used since in graphical applications to produce procedural textures, natural motion, shapes, terrains etc.

The main difference to the random() function is that Perlin noise is defined in an infinite n-dimensional space where each pair of coordinates corresponds to a fixed semi-random value (fixed only for the lifespan of the program; see the noiseSeed() function). p5.js can compute 1D, 2D and 3D noise, depending on the number of coordinates given. The resulting value will always be between 0.0 and 1.0. The noise value can be animated by moving through the noise space as demonstrated in the example above. The 2nd and 3rd dimension can also be interpreted as time.

The actual noise is structured similar to an audio signal, in respect to the function's use of frequencies. Similar to the concept of harmonics in physics, perlin noise is computed over several octaves which are added together for the final result.

Another way to adjust the character of the resulting sequence is the scale of the input coordinates. As the function works within an infinite space the value of the coordinates doesn't matter as such, only the distance between successive coordinates does (eg. when using noise() within a loop). As a general rule the smaller the difference between coordinates, the smoother the resulting noise sequence will be. Steps of 0.005-0.03 work best for most applications, but this will differ depending on use.
Parameters:
Name Type Attributes Description
x Number x-coordinate in noise space
y Number <optional>
y-coordinate in noise space
z Number <optional>
z-coordinate in noise space
Returns:
Number - Perlin noise value (between 0 and 1) at specified coordinates
Example
let xoff = 0.0;

function draw() {
  background(204);
  xoff = xoff + 0.01;
  let n = noise(xoff) * width;
  line(n, 0, n, height);
}

let noiseScale=0.02;

function draw() {
  background(0);
  for (let x=0; x < width; x++) {
    let noiseVal = noise((mouseX+x)*noiseScale, mouseY*noiseScale);
    stroke(noiseVal*255);
    line(x, mouseY+noiseVal*80, x, height);
  }
}

inner noiseDetail(lod, falloff)

Adjusts the character and level of detail produced by the Perlin noise function. Similar to harmonics in physics, noise is computed over several octaves. Lower octaves contribute more to the output signal and as such define the overall intensity of the noise, whereas higher octaves create finer grained details in the noise sequence.

By default, noise is computed over 4 octaves with each octave contributing exactly half than its predecessor, starting at 50% strength for the 1st octave. This falloff amount can be changed by adding an additional function parameter. Eg. a falloff factor of 0.75 means each octave will now have 75% impact (25% less) of the previous lower octave. Any value between 0.0 and 1.0 is valid, however note that values greater than 0.5 might result in greater than 1.0 values returned by noise().

By changing these parameters, the signal created by the noise() function can be adapted to fit very specific needs and characteristics.
Parameters:
Name Type Description
lod Number number of octaves to be used by the noise
falloff Number falloff factor for each octave
Example
let noiseVal;
let noiseScale = 0.02;

function setup() {
  createCanvas(100, 100);
}

function draw() {
  background(0);
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width / 2; x++) {
      noiseDetail(2, 0.2);
      noiseVal = noise((mouseX + x) * noiseScale, (mouseY + y) * noiseScale);
      stroke(noiseVal * 255);
      point(x, y);
      noiseDetail(8, 0.65);
      noiseVal = noise(
        (mouseX + x + width / 2) * noiseScale,
        (mouseY + y) * noiseScale
      );
      stroke(noiseVal * 255);
      point(x + width / 2, y);
    }
  }
}

inner noLoop()

Stops p5.js from continuously executing the code within draw(). If loop() is called, the code in draw() begins to run continuously again. If using noLoop() in setup(), it should be the last line inside the block.

When noLoop() is used, it's not possible to manipulate or access the screen inside event handling functions such as mousePressed() or keyPressed(). Instead, use those functions to call redraw() or loop(), which will run draw(), which can update the screen properly. This means that when noLoop() has been called, no drawing can happen, and functions like saveFrame() or loadPixels() may not be used.

Note that if the sketch is resized, redraw() will be called to update the sketch, even after noLoop() has been specified. Otherwise, the sketch would enter an odd state until loop() was called.
Example
function setup() {
  createCanvas(100, 100);
  background(200);
  noLoop();
}

function draw() {
  line(10, 10, 90, 90);
}

let x = 0;
function setup() {
  createCanvas(100, 100);
}

function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}

function mousePressed() {
  noLoop();
}

function mouseReleased() {
  loop();
}

inner norm(value, start, stop) → {Number}

Normalizes a number from another range into a value between 0 and 1. Identical to map(value, low, high, 0, 1). Numbers outside of the range are not clamped to 0 and 1, because out-of-range values are often intentional and useful. (See the second example above.)
Parameters:
Name Type Description
value Number incoming value to be normalized
start Number lower bound of the value's current range
stop Number upper bound of the value's current range
Returns:
Number - normalized number
Example
function draw() {
  background(200);
  let currentNum = mouseX;
  let lowerBound = 0;
  let upperBound = width; //100;
  let normalized = norm(currentNum, lowerBound, upperBound);
  let lineY = 70;
  line(0, lineY, width, lineY);
  //Draw an ellipse mapped to the non-normalized value.
  noStroke();
  fill(50);
  let s = 7; // ellipse size
  ellipse(currentNum, lineY, s, s);

  // Draw the guide
  let guideY = lineY + 15;
  text('0', 0, guideY);
  textAlign(RIGHT);
  text('100', width, guideY);

  // Draw the normalized value
  textAlign(LEFT);
  fill(0);
  textSize(32);
  let normalY = 40;
  let normalX = 20;
  text(normalized, normalX, normalY);
}

inner pow(n, e) → {Number}

Facilitates exponential expressions. The pow() function is an efficient way of multiplying numbers by themselves (or their reciprocals) in large quantities. For example, pow(3, 5) is equivalent to the expression 3*3*3*3*3 and pow(3, -5) is equivalent to 1 / 3*3*3*3*3. Maps to Math.pow().
Parameters:
Name Type Description
n Number base of the exponential expression
e Number power by which to raise the base
Returns:
Number - n^e
Example
function setup() {
  //Exponentially increase the size of an ellipse.
  let eSize = 3; // Original Size
  let eLoc = 10; // Original Location

  ellipse(eLoc, eLoc, eSize, eSize);

  ellipse(eLoc * 2, eLoc * 2, pow(eSize, 2), pow(eSize, 2));

  ellipse(eLoc * 4, eLoc * 4, pow(eSize, 3), pow(eSize, 3));

  ellipse(eLoc * 8, eLoc * 8, pow(eSize, 4), pow(eSize, 4));
}

inner radians(degrees) → {Number}

Converts a degree measurement to its corresponding value in radians. Radians and degrees are two ways of measuring the same thing. There are 360 degrees in a circle and 2*PI radians in a circle. For example, 90° = PI/2 = 1.5707964. This function does not take into account the current angleMode.
Parameters:
Name Type Description
degrees Number the degree value to convert to radians
Returns:
Number - the converted angle
Example
let deg = 45.0;
let rad = radians(deg);
print(deg + ' degrees is ' + rad + ' radians');
// Prints: 45 degrees is 0.7853981633974483 radians

inner random(minopt, maxopt) → {Number}

Return a random floating-point number. Takes either 0, 1 or 2 arguments. If no argument is given, returns a random number from 0 up to (but not including) 1. If one argument is given and it is a number, returns a random number from 0 up to (but not including) the number. If one argument is given and it is an array, returns a random element from that array. If two arguments are given, returns a random number from the first argument up to (but not including) the second argument.
Parameters:
Name Type Attributes Description
min Number <optional>
the lower bound (inclusive)
max Number <optional>
the upper bound (exclusive)
Returns:
Number - the random number
Example
for (let i = 0; i < 100; i++) {
  let r = random(50);
  stroke(r * 5);
  line(50, i, 50 + r, i);
}

for (let i = 0; i < 100; i++) {
  let r = random(-50, 50);
  line(50, i, 50 + r, i);
}

// Get a random element from an array using the random(Array) syntax
let words = ['apple', 'bear', 'cat', 'dog'];
let word = random(words); // select random word
text(word, 10, 50); // draw the word

inner randomGaussian(mean, sd) → {Number}

Returns a random number fitting a Gaussian, or normal, distribution. There is theoretically no minimum or maximum value that randomGaussian() might return. Rather, there is just a very low probability that values far from the mean will be returned; and a higher probability that numbers near the mean will be returned.

Takes either 0, 1 or 2 arguments.
If no args, returns a mean of 0 and standard deviation of 1.
If one arg, that arg is the mean (standard deviation is 1).
If two args, first is mean, second is standard deviation.
Parameters:
Name Type Description
mean Number the mean
sd Number the standard deviation
Returns:
Number - the random number
Example
for (let y = 0; y < 100; y++) {
  let x = randomGaussian(50, 15);
  line(50, y, x, y);
}

let distribution = new Array(360);

function setup() {
  createCanvas(100, 100);
  for (let i = 0; i < distribution.length; i++) {
    distribution[i] = floor(randomGaussian(0, 15));
  }
}

function draw() {
  background(204);

  translate(width / 2, width / 2);

  for (let i = 0; i < distribution.length; i++) {
    rotate(TWO_PI / distribution.length);
    stroke(0);
    let dist = abs(distribution[i]);
    line(0, 0, dist, 0);
  }
}

inner randomSeed(seed)

Sets the seed value for random(). By default, random() produces different results each time the program is run. Set the seed parameter to a constant to return the same pseudo-random numbers each time the software is run.
Parameters:
Name Type Description
seed Number the seed value
Example
randomSeed(99);
for (let i = 0; i < 100; i++) {
  let r = random(0, 255);
  stroke(r);
  line(i, 0, i, 100);
}

inner redraw(nopt)

Executes the code within draw() one time. This functions allows the program to update the display window only when necessary, for example when an event registered by mousePressed() or keyPressed() occurs.

In structuring a program, it only makes sense to call redraw() within events such as mousePressed(). This is because redraw() does not run draw() immediately (it only sets a flag that indicates an update is needed).

The redraw() function does not work properly when called inside draw(). To enable/disable animations, use loop() and noLoop().

In addition you can set the number of redraws per method call. Just add an integer as single parameter for the number of redraws.
Parameters:
Name Type Attributes Description
n Integer <optional>
Redraw for n-times. The default value is 1.
Example
let x = 0;

function setup() {
  createCanvas(100, 100);
  noLoop();
}

function draw() {
  background(204);
  line(x, 0, x, height);
}

function mousePressed() {
  x += 1;
  redraw();
}

let x = 0;

function setup() {
  createCanvas(100, 100);
  noLoop();
}

function draw() {
  background(204);
  x += 1;
  line(x, 0, x, height);
}

function mousePressed() {
  redraw(5);
}

inner reverse(list) → {Array}

Reverses the order of an array, maps to Array.reverse()
Parameters:
Name Type Description
list Array Array to reverse
Returns:
Array - the reversed list
Example
function setup() {
  var myArray = ['A', 'B', 'C'];
  print(myArray); // ['A','B','C']

  reverse(myArray);
  print(myArray); // ['C','B','A']
}

inner round(n) → {Integer}

Calculates the integer closest to the n parameter. For example, round(133.8) returns the value 134. Maps to Math.round().
Parameters:
Name Type Description
n Number number to round
Returns:
Integer - rounded number
Example
function draw() {
  background(200);
  //map, mouseX between 0 and 5.
  let ax = map(mouseX, 0, 100, 0, 5);
  let ay = 66;

  // Round the mapped number.
  let bx = round(map(mouseX, 0, 100, 0, 5));
  let by = 33;

  // Multiply the mapped numbers by 20 to more easily
  // see the changes.
  stroke(0);
  fill(0);
  line(0, ay, ax * 20, ay);
  line(0, by, bx * 20, by);

  // Reformat the float returned by map and draw it.
  noStroke();
  text(nfc(ax, 2), ax, ay - 5);
  text(nfc(bx, 1), bx, by - 5);
}

inner second() → {Integer}

The second() function returns the current second as a value from 0 - 59.
Returns:
Integer - the current second
Example
var s = second();
text('Current second: \n' + s, 5, 50);

inner shorten(list) → {Array}

Decreases an array by one element and returns the shortened array, maps to Array.pop().
Parameters:
Name Type Description
list Array Array to shorten
Returns:
Array - shortened Array
Example
function setup() {
  var myArray = ['A', 'B', 'C'];
  print(myArray); // ['A', 'B', 'C']
  var newArray = shorten(myArray);
  print(myArray); // ['A','B','C']
  print(newArray); // ['A','B']
}

inner shuffle(array, boolopt) → {Array}

Randomizes the order of the elements of an array. Implements Fisher-Yates Shuffle Algorithm.
Parameters:
Name Type Attributes Description
array Array Array to shuffle
bool Boolean <optional>
modify passed array
Returns:
Array - shuffled Array
Example
function setup() {
  var regularArr = ['ABC', 'def', createVector(), TAU, Math.E];
  print(regularArr);
  shuffle(regularArr, true); // force modifications to passed array
  print(regularArr);

  // By default shuffle() returns a shuffled cloned array:
  var newArr = shuffle(regularArr);
  print(regularArr);
  print(newArr);
}

inner sin(angle) → {Number}

Calculates the sine of an angle. This function takes into account the current angleMode. Values are returned in the range -1 to 1.
Parameters:
Name Type Description
angle Number the angle
Returns:
Number - the sine of the angle
Example
let a = 0.0;
let inc = TWO_PI / 25.0;
for (let i = 0; i < 25; i++) {
  line(i * 4, 50, i * 4, 50 + sin(a) * 40.0);
  a = a + inc;
}

inner sort(list, countopt) → {Array}

Sorts an array of numbers from smallest to largest, or puts an array of words in alphabetical order. The original array is not modified; a re-ordered array is returned. The count parameter states the number of elements to sort. For example, if there are 12 elements in an array and count is set to 5, only the first 5 elements in the array will be sorted.
Parameters:
Name Type Attributes Description
list Array Array to sort
count Integer <optional>
number of elements to sort, starting from 0
Returns:
Array - the sorted list
Example
function setup() {
  var words = ['banana', 'apple', 'pear', 'lime'];
  print(words); // ['banana', 'apple', 'pear', 'lime']
  var count = 4; // length of array

  words = sort(words, count);
  print(words); // ['apple', 'banana', 'lime', 'pear']
}

function setup() {
  var numbers = [2, 6, 1, 5, 14, 9, 8, 12];
  print(numbers); // [2, 6, 1, 5, 14, 9, 8, 12]
  var count = 5; // Less than the length of the array

  numbers = sort(numbers, count);
  print(numbers); // [1,2,5,6,14,9,8,12]
}

inner splice(list, value, position) → {Array}

Inserts a value or an array of values into an existing array. The first parameter specifies the initial array to be modified, and the second parameter defines the data to be inserted. The third parameter is an index value which specifies the array position from which to insert data. (Remember that array index numbering starts at zero, so the first position is 0, the second position is 1, and so on.)
Parameters:
Name Type Description
list Array Array to splice into
value any value to be spliced in
position Integer in the array from which to insert data
Returns:
Array - the list
Example
function setup() {
  var myArray = [0, 1, 2, 3, 4];
  var insArray = ['A', 'B', 'C'];
  print(myArray); // [0, 1, 2, 3, 4]
  print(insArray); // ['A','B','C']

  splice(myArray, insArray, 3);
  print(myArray); // [0,1,2,'A','B','C',3,4]
}

inner split(value, delim) → {Array.<String>}

The split() function maps to String.split(), it breaks a String into pieces using a character or string as the delimiter. The delim parameter specifies the character or characters that mark the boundaries between each piece. A String[] array is returned that contains each of the pieces. The splitTokens() function works in a similar fashion, except that it splits using a range of characters instead of a specific character or sequence.
Parameters:
Name Type Description
value String the String to be split
delim String the String used to separate the data
Returns:
Array.<String> - Array of Strings
Example
var names = 'Pat,Xio,Alex';
var splitString = split(names, ',');
text(splitString[0], 5, 30);
text(splitString[1], 5, 50);
text(splitString[2], 5, 70);

inner splitTokens(value, delimopt) → {Array.<String>}

The splitTokens() function splits a String at one or many character delimiters or "tokens." The delim parameter specifies the character or characters to be used as a boundary.

If no delim characters are specified, any whitespace character is used to split. Whitespace characters include tab (\t), line feed (\n), carriage return (\r), form feed (\f), and space.
Parameters:
Name Type Attributes Description
value String the String to be split
delim String <optional>
list of individual Strings that will be used as separators
Returns:
Array.<String> - Array of Strings
Example
function setup() {
  var myStr = 'Mango, Banana, Lime';
  var myStrArr = splitTokens(myStr, ',');

  print(myStrArr); // prints : ["Mango"," Banana"," Lime"]
}

inner sq(n) → {Number}

Squares a number (multiplies a number by itself). The result is always a positive number, as multiplying two negative numbers always yields a positive result. For example, -1 * -1 = 1.
Parameters:
Name Type Description
n Number number to square
Returns:
Number - squared number
Example
function draw() {
  background(200);
  let eSize = 7;
  let x1 = map(mouseX, 0, width, 0, 10);
  let y1 = 80;
  let x2 = sq(x1);
  let y2 = 20;

  // Draw the non-squared.
  line(0, y1, width, y1);
  ellipse(x1, y1, eSize, eSize);

  // Draw the squared.
  line(0, y2, width, y2);
  ellipse(x2, y2, eSize, eSize);

  // Draw dividing line.
  stroke(100);
  line(0, height / 2, width, height / 2);

  // Draw text.
  let spacing = 15;
  noStroke();
  fill(0);
  text('x = ' + x1, 0, y1 + spacing);
  text('sq(x) = ' + x2, 0, y2 + spacing);
}

inner sqrt(n) → {Number}

Calculates the square root of a number. The square root of a number is always positive, even though there may be a valid negative root. The square root s of number a is such that s*s = a. It is the opposite of squaring. Maps to Math.sqrt().
Parameters:
Name Type Description
n Number non-negative number to square root
Returns:
Number - square root of number
Example
function draw() {
  background(200);
  let eSize = 7;
  let x1 = mouseX;
  let y1 = 80;
  let x2 = sqrt(x1);
  let y2 = 20;

  // Draw the non-squared.
  line(0, y1, width, y1);
  ellipse(x1, y1, eSize, eSize);

  // Draw the squared.
  line(0, y2, width, y2);
  ellipse(x2, y2, eSize, eSize);

  // Draw dividing line.
  stroke(100);
  line(0, height / 2, width, height / 2);

  // Draw text.
  noStroke();
  fill(0);
  let spacing = 15;
  text('x = ' + x1, 0, y1 + spacing);
  text('sqrt(x) = ' + x2, 0, y2 + spacing);
}

inner str(n) → {String}

Converts a boolean, string or number to its string representation. When an array of values is passed in, then an array of strings of the same length is returned.
Parameters:
Name Type Description
n String | Boolean | Number | Array value to parse
Returns:
String - string representation of value
Example
print(str('10')); // "10"
print(str(10.31)); // "10.31"
print(str(-10)); // "-10"
print(str(true)); // "true"
print(str(false)); // "false"
print(str([true, '10.3', 9.8])); // [ "true", "10.3", "9.8" ]

inner subset(list, start, countopt) → {Array}

Extracts an array of elements from an existing array. The list parameter defines the array from which the elements will be copied, and the start and count parameters specify which elements to extract. If no count is given, elements will be extracted from the start to the end of the array. When specifying the start, remember that the first array element is 0. This function does not change the source array.
Parameters:
Name Type Attributes Description
list Array Array to extract from
start Integer position to begin
count Integer <optional>
number of values to extract
Returns:
Array - Array of extracted elements
Example
function setup() {
  var myArray = [1, 2, 3, 4, 5];
  print(myArray); // [1, 2, 3, 4, 5]

  var sub1 = subset(myArray, 0, 3);
  var sub2 = subset(myArray, 2, 2);
  print(sub1); // [1,2,3]
  print(sub2); // [3,4]
}

inner tan(angle) → {Number}

Calculates the tangent of an angle. This function takes into account the current angleMode. Values are returned in the range -1 to 1.
Parameters:
Name Type Description
angle Number the angle
Returns:
Number - the tangent of the angle
Example
let a = 0.0;
let inc = TWO_PI / 50.0;
for (let i = 0; i < 100; i = i + 2) {
  line(i, 50, i, 50 + tan(a) * 2.0);
  a = a + inc;
}

inner text(str, x, y)

Draws text to the screen. Displays the information specified in the first parameter on the screen in the position specified by the additional parameters. A default font will be used unless a font is set with the textFont() function and a default size will be used unless a font is set with textSize(). Change the color of the text with the fill() function. Change the outline of the text with the stroke() and strokeWeight() functions.

The text displays in relation to the textAlign() function, which gives the option to draw to the left, right, and center of the coordinates.

The x2 and y2 parameters define a rectangular area to display within and may only be used with string data. When these parameters are specified, they are interpreted based on the current rectMode() setting. Text that does not fit completely within the rectangle specified will not be drawn to the screen. If x2 and y2 are not specified, the baseline alignment is the default, which means that the text will be drawn upwards from x and y.

WEBGL: Only opentype/truetype fonts are supported. You must load a font using the loadFont() method (see the example above). stroke() currently has no effect in webgl mode.
Parameters:
Name Type Description
str String | Object | Array | Number | Boolean the alphanumeric symbols to be displayed
x Number x-coordinate of text
y Number y-coordinate of text
Example
text('word', 10, 30);
fill(0, 102, 153);
text('word', 10, 60);
fill(0, 102, 153, 51);
text('word', 10, 90);

let s = 'The quick brown fox jumped over the lazy dog.';
fill(50);
text(s, 10, 10, 70, 80); // Text wraps within text box

avenir;
function setup() {
  avenir = loadFont('assets/Avenir.otf');
  textFont(avenir);
  textSize(width / 3);
  textAlign(CENTER, CENTER);
}
function draw() {
  background(0);
  text('p5.js', 0, 0);
}

inner textAlign(horizAlign, vertAlignopt)

Sets the current alignment for drawing text. Accepts two arguments: horizAlign (LEFT, CENTER, or RIGHT) and vertAlign (TOP, BOTTOM, CENTER, or BASELINE). The horizAlign parameter is in reference to the x value of the text() function, while the vertAlign parameter is in reference to the y value. So if you write textAlign(LEFT), you are aligning the left edge of your text to the x value you give in text(). If you write textAlign(RIGHT, TOP), you are aligning the right edge of your text to the x value and the top of edge of the text to the y value.
Parameters:
Name Type Attributes Description
horizAlign Constant horizontal alignment, either LEFT, CENTER, or RIGHT
vertAlign Constant <optional>
vertical alignment, either TOP, BOTTOM, CENTER, or BASELINE
Example
textSize(16);
textAlign(RIGHT);
text('ABCD', 50, 30);
textAlign(CENTER);
text('EFGH', 50, 50);
textAlign(LEFT);
text('IJKL', 50, 70);

textSize(16);
strokeWeight(0.5);

line(0, 12, width, 12);
textAlign(CENTER, TOP);
text('TOP', 0, 12, width);

line(0, 37, width, 37);
textAlign(CENTER, CENTER);
text('CENTER', 0, 37, width);

line(0, 62, width, 62);
textAlign(CENTER, BASELINE);
text('BASELINE', 0, 62, width);

line(0, 87, width, 87);
textAlign(CENTER, BOTTOM);
text('BOTTOM', 0, 87, width);

inner textFont() → {Object}

Sets the current font that will be drawn with the text() function.

WEBGL: Only fonts loaded via loadFont() are supported.
Returns:
Object - the current font
Example
fill(0);
textSize(12);
textFont('Georgia');
text('Georgia', 12, 30);
textFont('Helvetica');
text('Helvetica', 12, 60);

let fontRegular, fontItalic, fontBold;
function setup() {
  fontRegular = loadFont('assets/Regular.otf');
  fontItalic = loadFont('assets/Italic.ttf');
  fontBold = loadFont('assets/Bold.ttf');
  background(210);
  fill(0);
  textFont(fontRegular);
  text('Font Style Normal', 10, 30);
  textFont(fontItalic);
  text('Font Style Italic', 10, 50);
  textFont(fontBold);
  text('Font Style Bold', 10, 70);
}

inner textSize() → {Number}

Gets the current font size.
Returns:
Number

inner textWidth(theText) → {Number}

Calculates and returns the width of any character or text string.
Parameters:
Name Type Description
theText String the String of characters to measure
Returns:
Number
Example
textSize(28);

let aChar = 'P';
let cWidth = textWidth(aChar);
text(aChar, 0, 40);
line(cWidth, 0, cWidth, 50);

let aString = 'p5.js';
let sWidth = textWidth(aString);
text(aString, 0, 85);
line(sWidth, 50, sWidth, 100);

inner trim(str) → {String}

Removes whitespace characters from the beginning and end of a String. In addition to standard whitespace characters such as space, carriage return, and tab, this function also removes the Unicode "nbsp" character.
Parameters:
Name Type Description
str String a String to be trimmed
Returns:
String - a trimmed String
Example
var string = trim('  No new lines\n   ');
text(string + ' here', 2, 50);

inner unchar(n) → {Number}

Converts a single-character string to its corresponding integer representation. When an array of single-character string values is passed in, then an array of integers of the same length is returned.
Parameters:
Name Type Description
n String value to parse
Returns:
Number - integer representation of value
Example
print(unchar('A')); // 65
print(unchar(['A', 'B', 'C'])); // [ 65, 66, 67 ]
print(unchar(split('ABC', ''))); // [ 65, 66, 67 ]

inner unhex(n) → {Number}

Converts a string representation of a hexadecimal number to its equivalent integer value. When an array of strings in hexadecimal notation is passed in, an array of integers of the same length is returned.
Parameters:
Name Type Description
n String value to parse
Returns:
Number - integer representation of hexadecimal value
Example
print(unhex('A')); // 10
print(unhex('FF')); // 255
print(unhex(['FF', 'AA', '00'])); // [ 255, 170, 0 ]

inner year() → {Integer}

The year() returns the current year as an integer (2014, 2015, 2016, etc).
Returns:
Integer - the current year
Example
var y = year();
text('Current year: \n' + y, 5, 50);