Classes
Members
# static ColorConversion
Conversions adapted from http://www.easyrgb.com/en/math.php.
In these functions, hue is always in the range [0, 1], just like all other components are in the range [0, 1]. 'Brightness' and 'value' are used interchangeably.
# static readonly displayHeight
System variable that stores the height of the screen display according to The default pixelDensity. This is used to run a full-screen program on any display size. To return actual screen size, multiply this by pixelDensity.
Properties:
Name | Type | Description |
---|---|---|
displayHeight |
Number |
Example
createCanvas(displayWidth, displayHeight);
# static readonly displayWidth
System variable that stores the width of the screen display according to The default pixelDensity. This is used to run a full-screen program on any display size. To return actual screen size, multiply this by pixelDensity.
Properties:
Name | Type | Description |
---|---|---|
displayWidth |
Number |
Example
createCanvas(displayWidth, displayHeight);
# static readonly focused
Confirms if the window a p5.js program is in is "focused," meaning that the sketch will accept mouse or keyboard input. This variable is "true" if the window is focused and "false" if not.
Properties:
Name | Type | Description |
---|---|---|
focused |
Boolean |
Example
// To demonstrate, put two windows side by side.
// Click on the window that the p5 sketch isn't in!
function draw() {
background(200);
noStroke();
fill(0, 200, 0);
ellipse(25, 25, 50, 50);
if (!focused) {
// or "if (focused === false)"
stroke(200, 0, 0);
line(0, 0, 100, 100);
line(100, 0, 0, 100);
}
}
# static readonly frameCount
The system variable frameCount contains the number of frames that have been displayed since the program started. Inside setup() the value is 0, after the first iteration of draw it is 1, etc.
Properties:
Name | Type | Description |
---|---|---|
frameCount |
Integer |
Example
function setup() {
frameRate(30);
textSize(30);
textAlign(CENTER);
}
function draw() {
background(200);
text(frameCount, width / 2, height / 2);
}
# static readonly height
System variable that stores the height of the drawing canvas.
Properties:
Name | Type | Description |
---|---|---|
height |
Number |
# static readonly key
The system variable key always contains the value of the most recent key on the keyboard that was typed.
Properties:
Name | Type | Description |
---|---|---|
key |
String |
Example
// Click any key to display it!
// (Not Guaranteed to be Case Sensitive)
function setup() {
fill(245, 123, 158);
textSize(50);
}
function draw() {
background(200);
text(key, 33, 65); // Display last key pressed.
}
# static readonly keyCode
The variable keyCode is used to detect special keys such as BACKSPACE, DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL, OPTION, ALT, UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.
Properties:
Name | Type | Description |
---|---|---|
keyCode |
Integer |
Example
let fillVal = 126;
function draw() {
fill(fillVal);
rect(25, 25, 50, 50);
}
function keyPressed() {
if (keyCode === UP_ARROW) {
fillVal = 255;
} else if (keyCode === DOWN_ARROW) {
fillVal = 0;
}
return false; // prevent default
}
# static readonly keyIsPressed
The boolean system variable keyIsPressed is true if any key is pressed and false if no keys are pressed.
Properties:
Name | Type | Description |
---|---|---|
keyIsPressed |
Boolean |
Example
function draw() {
if (keyIsPressed === true) {
fill(0);
} else {
fill(255);
}
rect(25, 25, 50, 50);
}
# static readonly mouseButton
Processing automatically tracks if the mouse button is pressed and which button is pressed. The value of the system variable mouseButton is either LEFT, RIGHT, or CENTER depending on which button was pressed last. Warning: different browsers may track mouseButton differently.
Properties:
Name | Type | Description |
---|---|---|
mouseButton |
Constant |
Example
function draw() {
background(237, 34, 93);
fill(0);
if (mouseIsPressed) {
if (mouseButton === LEFT) {
ellipse(50, 50, 50, 50);
}
if (mouseButton === RIGHT) {
rect(25, 25, 50, 50);
}
if (mouseButton === CENTER) {
triangle(23, 75, 50, 20, 78, 75);
}
}
print(mouseButton);
}
# static readonly mouseIsPressed
The boolean system variable mouseIsPressed is true if the mouse is pressed and false if not.
Properties:
Name | Type | Description |
---|---|---|
mouseIsPressed |
Boolean |
Example
function draw() {
background(237, 34, 93);
fill(0);
if (mouseIsPressed) {
ellipse(50, 50, 50, 50);
} else {
rect(25, 25, 50, 50);
}
print(mouseIsPressed);
}
# static readonly mouseX
The system variable mouseX always contains the current horizontal position of the mouse, relative to (0, 0) of the canvas. If touch is used instead of mouse input, mouseX will hold the x value of the most recent touch point.
Properties:
Name | Type | Description |
---|---|---|
mouseX |
Number |
Example
// Move the mouse across the canvas
function draw() {
background(244, 248, 252);
line(mouseX, 0, mouseX, 100);
}
# static readonly mouseY
The system variable mouseY always contains the current vertical position of the mouse, relative to (0, 0) of the canvas. If touch is used instead of mouse input, mouseY will hold the y value of the most recent touch point.
Properties:
Name | Type | Description |
---|---|---|
mouseY |
Number |
Example
// Move the mouse across the canvas
function draw() {
background(244, 248, 252);
line(0, mouseY, 100, mouseY);
}
# static readonly pmouseX
The system variable pmouseX always contains the horizontal position of the mouse or finger in the frame previous to the current frame, relative to (0, 0) of the canvas. Note: pmouseX will be reset to the current mouseX value at the start of each touch event.
Properties:
Name | Type | Description |
---|---|---|
pmouseX |
Number |
Example
// Move the mouse across the canvas to leave a trail
function setup() {
//slow down the frameRate to make it more visible
frameRate(10);
}
function draw() {
background(244, 248, 252);
line(mouseX, mouseY, pmouseX, pmouseY);
print(pmouseX + ' -> ' + mouseX);
}
# static readonly pmouseY
The system variable pmouseY always contains the vertical position of the mouse or finger in the frame previous to the current frame, relative to (0, 0) of the canvas. Note: pmouseY will be reset to the current mouseY value at the start of each touch event.
Properties:
Name | Type | Description |
---|---|---|
pmouseY |
Number |
Example
function draw() {
background(237, 34, 93);
fill(0);
//draw a square only if the mouse is not moving
if (mouseY === pmouseY && mouseX === pmouseX) {
rect(20, 20, 60, 60);
}
print(pmouseY + ' -> ' + mouseY);
}
# static readonly pwinMouseX
The system variable pwinMouseX always contains the horizontal position of the mouse in the frame previous to the current frame, relative to (0, 0) of the window. Note: pwinMouseX will be reset to the current winMouseX value at the start of each touch event.
Properties:
Name | Type | Description |
---|---|---|
pwinMouseX |
Number |
Example
let myCanvas;
function setup() {
//use a variable to store a pointer to the canvas
myCanvas = createCanvas(100, 100);
noStroke();
fill(237, 34, 93);
}
function draw() {
clear();
//the difference between previous and
//current x position is the horizontal mouse speed
let speed = abs(winMouseX - pwinMouseX);
//change the size of the circle
//according to the horizontal speed
ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);
//move the canvas to the mouse position
myCanvas.position(winMouseX + 1, winMouseY + 1);
}
# static readonly pwinMouseY
The system variable pwinMouseY always contains the vertical position of the mouse in the frame previous to the current frame, relative to (0, 0) of the window. Note: pwinMouseY will be reset to the current winMouseY value at the start of each touch event.
Properties:
Name | Type | Description |
---|---|---|
pwinMouseY |
Number |
Example
let myCanvas;
function setup() {
//use a variable to store a pointer to the canvas
myCanvas = createCanvas(100, 100);
noStroke();
fill(237, 34, 93);
}
function draw() {
clear();
//the difference between previous and
//current y position is the vertical mouse speed
let speed = abs(winMouseY - pwinMouseY);
//change the size of the circle
//according to the vertical speed
ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);
//move the canvas to the mouse position
myCanvas.position(winMouseX + 1, winMouseY + 1);
}
# static readonly width
System variable that stores the width of the drawing canvas.
Properties:
Name | Type | Description |
---|---|---|
width |
Number |
# static readonly windowHeight
System variable that stores the height of the inner window.
Properties:
Name | Type | Description |
---|---|---|
windowHeight |
Number |
Example
createCanvas(windowWidth, windowHeight);
# static readonly windowWidth
System variable that stores the width of the inner window.
Properties:
Name | Type | Description |
---|---|---|
windowWidth |
Number |
Example
createCanvas(windowWidth, windowHeight);
# static readonly winMouseX
The system variable winMouseX always contains the current horizontal position of the mouse, relative to (0, 0) of the window.
Properties:
Name | Type | Description |
---|---|---|
winMouseX |
Number |
Example
let myCanvas;
function setup() {
//use a variable to store a pointer to the canvas
myCanvas = createCanvas(100, 100);
const body = document.getElementsByTagName('body')[0];
myCanvas.parent(body);
}
function draw() {
background(237, 34, 93);
fill(0);
//move the canvas to the horizontal mouse position
//relative to the window
myCanvas.position(winMouseX + 1, windowHeight / 2);
//the y of the square is relative to the canvas
rect(20, mouseY, 60, 60);
}
# static readonly winMouseY
The system variable winMouseY always contains the current vertical position of the mouse, relative to (0, 0) of the window.
Properties:
Name | Type | Description |
---|---|---|
winMouseY |
Number |
Example
let myCanvas;
function setup() {
//use a variable to store a pointer to the canvas
myCanvas = createCanvas(100, 100);
const body = document.getElementsByTagName('body')[0];
myCanvas.parent(body);
}
function draw() {
background(237, 34, 93);
fill(0);
//move the canvas to the vertical mouse position
//relative to the window
myCanvas.position(windowWidth / 2, winMouseY + 1);
//the x of the square is relative to the canvas
rect(mouseX, 20, 60, 60);
}
# inner WHITESPACE
These regular expressions are used to build up the patterns for matching viable CSS color strings: fragmenting the regexes in this way increases the legibility and comprehensibility of the code.
Note that RGB values of .9 are not parsed by IE, but are supported here for color string consistency.
Methods
# static _transX(x, y) → {number}
translate a point with the current matrix (if any).
Parameters:
Name | Type | Description |
---|---|---|
x |
number | point |
y |
number | point |
the translated x coordinate.
# static _transY(x, y) → {number}
translate a point with the current matrix (if any).
Parameters:
Name | Type | Description |
---|---|---|
x |
number | point |
y |
number | point |
the translated y coordinate.
# 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 |
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 |
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 alpha(color) → {Number}
Extracts the alpha value from a color or pixel array.
Parameters:
Name | Type | Description |
---|---|---|
color |
Color | Array.<Number> | String | Color object, color components, or CSS color |
the alpha value
Example
noStroke();
let c = color(0, 126, 255, 102);
fill(c);
rect(15, 15, 35, 70);
let value = alpha(c); // Sets 'value' to 102
fill(value);
rect(50, 15, 35, 70);
# 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 |
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 applyMatrix(a, b, c, d, e, f)
Multiplies the current matrix by the one specified through the parameters. This is a powerful operation that can perform the equivalent of translate, scale, shear and rotate all at once. You can learn more about transformation matrices on Wikipedia.
The naming of the arguments here follows the naming of the WHATWG specification and corresponds to a transformation matrix of the form:
Parameters:
Name | Type | Description |
---|---|---|
a |
Number | numbers which define the 2x3 matrix to be multiplied |
b |
Number | numbers which define the 2x3 matrix to be multiplied |
c |
Number | numbers which define the 2x3 matrix to be multiplied |
d |
Number | numbers which define the 2x3 matrix to be multiplied |
e |
Number | numbers which define the 2x3 matrix to be multiplied |
f |
Number | numbers which define the 2x3 matrix to be multiplied |
Example
function setup() {
frameRate(10);
rectMode(CENTER);
}
function draw() {
var step = frameCount % 20;
background(200);
// Equivalent to translate(x, y);
applyMatrix(1, 0, 0, 1, 40 + step, 50);
rect(0, 0, 50, 50);
}
function setup() {
frameRate(10);
rectMode(CENTER);
}
function draw() {
var step = frameCount % 20;
background(200);
translate(50, 50);
// Equivalent to scale(x, y);
applyMatrix(1 / step, 0, 0, 1 / step, 0, 0);
rect(0, 0, 50, 50);
}
function setup() {
frameRate(10);
rectMode(CENTER);
}
function draw() {
var step = frameCount % 20;
var angle = map(step, 0, 20, 0, TWO_PI);
var cos_a = cos(angle);
var sin_a = sin(angle);
background(200);
translate(50, 50);
// Equivalent to rotate(angle);
applyMatrix(cos_a, sin_a, -sin_a, cos_a, 0, 0);
rect(0, 0, 50, 50);
}
function setup() {
frameRate(10);
rectMode(CENTER);
}
function draw() {
var step = frameCount % 20;
var angle = map(step, 0, 20, -PI / 4, PI / 4);
background(200);
translate(50, 50);
// equivalent to shearX(angle);
var shear_factor = 1 / tan(PI / 2 - angle);
applyMatrix(1, 0, shear_factor, 1, 0, 0);
rect(0, 0, 50, 50);
}
# inner arc(x, y, w, h, start, stop, modeopt)
Draw an arc to the screen. If called with only x, y, w, h, start, and
stop, the arc will be drawn and filled as an open pie segment. If a mode parameter is provided, the arc
will be filled like an open semi-circle (OPEN) , a closed semi-circle (CHORD), or as a closed pie segment (PIE). The
origin may be changed with the ellipseMode() function.
The arc is always drawn clockwise from wherever start falls to wherever stop falls on the ellipse.
Adding or subtracting TWO_PI to either angle does not change where they fall.
If both start and stop fall at the same place, a full ellipse will be drawn.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
x |
Number | x-coordinate of the arc's ellipse |
|
y |
Number | y-coordinate of the arc's ellipse |
|
w |
Number | width of the arc's ellipse by default |
|
h |
Number | height of the arc's ellipse by default |
|
start |
Number | angle to start the arc, specified in radians |
|
stop |
Number | angle to stop the arc, specified in radians |
|
mode |
Constant |
<optional> |
optional parameter to determine the way of drawing the arc. either CHORD, PIE or OPEN |
Example
arc(50, 55, 50, 50, 0, HALF_PI);
noFill();
arc(50, 55, 60, 60, HALF_PI, PI);
arc(50, 55, 70, 70, PI, PI + QUARTER_PI);
arc(50, 55, 80, 80, PI + QUARTER_PI, TWO_PI);
arc(50, 50, 80, 80, 0, PI + QUARTER_PI);
arc(50, 50, 80, 80, 0, PI + QUARTER_PI, OPEN);
arc(50, 50, 80, 80, 0, PI + QUARTER_PI, CHORD);
arc(50, 50, 80, 80, 0, PI + QUARTER_PI, PIE);
# 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 |
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 |
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 |
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 background(values)
Parameters:
Name | Type | Description |
---|---|---|
values |
Array.<Number> | an array containing the red,green,blue & and alpha components of the color |
# inner background(colorstring, aopt)
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
colorstring |
String | color string, possible formats include: integer rgb() or rgba(), percentage rgb() or rgba(), 3-digit hex, 6-digit hex |
|
a |
Number |
<optional> |
opacity of the background relative to current color range (default is 0-255) |
# inner background(gray, aopt)
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
gray |
Number | specifies a value between white and black |
|
a |
Number |
<optional> |
# inner background(bitmap, aopt)
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
bitmap |
Bitmap | image created with loadImage() or createImage(), to set as background (must be same size as the sketch window) |
|
a |
Number |
<optional> |
# inner background(color)
The background() function sets the color used for the background of the
p5.js canvas. The default background is transparent. This function is
typically used within draw() to clear the display window at the beginning
of each frame, but it can be used inside setup() to set the background on
the first frame of animation or if the background need only be set once.
The color is either specified in terms of the RGB, HSB, or HSL color
depending on the current colorMode. (The default color space is RGB, with
each value in the range from 0 to 255). The alpha range by default is also 0 to 255.
If a single string argument is provided, RGB, RGBA and Hex CSS color strings
and all named color strings are supported. In this case, an alpha number
value as a second argument is not supported, the RGBA form should be used.
A Color object can also be provided to set the background color.
An Image can also be provided to set the background image.
Parameters:
Name | Type | Description |
---|---|---|
color |
Color | any value created by the color() function |
Example
// Grayscale integer value
background(51);
// R, G & B integer values
background(255, 204, 0);
// H, S & B integer values
colorMode(HSB);
background(255, 204, 100);
// Named SVG/CSS color string
background('red');
// three-digit hexadecimal RGB notation
background('#fae');
// six-digit hexadecimal RGB notation
background('#222222');
// integer RGB notation
background('rgb(0,255,0)');
// integer RGBA notation
background('rgba(0,255,0, 0.25)');
// percentage RGB notation
background('rgb(100%,0%,10%)');
// percentage RGBA notation
background('rgba(100%,0%,100%,0.5)');
// p5 Color object
background(color(0, 0, 255));
# inner background(v1, v2, v3, aopt)
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
v1 |
Number | red or hue value (depending on the current color mode) |
|
v2 |
Number | green or saturation value (depending on the current color mode) |
|
v3 |
Number | blue or brightness value (depending on the current color mode) |
|
a |
Number |
<optional> |
# inner beginShape(kindopt)
Using the beginShape() and endShape() functions allow creating more
complex forms. beginShape() begins recording vertices for a shape and
endShape() stops recording. The value of the kind parameter tells it which
types of shapes to create from the provided vertices. With no mode
specified, the shape can be any irregular polygon.
The parameters available for beginShape() are POINTS, LINES, TRIANGLES,
TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP. After calling the
beginShape() function, a series of vertex() commands must follow. To stop
drawing the shape, call endShape(). Each shape will be outlined with the
current stroke color and filled with the fill color.
Transformations such as translate(), rotate(), and scale() do not work
within beginShape(). It is also not possible to use other shapes, such as
ellipse() or rect() within beginShape().
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
kind |
Constant |
<optional> |
either POINTS, LINES, TRIANGLES, TRIANGLE_FAN TRIANGLE_STRIP, QUADS, or QUAD_STRIP |
Example
beginShape();
vertex(30, 20);
vertex(85, 20);
vertex(85, 75);
vertex(30, 75);
endShape(CLOSE);
beginShape(POINTS);
vertex(30, 20);
vertex(85, 20);
vertex(85, 75);
vertex(30, 75);
endShape();
beginShape(LINES);
vertex(30, 20);
vertex(85, 20);
vertex(85, 75);
vertex(30, 75);
endShape();
noFill();
beginShape();
vertex(30, 20);
vertex(85, 20);
vertex(85, 75);
vertex(30, 75);
endShape();
noFill();
beginShape();
vertex(30, 20);
vertex(85, 20);
vertex(85, 75);
vertex(30, 75);
endShape(CLOSE);
beginShape(TRIANGLES);
vertex(30, 75);
vertex(40, 20);
vertex(50, 75);
vertex(60, 20);
vertex(70, 75);
vertex(80, 20);
endShape();
beginShape();
vertex(20, 20);
vertex(40, 20);
vertex(40, 40);
vertex(60, 40);
vertex(60, 60);
vertex(20, 60);
endShape(CLOSE);
# inner blue(color) → {Number}
Extracts the blue value from a color or pixel array.
Parameters:
Name | Type | Description |
---|---|---|
color |
Color | Array.<Number> | String | Color object, color components, or CSS color |
the blue value
Example
let c = color(175, 100, 220); // Define color 'c'
fill(c); // Use color variable 'c' as fill color
rect(15, 20, 35, 60); // Draw left rectangle
let blueValue = blue(c); // Get blue in 'c'
print(blueValue); // Prints "220.0"
fill(0, 0, blueValue); // Use 'blueValue' in new fill
rect(50, 20, 35, 60); // Draw right rectangle
# 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 |
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 brightness(color) → {Number}
Extracts the HSB brightness value from a color or pixel array.
Parameters:
Name | Type | Description |
---|---|---|
color |
Color | Array.<Number> | String | Color object, color components, or CSS color |
the brightness value
Example
noStroke();
colorMode(HSB, 255);
let c = color(0, 126, 255);
fill(c);
rect(15, 20, 35, 60);
let value = brightness(c); // Sets 'value' to 255
fill(value);
rect(50, 20, 35, 60);
# 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 |
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 |
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 |
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 circle(x, y, d)
Draws a circle to the screen. A circle is a simple closed shape. It is the set of all points in a plane that are at a given distance from a given point, the centre. This function is a special case of the ellipse() function, where the width and height of the ellipse are the same. Height and width of the ellipse correspond to the diameter of the circle. By default, the first two parameters set the location of the centre of the circle, the third sets the diameter of the circle.
Parameters:
Name | Type | Description |
---|---|---|
x |
Number | x-coordinate of the centre of the circle. |
y |
Number | y-coordinate of the centre of the circle. |
d |
Number | diameter of the circle. |
Example
// Draw a circle at location (30, 30) with a diameter of 20.
circle(30, 30, 20);
# inner clear()
Clears the pixels within a buffer. This function only clears the canvas. It will not clear objects created by createX() methods such as createVideo() or createDiv(). Unlike the main graphics context, pixels in additional graphics areas created with createGraphics() can be entirely or partially transparent. This function clears everything to make all of the pixels 100% transparent.
Example
// Clear the screen on mouse press.
function setup() {
createCanvas(100, 100);
}
function draw() {
ellipse(mouseX, mouseY, 20, 20);
}
function mousePressed() {
clear();
}
# inner color(gray, alphaopt) → {Color}
Creates colors for storing in variables of the color datatype. The
parameters are interpreted as RGB or HSB values depending on the
current colorMode(). The default mode is RGB values from 0 to 255
and, therefore, the function call color(255, 204, 0) will return a
bright yellow color.
Note that if only one value is provided to color(), it will be interpreted
as a grayscale value. Add a second value, and it will be used for alpha
transparency. When three values are specified, they are interpreted as
either RGB or HSB values. Adding a fourth value applies alpha
transparency.
If a single string argument is provided, RGB, RGBA and Hex CSS color
strings and all named color strings are supported. In this case, an alpha
number value as a second argument is not supported, the RGBA form should be
used.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
gray |
Number | number specifying value between white and black. |
|
alpha |
Number |
<optional> |
alpha value relative to current color range (default is 0-255) |
resulting color
Example
let c = color(255, 204, 0); // Define color 'c'
fill(c); // Use color variable 'c' as fill color
noStroke(); // Don't draw a stroke around shapes
rect(30, 20, 55, 55); // Draw rectangle
let c = color(255, 204, 0); // Define color 'c'
fill(c); // Use color variable 'c' as fill color
noStroke(); // Don't draw a stroke around shapes
ellipse(25, 25, 80, 80); // Draw left circle
// Using only one value with color()
// generates a grayscale value.
c = color(65); // Update 'c' with grayscale value
fill(c); // Use updated 'c' as fill color
ellipse(75, 75, 80, 80); // Draw right circle
// Named SVG & CSS colors may be used,
let c = color('magenta');
fill(c); // Use 'c' as fill color
noStroke(); // Don't draw a stroke around shapes
rect(20, 20, 60, 60); // Draw rectangle
// as can hex color codes:
noStroke(); // Don't draw a stroke around shapes
let c = color('#0f0');
fill(c); // Use 'c' as fill color
rect(0, 10, 45, 80); // Draw rectangle
c = color('#00ff00');
fill(c); // Use updated 'c' as fill color
rect(55, 10, 45, 80); // Draw rectangle
// RGB and RGBA color strings are also supported:
// these all set to the same color (solid blue)
let c;
noStroke(); // Don't draw a stroke around shapes
c = color('rgb(0,0,255)');
fill(c); // Use 'c' as fill color
rect(10, 10, 35, 35); // Draw rectangle
c = color('rgb(0%, 0%, 100%)');
fill(c); // Use updated 'c' as fill color
rect(55, 10, 35, 35); // Draw rectangle
c = color('rgba(0, 0, 255, 1)');
fill(c); // Use updated 'c' as fill color
rect(10, 55, 35, 35); // Draw rectangle
c = color('rgba(0%, 0%, 100%, 1)');
fill(c); // Use updated 'c' as fill color
rect(55, 55, 35, 35); // Draw rectangle
// HSL color is also supported and can be specified
// by value
let c;
noStroke(); // Don't draw a stroke around shapes
c = color('hsl(160, 100%, 50%)');
fill(c); // Use 'c' as fill color
rect(0, 10, 45, 80); // Draw rectangle
c = color('hsla(160, 100%, 50%, 0.5)');
fill(c); // Use updated 'c' as fill color
rect(55, 10, 45, 80); // Draw rectangle
// HSB color is also supported and can be specified
// by value
let c;
noStroke(); // Don't draw a stroke around shapes
c = color('hsb(160, 100%, 50%)');
fill(c); // Use 'c' as fill color
rect(0, 10, 45, 80); // Draw rectangle
c = color('hsba(160, 100%, 50%, 0.5)');
fill(c); // Use updated 'c' as fill color
rect(55, 10, 45, 80); // Draw rectangle
let c; // Declare color 'c'
noStroke(); // Don't draw a stroke around shapes
// If no colorMode is specified, then the
// default of RGB with scale of 0-255 is used.
c = color(50, 55, 100); // Create a color for 'c'
fill(c); // Use color variable 'c' as fill color
rect(0, 10, 45, 80); // Draw left rect
colorMode(HSB, 100); // Use HSB with scale of 0-100
c = color(50, 55, 100); // Update 'c' with new color
fill(c); // Use updated 'c' as fill color
rect(55, 10, 45, 80); // Draw right rect
# inner color(v1, v2, v3, alphaopt) → {Color}
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
v1 |
Number | red or hue value relative to the current color range |
|
v2 |
Number | green or saturation value relative to the current color range |
|
v3 |
Number | blue or brightness value relative to the current color range |
|
alpha |
Number |
<optional> |
# inner color(values) → {Color}
Parameters:
Name | Type | Description |
---|---|---|
values |
Array.<Number> | an array containing the red,green,blue & and alpha components of the color |
# inner colorMode(mode, max1, max2, max3, maxAopt)
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
mode |
Constant | ||
max1 |
Number | range for the red or hue depending on the current color mode |
|
max2 |
Number | range for the green or saturation depending on the current color mode |
|
max3 |
Number | range for the blue or brightness/lightness depending on the current color mode |
|
maxA |
Number |
<optional> |
range for the alpha |
# inner colorMode(mode, maxopt)
colorMode() changes the way p5.js interprets color data. By default, the
parameters for fill(), stroke(), background(), and color() are defined by
values between 0 and 255 using the RGB color model. This is equivalent to
setting colorMode(RGB, 255). Setting colorMode(HSB) lets you use the HSB
system instead. By default, this is colorMode(HSB, 360, 100, 100, 1). You
can also use HSL.
Note: existing color objects remember the mode that they were created in,
so you can change modes as you like without affecting their appearance.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
mode |
Constant | either RGB, HSB or HSL, corresponding to Red/Green/Blue and Hue/Saturation/Brightness (or Lightness) |
|
max |
Number |
<optional> |
range for all values |
Example
noStroke();
colorMode(RGB, 100);
for (let i = 0; i < 100; i++) {
for (let j = 0; j < 100; j++) {
stroke(i, j, 0);
point(i, j);
}
}
noStroke();
colorMode(HSB, 100);
for (let i = 0; i < 100; i++) {
for (let j = 0; j < 100; j++) {
stroke(i, j, 100);
point(i, j);
}
}
colorMode(RGB, 255);
let c = color(127, 255, 0);
colorMode(RGB, 1);
let myColor = c._getRed();
text(myColor, 10, 10, 80, 80);
noFill();
colorMode(RGB, 255, 255, 255, 1);
background(255);
strokeWeight(4);
stroke(255, 0, 10, 0.3);
ellipse(40, 40, 50, 50);
ellipse(50, 50, 40, 40);
# 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 |
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 |
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 |
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 createImage(width, height) → {Bitmap}
Creates a new p5.Image (the datatype for storing images). This provides a
fresh buffer of pixels to play with. Set the size of the buffer with the
width and height parameters.
.pixels gives access to an array containing the values for all the pixels
in the display window.
These values are numbers. This array is the size (including an appropriate
factor for the pixelDensity) of the display window x4,
representing the R, G, B, A values in order for each pixel, moving from
left to right across each row, then down each column. See .pixels for
more info. It may also be simpler to use set() or get().
Before accessing the pixels of an image, the data must loaded with the
loadPixels() function. After the array data has been modified, the
updatePixels() function must be run to update the changes.
Parameters:
Name | Type | Description |
---|---|---|
width |
Number | width in pixels |
height |
Number | height in pixels |
the Image object
Example
let img = createImage(66, 66);
img.loadPixels();
for (let i = 0; i < img.width; i++) {
for (let j = 0; j < img.height; j++) {
img.set(i, j, color(0, 90, 102));
}
}
img.updatePixels();
image(img, 17, 17);
let img = createImage(66, 66);
img.loadPixels();
for (let i = 0; i < img.width; i++) {
for (let j = 0; j < img.height; j++) {
img.set(i, j, color(0, 90, 102, (i % img.width) * 2));
}
}
img.updatePixels();
image(img, 17, 17);
image(img, 34, 34);
let pink = color(255, 102, 204);
let img = createImage(66, 66);
img.loadPixels();
let d = pixelDensity();
let halfImage = 4 * (img.width * d) * (img.height / 2 * d);
for (let i = 0; i < halfImage; i += 4) {
img.pixels[i] = red(pink);
img.pixels[i + 1] = green(pink);
img.pixels[i + 2] = blue(pink);
img.pixels[i + 3] = alpha(pink);
}
img.updatePixels();
image(img, 17, 17);
# 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 |
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 |
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 |
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.
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 |
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).
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 |
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 ellipse(x, y, w, hopt)
Draws an ellipse (oval) to the screen. An ellipse with equal width and height is a circle. By default, the first two parameters set the location, and the third and fourth parameters set the shape's width and height. If no height is specified, the value of width is used for both the width and height. If a negative height or width is specified, the absolute value is taken. The origin may be changed with the ellipseMode() function.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
x |
Number | x-coordinate of the ellipse. |
|
y |
Number | y-coordinate of the ellipse. |
|
w |
Number | width of the ellipse. |
|
h |
Number |
<optional> |
height of the ellipse. |
Example
ellipse(56, 46, 55, 55);
# inner ellipseMode(mode)
Modifies the location from which ellipses are drawn by changing the way
in which parameters given to ellipse() are interpreted.
The default mode is ellipseMode(CENTER), which interprets the first two
parameters of ellipse() as the shape's center point, while the third and
fourth parameters are its width and height.
ellipseMode(RADIUS) also uses the first two parameters of ellipse() as
the shape's center point, but uses the third and fourth parameters to
specify half of the shapes's width and height.
ellipseMode(CORNER) interprets the first two parameters of ellipse() as
the upper-left corner of the shape, while the third and fourth parameters
are its width and height.
ellipseMode(CORNERS) interprets the first two parameters of ellipse() as
the location of one corner of the ellipse's bounding box, and the third
and fourth parameters as the location of the opposite corner.
The parameter must be written in ALL CAPS because Javascript is a
case-sensitive language.
Parameters:
Name | Type | Description |
---|---|---|
mode |
Constant | either CENTER, RADIUS, CORNER, or CORNERS |
Example
ellipseMode(RADIUS); // Set ellipseMode to RADIUS
fill(255); // Set fill to white
ellipse(50, 50, 30, 30); // Draw white ellipse using RADIUS mode
ellipseMode(CENTER); // Set ellipseMode to CENTER
fill(100); // Set fill to gray
ellipse(50, 50, 30, 30); // Draw gray ellipse using CENTER mode
ellipseMode(CORNER); // Set ellipseMode is CORNER
fill(255); // Set fill to white
ellipse(25, 25, 50, 50); // Draw white ellipse using CORNER mode
ellipseMode(CORNERS); // Set ellipseMode to CORNERS
fill(100); // Set fill to gray
ellipse(25, 25, 50, 50); // Draw gray ellipse using CORNERS mode
# inner endShape(modeopt)
The endShape() function is the companion to beginShape() and may only be called after beginShape(). When endshape() is called, all of image data defined since the previous call to beginShape() is written into the image buffer. The constant CLOSE as the value for the MODE parameter to close the shape (to connect the beginning and the end).
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
mode |
Constant |
<optional> |
use CLOSE to close the shape |
Example
noFill();
beginShape();
vertex(20, 20);
vertex(45, 20);
vertex(45, 80);
endShape(CLOSE);
beginShape();
vertex(50, 20);
vertex(75, 20);
vertex(75, 80);
endShape();
TODO: QUADS, QUAD_STRIP, TRIANGLE_STRIP
# 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 |
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 fill(values)
Parameters:
Name | Type | Description |
---|---|---|
values |
Array.<Number> | an array containing the red,green,blue & and alpha components of the color |
# inner fill(v1, v2, v3, alphaopt)
Sets the color used to fill shapes. For example, if you run
fill(204, 102, 0), all subsequent shapes will be filled with orange. This
color is either specified in terms of the RGB or HSB color depending on
the current colorMode(). (The default color space is RGB, with each value
in the range from 0 to 255). The alpha range by default is also 0 to 255.
If a single string argument is provided, RGB, RGBA and Hex CSS color strings
and all named color strings are supported. In this case, an alpha number
value as a second argument is not supported, the RGBA form should be used.
A p5 Color object can also be provided to set the fill color.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
v1 |
Number | red or hue value relative to the current color range |
|
v2 |
Number | green or saturation value relative to the current color range |
|
v3 |
Number | blue or brightness value relative to the current color range |
|
alpha |
Number |
<optional> |
Example
// Grayscale integer value
fill(51);
rect(20, 20, 60, 60);
// R, G & B integer values
fill(255, 204, 0);
rect(20, 20, 60, 60);
// H, S & B integer values
colorMode(HSB);
fill(255, 204, 100);
rect(20, 20, 60, 60);
// Named SVG/CSS color string
fill('red');
rect(20, 20, 60, 60);
// three-digit hexadecimal RGB notation
fill('#fae');
rect(20, 20, 60, 60);
// six-digit hexadecimal RGB notation
fill('#222222');
rect(20, 20, 60, 60);
// integer RGB notation
fill('rgb(0,255,0)');
rect(20, 20, 60, 60);
// integer RGBA notation
fill('rgba(0,255,0, 0.25)');
rect(20, 20, 60, 60);
// percentage RGB notation
fill('rgb(100%,0%,10%)');
rect(20, 20, 60, 60);
// percentage RGBA notation
fill('rgba(100%,0%,100%,0.5)');
rect(20, 20, 60, 60);
// p5 Color object
fill(color(0, 0, 255));
rect(20, 20, 60, 60);
# inner fill(gray, alphaopt)
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
gray |
Number | a gray value |
|
alpha |
Number |
<optional> |
# 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 |
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 |
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 frameRate(fps)
Specifies the number of frames to be displayed every second. For example,
the function call frameRate(30) will attempt to refresh 30 times a second.
If the processor is not fast enough to maintain the specified rate, the
frame rate will not be achieved. Setting the frame rate within setup() is
recommended. The default frame rate is based on the frame rate of the display
(here also called "refresh rate"), which is set to 60 frames per second on most
computers. A frame rate of 24 frames per second (usual for movies) or above
will be enough for smooth animations
This is the same as setFrameRate(val).
Calling frameRate() with no arguments returns the current framerate. The
draw function must run at least once before it will return a value. This
is the same as getFrameRate().
Calling frameRate() with arguments that are not of the type numbers
or are non positive also returns current framerate.
Parameters:
Name | Type | Description |
---|---|---|
fps |
Number | number of frames to be displayed every second |
Example
let rectX = 0;
let fr = 30; //starting FPS
let clr;
function setup() {
background(200);
frameRate(fr); // Attempt to refresh at starting FPS
clr = color(255, 0, 0);
}
function draw() {
background(200);
rectX = rectX += 1; // Move Rectangle
if (rectX >= width) {
// If you go off screen.
if (fr === 30) {
clr = color(0, 0, 255);
fr = 10;
frameRate(fr); // make frameRate 10 FPS
} else {
clr = color(255, 0, 0);
fr = 30;
frameRate(fr); // make frameRate 30 FPS
}
rectX = 0;
}
fill(clr);
rect(rectX, 40, 20, 20);
}
# inner fullscreen(valopt) → {Boolean}
If argument is given, sets the sketch to fullscreen or not based on the value of the argument. If no argument is given, returns the current fullscreen state. Note that due to browser restrictions this can only be called on user input, for example, on mouse press like the example below.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
val |
Boolean |
<optional> |
whether the sketch should be in fullscreen mode or not |
current fullscreen state
Example
// Clicking in the box toggles fullscreen on and off.
function setup() {
background(200);
}
function mousePressed() {
if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {
let fs = fullscreen();
fullscreen(!fs);
}
}
# inner getURL() → {String}
Gets the current URL.
url
Example
let url;
let x = 100;
function setup() {
fill(0);
noStroke();
url = getURL();
}
function draw() {
background(200);
text(url, x, height / 2);
x--;
}
# inner getURLParams() → {Object}
Gets the current URL params as an Object.
URL params
Example
// Example: http://p5js.org?year=2014&month=May&day=15
function setup() {
let params = getURLParams();
text(params.day, 10, 20);
text(params.month, 10, 40);
text(params.year, 10, 60);
}
# inner getURLPath() → {Array.<String>}
Gets the current URL path as an array.
path components
Example
function setup() {
let urlPath = getURLPath();
for (let i = 0; i < urlPath.length; i++) {
text(urlPath[i], 10, i * 20 + 20);
}
}
# inner green(color) → {Number}
Extracts the green value from a color or pixel array.
Parameters:
Name | Type | Description |
---|---|---|
color |
Color | Array.<Number> | String | Color object, color components, or CSS color |
the green value
Example
let c = color(20, 75, 200); // Define color 'c'
fill(c); // Use color variable 'c' as fill color
rect(15, 20, 35, 60); // Draw left rectangle
let greenValue = green(c); // Get green in 'c'
print(greenValue); // Print "75.0"
fill(0, greenValue, 0); // Use 'greenValue' in new fill
rect(50, 20, 35, 60); // Draw right rectangle
# 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> |
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.
the current hour
Example
var h = hour();
text('Current hour:\n' + h, 5, 50);
# inner hue(color) → {Number}
Extracts the hue value from a color or pixel array.
Hue exists in both HSB and HSL. This function will return the HSB-normalized hue when supplied with an HSB color object (or when supplied with a pixel array while the color mode is HSB), but will default to the HSL-normalized hue otherwise. (The values will only be different if the maximum hue setting for each system is different.)
Parameters:
Name | Type | Description |
---|---|---|
color |
Color | Array.<Number> | String | Color object, color components, or CSS color |
the hue
Example
noStroke();
colorMode(HSB, 255);
let c = color(0, 126, 255);
fill(c);
rect(15, 20, 35, 60);
let value = hue(c); // Sets 'value' to "0"
fill(value);
rect(50, 20, 35, 60);
# inner image(img, x, y)
Draw an image to the p5.js canvas.
This function can be used with different numbers of parameters. The simplest use requires only three parameters: img, x, and y—where (x, y) is the position of the image. Two more parameters can optionally be added to specify the width and height of the image.
This function can also be used with all eight Number parameters. To differentiate between all these parameters, p5.js uses the language of "destination rectangle" (which corresponds to "dx", "dy", etc.) and "source image" (which corresponds to "sx", "sy", etc.) below. Specifying the "source image" dimensions can be useful when you want to display a subsection of the source image instead of the whole thing.
Parameters:
Name | Type | Description |
---|---|---|
img |
Bitmap | the image to display |
x |
Number | the x-coordinate of the top-left corner of the image |
y |
Number | the y-coordinate of the top-left corner of the image |
Example
let img;
function setup() {
img = loadImage('assets/laDefense.jpg');
// Top-left corner of the img is at (0, 0)
// Width and height are the img's original width and height
image(img, 0, 0);
}
# inner imageMode(mode)
Set image mode. Modifies the location from which images are drawn by
changing the way in which parameters given to image() are interpreted.
The default mode is imageMode(CORNER), which interprets the second and
third parameters of image() as the upper-left corner of the image. If
two additional parameters are specified, they are used to set the image's
width and height.
imageMode(CORNERS) interprets the second and third parameters of image()
as the location of one corner, and the fourth and fifth parameters as the
opposite corner.
imageMode(CENTER) interprets the second and third parameters of image()
as the image's center point. If two additional parameters are specified,
they are used to set the image's width and height.
Parameters:
Name | Type | Description |
---|---|---|
mode |
Constant | either CORNER, CORNERS, or CENTER |
Example
let img;
function setup() {
img = loadImage('assets/bricks.jpg');
imageMode(CORNER);
image(img, 10, 10, 50, 50);
}
let img;
function setup() {
img = loadImage('assets/bricks.jpg');
imageMode(CORNERS);
image(img, 10, 10, 90, 40);
}
let img;
function setup() {
img = loadImage('assets/bricks.jpg');
imageMode(CENTER);
image(img, 50, 50, 80, 80);
}
# 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) |
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 |
joined String
Example
var array = ['Hello', 'world!'];
var separator = ' ';
var message = join(array, separator);
text(message, 5, 50);
# inner keyPressed()
The keyPressed() function is called once every time a key is pressed. The
keyCode for the key that was pressed is stored in the keyCode variable.
Example
let value = 0;
function draw() {
fill(value);
rect(25, 25, 50, 50);
}
function keyPressed() {
if (value === 0) {
value = 255;
} else {
value = 0;
}
}
let value = 0;
function draw() {
fill(value);
rect(25, 25, 50, 50);
}
function keyPressed() {
if (keyCode === LEFT_ARROW) {
value = 255;
} else if (keyCode === RIGHT_ARROW) {
value = 0;
}
}
# inner keyReleased()
The keyReleased() function is called once every time a key is released.
See key and keyCode for more information.
Browsers may have different default
behaviors attached to various key events. To prevent any default
behavior for this event, add "return false" to the end of the method.
Example
let value = 0;
function draw() {
fill(value);
rect(25, 25, 50, 50);
}
function keyReleased() {
if (value === 0) {
value = 255;
} else {
value = 0;
}
return false; // prevent any default behavior
}
# inner keyTyped()
The keyTyped() function is called once every time a key is pressed, but
action keys such as Ctrl, Shift, and Alt are ignored. The most recent
key pressed will be stored in the key variable.
Because of how operating systems handle key repeats, holding down a key
will cause multiple calls to keyTyped() (and keyReleased() as well). The
rate of repeat is set by the operating system and how each computer is
configured.
Browsers may have different default behaviors attached to various key
events. To prevent any default behavior for this event, add "return false"
to the end of the method.
Example
let value = 0;
function draw() {
fill(value);
rect(25, 25, 50, 50);
}
function keyTyped() {
if (key === 'a') {
value = 255;
} else if (key === 'b') {
value = 0;
}
// uncomment to prevent any default behavior
// return false;
}
# 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 |
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 lerpColor(c1, c2, amt) → {Color}
Blends two colors to find a third color somewhere between them. The amt
parameter is the amount to interpolate between the two values where 0.0
equal to the first color, 0.1 is very near the first color, 0.5 is halfway
in between, etc. An amount below 0 will be treated as 0. Likewise, amounts
above 1 will be capped at 1. This is different from the behavior of lerp(),
but necessary because otherwise numbers outside the range will produce
strange and unexpected colors.
The way that colours are interpolated depends on the current color mode.
Parameters:
Name | Type | Description |
---|---|---|
c1 |
Color | interpolate from this color |
c2 |
Color | interpolate to this color |
amt |
Number | number between 0 and 1 |
interpolated color
Example
colorMode(RGB);
stroke(255);
background(51);
let from = color(218, 165, 32);
let to = color(72, 61, 139);
colorMode(RGB); // Try changing to HSB.
let interA = lerpColor(from, to, 0.33);
let interB = lerpColor(from, to, 0.66);
fill(from);
rect(10, 20, 20, 60);
fill(interA);
rect(30, 20, 20, 60);
fill(interB);
rect(50, 20, 20, 60);
fill(to);
rect(70, 20, 20, 60);
# inner lightness(color) → {Number}
Extracts the HSL lightness value from a color or pixel array.
Parameters:
Name | Type | Description |
---|---|---|
color |
Color | Array.<Number> | String | Color object, color components, or CSS color |
the lightness
Example
noStroke();
colorMode(HSL);
let c = color(156, 100, 50, 1);
fill(c);
rect(15, 20, 35, 60);
let value = lightness(c); // Sets 'value' to 50
fill(value);
rect(50, 20, 35, 60);
# inner line(x1, y1, x2, y2)
Draws a line (a direct path between two points) to the screen. The version of line() with four parameters draws the line in 2D. To color a line, use the stroke() function. A line cannot be filled, therefore the fill() function will not affect the color of a line. 2D lines are drawn with a width of one pixel by default, but this can be changed with the strokeWeight() function.
Parameters:
Name | Type | Description |
---|---|---|
x1 |
Number | the x-coordinate of the first point |
y1 |
Number | the y-coordinate of the first point |
x2 |
Number | the x-coordinate of the second point |
y2 |
Number | the y-coordinate of the second point |
Example
line(30, 20, 85, 75);
line(30, 20, 85, 20);
stroke(126);
line(85, 20, 85, 75);
stroke(255);
line(85, 75, 30, 75);
# inner loadBytes(file) → {Array.<number>}
This method is suitable for fetching files up to size of 64MB.
Parameters:
Name | Type | Description |
---|---|---|
file |
string | name of the file or URL to load |
an object whose 'bytes' property will be the loaded buffer
Example
let data;
function preload() {
data = loadBytes('assets/mammals.xml');
}
function setup() {
for (let i = 0; i < 5; i++) {
console.log(data.bytes[i].toString(16));
}
}
# 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 |
Font object
# inner loadImage(path) → {Bitmap}
Loads an image from a path and creates a Image from it.
Parameters:
Name | Type | Description |
---|---|---|
path |
String | Path of the image to be loaded |
the Image object
Example
let img;
function setup() {
img = loadImage('assets/laDefense.jpg');
image(img, 0, 0);
}
# inner loadStrings(filename) → {Array.<String>}
Reads the contents of a file and creates a String array of its individual
lines. If the name of the file is used as the parameter, as in the above
example, the file must be located in the sketch directory/folder.
Alternatively, the file maybe be loaded from anywhere on the local
computer using an absolute path (something that starts with / on Unix and
Linux, or a drive letter on Windows), or the filename parameter can be a
URL for a file found on a network.
This method is asynchronous, meaning it may not finish before the next
line in your sketch is executed.
This method is suitable for fetching files up to size of 64MB.
Parameters:
Name | Type | Description |
---|---|---|
filename |
String | name of the file or url to load |
Array of Strings
Example
let result;
function preload() {
result = loadStrings('assets/test.txt');
}
function setup() {
background(200);
let ind = floor(random(result.length));
text(result[ind], 10, 10, 80, 80);
}
function setup() {
loadStrings('assets/test.txt', pickString);
}
function pickString(result) {
background(200);
let ind = floor(random(result.length));
text(result[ind], 10, 10, 80, 80);
}
# 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 |
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 |
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 |
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 |
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 |
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 |
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.
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 |
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.
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.
the current month
Example
var m = month();
text('Current month: \n' + m, 5, 50);
# inner mouseClicked(eventopt)
The mouseClicked() function is called once after a mouse button has been
pressed and then released.
Browsers handle clicks differently, so this function is only guaranteed to be
run when the left mouse button is clicked. To handle other mouse buttons
being pressed or released, see mousePressed() or mouseReleased().
Browsers may have different default
behaviors attached to various mouse events. To prevent any default
behavior for this event, add "return false" to the end of the method.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
event |
Object |
<optional> |
optional MouseEvent callback argument. |
Example
// Click within the image to change
// the value of the rectangle
// after the mouse has been clicked
let value = 0;
function draw() {
fill(value);
rect(25, 25, 50, 50);
}
function mouseClicked() {
if (value === 0) {
value = 255;
} else {
value = 0;
}
}
function mouseClicked() {
ellipse(mouseX, mouseY, 5, 5);
// prevent default
return false;
}
// returns a MouseEvent object
// as a callback argument
function mouseClicked(event) {
console.log(event);
}
# inner mouseMoved(eventopt)
The >mouseMoved() function is called every time the mouse moves and a mouse
button is not pressed.
Browsers may have different default
behaviors attached to various mouse events. To prevent any default
behavior for this event, add "return false" to the end of the method.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
event |
Object |
<optional> |
optional MouseEvent callback argument. |
Example
// Move the mouse across the page
// to change its value
let value = 0;
function draw() {
fill(value);
rect(25, 25, 50, 50);
}
function mouseMoved() {
value = value + 5;
if (value > 255) {
value = 0;
}
}
function mouseMoved() {
ellipse(mouseX, mouseY, 5, 5);
// prevent default
return false;
}
// returns a MouseEvent object
// as a callback argument
function mouseMoved(event) {
console.log(event);
}
# inner mousePressed(eventopt)
The mousePressed() function is called once after every time a mouse button
is pressed. The mouseButton variable (see the related reference entry)
can be used to determine which button has been pressed.
Browsers may have different default
behaviors attached to various mouse events. To prevent any default
behavior for this event, add "return false" to the end of the method.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
event |
Object |
<optional> |
optional MouseEvent callback argument. |
Example
// Click within the image to change
// the value of the rectangle
let value = 0;
function draw() {
fill(value);
rect(25, 25, 50, 50);
}
function mousePressed() {
if (value === 0) {
value = 255;
} else {
value = 0;
}
}
function mousePressed() {
ellipse(mouseX, mouseY, 5, 5);
// prevent default
return false;
}
// returns a MouseEvent object
// as a callback argument
function mousePressed(event) {
console.log(event);
}
# inner mouseReleased(eventopt)
The mouseReleased() function is called every time a mouse button is
released.
Browsers may have different default
behaviors attached to various mouse events. To prevent any default
behavior for this event, add "return false" to the end of the method.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
event |
Object |
<optional> |
optional MouseEvent callback argument. |
Example
// Click within the image to change
// the value of the rectangle
// after the mouse has been clicked
let value = 0;
function draw() {
fill(value);
rect(25, 25, 50, 50);
}
function mouseReleased() {
if (value === 0) {
value = 255;
} else {
value = 0;
}
}
function mouseReleased() {
ellipse(mouseX, mouseY, 5, 5);
// prevent default
return false;
}
// returns a MouseEvent object
// as a callback argument
function mouseReleased(event) {
console.log(event);
}
# 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 |
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 |
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 |
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 |
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 noFill()
Disables filling geometry. If both noStroke() and noFill() are called, nothing will be drawn to the screen.
Example
rect(15, 10, 55, 55);
noFill();
rect(20, 20, 60, 60);
function setup() {
createCanvas(100, 100, WEBGL);
}
function draw() {
background(0);
noFill();
stroke(100, 100, 240);
rotateX(frameCount * 0.01);
rotateY(frameCount * 0.01);
box(45, 45, 45);
}
# 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 |
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 |
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 noStroke()
Disables drawing the stroke (outline). If both noStroke() and noFill() are called, nothing will be drawn to the screen.
Example
noStroke();
rect(20, 20, 60, 60);
function setup() {
createCanvas(100, 100, WEBGL);
}
function draw() {
background(0);
noStroke();
fill(240, 150, 150);
rotateX(frameCount * 0.01);
rotateY(frameCount * 0.01);
box(45, 45, 45);
}
# inner pixelDensity(val)
Sets the pixel scaling for high pixel density displays. By default pixel density is set to match display density, call pixelDensity(1) to turn this off. Calling pixelDensity() with no arguments returns the current pixel density of the sketch.
Parameters:
Name | Type | Description |
---|---|---|
val |
Number | whether or how much the sketch should scale |
Example
function setup() {
pixelDensity(1);
createCanvas(100, 100);
background(200);
ellipse(width / 2, height / 2, 50, 50);
}
function setup() {
pixelDensity(3.0);
createCanvas(100, 100);
background(200);
ellipse(width / 2, height / 2, 50, 50);
}
# inner point(x, y, zopt)
Draws a point, a coordinate in space at the dimension of one pixel. The first parameter is the horizontal value for the point, the second value is the vertical value for the point. The color of the point is determined by the current stroke.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
x |
Number | the x-coordinate |
|
y |
Number | the y-coordinate |
|
z |
Number |
<optional> |
the z-coordinate (for WebGL mode) |
Example
point(30, 20);
point(85, 20);
point(85, 75);
point(30, 75);
# inner pop()
The push() function saves the current drawing style settings and
transformations, while pop() restores these settings. Note that these
functions are always used together. They allow you to change the style
and transformation settings and later return to what you had. When a new
state is started with push(), it builds on the current style and transform
information. The push() and pop() functions can be embedded to provide
more control. (See the second example for a demonstration.)
push() stores information related to the current transformation state
and style settings controlled by the following functions: fill(),
stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(),
imageMode(), rectMode(), ellipseMode(), colorMode(), textAlign(),
textFont(), textSize(), textLeading().
Example
ellipse(0, 50, 33, 33); // Left circle
push(); // Start a new drawing state
translate(50, 0);
strokeWeight(10);
fill(204, 153, 0);
ellipse(0, 50, 33, 33); // Middle circle
pop(); // Restore original state
ellipse(100, 50, 33, 33); // Right circle
</code>
</div>
<div>
<code>
ellipse(0, 50, 33, 33); // Left circle
push(); // Start a new drawing state
strokeWeight(10);
fill(204, 153, 0);
ellipse(33, 50, 33, 33); // Left-middle circle
push(); // Start another new drawing state
stroke(0, 102, 153);
ellipse(66, 50, 33, 33); // Right-middle circle
pop(); // Restore previous state
pop(); // Restore original state
ellipse(100, 50, 33, 33); // Right circle
# 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 33333 and pow(3, -5) is equivalent to 1 / 33333. Maps to Math.pow().
Parameters:
Name | Type | Description |
---|---|---|
n |
Number | base of the exponential expression |
e |
Number | power by which to raise the base |
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 print(contents)
The print() function writes to the logfile. This function is often helpful for looking at the data a program is producing. This function creates a new line of text for each call to the function. Individual elements can be separated with quotes ("") and joined with the addition operator (+).
Parameters:
Name | Type | Description |
---|---|---|
contents |
Any | any combination of Number, String, Object, Boolean, Array to print |
Example
let x = 10;
print('The value of x is ' + x);
// prints "The value of x is 10"
# inner print(contents)
The println() function writes to the logfile. This function is often helpful for looking at the data a program is producing. This function creates a new line of text for each call to the function. Individual elements can be separated with quotes ("") and joined with the addition operator (+).
Parameters:
Name | Type | Description |
---|---|---|
contents |
Any | any combination of Number, String, Object, Boolean, Array to print |
Example
let x = 10;
print('The value of x is ' + x);
// prints "The value of x is 10"
# inner push()
The push() function saves the current drawing style settings and
transformations, while pop() restores these settings. Note that these
functions are always used together. They allow you to change the style
and transformation settings and later return to what you had. When a new
state is started with push(), it builds on the current style and transform
information. The push() and pop() functions can be embedded to provide
more control. (See the second example for a demonstration.)
push() stores information related to the current transformation state
and style settings controlled by the following functions: fill(),
stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(),
imageMode(), rectMode(), ellipseMode(), colorMode(), textAlign(),
textFont(), textSize(), textLeading().
Example
ellipse(0, 50, 33, 33); // Left circle
push(); // Start a new drawing state
strokeWeight(10);
fill(204, 153, 0);
translate(50, 0);
ellipse(0, 50, 33, 33); // Middle circle
pop(); // Restore original state
ellipse(100, 50, 33, 33); // Right circle
</code>
</div>
<div>
<code>
ellipse(0, 50, 33, 33); // Left circle
push(); // Start a new drawing state
strokeWeight(10);
fill(204, 153, 0);
ellipse(33, 50, 33, 33); // Left-middle circle
push(); // Start another new drawing state
stroke(0, 102, 153);
ellipse(66, 50, 33, 33); // Right-middle circle
pop(); // Restore previous state
pop(); // Restore original state
ellipse(100, 50, 33, 33); // Right circle
# inner quad(x1, y1, x2, y2, x3, y3, x4, y4)
Draw a quad. A quad is a quadrilateral, a four sided polygon. It is similar to a rectangle, but the angles between its edges are not constrained to ninety degrees. The first pair of parameters (x1,y1) sets the first vertex and the subsequent pairs should proceed clockwise or counter-clockwise around the defined shape.
Parameters:
Name | Type | Description |
---|---|---|
x1 |
Number | the x-coordinate of the first point |
y1 |
Number | the y-coordinate of the first point |
x2 |
Number | the x-coordinate of the second point |
y2 |
Number | the y-coordinate of the second point |
x3 |
Number | the x-coordinate of the third point |
y3 |
Number | the y-coordinate of the third point |
x4 |
Number | the x-coordinate of the fourth point |
y4 |
Number | the y-coordinate of the fourth point |
Example
quad(38, 31, 86, 20, 69, 63, 30, 76);
# 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 |
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) |
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 |
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 rect(x, y, w, h)
Draws a rectangle to the screen. A rectangle is a four-sided shape with
every angle at ninety degrees. By default, the first two parameters set
the location of the upper-left corner, the third sets the width, and the
fourth sets the height. The way these parameters are interpreted, however,
may be changed with the rectMode() function.
The fifth, sixth, seventh and eighth parameters, if specified,
determine corner radius for the top-left, top-right, lower-right and
lower-left corners, respectively. An omitted corner radius parameter is set
to the value of the previously specified radius value in the parameter list.
Parameters:
Name | Type | Description |
---|---|---|
x |
Number | x-coordinate of the rectangle. |
y |
Number | y-coordinate of the rectangle. |
w |
Number | width of the rectangle. |
h |
Number | height of the rectangle. |
Example
// Draw a rectangle at location (30, 20) with a width and height of 55.
rect(30, 20, 55, 55);
# inner rectMode(mode)
Modifies the location from which rectangles are drawn by changing the way
in which parameters given to rect() are interpreted.
The default mode is rectMode(CORNER), which interprets the first two
parameters of rect() as the upper-left corner of the shape, while the
third and fourth parameters are its width and height.
rectMode(CORNERS) interprets the first two parameters of rect() as the
location of one corner, and the third and fourth parameters as the
location of the opposite corner.
rectMode(CENTER) interprets the first two parameters of rect() as the
shape's center point, while the third and fourth parameters are its
width and height.
rectMode(RADIUS) also uses the first two parameters of rect() as the
shape's center point, but uses the third and fourth parameters to specify
half of the shapes's width and height.
The parameter must be written in ALL CAPS because Javascript is a
case-sensitive language.
Parameters:
Name | Type | Description |
---|---|---|
mode |
Constant | either CORNER, CORNERS, CENTER, or RADIUS |
Example
rectMode(CORNER); // Default rectMode is CORNER
fill(255); // Set fill to white
rect(25, 25, 50, 50); // Draw white rect using CORNER mode
rectMode(CORNERS); // Set rectMode to CORNERS
fill(100); // Set fill to gray
rect(25, 25, 50, 50); // Draw gray rect using CORNERS mode
rectMode(RADIUS); // Set rectMode to RADIUS
fill(255); // Set fill to white
rect(50, 50, 30, 30); // Draw white rect using RADIUS mode
rectMode(CENTER); // Set rectMode to CENTER
fill(100); // Set fill to gray
rect(50, 50, 30, 30); // Draw gray rect using CENTER mode
# inner red(color) → {Number}
Extracts the red value from a color or pixel array.
Parameters:
Name | Type | Description |
---|---|---|
color |
Color | Array.<Number> | String | Color object, color components, or CSS color |
the red value
Example
let c = color(255, 204, 0); // Define color 'c'
fill(c); // Use color variable 'c' as fill color
rect(15, 20, 35, 60); // Draw left rectangle
let redValue = red(c); // Get red in 'c'
print(redValue); // Print "255.0"
fill(redValue, 0, 0); // Use 'redValue' in new fill
rect(50, 20, 35, 60); // Draw right rectangle
colorMode(RGB, 255);
let c = color(127, 255, 0);
colorMode(RGB, 1);
let myColor = red(c);
print(myColor);
# 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 resetMatrix()
Replaces the current matrix with the identity matrix.
Example
translate(50, 50);
applyMatrix(0.5, 0.5, -0.5, 0.5, 0, 0);
rect(0, 0, 20, 20);
// Note that the translate is also reset.
resetMatrix();
rect(0, 0, 20, 20);
# inner reverse(list) → {Array}
Reverses the order of an array, maps to Array.reverse()
Parameters:
Name | Type | Description |
---|---|---|
list |
Array | Array to reverse |
the reversed list
Example
function setup() {
var myArray = ['A', 'B', 'C'];
print(myArray); // ['A','B','C']
reverse(myArray);
print(myArray); // ['C','B','A']
}
# inner rotate(angle)
Rotates a shape the amount specified by the angle parameter. This
function accounts for angleMode, so angles can be entered in either
RADIANS or DEGREES.
Objects are always rotated around their relative position to the
origin and positive numbers rotate objects in a clockwise direction.
Transformations apply to everything that happens after and subsequent
calls to the function accumulates the effect. For example, calling
rotate(HALF_PI) and then rotate(HALF_PI) is the same as rotate(PI).
All tranformations are reset when draw() begins again.
Technically, rotate() multiplies the current transformation matrix
by a rotation matrix. This function can be further controlled by
the push() and pop().
Parameters:
Name | Type | Description |
---|---|---|
angle |
Number | the angle of rotation, specified in radians or degrees, depending on current angleMode |
Example
translate(width / 2, height / 2);
rotate(PI / 3.0);
rect(-26, -26, 52, 52);
# 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 |
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 saturation(color) → {Number}
Extracts the saturation value from a color or pixel array.
Saturation is scaled differently in HSB and HSL. This function will return the HSB saturation when supplied with an HSB color object (or when supplied with a pixel array while the color mode is HSB), but will default to the HSL saturation otherwise.
Parameters:
Name | Type | Description |
---|---|---|
color |
Color | Array.<Number> | String | Color object, color components, or CSS color |
the saturation value
Example
noStroke();
colorMode(HSB, 255);
let c = color(0, 126, 255);
fill(c);
rect(15, 20, 35, 60);
let value = saturation(c); // Sets 'value' to 126
fill(value);
rect(50, 20, 35, 60);
# inner saveStrings(list, filename, extensionopt)
Writes an array of Strings to a text file, one line per String. The file saving process and location of the saved file will vary between web browsers.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
list |
Array.<String> | string array to be written |
|
filename |
String | filename for output |
|
extension |
String |
<optional> |
the filename's extension |
Example
let words = 'apple bear cat dog';
// .split() outputs an Array
let list = split(words, ' ');
function setup() {
createCanvas(100, 100);
background(200);
text('click here to save', 10, 10, 70, 80);
}
function mousePressed() {
if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {
saveStrings(list, 'nouns.txt');
}
}
// Saves the following to a file called 'nouns.txt':
//
// apple
// bear
// cat
// dog
# inner scale(s, yopt)
Increases or decreases the size of a shape by expanding and contracting
vertices. Objects always scale from their relative origin to the
coordinate system. Scale values are specified as decimal percentages.
For example, the function call scale(2.0) increases the dimension of a
shape by 200%.
Transformations apply to everything that happens after and subsequent
calls to the function multiply the effect. For example, calling scale(2.0)
and then scale(1.5) is the same as scale(3.0). If scale() is called
within draw(), the transformation is reset when the loop begins again.
Using this function with the z parameter is only available in WEBGL mode.
This function can be further controlled with push() and pop().
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
s |
Number | p5.Vector | Array.<Number> | percent to scale the object, or percentage to scale the object in the x-axis if multiple arguments are given |
|
y |
Number |
<optional> |
percent to scale the object in the y-axis |
Example
rect(30, 20, 50, 50);
scale(0.5);
rect(30, 20, 50, 50);
rect(30, 20, 50, 50);
scale(0.5, 1.3);
rect(30, 20, 50, 50);
# inner scale(scales)
Parameters:
Name | Type | Description |
---|---|---|
scales |
p5.Vector | Array.<Number> | per-axis percents to scale the object |
# inner second() → {Integer}
The second() function returns the current second as a value from 0 - 59.
the current second
Example
var s = second();
text('Current second: \n' + s, 5, 50);
# inner setAlpha(alpha)
Parameters:
Name | Type | Description |
---|---|---|
alpha |
Number | the new alpha value |
Example
let squareColor;
function setup() {
ellipseMode(CORNERS);
strokeWeight(4);
squareColor = color(100, 50, 150);
}
function draw() {
background(255);
noFill();
stroke(0);
ellipse(10, 10, width - 10, height - 10);
squareColor.setAlpha(128 + 128 * sin(millis() / 1000));
fill(squareColor);
noStroke();
rect(13, 13, width - 26, height - 26);
}
# inner setBlue(blue)
Parameters:
Name | Type | Description |
---|---|---|
blue |
Number | the new blue value |
Example
let backgroundColor;
function setup() {
backgroundColor = color(100, 50, 150);
}
function draw() {
backgroundColor.setBlue(128 + 128 * sin(millis() / 1000));
background(backgroundColor);
}
# inner setGreen(green)
Parameters:
Name | Type | Description |
---|---|---|
green |
Number | the new green value |
Example
let backgroundColor;
function setup() {
backgroundColor = color(100, 50, 150);
}
function draw() {
backgroundColor.setGreen(128 + 128 * sin(millis() / 1000));
background(backgroundColor);
}
# inner setRed(red)
Parameters:
Name | Type | Description |
---|---|---|
red |
Number | the new red value |
Example
let backgroundColor;
function setup() {
backgroundColor = color(100, 50, 150);
}
function draw() {
backgroundColor.setRed(128 + 128 * sin(millis() / 1000));
background(backgroundColor);
}
# inner shearX(angle)
Shears a shape around the x-axis the amount specified by the angle
parameter. Angles should be specified in the current angleMode.
Objects are always sheared around their relative position to the origin
and positive numbers shear objects in a clockwise direction.
Transformations apply to everything that happens after and subsequent
calls to the function accumulates the effect. For example, calling
shearX(PI/2) and then shearX(PI/2) is the same as shearX(PI).
If shearX() is called within the draw(), the transformation is reset when
the loop begins again.
Technically, shearX() multiplies the current transformation matrix by a
rotation matrix. This function can be further controlled by the
push() and pop() functions.
Parameters:
Name | Type | Description |
---|---|---|
angle |
Number | angle of shear specified in radians or degrees, depending on current angleMode |
Example
translate(width / 4, height / 4);
shearX(PI / 4.0);
rect(0, 0, 30, 30);
# inner shearY(angle)
Shears a shape around the y-axis the amount specified by the angle
parameter. Angles should be specified in the current angleMode. Objects
are always sheared around their relative position to the origin and
positive numbers shear objects in a clockwise direction.
Transformations apply to everything that happens after and subsequent
calls to the function accumulates the effect. For example, calling
shearY(PI/2) and then shearY(PI/2) is the same as shearY(PI). If
shearY() is called within the draw(), the transformation is reset when
the loop begins again.
Technically, shearY() multiplies the current transformation matrix by a
rotation matrix. This function can be further controlled by the
push() and pop() functions.
Parameters:
Name | Type | Description |
---|---|---|
angle |
Number | angle of shear specified in radians or degrees, depending on current angleMode |
Example
translate(width / 4, height / 4);
shearY(PI / 4.0);
rect(0, 0, 30, 30);
# 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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 square(x, y, s)
Draws a square to the screen. A square is a four-sided shape with
every angle at ninety degrees, and equal side size.
This function is a special case of the rect() function, where the width and height are the same, and the parameter is called "s" for side size.
By default, the first two parameters set the location of the upper-left corner, the third sets the side size of the square.
The way these parameters are interpreted, however,
may be changed with the rectMode() function.
The fourth, fifth, sixth and seventh parameters, if specified,
determine corner radius for the top-left, top-right, lower-right and
lower-left corners, respectively. An omitted corner radius parameter is set
to the value of the previously specified radius value in the parameter list.
Parameters:
Name | Type | Description |
---|---|---|
x |
Number | x-coordinate of the square. |
y |
Number | y-coordinate of the square. |
s |
Number | side size of the square. |
Example
// Draw a square at location (30, 20) with a side size of 55.
square(30, 20, 55);
# 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 |
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 stroke(v1, v2, v3, alphaopt)
Sets the color used to draw lines and borders around shapes. This color
is either specified in terms of the RGB or HSB color depending on the
current colorMode() (the default color space is RGB, with each value in
the range from 0 to 255). The alpha range by default is also 0 to 255.
If a single string argument is provided, RGB, RGBA and Hex CSS color
strings and all named color strings are supported. In this case, an alpha
number value as a second argument is not supported, the RGBA form should be
used.
A p5 Color object can also be provided to set the stroke color.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
v1 |
Number | red or hue value relative to the current color range |
|
v2 |
Number | green or saturation value relative to the current color range |
|
v3 |
Number | blue or brightness value relative to the current color range |
|
alpha |
Number |
<optional> |
Example
// Grayscale integer value
strokeWeight(4);
stroke(51);
rect(20, 20, 60, 60);
// R, G & B integer values
stroke(255, 204, 0);
strokeWeight(4);
rect(20, 20, 60, 60);
// H, S & B integer values
colorMode(HSB);
strokeWeight(4);
stroke(255, 204, 100);
rect(20, 20, 60, 60);
// Named SVG/CSS color string
stroke('red');
strokeWeight(4);
rect(20, 20, 60, 60);
// three-digit hexadecimal RGB notation
stroke('#fae');
strokeWeight(4);
rect(20, 20, 60, 60);
// six-digit hexadecimal RGB notation
stroke('#222222');
strokeWeight(4);
rect(20, 20, 60, 60);
// integer RGB notation
stroke('rgb(0,255,0)');
strokeWeight(4);
rect(20, 20, 60, 60);
// integer RGBA notation
stroke('rgba(0,255,0,0.25)');
strokeWeight(4);
rect(20, 20, 60, 60);
// percentage RGB notation
stroke('rgb(100%,0%,10%)');
strokeWeight(4);
rect(20, 20, 60, 60);
// percentage RGBA notation
stroke('rgba(100%,0%,100%,0.5)');
strokeWeight(4);
rect(20, 20, 60, 60);
// p5 Color object
stroke(color(0, 0, 255));
strokeWeight(4);
rect(20, 20, 60, 60);
# inner stroke(gray, alphaopt)
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
gray |
Number | a gray value |
|
alpha |
Number |
<optional> |
# inner stroke(values)
Parameters:
Name | Type | Description |
---|---|---|
values |
Array.<Number> | an array containing the red,green,blue & and alpha components of the color |
# inner strokeWeight(weight)
Sets the width of the stroke used for lines, points, and the border around shapes. All widths are set in units of pixels.
Parameters:
Name | Type | Description |
---|---|---|
weight |
Number | the weight (in pixels) of the stroke |
Example
strokeWeight(1); // Default
line(20, 20, 80, 20);
strokeWeight(4); // Thicker
line(20, 40, 80, 40);
strokeWeight(10); // Beastly
line(20, 70, 80, 70);
# 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 |
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 |
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.
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.
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 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 |
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 toString(formatopt) → {String}
This function returns the color formatted as a string. This can be useful for debugging, or for using p5.js with other libraries.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
format |
String |
<optional> |
How the color string will be formatted. Leaving this empty formats the string as rgba(r, g, b, a). '#rgb' '#rgba' '#rrggbb' and '#rrggbbaa' format as hexadecimal color codes. 'rgb' 'hsb' and 'hsl' return the color formatted in the specified color mode. 'rgba' 'hsba' and 'hsla' are the same as above but with alpha channels. 'rgb%' 'hsb%' 'hsl%' 'rgba%' 'hsba%' and 'hsla%' format as percentages. |
the formatted string
Example
let myColor;
function setup() {
createCanvas(200, 200);
stroke(255);
myColor = color(100, 100, 250);
fill(myColor);
}
function draw() {
rotate(HALF_PI);
text(myColor.toString(), 0, -5);
text(myColor.toString('#rrggbb'), 0, -30);
text(myColor.toString('rgba%'), 0, -55);
}
# inner translate(x, y, zopt)
Specifies an amount to displace objects within the display window.
The x parameter specifies left/right translation, the y parameter
specifies up/down translation.
Transformations are cumulative and apply to everything that happens after
and subsequent calls to the function accumulates the effect. For example,
calling translate(50, 0) and then translate(20, 0) is the same as
translate(70, 0). If translate() is called within draw(), the
transformation is reset when the loop begins again. This function can be
further controlled by using push() and pop().
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
x |
Number | left/right translation |
|
y |
Number | up/down translation |
|
z |
Number |
<optional> |
forward/backward translation (webgl only) |
Example
translate(30, 20);
rect(0, 0, 55, 55);
rect(0, 0, 55, 55); // Draw rect at original 0,0
translate(30, 20);
rect(0, 0, 55, 55); // Draw rect at new 0,0
translate(14, 14);
rect(0, 0, 55, 55); // Draw rect at new 0,0
function draw() {
background(200);
rectMode(CENTER);
translate(width / 2, height / 2);
translate(p5.Vector.fromAngle(millis() / 1000, 40));
rect(0, 0, 20, 20);
}
# inner translate(vector)
Parameters:
Name | Type | Description |
---|---|---|
vector |
p5.Vector | the vector to translate by |
# inner triangle(x1, y1, x2, y2, x3, y3)
A triangle is a plane created by connecting three points. The first two arguments specify the first point, the middle two arguments specify the second point, and the last two arguments specify the third point.
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 |
x3 |
Number | x-coordinate of the third point |
y3 |
Number | y-coordinate of the third point |
Example
triangle(30, 75, 58, 20, 86, 75);
# 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 |
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 |
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 |
integer representation of hexadecimal value
Example
print(unhex('A')); // 10
print(unhex('FF')); // 255
print(unhex(['FF', 'AA', '00'])); // [ 255, 170, 0 ]
# inner vertex(x, y)
All shapes are constructed by connecting a series of vertices. vertex() is used to specify the vertex coordinates for points, lines, triangles, quads, and polygons. It is used exclusively within the beginShape() and endShape() functions.
Parameters:
Name | Type | Description |
---|---|---|
x |
Number | x-coordinate of the vertex |
y |
Number | y-coordinate of the vertex |
Example
strokeWeight(3);
beginShape(POINTS);
vertex(30, 20);
vertex(85, 20);
vertex(85, 75);
vertex(30, 75);
endShape();
# inner year() → {Integer}
The year() returns the current year as an integer (2014, 2015, 2016, etc).
the current year
Example
var y = year();
text('Current year: \n' + y, 5, 50);