# project
p5

[![npm version](https://badge.fury.io/js/p5.svg)](https://www.npmjs.com/package/p5)

1.11.10

https://github.com/processing/p5.js#readme

# files
## src/accessibility/color_namer.js
src/accessibility/color_namer.js

### modules
### classes
### namespaces
## src/accessibility/describe.js
src/accessibility/describe.js

### modules
### classes
### namespaces
## src/accessibility/gridOutput.js
src/accessibility/gridOutput.js

### modules
### classes
### namespaces
## src/accessibility/outputs.js
src/accessibility/outputs.js

### modules
### classes
### namespaces
## src/accessibility/textOutput.js
src/accessibility/textOutput.js

### modules
### classes
### namespaces
## src/color/color_conversion.js
src/color/color_conversion.js

### modules
### classes
### namespaces
## src/color/creating_reading.js
src/color/creating_reading.js

### modules
### classes
### namespaces
## src/color/p5.Color.js
src/color/p5.Color.js

### modules
### classes
### namespaces
## src/color/setting.js
src/color/setting.js

### modules
### classes
### namespaces
## src/core/friendly_errors/fes_core.js
src/core/friendly_errors/fes_core.js

### modules
### classes
### namespaces
## src/core/friendly_errors/file_errors.js
src/core/friendly_errors/file_errors.js

### modules
### classes
### namespaces
## src/core/friendly_errors/sketch_reader.js
src/core/friendly_errors/sketch_reader.js

### modules
### classes
### namespaces
## src/core/friendly_errors/stacktrace.js
src/core/friendly_errors/stacktrace.js

### modules
### classes
### namespaces
## src/core/friendly_errors/validate_params.js
src/core/friendly_errors/validate_params.js

### modules
### classes
### namespaces
## src/core/shape/2d_primitives.js
src/core/shape/2d_primitives.js

### modules
### classes
### namespaces
## src/core/shape/attributes.js
src/core/shape/attributes.js

### modules
### classes
### namespaces
## src/core/shape/curves.js
src/core/shape/curves.js

### modules
### classes
### namespaces
## src/core/shape/vertex.js
src/core/shape/vertex.js

### modules
### classes
### namespaces
## src/core/constants.js
src/core/constants.js

### modules
### classes
### namespaces
## src/core/environment.js
src/core/environment.js

### modules
### classes
### namespaces
## src/core/helpers.js
src/core/helpers.js

### modules
### classes
### namespaces
## src/core/init.js
src/core/init.js

### modules
### classes
### namespaces
## src/core/internationalization.js
src/core/internationalization.js

### modules
### classes
### namespaces
## src/core/legacy.js
src/core/legacy.js

### modules
### classes
### namespaces
## src/core/main.js
src/core/main.js

### modules
### classes
### namespaces
## src/core/p5.Element.js
src/core/p5.Element.js

### modules
### classes
### namespaces
## src/core/p5.Graphics.js
src/core/p5.Graphics.js

### modules
### classes
### namespaces
## src/core/p5.Renderer.js
src/core/p5.Renderer.js

### modules
### classes
### namespaces
## src/core/p5.Renderer2D.js
src/core/p5.Renderer2D.js

### modules
### classes
### namespaces
## src/core/reference.js
src/core/reference.js

### modules
### classes
### namespaces
## src/core/rendering.js
src/core/rendering.js

### modules
### classes
### namespaces
## src/core/structure.js
src/core/structure.js

### modules
### classes
### namespaces
## src/core/transform.js
src/core/transform.js

### modules
### classes
### namespaces
## src/data/local_storage.js
src/data/local_storage.js

### modules
### classes
### namespaces
## src/data/p5.TypedDict.js
src/data/p5.TypedDict.js

### modules
### classes
### namespaces
## src/dom/dom.js
src/dom/dom.js

### modules
### classes
### namespaces
## src/events/acceleration.js
src/events/acceleration.js

### modules
### classes
### namespaces
## src/events/keyboard.js
src/events/keyboard.js

### modules
### classes
### namespaces
## src/events/mouse.js
src/events/mouse.js

### modules
### classes
### namespaces
## src/events/touch.js
src/events/touch.js

### modules
### classes
### namespaces
## src/image/filters.js
src/image/filters.js

### modules
### classes
### namespaces
## src/image/image.js
src/image/image.js

### modules
### classes
### namespaces
## src/image/loading_displaying.js
src/image/loading_displaying.js

### modules
### classes
### namespaces
## src/image/p5.Image.js
src/image/p5.Image.js

### modules
### classes
### namespaces
## src/image/pixels.js
src/image/pixels.js

### modules
### classes
### namespaces
## src/io/files.js
src/io/files.js

### modules
### classes
### namespaces
## src/io/p5.Table.js
src/io/p5.Table.js

### modules
### classes
### namespaces
## src/io/p5.TableRow.js
src/io/p5.TableRow.js

### modules
### classes
### namespaces
## src/io/p5.XML.js
src/io/p5.XML.js

### modules
### classes
### namespaces
## src/math/calculation.js
src/math/calculation.js

### modules
### classes
### namespaces
## src/math/math.js
src/math/math.js

### modules
### classes
### namespaces
## src/math/noise.js
src/math/noise.js

### modules
### classes
### namespaces
## src/math/p5.Vector.js
src/math/p5.Vector.js

### modules
### classes
### namespaces
## src/math/random.js
src/math/random.js

### modules
### classes
### namespaces
## src/math/trigonometry.js
src/math/trigonometry.js

### modules
### classes
### namespaces
## src/typography/attributes.js
src/typography/attributes.js

### modules
### classes
### namespaces
## src/typography/loading_displaying.js
src/typography/loading_displaying.js

### modules
### classes
### namespaces
## src/typography/p5.Font.js
src/typography/p5.Font.js

### modules
### classes
### namespaces
## src/utilities/array_functions.js
src/utilities/array_functions.js

### modules
### classes
### namespaces
## src/utilities/conversion.js
src/utilities/conversion.js

### modules
### classes
### namespaces
## src/utilities/string_functions.js
src/utilities/string_functions.js

### modules
### classes
### namespaces
## src/utilities/time_date.js
src/utilities/time_date.js

### modules
### classes
### namespaces
## src/webgl/3d_primitives.js
src/webgl/3d_primitives.js

### modules
### classes
### namespaces
## src/webgl/GeometryBuilder.js
src/webgl/GeometryBuilder.js

### modules
### classes
### namespaces
## src/webgl/interaction.js
src/webgl/interaction.js

### modules
### classes
### namespaces
## src/webgl/light.js
src/webgl/light.js

### modules
### classes
### namespaces
## src/webgl/loading.js
src/webgl/loading.js

### modules
### classes
### namespaces
## src/webgl/material.js
src/webgl/material.js

### modules
### classes
### namespaces
## src/webgl/p5.Camera.js
src/webgl/p5.Camera.js

### modules
### classes
### namespaces
## src/webgl/p5.DataArray.js
src/webgl/p5.DataArray.js

### modules
### classes
### namespaces
## src/webgl/p5.Framebuffer.js
src/webgl/p5.Framebuffer.js

### modules
### classes
### namespaces
## src/webgl/p5.Geometry.js
src/webgl/p5.Geometry.js

### modules
### classes
### namespaces
## src/webgl/p5.Matrix.js
src/webgl/p5.Matrix.js

### modules
### classes
### namespaces
## src/webgl/p5.Quat.js
src/webgl/p5.Quat.js

### modules
### classes
### namespaces
## src/webgl/p5.RenderBuffer.js
src/webgl/p5.RenderBuffer.js

### modules
### classes
### namespaces
## src/webgl/p5.RendererGL.Immediate.js
src/webgl/p5.RendererGL.Immediate.js

### modules
### classes
### namespaces
## src/webgl/p5.RendererGL.Retained.js
src/webgl/p5.RendererGL.Retained.js

### modules
### classes
### namespaces
## src/webgl/p5.RendererGL.js
src/webgl/p5.RendererGL.js

### modules
### classes
### namespaces
## src/webgl/p5.Shader.js
src/webgl/p5.Shader.js

### modules
### classes
### namespaces
## src/webgl/p5.Texture.js
src/webgl/p5.Texture.js

### modules
### classes
### namespaces
## src/webgl/text.js
src/webgl/text.js

### modules
### classes
### namespaces
## lib/addons/p5.sound.js
lib/addons/p5.sound.js

### modules
### classes
### namespaces
## lib/addons/p5.sound.min.js
lib/addons/p5.sound.min.js

### modules
### classes
### namespaces
# modules
## Environment
Environment

### submodules
### elements
### classes
### namespaces
Environment

## Color
Color

### submodules
### elements
### classes
### namespaces
## Color Conversion
Color Conversion

### submodules
### elements
### classes
### namespaces
Color



## Creating & Reading
Creating & Reading

### submodules
### elements
### classes
### namespaces
Color



A class to describe a color.
Each `p5.Color` object stores the color mode and level maxes that were active during its construction. These values are used to interpret the arguments passed to the object's constructor. They also determine output formatting such as when saturation() is called.
Color is stored internally as an array of ideal RGBA values in floating point form, normalized from 0 to 1. These values are used to calculate the closest screen colors, which are RGBA levels from 0 to 255. Screen colors are sent to the renderer.
When different color representations are calculated, the results are cached for performance. These values are normalized, floating-point numbers.
Note: color() is the recommended way to create an instance of this class.

## Setting
Setting

### submodules
### elements
### classes
### namespaces
Color



## Shape
Shape

### submodules
### elements
### classes
### namespaces
## 2D Primitives
2D Primitives

### submodules
### elements
### classes
### namespaces
Shape



## Attributes
Attributes

### submodules
### elements
### classes
### namespaces
Typography



## Curves
Curves

### submodules
### elements
### classes
### namespaces
Shape



## Vertex
Vertex

### submodules
### elements
### classes
### namespaces
Shape



## Constants
Constants

### submodules
### elements
### classes
### namespaces
Constants

## Structure
Structure

### submodules
### elements
### classes
### namespaces
IO

## DOM
DOM

### submodules
### elements
### classes
### namespaces
DOM

The web is much more than just canvas and the DOM functionality makes it easy to interact with other HTML5 objects, including text, hyperlink, image, input, video, audio, and webcam. There is a set of creation methods, DOM manipulation methods, and an extended p5.Element that supports a range of HTML elements. See the  beyond the canvas tutorial for a full overview of how this addon works.
See tutorial: beyond the canvas for more info on how to use this library.

## Rendering
Rendering

### submodules
### elements
### classes
### namespaces
Rendering

module

A class to describe a drawing surface that's separate from the main canvas.
Each `p5.Graphics` object provides a dedicated drawing surface called a graphics buffer. Graphics buffers are helpful when drawing should happen offscreen. For example, separate scenes can be drawn offscreen and displayed only when needed.
`p5.Graphics` objects have nearly all the drawing features of the main canvas. For example, calling the method `myGraphics.circle(50, 50, 20)` draws to the graphics buffer. The resulting image can be displayed on the main canvas by passing the `p5.Graphics` object to the image() function, as in `image(myGraphics, 0, 0)`.
Note: createGraphics() is the recommended way to create an instance of this class.

## Foundation
Foundation

### submodules
### elements
### classes
### namespaces
Foundation

## Transform
Transform

### submodules
### elements
### classes
### namespaces
Transform

## Data
Data

### submodules
### elements
### classes
### namespaces
## LocalStorage
LocalStorage

### submodules
### elements
### classes
### namespaces
Data



## Dictionary
Dictionary

### submodules
### elements
### classes
### namespaces
Data



Base class for all p5.Dictionary types. Specifically typed Dictionary classes inherit from this class.

## Events
Events

### submodules
### elements
### classes
### namespaces
main

main

## Acceleration
Acceleration

### submodules
### elements
### classes
### namespaces
Events



main

main

## Keyboard
Keyboard

### submodules
### elements
### classes
### namespaces
Events



## Mouse
Mouse

### submodules
### elements
### classes
### namespaces
Events



## Touch
Touch

### submodules
### elements
### classes
### namespaces
Events



## Image
Image

### submodules
### elements
### classes
### namespaces
Image

A class to describe an image.
Images are rectangular grids of pixels that can be displayed and modified.
Existing images can be loaded by calling loadImage(). Blank images can be created by calling createImage(). `p5.Image` objects have methods for common tasks such as applying filters and modifying pixel values.

## Loading & Displaying
Loading & Displaying

### submodules
### elements
### classes
### namespaces
Typography



This module defines the p5.Font class and functions for drawing text to the display canvas.

## Pixels
Pixels

### submodules
### elements
### classes
### namespaces
Image



## IO
IO

### submodules
### elements
### classes
### namespaces
## Input
Input

### submodules
### elements
### classes
### namespaces
IO



A class to describe an XML object.
Each `p5.XML` object provides an easy way to interact with XML data. Extensible Markup Language (XML) is a standard format for sending data between applications. Like HTML, the XML format is based on tags and attributes, as in `<time units="s">1234</time>`.
Note: Use loadXML() to load external XML files.

## Output
Output

### submodules
### elements
### classes
### namespaces
IO



This is the p5 instance constructor.
A p5 instance holds all the properties and methods related to a p5 sketch. It expects an incoming sketch closure and it can also take an optional node parameter for attaching the generated p5 canvas to a node. The sketch closure takes the newly created p5 instance as its sole argument and may optionally set preload(), setup(), and/or draw() properties on it for running a sketch.
A p5 sketch can run in "global" or "instance" mode: "global" - all properties and methods are attached to the window "instance" - all properties and methods are bound to this p5 object

## Table
Table

### submodules
### elements
### classes
### namespaces
IO



Table objects store data with multiple rows and columns, much like in a traditional spreadsheet. Tables can be generated from scratch, dynamically, or using data from an existing file.

## Math
Math

### submodules
### elements
### classes
### namespaces
## Calculation
Calculation

### submodules
### elements
### classes
### namespaces
Math



## Vector
Vector

### submodules
### elements
### classes
### namespaces
Math



A class to describe a two or three-dimensional vector.
A vector can be thought of in different ways. In one view, a vector is like an arrow pointing in space. Vectors have both magnitude (length) and direction.
`p5.Vector` objects are often used to program motion because they simplify the math. For example, a moving ball has a position and a velocity. Position describes where the ball is in space. The ball's position vector extends from the origin to the ball's center. Velocity describes the ball's speed and the direction it's moving. If the ball is moving straight up, its velocity vector points straight up. Adding the ball's velocity vector to its position vector moves it, as in `pos.add(vel)`. Vector math relies on methods inside the `p5.Vector` class.
Note: createVector() is the recommended way to make an instance of this class.

## Noise
Noise

### submodules
### elements
### classes
### namespaces
Math



## Random
Random

### submodules
### elements
### classes
### namespaces
Math



## Trigonometry
Trigonometry

### submodules
### elements
### classes
### namespaces
Math



## Typography
Typography

### submodules
### elements
### classes
### namespaces
## Array Functions
Array Functions

### submodules
### elements
### classes
### namespaces
Data



## Conversion
Conversion

### submodules
### elements
### classes
### namespaces
Data



## String Functions
String Functions

### submodules
### elements
### classes
### namespaces
Data



## Time & Date
Time & Date

### submodules
### elements
### classes
### namespaces
IO



## 3D Primitives
3D Primitives

### submodules
### elements
### classes
### namespaces
Shape



A class to describe a 3D shape.
Each `p5.Geometry` object represents a 3D shape as a set of connected points called vertices. All 3D shapes are made by connecting vertices to form triangles that are stitched together. Each triangular patch on the geometry's surface is called a face. The geometry stores information about its vertices and faces for use with effects such as lighting and texture mapping.
The first parameter, `detailX`, is optional. If a number is passed, as in `new p5.Geometry(24)`, it sets the number of triangle subdivisions to use along the geometry's x-axis. By default, `detailX` is 1.
The second parameter, `detailY`, is also optional. If a number is passed, as in `new p5.Geometry(24, 16)`, it sets the number of triangle subdivisions to use along the geometry's y-axis. By default, `detailX` is 1.
The third parameter, `callback`, is also optional. If a function is passed, as in `new p5.Geometry(24, 16, createShape)`, it will be called once to add vertices to the new 3D shape.

## 3D
3D

### submodules
### elements
### classes
### namespaces
## Interaction
Interaction

### submodules
### elements
### classes
### namespaces
3D



## Lights
Lights

### submodules
### elements
### classes
### namespaces
3D



## 3D Models
3D Models

### submodules
### elements
### classes
### namespaces
Shape



## Material
Material

### submodules
### elements
### classes
### namespaces
3D



This module defines the p5.Shader class

## Camera
Camera

### submodules
### elements
### classes
### namespaces
3D



A class to describe a camera for viewing a 3D sketch.
Each `p5.Camera` object represents a camera that views a section of 3D space. It stores information about the camera’s position, orientation, and projection.
In WebGL mode, the default camera is a `p5.Camera` object that can be controlled with the camera(), perspective(), ortho(), and frustum() functions. Additional cameras can be created with createCamera() and activated with setCamera().
Note: `p5.Camera`’s methods operate in two coordinate systems:
  * The “world” coordinate system describes positions in terms of their relationship to the origin along the x-, y-, and z-axes. For example, calling `myCamera.setPosition()` places the camera in 3D space using "world" coordinates.
  * The "local" coordinate system describes positions from the camera's point of view: left-right, up-down, and forward-backward. For example, calling `myCamera.move()` moves the camera along its own axes.



## Quaternion
Quaternion

### submodules
### elements
### classes
### namespaces
Math



A class to describe a Quaternion for vector rotations in the p5js webgl renderer. Please refer the following link for details on the implementation https://danceswithcode.net/engineeringnotes/quaternions/quaternions.html

## p5.sound
p5.sound

### submodules
### elements
### classes
### namespaces
p5.sound

p5.sound extends p5 with Web Audio functionality including audio input, playback, analysis and synthesis. 
  * p5.SoundFile: Load and play sound files.
  * p5.Amplitude: Get the current volume of a sound.
  * p5.AudioIn: Get sound from an input source, typically a computer microphone.
  * p5.FFT: Analyze the frequency of sound. Returns results from the frequency spectrum or time domain (waveform).
  * p5.Oscillator: Generate Sine, Triangle, Square and Sawtooth waveforms. Base class of 
  * p5.Noise and p5.Pulse. 
  * p5.MonoSynth and p5.PolySynth: Play musical notes 
  * p5.Envelope: An Envelope is a series of fades over time. Often used to control an object's output gain level as an "ADSR Envelope" (Attack, Decay, Sustain, Release). Can also modulate other parameters.
  * p5.Delay: A delay effect with parameters for feedback, delayTime, and lowpass filter.
  * p5.Filter: Filter the frequency range of a sound. 
  * p5.Reverb: Add reverb to a sound by specifying duration and decay. 
  * p5.Convolver: Extends p5.Reverb to simulate the sound of real physical spaces through convolution.
  * p5.SoundRecorder: Record sound for playback / save the .wav file. 
  * p5.SoundLoop, p5.Phrase, p5.Part and p5.Score: Compose musical sequences. 
  * userStartAudio: Enable audio in a browser- and user-friendly way.
p5.sound is on GitHub. Download the latest version here.

main

main

# classes
## p5
p5

p5

IO

Output



This is the p5 instance constructor.
A p5 instance holds all the properties and methods related to a p5 sketch. It expects an incoming sketch closure and it can also take an optional node parameter for attaching the generated p5 canvas to a node. The sketch closure takes the newly created p5 instance as its sole argument and may optionally set preload(), setup(), and/or draw() properties on it for running a sketch.
A p5 sketch can run in "global" or "instance" mode: "global" - all properties and methods are attached to the window "instance" - all properties and methods are bound to this p5 object

sketch

a closure that can set optional preload(), setup(), and/or draw() properties on the given p5 instance

Function(p5)

node

element to attach canvas to

HTMLElement

### return
a p5 instance

P5

## p5.Color
p5.Color

p5.Color

Color

Creating & Reading



A class to describe a color.
Each `p5.Color` object stores the color mode and level maxes that were active during its construction. These values are used to interpret the arguments passed to the object's constructor. They also determine output formatting such as when saturation() is called.
Color is stored internally as an array of ideal RGBA values in floating point form, normalized from 0 to 1. These values are used to calculate the closest screen colors, which are RGBA levels from 0 to 255. Screen colors are sent to the renderer.
When different color representations are calculated, the results are cached for performance. These values are normalized, floating-point numbers.
Note: color() is the recommended way to create an instance of this class.

pInst

pointer to p5 instance.

P5

vals

an array containing the color values for red, green, blue and alpha channel or CSS color.

Number[]|String

## p5.Element
p5.Element

p5.Element

DOM

DOM



A class to describe an HTML element.
Sketches can use many elements. Common elements include the drawing canvas, buttons, sliders, webcam feeds, and so on.
All elements share the methods of the `p5.Element` class. They're created with functions such as createCanvas() and createButton().

elt

wrapped DOM element.

HTMLElement

pInst

pointer to p5 instance.

P5

` function setup() { createCanvas(100, 100); background(200); // Create a button element and // place it beneath the canvas. let btn = createButton('change'); btn.position(0, 100); // Call randomColor() when // the button is pressed. btn.mousePressed(randomColor); describe('A gray square with a button that says "change" beneath it. The square changes color when the user presses the button.'); } // Paint the background either // red, yellow, blue, or green. function randomColor() { let c = random(['red', 'yellow', 'blue', 'green']); background(c); } `

## p5.Graphics
p5.Graphics

p5.Graphics

Rendering

Rendering



A class to describe a drawing surface that's separate from the main canvas.
Each `p5.Graphics` object provides a dedicated drawing surface called a graphics buffer. Graphics buffers are helpful when drawing should happen offscreen. For example, separate scenes can be drawn offscreen and displayed only when needed.
`p5.Graphics` objects have nearly all the drawing features of the main canvas. For example, calling the method `myGraphics.circle(50, 50, 20)` draws to the graphics buffer. The resulting image can be displayed on the main canvas by passing the `p5.Graphics` object to the image() function, as in `image(myGraphics, 0, 0)`.
Note: createGraphics() is the recommended way to create an instance of this class.

p5.Element

width

width of the graphics buffer in pixels.

Number

height

height of the graphics buffer in pixels.

Number

renderer

renderer to use, either P2D or WEBGL.

Constant

pInst

sketch instance.

P5

canvas

existing `<canvas>` element to use.

HTMLCanvasElement

` let pg; function setup() { createCanvas(100, 100); // Create a p5.Graphics object. pg = createGraphics(50, 50); // Draw to the p5.Graphics object. pg.background(100); pg.circle(25, 25, 20); describe('A dark gray square with a white circle at its center drawn on a gray background.'); } function draw() { background(200); // Display the p5.Graphics object. image(pg, 25, 25); } `
` // Click the canvas to display the graphics buffer. let pg; function setup() { createCanvas(100, 100); // Create a p5.Graphics object. pg = createGraphics(50, 50); describe('A square appears on a gray background when the user presses the mouse. The square cycles between white and black.'); } function draw() { background(200); // Calculate the background color. let bg = frameCount % 255; // Draw to the p5.Graphics object. pg.background(bg); // Display the p5.Graphics object while // the user presses the mouse. if (mouseIsPressed === true) { image(pg, 25, 25); } } `

## p5.Renderer
p5.Renderer

p5.Renderer

Rendering

Rendering



Main graphics and rendering context, as well as the base API implementation for p5.js "core". To be used as the superclass for Renderer2D and Renderer3D classes, respectively.

p5.Element

elt

DOM node that is wrapped

HTMLElement

pInst

pointer to p5 instance

P5

isMainCanvas

whether we're using it as main canvas

Boolean

## p5.TypedDict
p5.TypedDict

p5.TypedDict

Data

Dictionary



Base class for all p5.Dictionary types. Specifically typed Dictionary classes inherit from this class.

## p5.StringDict
p5.StringDict

p5.StringDict

Data

Dictionary



A simple Dictionary class for Strings.

p5.TypedDict

## p5.NumberDict
p5.NumberDict

p5.NumberDict

Data

Dictionary



A simple Dictionary class for Numbers.

p5.TypedDict

## p5.MediaElement
p5.MediaElement

p5.MediaElement

DOM

DOM



A class to handle audio and video.
`p5.MediaElement` extends p5.Element with methods to handle audio and video. `p5.MediaElement` objects are created by calling createVideo, createAudio, and createCapture.

elt

DOM node that is wrapped

String

p5.Element

` let capture; function setup() { createCanvas(100, 100); // Create a p5.MediaElement using createCapture(). capture = createCapture(VIDEO); capture.hide(); describe('A webcam feed with inverted colors.'); } function draw() { // Display the video stream and invert the colors. image(capture, 0, 0, width, width * capture.height / capture.width); filter(INVERT); } `

## p5.File
p5.File

p5.File

DOM

DOM



A class to describe a file.
`p5.File` objects are used by myElement.drop() and created by createFileInput.

file

wrapped file.

File

` // Use the file input to load a // file and display its info. function setup() { createCanvas(100, 100); background(200); // Create a file input and place it beneath the canvas. // Call displayInfo() when the file loads. let input = createFileInput(displayInfo); input.position(0, 100); describe('A gray square with a file input beneath it. If the user loads a file, its info is written in black.'); } // Display the p5.File's info once it loads. function displayInfo(file) { background(200); // Display the p5.File's name. text(file.name, 10, 10, 80, 40); // Display the p5.File's type and subtype. text(`${file.type}/${file.subtype}`, 10, 70); // Display the p5.File's size in bytes. text(file.size, 10, 90); } `
` // Use the file input to select an image to // load and display. let img; function setup() { createCanvas(100, 100); // Create a file input and place it beneath the canvas. // Call handleImage() when the file image loads. let input = createFileInput(handleImage); input.position(0, 100); describe('A gray square with a file input beneath it. If the user selects an image file to load, it is displayed on the square.'); } function draw() { background(200); // Draw the image if it's ready. if (img) { image(img, 0, 0, width, height); } } // Use the p5.File's data once it loads. function handleImage(file) { // Check the p5.File's type. if (file.type === 'image') { // Create an image using using the p5.File's data. img = createImg(file.data, ''); // Hide the image element so it doesn't appear twice. img.hide(); } else { img = null; } } `

## p5.Image
p5.Image

p5.Image

Image

Image



A class to describe an image.
Images are rectangular grids of pixels that can be displayed and modified.
Existing images can be loaded by calling loadImage(). Blank images can be created by calling createImage(). `p5.Image` objects have methods for common tasks such as applying filters and modifying pixel values.

` let img; // Load the image. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0); describe('An image of a brick wall.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); // Apply the GRAY filter. img.filter(GRAY); // Display the image. image(img, 0, 0); describe('A grayscale image of a brick wall.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create a p5.Image object. let img = createImage(66, 66); // Load the image's pixels. img.loadPixels(); // Set the pixels to black. for (let x = 0; x < img.width; x += 1) { for (let y = 0; y < img.height; y += 1) { img.set(x, y, 0); } } // Update the image. img.updatePixels(); // Display the image. image(img, 17, 17); describe('A black square drawn in the middle of a gray square.'); } `

width



Number

height



Number

## p5.PrintWriter
p5.PrintWriter

p5.PrintWriter

IO

Output



A class to describe a print stream.
Each `p5.PrintWriter` object provides a way to save a sequence of text data, called the print stream, to the user's computer. It's a low-level object that enables precise control of text output. Functions such as saveStrings() and saveJSON() are easier to use for simple file saving.
Note: createWriter() is the recommended way to make an instance of this class.

filename

name of the file to create.

String

extension

format to use for the file.

String

` function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(12); // Display instructions. text('Double-click to save', 5, 50, 90); describe('The text "Double-click to save" written in black on a gray background.'); } // Save the file when the user double-clicks. function doubleClicked() { // Create a p5.PrintWriter object. let myWriter = createWriter('xo.txt'); // Add some lines to the print stream. myWriter.print('XOO'); myWriter.print('OXO'); myWriter.print('OOX'); // Save the file and close the print stream. myWriter.close(); } `

## p5.Table
p5.Table

p5.Table

IO

Table



Table objects store data with multiple rows and columns, much like in a traditional spreadsheet. Tables can be generated from scratch, dynamically, or using data from an existing file.

rows

An array of p5.TableRow objects

p5.TableRow[]

## p5.TableRow
p5.TableRow

p5.TableRow

IO

Table



A TableRow object represents a single row of data values, stored in columns, from a table.
A Table Row contains both an ordered array, and an unordered JSON object.

str

optional: populate the row with a string of values, separated by the separator

String

separator

comma separated values (csv) by default

String

## p5.XML
p5.XML

p5.XML

IO

Input



A class to describe an XML object.
Each `p5.XML` object provides an easy way to interact with XML data. Extensible Markup Language (XML) is a standard format for sending data between applications. Like HTML, the XML format is based on tags and attributes, as in `<time units="s">1234</time>`.
Note: Use loadXML() to load external XML files.

` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Get an array with all mammal tags. let mammals = myXML.getChildren('mammal'); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(14); // Iterate over the mammals array. for (let i = 0; i < mammals.length; i += 1) { // Calculate the y-coordinate. let y = (i + 1) * 25; // Get the mammal's common name. let name = mammals[i].getContent(); // Display the mammal's name. text(name, 20, y); } describe( 'The words "Goat", "Leopard", and "Zebra" written on three separate lines. The text is black on a gray background.' ); } `

## p5.Vector
p5.Vector

p5.Vector

Math

Vector



A class to describe a two or three-dimensional vector.
A vector can be thought of in different ways. In one view, a vector is like an arrow pointing in space. Vectors have both magnitude (length) and direction.
`p5.Vector` objects are often used to program motion because they simplify the math. For example, a moving ball has a position and a velocity. Position describes where the ball is in space. The ball's position vector extends from the origin to the ball's center. Velocity describes the ball's speed and the direction it's moving. If the ball is moving straight up, its velocity vector points straight up. Adding the ball's velocity vector to its position vector moves it, as in `pos.add(vel)`. Vector math relies on methods inside the `p5.Vector` class.
Note: createVector() is the recommended way to make an instance of this class.

x

x component of the vector.

Number

y

y component of the vector.

Number

z

z component of the vector.

Number

` function setup() { createCanvas(100, 100); background(200); // Create p5.Vector objects. let p1 = createVector(25, 25); let p2 = createVector(75, 75); // Style the points. strokeWeight(5); // Draw the first point using a p5.Vector. point(p1); // Draw the second point using a p5.Vector's components. point(p2.x, p2.y); describe('Two black dots on a gray square, one at the top left and the other at the bottom right.'); } `
` let pos; let vel; function setup() { createCanvas(100, 100); // Create p5.Vector objects. pos = createVector(50, 100); vel = createVector(0, -1); describe('A black dot moves from bottom to top on a gray square. The dot reappears at the bottom when it reaches the top.'); } function draw() { background(200); // Add velocity to position. pos.add(vel); // If the dot reaches the top of the canvas, // restart from the bottom. if (pos.y < 0) { pos.y = 100; } // Draw the dot. strokeWeight(5); point(pos); } `

## p5.Font
p5.Font

p5.Font

Typography

Loading & Displaying



A class to describe fonts.

pInst

pointer to p5 instance.

P5

` let font; function preload() { // Creates a p5.Font object. font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100); // Style the text. fill('deeppink'); textFont(font); textSize(36); // Display the text. text('p5*js', 10, 50); describe('The text "p5*js" written in pink on a gray background.'); } `

## p5.Camera
p5.Camera

p5.Camera

3D

Camera



A class to describe a camera for viewing a 3D sketch.
Each `p5.Camera` object represents a camera that views a section of 3D space. It stores information about the camera’s position, orientation, and projection.
In WebGL mode, the default camera is a `p5.Camera` object that can be controlled with the camera(), perspective(), ortho(), and frustum() functions. Additional cameras can be created with createCamera() and activated with setCamera().
Note: `p5.Camera`’s methods operate in two coordinate systems:
    * The “world” coordinate system describes positions in terms of their relationship to the origin along the x-, y-, and z-axes. For example, calling `myCamera.setPosition()` places the camera in 3D space using "world" coordinates.
    * The "local" coordinate system describes positions from the camera's point of view: left-right, up-down, and forward-backward. For example, calling `myCamera.move()` moves the camera along its own axes.

rendererGL

instance of WebGL renderer

RendererGL

` let cam; let delta = 0.001; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Camera object. cam = createCamera(); // Place the camera at the top-center. cam.setPosition(0, -400, 800); // Point the camera at the origin. cam.lookAt(0, 0, 0); describe( 'A white cube on a gray background. The cube goes in and out of view as the camera pans left and right.' ); } function draw() { background(200); // Turn the camera left and right, called "panning". cam.pan(delta); // Switch directions every 120 frames. if (frameCount % 120 === 0) { delta *= -1; } // Draw the box. box(); } `
` // Double-click to toggle between cameras. let cam1; let cam2; let isDefaultCamera = true; function setup() { createCanvas(100, 100, WEBGL); // Create the first camera. // Keep its default settings. cam1 = createCamera(); // Create the second camera. // Place it at the top-left. // Point it at the origin. cam2 = createCamera(); cam2.setPosition(400, -400, 800); cam2.lookAt(0, 0, 0); // Set the current camera to cam1. setCamera(cam1); describe( 'A white cube on a gray background. The camera toggles between frontal and aerial views when the user double-clicks.' ); } function draw() { background(200); // Draw the box. box(); } // Toggle the current camera when the user double-clicks. function doubleClicked() { if (isDefaultCamera === true) { setCamera(cam2); isDefaultCamera = false; } else { setCamera(cam1); isDefaultCamera = true; } } `

## p5.Framebuffer
p5.Framebuffer

p5.Framebuffer

Rendering



A class to describe a high-performance drawing surface for textures.
Each `p5.Framebuffer` object provides a dedicated drawing surface called a framebuffer. They're similar to p5.Graphics objects but can run much faster. Performance is improved because the framebuffer shares the same WebGL context as the canvas used to create it.
`p5.Framebuffer` objects have all the drawing features of the main canvas. Drawing instructions meant for the framebuffer must be placed between calls to myBuffer.begin() and myBuffer.end(). The resulting image can be applied as a texture by passing the `p5.Framebuffer` object to the texture() function, as in `texture(myBuffer)`. It can also be displayed on the main canvas by passing it to the image() function, as in `image(myBuffer, 0, 0)`.
Note: createFramebuffer() is the recommended way to create an instance of this class.

target

sketch instance or p5.Graphics object.

p5.Graphics|p5

settings

configuration options.

Object

## p5.Geometry
p5.Geometry

p5.Geometry

Shape

3D Primitives



A class to describe a 3D shape.
Each `p5.Geometry` object represents a 3D shape as a set of connected points called vertices. All 3D shapes are made by connecting vertices to form triangles that are stitched together. Each triangular patch on the geometry's surface is called a face. The geometry stores information about its vertices and faces for use with effects such as lighting and texture mapping.
The first parameter, `detailX`, is optional. If a number is passed, as in `new p5.Geometry(24)`, it sets the number of triangle subdivisions to use along the geometry's x-axis. By default, `detailX` is 1.
The second parameter, `detailY`, is also optional. If a number is passed, as in `new p5.Geometry(24, 16)`, it sets the number of triangle subdivisions to use along the geometry's y-axis. By default, `detailX` is 1.
The third parameter, `callback`, is also optional. If a function is passed, as in `new p5.Geometry(24, 16, createShape)`, it will be called once to add vertices to the new 3D shape.

detailX

number of vertices along the x-axis.

Integer

detailY

number of vertices along the y-axis.

Integer

callback

function to call once the geometry is created.

Function

` // Click and drag the mouse to view the scene from different angles. let myGeometry; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Geometry object. myGeometry = new p5.Geometry(); // Create p5.Vector objects to position the vertices. let v0 = createVector(-40, 0, 0); let v1 = createVector(0, -40, 0); let v2 = createVector(40, 0, 0); // Add the vertices to the p5.Geometry object's vertices array. myGeometry.vertices.push(v0, v1, v2); describe('A white triangle drawn on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the p5.Geometry object. model(myGeometry); } `
` // Click and drag the mouse to view the scene from different angles. let myGeometry; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Geometry object using a callback function. myGeometry = new p5.Geometry(1, 1, createShape); describe('A white triangle drawn on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the p5.Geometry object. model(myGeometry); } function createShape() { // Create p5.Vector objects to position the vertices. let v0 = createVector(-40, 0, 0); let v1 = createVector(0, -40, 0); let v2 = createVector(40, 0, 0); // "this" refers to the p5.Geometry object being created. // Add the vertices to the p5.Geometry object's vertices array. this.vertices.push(v0, v1, v2); // Add an array to list which vertices belong to the face. // Vertices are listed in clockwise "winding" order from // left to top to right. this.faces.push([0, 1, 2]); } `
` // Click and drag the mouse to view the scene from different angles. let myGeometry; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Geometry object using a callback function. myGeometry = new p5.Geometry(1, 1, createShape); describe('A white triangle drawn on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the p5.Geometry object. model(myGeometry); } function createShape() { // Create p5.Vector objects to position the vertices. let v0 = createVector(-40, 0, 0); let v1 = createVector(0, -40, 0); let v2 = createVector(40, 0, 0); // "this" refers to the p5.Geometry object being created. // Add the vertices to the p5.Geometry object's vertices array. this.vertices.push(v0, v1, v2); // Add an array to list which vertices belong to the face. // Vertices are listed in clockwise "winding" order from // left to top to right. this.faces.push([0, 1, 2]); // Compute the surface normals to help with lighting. this.computeNormals(); } `
` // Click and drag the mouse to view the scene from different angles. // Adapted from Paul Wheeler's wonderful p5.Geometry tutorial. // https://www.paulwheeler.us/articles/custom-3d-geometry-in-p5js/ // CC-BY-SA 4.0 let myGeometry; function setup() { createCanvas(100, 100, WEBGL); // Create the p5.Geometry object. // Set detailX to 48 and detailY to 2. // >>> try changing them. myGeometry = new p5.Geometry(48, 2, createShape); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Style the p5.Geometry object. strokeWeight(0.2); // Draw the p5.Geometry object. model(myGeometry); } function createShape() { // "this" refers to the p5.Geometry object being created. // Define the Möbius strip with a few parameters. let spread = 0.1; let radius = 30; let stripWidth = 15; let xInterval = 4 * PI / this.detailX; let yOffset = -stripWidth / 2; let yInterval = stripWidth / this.detailY; for (let j = 0; j <= this.detailY; j += 1) { // Calculate the "vertical" point along the strip. let v = yOffset + yInterval * j; for (let i = 0; i <= this.detailX; i += 1) { // Calculate the angle of rotation around the strip. let u = i * xInterval; // Calculate the coordinates of the vertex. let x = (radius + v * cos(u / 2)) * cos(u) - sin(u / 2) * 2 * spread; let y = (radius + v * cos(u / 2)) * sin(u); if (u < TWO_PI) { y += sin(u) * spread; } else { y -= sin(u) * spread; } let z = v * sin(u / 2) + sin(u / 4) * 4 * spread; // Create a p5.Vector object to position the vertex. let vert = createVector(x, y, z); // Add the vertex to the p5.Geometry object's vertices array. this.vertices.push(vert); } } // Compute the faces array. this.computeFaces(); // Compute the surface normals to help with lighting. this.computeNormals(); } `

## p5.Shader
p5.Shader

p5.Shader

3D

Material



A class to describe a shader program.
Each `p5.Shader` object contains a shader program that runs on the graphics processing unit (GPU). Shaders can process many pixels or vertices at the same time, making them fast for many graphics tasks. They’re written in a language called GLSL and run along with the rest of the code in a sketch.
A shader program consists of two files, a vertex shader and a fragment shader. The vertex shader affects where 3D geometry is drawn on the screen and the fragment shader affects color. Once the `p5.Shader` object is created, it can be used with the shader() function, as in `shader(myShader)`.
A shader can optionally describe hooks, which are functions in GLSL that users may choose to provide to customize the behavior of the shader. For the vertex or the fragment shader, users can pass in an object where each key is the type and name of a hook function, and each value is a string with the parameter list and default implementation of the hook. For example, to let users optionally run code at the start of the vertex shader, the options object could include:
    {
      vertex: {
        'void beforeVertex': '() {}'
      }
    }
    
Then, in your vertex shader source, you can run a hook by calling a function with the same name prefixed by `HOOK_`:
    void main() {
      HOOK_beforeVertex();
      // Add the rest of your shader code here!
    }
    
Note: createShader(), createFilterShader(), and loadShader() are the recommended ways to create an instance of this class.

renderer

WebGL context for this shader.

p5.RendererGL

vertSrc

source code for the vertex shader program.

String

fragSrc

source code for the fragment shader program.

String

options

An optional object describing how this shader can be augmented with hooks. It can include:
    * `vertex`: An object describing the available vertex shader hooks.
    * `fragment`: An object describing the available frament shader hooks.

Object

` // Note: A "uniform" is a global variable within a shader program. // Create a string with the vertex shader program. // The vertex shader is called for each vertex. let vertSrc = ` precision highp float; uniform mat4 uModelViewMatrix; uniform mat4 uProjectionMatrix; attribute vec3 aPosition; attribute vec2 aTexCoord; varying vec2 vTexCoord; void main() { vTexCoord = aTexCoord; vec4 positionVec4 = vec4(aPosition, 1.0); gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4; } `; // Create a string with the fragment shader program. // The fragment shader is called for each pixel. let fragSrc = ` precision highp float; void main() { // Set each pixel's RGBA value to yellow. gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0); } `; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Shader object. let myShader = createShader(vertSrc, fragSrc); // Apply the p5.Shader object. shader(myShader); // Style the drawing surface. noStroke(); // Add a plane as a drawing surface. plane(100, 100); describe('A yellow square.'); } `
` // Note: A "uniform" is a global variable within a shader program. let mandelbrot; // Load the shader and create a p5.Shader object. function preload() { mandelbrot = loadShader('assets/shader.vert', 'assets/shader.frag'); } function setup() { createCanvas(100, 100, WEBGL); // Use the p5.Shader object. shader(mandelbrot); // Set the shader uniform p to an array. mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]); describe('A fractal image zooms in and out of focus.'); } function draw() { // Set the shader uniform r to a value that oscillates between 0 and 2. mandelbrot.setUniform('r', sin(frameCount * 0.01) + 1); // Add a quad as a display surface for the shader. quad(-1, -1, 1, -1, 1, 1, -1, 1); } `

## p5.sound
p5.sound

p5.sound

p5.sound

p5.sound



## p5.SoundFile
p5.SoundFile

p5.SoundFile

p5.sound

p5.sound



SoundFile object with a path to a file.
The p5.SoundFile may not be available immediately because it loads the file information asynchronously.
To do something with the sound as soon as it loads pass the name of a function as the second parameter.
Only one file path is required. However, audio file formats (i.e. mp3, ogg, wav and m4a/aac) are not supported by all web browsers. If you want to ensure compatability, instead of a single file path, you may include an Array of filepaths, and the browser will choose a format that works.

path

path to a sound file (String). Optionally, you may include multiple file formats in an array. Alternately, accepts an object from the HTML5 File API, or a p5.File.

String|Array

successCallback

Name of a function to call once file loads

Function

errorCallback

Name of a function to call if file fails to load. This function will receive an error or XMLHttpRequest object with information about what went wrong.

Function

whileLoadingCallback

Name of a function to call while file is loading. That function will receive progress of the request to load the sound file (between 0 and 1) as its first parameter. This progress does not account for the additional time needed to decode the audio data.

Function

` let mySound; function preload() { soundFormats('mp3', 'ogg'); mySound = loadSound('assets/doorbell'); } function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(canvasPressed); background(220); text('tap here to play', 10, 20); } function canvasPressed() { // playing a sound file on a user gesture // is equivalent to `userStartAudio()` mySound.play(); } `

## p5.Amplitude
p5.Amplitude

p5.Amplitude

p5.sound

p5.sound



Amplitude measures volume between 0.0 and 1.0. Listens to all p5sound by default, or use setInput() to listen to a specific sound source. Accepts an optional smoothing value, which defaults to 0.

smoothing

between 0.0 and .999 to smooth amplitude readings (defaults to 0)

Number

` let sound, amplitude; function preload(){ sound = loadSound('assets/beat.mp3'); } function setup() { let cnv = createCanvas(100,100); cnv.mouseClicked(togglePlay); amplitude = new p5.Amplitude(); } function draw() { background(220); text('tap to play', 20, 20); let level = amplitude.getLevel(); let size = map(level, 0, 1, 0, 200); ellipse(width/2, height/2, size, size); } function togglePlay() { if (sound.isPlaying() ){ sound.pause(); } else { sound.loop(); amplitude = new p5.Amplitude(); amplitude.setInput(sound); } } `

## p5.FFT
p5.FFT

p5.FFT

p5.sound

p5.sound



FFT (Fast Fourier Transform) is an analysis algorithm that isolates individual  audio frequencies within a waveform.
Once instantiated, a p5.FFT object can return an array based on two types of analyses:   
• `FFT.waveform()` computes amplitude values along the time domain. The array indices correspond to samples across a brief moment in time. Each value represents amplitude of the waveform at that sample of time.  
• `FFT.analyze() ` computes amplitude values along the frequency domain. The array indices correspond to frequencies (i.e. pitches), from the lowest to the highest that humans can hear. Each value represents amplitude at that slice of the frequency spectrum. Use with `getEnergy()` to measure amplitude at specific frequencies, or within a range of frequencies. 
FFT analyzes a very short snapshot of sound called a sample buffer. It returns an array of amplitude measurements, referred to as `bins`. The array is 1024 bins long by default. You can change the bin array length, but it must be a power of 2 between 16 and 1024 in order for the FFT algorithm to function correctly. The actual size of the FFT buffer is twice the number of bins, so given a standard sample rate, the buffer is 2048/44100 seconds long.

smoothing

Smooth results of Freq Spectrum. 0.0 < smoothing < 1.0. Defaults to 0.8.

Number

bins

Length of resulting array. Must be a power of two between 16 and 1024. Defaults to 1024.

Number

` function preload(){ sound = loadSound('assets/Damscray_DancingTiger.mp3'); } function setup(){ let cnv = createCanvas(100,100); cnv.mouseClicked(togglePlay); fft = new p5.FFT(); sound.amp(0.2); } function draw(){ background(220); let spectrum = fft.analyze(); noStroke(); fill(255, 0, 255); for (let i = 0; i< spectrum.length; i++){ let x = map(i, 0, spectrum.length, 0, width); let h = -height + map(spectrum[i], 0, 255, height, 0); rect(x, height, width / spectrum.length, h ) } let waveform = fft.waveform(); noFill(); beginShape(); stroke(20); for (let i = 0; i < waveform.length; i++){ let x = map(i, 0, waveform.length, 0, width); let y = map( waveform[i], -1, 1, 0, height); vertex(x,y); } endShape(); text('tap to play', 20, 20); } function togglePlay() { if (sound.isPlaying()) { sound.pause(); } else { sound.loop(); } } `

## p5.Oscillator
p5.Oscillator

p5.Oscillator

p5.sound

p5.sound



Creates a signal that oscillates between -1.0 and 1.0. By default, the oscillation takes the form of a sinusoidal shape ('sine'). Additional types include 'triangle', 'sawtooth' and 'square'. The frequency defaults to 440 oscillations per second (440Hz, equal to the pitch of an 'A' note).
Set the type of oscillation with setType(), or by instantiating a specific oscillator: p5.SinOsc, p5.TriOsc, p5.SqrOsc, or p5.SawOsc. 

freq

frequency defaults to 440Hz

Number

type

type of oscillator. Options: 'sine' (default), 'triangle', 'sawtooth', 'square'

String

` let osc, playing, freq, amp; function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(playOscillator); osc = new p5.Oscillator('sine'); } function draw() { background(220) freq = constrain(map(mouseX, 0, width, 100, 500), 100, 500); amp = constrain(map(mouseY, height, 0, 0, 1), 0, 1); text('tap to play', 20, 20); text('freq: ' + freq, 20, 40); text('amp: ' + amp, 20, 60); if (playing) { // smooth the transitions by 0.1 seconds osc.freq(freq, 0.1); osc.amp(amp, 0.1); } } function playOscillator() { // starting an oscillator on a user gesture will enable audio // in browsers that have a strict autoplay policy. // See also: userStartAudio(); osc.start(); playing = true; } function mouseReleased() { // ramp amplitude to 0 over 0.5 seconds osc.amp(0, 0.5); playing = false; } `

## p5.SinOsc
p5.SinOsc

p5.SinOsc

p5.sound

p5.sound



Constructor: `new p5.SinOsc()`. This creates a Sine Wave Oscillator and is equivalent to ` new p5.Oscillator('sine') ` or creating a p5.Oscillator and then calling its method `setType('sine')`. See p5.Oscillator for methods.

p5.Oscillator

freq

Set the frequency

Number

## p5.TriOsc
p5.TriOsc

p5.TriOsc

p5.sound

p5.sound



Constructor: `new p5.TriOsc()`. This creates a Triangle Wave Oscillator and is equivalent to `new p5.Oscillator('triangle') ` or creating a p5.Oscillator and then calling its method `setType('triangle')`. See p5.Oscillator for methods.

p5.Oscillator

freq

Set the frequency

Number

## p5.SawOsc
p5.SawOsc

p5.SawOsc

p5.sound

p5.sound



Constructor: `new p5.SawOsc()`. This creates a SawTooth Wave Oscillator and is equivalent to ` new p5.Oscillator('sawtooth') ` or creating a p5.Oscillator and then calling its method `setType('sawtooth')`. See p5.Oscillator for methods.

p5.Oscillator

freq

Set the frequency

Number

## p5.SqrOsc
p5.SqrOsc

p5.SqrOsc

p5.sound

p5.sound



Constructor: `new p5.SqrOsc()`. This creates a Square Wave Oscillator and is equivalent to ` new p5.Oscillator('square') ` or creating a p5.Oscillator and then calling its method `setType('square')`. See p5.Oscillator for methods.

p5.Oscillator

freq

Set the frequency

Number

## p5.Envelope
p5.Envelope

p5.Envelope

p5.sound

p5.sound



Envelopes are pre-defined amplitude distribution over time. Typically, envelopes are used to control the output volume of an object, a series of fades referred to as Attack, Decay, Sustain and Release ( ADSR ). Envelopes can also control other Web Audio Parameters—for example, a p5.Envelope can control an Oscillator's frequency like this: `osc.freq(env)`.
Use `setRange` to change the attack/release level. Use `setADSR` to change attackTime, decayTime, sustainPercent and releaseTime.
Use the `play` method to play the entire envelope, the `ramp` method for a pingable trigger, or `triggerAttack`/ `triggerRelease` to trigger noteOn/noteOff.

` let t1 = 0.1; // attack time in seconds let l1 = 0.7; // attack level 0.0 to 1.0 let t2 = 0.3; // decay time in seconds let l2 = 0.1; // decay level 0.0 to 1.0 let env; let triOsc; function setup() { let cnv = createCanvas(100, 100); background(220); text('tap to play', 20, 20); cnv.mousePressed(playSound); env = new p5.Envelope(t1, l1, t2, l2); triOsc = new p5.Oscillator('triangle'); } function playSound() { // starting the oscillator ensures that audio is enabled. triOsc.start(); env.play(triOsc); } `

## p5.Noise
p5.Noise

p5.Noise

p5.sound

p5.sound



Noise is a type of oscillator that generates a buffer with random values.

p5.Oscillator

type

Type of noise can be 'white' (default), 'brown' or 'pink'.

String

## p5.Pulse
p5.Pulse

p5.Pulse

p5.sound

p5.sound



Creates a Pulse object, an oscillator that implements Pulse Width Modulation. The pulse is created with two oscillators. Accepts a parameter for frequency, and to set the width between the pulses. See  `p5.Oscillator` for a full list of methods.

p5.Oscillator

freq

Frequency in oscillations per second (Hz)

Number

w

Width between the pulses (0 to 1.0, defaults to 0)

Number

` let pulse; function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(startPulse); background(220); pulse = new p5.Pulse(); pulse.amp(0.5); pulse.freq(220); } function startPulse() { pulse.start(); pulse.amp(0.5, 0.02); } function mouseReleased() { pulse.amp(0, 0.2); } function draw() { background(220); text('tap to play', 5, 20, width - 20); let w = map(mouseX, 0, width, 0, 1); w = constrain(w, 0, 1); pulse.width(w); text('pulse width: ' + w, 5, height - 20); } `

## p5.AudioIn
p5.AudioIn

p5.AudioIn

p5.sound

p5.sound



Get audio from an input, i.e. your computer's microphone.
Turn the mic on/off with the start() and stop() methods. When the mic is on, its volume can be measured with getLevel or by connecting an FFT object.
If you want to hear the AudioIn, use the .connect() method. AudioIn does not connect to p5.sound output by default to prevent feedback.
Note: This uses the getUserMedia/ Stream API, which is not supported by certain browsers. Access in Chrome browser is limited to localhost and https, but access over http may be limited.

errorCallback

A function to call if there is an error accessing the AudioIn. For example, Safari and iOS devices do not currently allow microphone access.

Function

` let mic; function setup(){ let cnv = createCanvas(100, 100); cnv.mousePressed(userStartAudio); textAlign(CENTER); mic = new p5.AudioIn(); mic.start(); } function draw(){ background(0); fill(255); text('tap to start', width/2, 20); micLevel = mic.getLevel(); let y = height - micLevel * height; ellipse(width/2, y, 10, 10); } `

## p5.Effect
p5.Effect

p5.Effect

p5.sound

p5.sound



Effect is a base class for audio effects in p5.   
This module handles the nodes and methods that are common and useful for current and future effects.
This class is extended by p5.Distortion, p5.Compressor, p5.Delay, p5.Filter, p5.Reverb.

ac

Reference to the audio context of the p5 object

Object

input

Gain Node effect wrapper

AudioNode

output

Gain Node effect wrapper

AudioNode

_drywet

Tone.JS CrossFade node (defaults to value: 1)

Object

wet

Effects that extend this class should connect to the wet signal to this gain node, so that dry and wet signals are mixed properly.

AudioNode

## p5.Filter
p5.Filter

p5.Filter

p5.sound

p5.sound



A p5.Filter uses a Web Audio Biquad Filter to filter the frequency response of an input source. Subclasses include:
`p5.LowPass`: Allows frequencies below the cutoff frequency to pass through, and attenuates frequencies above the cutoff.  
`p5.HighPass`: The opposite of a lowpass filter.   
`p5.BandPass`: Allows a range of frequencies to pass through and attenuates the frequencies below and above this frequency range.  

The `.res()` method controls either width of the bandpass, or resonance of the low/highpass cutoff frequency.
This class extends p5.Effect. Methods amp(), chain(), drywet(), connect(), and disconnect() are available.

p5.Effect

type

'lowpass' (default), 'highpass', 'bandpass'

String

` let fft, noise, filter; function setup() { let cnv = createCanvas(100,100); cnv.mousePressed(makeNoise); fill(255, 0, 255); filter = new p5.BandPass(); noise = new p5.Noise(); noise.disconnect(); noise.connect(filter); fft = new p5.FFT(); } function draw() { background(220); // set the BandPass frequency based on mouseX let freq = map(mouseX, 0, width, 20, 10000); freq = constrain(freq, 0, 22050); filter.freq(freq); // give the filter a narrow band (lower res = wider bandpass) filter.res(50); // draw filtered spectrum let spectrum = fft.analyze(); noStroke(); for (let i = 0; i < spectrum.length; i++) { let x = map(i, 0, spectrum.length, 0, width); let h = -height + map(spectrum[i], 0, 255, height, 0); rect(x, height, width/spectrum.length, h); } if (!noise.started) { text('tap here and drag to change frequency', 10, 20, width - 20); } else { text('Frequency: ' + round(freq)+'Hz', 20, 20, width - 20); } } function makeNoise() { // see also: `userStartAudio()` noise.start(); noise.amp(0.5, 0.2); } function mouseReleased() { noise.amp(0, 0.2); } `

## p5.LowPass
p5.LowPass

p5.LowPass

p5.sound

p5.sound



Constructor: `new p5.LowPass()` Filter. This is the same as creating a p5.Filter and then calling its method `setType('lowpass')`. See p5.Filter for methods.

p5.Filter

## p5.HighPass
p5.HighPass

p5.HighPass

p5.sound

p5.sound



Constructor: `new p5.HighPass()` Filter. This is the same as creating a p5.Filter and then calling its method `setType('highpass')`. See p5.Filter for methods.

p5.Filter

## p5.BandPass
p5.BandPass

p5.BandPass

p5.sound

p5.sound



Constructor: `new p5.BandPass()` Filter. This is the same as creating a p5.Filter and then calling its method `setType('bandpass')`. See p5.Filter for methods.

p5.Filter

## p5.EQ
p5.EQ

p5.EQ

p5.sound

p5.sound



p5.EQ is an audio effect that performs the function of a multiband audio equalizer. Equalization is used to adjust the balance of frequency compoenents of an audio signal. This process is commonly used in sound production and recording to change the waveform before it reaches a sound output device. EQ can also be used as an audio effect to create interesting distortions by filtering out parts of the spectrum. p5.EQ is built using a chain of Web Audio Biquad Filter Nodes and can be instantiated with 3 or 8 bands. Bands can be added or removed from the EQ by directly modifying p5.EQ.bands (the array that stores filters).
This class extends p5.Effect. Methods amp(), chain(), drywet(), connect(), and disconnect() are available.

p5.Effect

_eqsize

Constructor will accept 3 or 8, defaults to 3

Number

### return
p5.EQ object

Object

` let eq, soundFile let eqBandIndex = 0; let eqBandNames = ['lows', 'mids', 'highs']; function preload() { soundFormats('mp3', 'ogg'); soundFile = loadSound('assets/beat'); } function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(toggleSound); eq = new p5.EQ(eqBandNames.length); soundFile.disconnect(); eq.process(soundFile); } function draw() { background(30); noStroke(); fill(255); textAlign(CENTER); text('filtering ', 50, 25); fill(255, 40, 255); textSize(26); text(eqBandNames[eqBandIndex], 50, 55); fill(255); textSize(9); if (!soundFile.isPlaying()) { text('tap to play', 50, 80); } else { text('tap to filter next band', 50, 80) } } function toggleSound() { if (!soundFile.isPlaying()) { soundFile.play(); } else { eqBandIndex = (eqBandIndex + 1) % eq.bands.length; } for (let i = 0; i < eq.bands.length; i++) { eq.bands[i].gain(0); } // filter the band we want to filter eq.bands[eqBandIndex].gain(-40); } `

## p5.Panner3D
p5.Panner3D

p5.Panner3D

p5.sound

p5.sound



Panner3D is based on the  Web Audio Spatial Panner Node. This panner is a spatial processing node that allows audio to be positioned and oriented in 3D space.
The position is relative to an  Audio Context Listener, which can be accessed by `p5.soundOut.audiocontext.listener`

## p5.Delay
p5.Delay

p5.Delay

p5.sound

p5.sound



Delay is an echo effect. It processes an existing sound source, and outputs a delayed version of that sound. The p5.Delay can produce different effects depending on the delayTime, feedback, filter, and type. In the example below, a feedback of 0.5 (the default value) will produce a looping delay that decreases in volume by 50% each repeat. A filter will cut out the high frequencies so that the delay does not sound as piercing as the original source.
This class extends p5.Effect. Methods amp(), chain(), drywet(), connect(), and disconnect() are available.

p5.Effect

` let osc; function setup() { let cnv = createCanvas(100, 100); background(220); textAlign(CENTER); text('tap to play', width/2, height/2); osc = new p5.Oscillator('square'); osc.amp(0.5); delay = new p5.Delay(); // delay.process() accepts 4 parameters: // source, delayTime (in seconds), feedback, filter frequency delay.process(osc, 0.12, .7, 2300); cnv.mousePressed(oscStart); } function oscStart() { osc.start(); } function mouseReleased() { osc.stop(); } `

## p5.Reverb
p5.Reverb

p5.Reverb

p5.sound

p5.sound



Reverb adds depth to a sound through a large number of decaying echoes. It creates the perception that sound is occurring in a physical space. The p5.Reverb has parameters for Time (how long does the reverb last) and decayRate (how much the sound decays with each echo) that can be set with the .set() or .process() methods. The p5.Convolver extends p5.Reverb allowing you to recreate the sound of actual physical spaces through convolution.
This class extends p5.Effect. Methods amp(), chain(), drywet(), connect(), and disconnect() are available.

p5.Effect

` let soundFile, reverb; function preload() { soundFile = loadSound('assets/Damscray_DancingTiger.mp3'); } function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(playSound); reverb = new p5.Reverb(); soundFile.disconnect(); // so we'll only hear reverb... // connect soundFile to reverb, process w/ // 3 second reverbTime, decayRate of 2% reverb.process(soundFile, 3, 2); } function draw() { let dryWet = constrain(map(mouseX, 0, width, 0, 1), 0, 1); // 1 = all reverb, 0 = no reverb reverb.drywet(dryWet); background(220); text('tap to play', 10, 20); text('dry/wet: ' + round(dryWet * 100) + '%', 10, height - 20); } function playSound() { soundFile.play(); } `

## p5.Convolver
p5.Convolver

p5.Convolver

p5.sound

p5.sound



p5.Convolver extends p5.Reverb. It can emulate the sound of real physical spaces through a process called  convolution.
Convolution multiplies any audio input by an "impulse response" to simulate the dispersion of sound over time. The impulse response is generated from an audio file that you provide. One way to generate an impulse response is to pop a balloon in a reverberant space and record the echo. Convolution can also be used to experiment with sound.
Use the method `createConvolution(path)` to instantiate a p5.Convolver with a path to your impulse response audio file.

p5.Effect

path

path to a sound file

String

callback

function to call when loading succeeds

Function

errorCallback

function to call if loading fails. This function will receive an error or XMLHttpRequest object with information about what went wrong.

Function

` let cVerb, sound; function preload() { // We have both MP3 and OGG versions of all sound assets soundFormats('ogg', 'mp3'); // Try replacing 'bx-spring' with other soundfiles like // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox' cVerb = createConvolver('assets/bx-spring.mp3'); // Try replacing 'Damscray_DancingTiger' with // 'beat', 'doorbell', lucky_dragons_-_power_melody' sound = loadSound('assets/Damscray_DancingTiger.mp3'); } function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(playSound); background(220); text('tap to play', 20, 20); // disconnect from main output... sound.disconnect(); // ...and process with cVerb // so that we only hear the convolution cVerb.process(sound); } function playSound() { sound.play(); } `

## p5.Phrase
p5.Phrase

p5.Phrase

p5.sound

p5.sound



A phrase is a pattern of musical events over time, i.e. a series of notes and rests.
Phrases must be added to a p5.Part for playback, and each part can play multiple phrases at the same time. For example, one Phrase might be a kick drum, another could be a snare, and another could be the bassline.
The first parameter is a name so that the phrase can be modified or deleted later. The callback is a a function that this phrase will call at every step—for example it might be called `playNote(value){}`. The array determines which value is passed into the callback at each step of the phrase. It can be numbers, an object with multiple numbers, or a zero (0) indicates a rest so the callback won't be called).

name

Name so that you can access the Phrase.

String

callback

The name of a function that this phrase will call. Typically it will play a sound, and accept two parameters: a time at which to play the sound (in seconds from now), and a value from the sequence array. The time should be passed into the play() or start() method to ensure precision.

Function

sequence

Array of values to pass into the callback at each step of the phrase.

Array

` let mySound, myPhrase, myPart; let pattern = [1,0,0,2,0,2,0,0]; function preload() { mySound = loadSound('assets/beatbox.mp3'); } function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(playMyPart); background(220); text('tap to play', width/2, height/2); textAlign(CENTER, CENTER); myPhrase = new p5.Phrase('bbox', onEachStep, pattern); myPart = new p5.Part(); myPart.addPhrase(myPhrase); myPart.setBPM(60); } function onEachStep(time, playbackRate) { mySound.rate(playbackRate); mySound.play(time); } function playMyPart() { userStartAudio(); myPart.start(); } `

## p5.Part
p5.Part

p5.Part

p5.sound

p5.sound



A p5.Part plays back one or more p5.Phrases. Instantiate a part with steps and tatums. By default, each step represents a 1/16th note.
See p5.Phrase for more about musical timing.

steps

Steps in the part

Number

tatums

Divisions of a beat, e.g. use 1/4, or 0.25 for a quater note (default is 1/16, a sixteenth note)

Number

` let box, drum, myPart; let boxPat = [1,0,0,2,0,2,0,0]; let drumPat = [0,1,1,0,2,0,1,0]; function preload() { box = loadSound('assets/beatbox.mp3'); drum = loadSound('assets/drum.mp3'); } function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(playMyPart); background(220); textAlign(CENTER, CENTER); text('tap to play', width/2, height/2); let boxPhrase = new p5.Phrase('box', playBox, boxPat); let drumPhrase = new p5.Phrase('drum', playDrum, drumPat); myPart = new p5.Part(); myPart.addPhrase(boxPhrase); myPart.addPhrase(drumPhrase); myPart.setBPM(60); } function playBox(time, playbackRate) { box.rate(playbackRate); box.play(time); } function playDrum(time, playbackRate) { drum.rate(playbackRate); drum.play(time); } function playMyPart() { userStartAudio(); myPart.start(); } `

## p5.Score
p5.Score

p5.Score

p5.sound

p5.sound



A Score consists of a series of Parts. The parts will be played back in order. For example, you could have an A part, a B part, and a C part, and play them back in this order `new p5.Score(a, a, b, a, c)`

parts

One or multiple parts, to be played in sequence.

p5.Part

## p5.SoundLoop
p5.SoundLoop

p5.SoundLoop

p5.sound

p5.sound



SoundLoop

callback

this function will be called on each iteration of theloop

Function

interval

amount of time (if a number) or beats (if a string, following Tone.Time convention) for each iteration of the loop. Defaults to 1 second.

Number|String

` let synth, soundLoop; let notePattern = [60, 62, 64, 67, 69, 72]; function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(canvasPressed); colorMode(HSB); background(0, 0, 86); text('tap to start/stop', 10, 20); //the looper's callback is passed the timeFromNow //this value should be used as a reference point from //which to schedule sounds let intervalInSeconds = 0.2; soundLoop = new p5.SoundLoop(onSoundLoop, intervalInSeconds); synth = new p5.MonoSynth(); } function canvasPressed() { // ensure audio is enabled userStartAudio(); if (soundLoop.isPlaying) { soundLoop.stop(); } else { // start the loop soundLoop.start(); } } function onSoundLoop(timeFromNow) { let noteIndex = (soundLoop.iterations - 1) % notePattern.length; let note = midiToFreq(notePattern[noteIndex]); synth.play(note, 0.5, timeFromNow); background(noteIndex * 360 / notePattern.length, 50, 100); } `

## p5.Compressor
p5.Compressor

p5.Compressor

p5.sound

p5.sound



Compressor is an audio effect class that performs dynamics compression on an audio input source. This is a very commonly used technique in music and sound production. Compression creates an overall louder, richer, and fuller sound by lowering the volume of louds and raising that of softs. Compression can be used to avoid clipping (sound distortion due to peaks in volume) and is especially useful when many sounds are played at once. Compression can be used on indivudal sound sources in addition to the main output.
This class extends p5.Effect. Methods amp(), chain(), drywet(), connect(), and disconnect() are available.

p5.Effect

## p5.PeakDetect
p5.PeakDetect

p5.PeakDetect

p5.sound

p5.sound



PeakDetect works in conjunction with p5.FFT to look for onsets in some or all of the frequency spectrum. 
To use p5.PeakDetect, call `update` in the draw loop and pass in a p5.FFT object. 
You can listen for a specific part of the frequency spectrum by setting the range between `freq1` and `freq2`. 
`threshold` is the threshold for detecting a peak, scaled between 0 and 1. It is logarithmic, so 0.1 is half as loud as 1.0.
The update method is meant to be run in the draw loop, and frames determines how many loops must pass before another peak can be detected. For example, if the frameRate() = 60, you could detect the beat of a 120 beat-per-minute song with this equation: ` framesPerPeak = 60 / (estimatedBPM / 60 );`
Based on example contribtued by @b2renger, and a simple beat detection explanation by Felix Turner. 

freq1

lowFrequency - defaults to 20Hz

Number

freq2

highFrequency - defaults to 20000 Hz

Number

threshold

Threshold for detecting a beat between 0 and 1 scaled logarithmically where 0.1 is 1/2 the loudness of 1.0. Defaults to 0.35.

Number

framesPerPeak

Defaults to 20.

Number

` var cnv, soundFile, fft, peakDetect; var ellipseWidth = 10; function preload() { soundFile = loadSound('assets/beat.mp3'); } function setup() { background(0); noStroke(); fill(255); textAlign(CENTER); // p5.PeakDetect requires a p5.FFT fft = new p5.FFT(); peakDetect = new p5.PeakDetect(); } function draw() { background(0); text('click to play/pause', width/2, height/2); // peakDetect accepts an fft post-analysis fft.analyze(); peakDetect.update(fft); if ( peakDetect.isDetected ) { ellipseWidth = 50; } else { ellipseWidth *= 0.95; } ellipse(width/2, height/2, ellipseWidth, ellipseWidth); } // toggle play/stop when canvas is clicked function mouseClicked() { if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { if (soundFile.isPlaying() ) { soundFile.stop(); } else { soundFile.play(); } } } `

## p5.SoundRecorder
p5.SoundRecorder

p5.SoundRecorder

p5.sound

p5.sound



Record sounds for playback and/or to save as a .wav file. The p5.SoundRecorder records all sound output from your sketch, or can be assigned a specific source with setInput().
The record() method accepts a p5.SoundFile as a parameter. When playback is stopped (either after the given amount of time, or with the stop() method), the p5.SoundRecorder will send its recording to that p5.SoundFile for playback.

` let mic, recorder, soundFile; let state = 0; function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(canvasPressed); background(220); textAlign(CENTER, CENTER); // create an audio in mic = new p5.AudioIn(); // prompts user to enable their browser mic mic.start(); // create a sound recorder recorder = new p5.SoundRecorder(); // connect the mic to the recorder recorder.setInput(mic); // this sound file will be used to // playback & save the recording soundFile = new p5.SoundFile(); text('tap to record', width/2, height/2); } function canvasPressed() { // ensure audio is enabled userStartAudio(); // make sure user enabled the mic if (state === 0 && mic.enabled) { // record to our p5.SoundFile recorder.record(soundFile); background(255,0,0); text('Recording!', width/2, height/2); state++; } else if (state === 1) { background(0,255,0); // stop recorder and // send result to soundFile recorder.stop(); text('Done! Tap to play and download', width/2, height/2, width - 20); state++; } else if (state === 2) { soundFile.play(); // play the result! save(soundFile, 'mySound.wav'); state++; } } 
`

## p5.Distortion
p5.Distortion

p5.Distortion

p5.sound

p5.sound



A Distortion effect created with a Waveshaper Node, with an approach adapted from Kevin Ennis
This class extends p5.Effect. Methods amp(), chain(), drywet(), connect(), and disconnect() are available.

p5.Effect

amount

Unbounded distortion amount. Normal values range from 0-1.

Number

0.25

oversample

'none', '2x', or '4x'.

String

'none'

## p5.Gain
p5.Gain

p5.Gain

p5.sound

p5.sound



A gain node is usefull to set the relative volume of sound. It's typically used to build mixers.

` // load two soundfile and crossfade beetween them let sound1,sound2; let sound1Gain, sound2Gain, mixGain; function preload(){ soundFormats('ogg', 'mp3'); sound1 = loadSound('assets/Damscray_-_Dancing_Tiger_01'); sound2 = loadSound('assets/beat'); } function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(startSound); // create a 'mix' gain bus to which we will connect both soundfiles mixGain = new p5.Gain(); mixGain.connect(); sound1.disconnect(); // diconnect from p5 output sound1Gain = new p5.Gain(); // setup a gain node sound1Gain.setInput(sound1); // connect the first sound to its input sound1Gain.connect(mixGain); // connect its output to the final mix bus sound2.disconnect(); sound2Gain = new p5.Gain(); sound2Gain.setInput(sound2); sound2Gain.connect(mixGain); } function startSound() { sound1.loop(); sound2.loop(); loop(); } function mouseReleased() { sound1.stop(); sound2.stop(); } function draw(){ background(220); textAlign(CENTER); textSize(11); fill(0); if (!sound1.isPlaying()) { text('tap and drag to play', width/2, height/2); return; } // map the horizontal position of the mouse to values useable for volume * control of sound1 var sound1Volume = constrain(map(mouseX,width,0,0,1), 0, 1); var sound2Volume = 1-sound1Volume; sound1Gain.amp(sound1Volume); sound2Gain.amp(sound2Volume); // map the vertical position of the mouse to values useable for 'output * volume control' var outputVolume = constrain(map(mouseY,height,0,0,1), 0, 1); mixGain.amp(outputVolume); text('output', width/2, height - outputVolume * height * 0.9) fill(255, 0, 255); textAlign(LEFT); text('sound1', 5, height - sound1Volume * height * 0.9); textAlign(RIGHT); text('sound2', width - 5, height - sound2Volume * height * 0.9); } `

## p5.AudioVoice
p5.AudioVoice

p5.AudioVoice

p5.sound

p5.sound



Base class for monophonic synthesizers. Any extensions of this class should follow the API and implement the methods below in order to remain compatible with p5.PolySynth();

## p5.MonoSynth
p5.MonoSynth

p5.MonoSynth

p5.sound

p5.sound



A MonoSynth is used as a single voice for sound synthesis. This is a class to be used in conjunction with the PolySynth class. Custom synthetisers should be built inheriting from this class.

` let monoSynth; function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(playSynth); background(220); textAlign(CENTER); text('tap to play', width/2, height/2); monoSynth = new p5.MonoSynth(); } function playSynth() { userStartAudio(); let note = random(['Fb4', 'G4']); // note velocity (volume, from 0 to 1) let velocity = random(); // time from now (in seconds) let time = 0; // note duration (in seconds) let dur = 1/6; monoSynth.play(note, velocity, time, dur); } `

## p5.OnsetDetect
p5.OnsetDetect

p5.OnsetDetect

p5.sound

p5.sound



Listen for onsets (a sharp increase in volume) within a given frequency range.

freqLow

Low frequency

Number

freqHigh

High frequency

Number

threshold

Amplitude threshold between 0 (no energy) and 1 (maximum)

Number

callback

Function to call when an onset is detected

Function

## p5.PolySynth
p5.PolySynth

p5.PolySynth

p5.sound

p5.sound



An AudioVoice is used as a single voice for sound synthesis. The PolySynth class holds an array of AudioVoice, and deals with voices allocations, with setting notes to be played, and parameters to be set.

synthVoice

A monophonic synth voice inheriting the AudioVoice class. Defaults to p5.MonoSynth

Number

maxVoices

Number of voices, defaults to 8;

Number

` let polySynth; function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(playSynth); background(220); text('click to play', 20, 20); polySynth = new p5.PolySynth(); } function playSynth() { userStartAudio(); // note duration (in seconds) let dur = 1.5; // time from now (in seconds) let time = 0; // velocity (volume, from 0 to 1) let vel = 0.1; // notes can overlap with each other polySynth.play('G2', vel, 0, dur); polySynth.play('C3', vel, time += 1/3, dur); polySynth.play('G3', vel, time += 1/3, dur); } `

# elements
Creates a screen reader-accessible description of the canvas.
The first parameter, `text`, is the description of the canvas.
The second parameter, `display`, is optional. It determines how the description is displayed. If `LABEL` is passed, as in `describe('A description.', LABEL)`, the description will be visible in a div element next to the canvas. If `FALLBACK` is passed, as in `describe('A description.', FALLBACK)`, the description will only be visible to screen readers. This is the default mode.
Read Writing accessible canvas descriptions to learn more about making sketches accessible.

method

describe

text

description of the canvas.

String

display

either LABEL or FALLBACK.

Constant

` function setup() { background('pink'); // Draw a heart. fill('red'); noStroke(); circle(67, 67, 20); circle(83, 67, 20); triangle(91, 73, 75, 95, 59, 73); // Add a general description of the canvas. describe('A pink square with a red heart in the bottom-right corner.'); } `
` function setup() { background('pink'); // Draw a heart. fill('red'); noStroke(); circle(67, 67, 20); circle(83, 67, 20); triangle(91, 73, 75, 95, 59, 73); // Add a general description of the canvas // and display it for debugging. describe('A pink square with a red heart in the bottom-right corner.', LABEL); } `
` function draw() { background(200); // The expression // frameCount % 100 // causes x to increase from 0 // to 99, then restart from 0. let x = frameCount % 100; // Draw the circle. fill(0, 255, 0); circle(x, 50, 40); // Add a general description of the canvas. describe(`A green circle at (${x}, 50) moves from left to right on a gray square.`); } `
` function draw() { background(200); // The expression // frameCount % 100 // causes x to increase from 0 // to 99, then restart from 0. let x = frameCount % 100; // Draw the circle. fill(0, 255, 0); circle(x, 50, 40); // Add a general description of the canvas // and display it for debugging. describe(`A green circle at (${x}, 50) moves from left to right on a gray square.`, LABEL); } `

p5

Environment

Environment

Creates a screen reader-accessible description of elements in the canvas.
Elements are shapes or groups of shapes that create meaning together. For example, a few overlapping circles could make an "eye" element.
The first parameter, `name`, is the name of the element.
The second parameter, `text`, is the description of the element.
The third parameter, `display`, is optional. It determines how the description is displayed. If `LABEL` is passed, as in `describe('A description.', LABEL)`, the description will be visible in a div element next to the canvas. Using `LABEL` creates unhelpful duplicates for screen readers. Only use `LABEL` during development. If `FALLBACK` is passed, as in `describe('A description.', FALLBACK)`, the description will only be visible to screen readers. This is the default mode.
Read Writing accessible canvas descriptions to learn more about making sketches accessible.

method

describeElement

name

name of the element.

String

text

description of the element.

String

display

either LABEL or FALLBACK.

Constant

` function setup() { background('pink'); // Describe the first element // and draw it. describeElement('Circle', 'A yellow circle in the top-left corner.'); noStroke(); fill('yellow'); circle(25, 25, 40); // Describe the second element // and draw it. describeElement('Heart', 'A red heart in the bottom-right corner.'); fill('red'); circle(66.6, 66.6, 20); circle(83.2, 66.6, 20); triangle(91.2, 72.6, 75, 95, 58.6, 72.6); // Add a general description of the canvas. describe('A red heart and yellow circle over a pink background.'); } `
` function setup() { background('pink'); // Describe the first element // and draw it. Display the // description for debugging. describeElement('Circle', 'A yellow circle in the top-left corner.', LABEL); noStroke(); fill('yellow'); circle(25, 25, 40); // Describe the second element // and draw it. Display the // description for debugging. describeElement('Heart', 'A red heart in the bottom-right corner.', LABEL); fill('red'); circle(66.6, 66.6, 20); circle(83.2, 66.6, 20); triangle(91.2, 72.6, 75, 95, 58.6, 72.6); // Add a general description of the canvas. describe('A red heart and yellow circle over a pink background.'); } `

p5

Environment

Environment

Creates a screen reader-accessible description of shapes on the canvas.
`textOutput()` adds a general description, list of shapes, and table of shapes to the web page. The general description includes the canvas size, canvas color, and number of shapes. For example, `Your output is a, 100 by 100 pixels, gray canvas containing the following 2 shapes:`.
A list of shapes follows the general description. The list describes the color, location, and area of each shape. For example, `a red circle at middle covering 3% of the canvas`. Each shape can be selected to get more details.
`textOutput()` uses its table of shapes as a list. The table describes the shape, color, location, coordinates and area. For example, `red circle location = middle area = 3%`. This is different from gridOutput(), which uses its table as a grid.
The `display` parameter is optional. It determines how the description is displayed. If `LABEL` is passed, as in `textOutput(LABEL)`, the description will be visible in a div element next to the canvas. Using `LABEL` creates unhelpful duplicates for screen readers. Only use `LABEL` during development. If `FALLBACK` is passed, as in `textOutput(FALLBACK)`, the description will only be visible to screen readers. This is the default mode.
Read Writing accessible canvas descriptions to learn more about making sketches accessible.

method

textOutput

display

either FALLBACK or LABEL.

Constant

` function setup() { // Add the text description. textOutput(); // Draw a couple of shapes. background(200); fill(255, 0, 0); circle(20, 20, 20); fill(0, 0, 255); square(50, 50, 50); // Add a general description of the canvas. describe('A red circle and a blue square on a gray background.'); } `
` function setup() { // Add the text description and // display it for debugging. textOutput(LABEL); // Draw a couple of shapes. background(200); fill(255, 0, 0); circle(20, 20, 20); fill(0, 0, 255); square(50, 50, 50); // Add a general description of the canvas. describe('A red circle and a blue square on a gray background.'); } `
` function draw() { // Add the text description. textOutput(); // Draw a moving circle. background(200); let x = frameCount * 0.1; fill(255, 0, 0); circle(x, 20, 20); fill(0, 0, 255); square(50, 50, 50); // Add a general description of the canvas. describe('A red circle moves from left to right above a blue square.'); } `
` function draw() { // Add the text description and // display it for debugging. textOutput(LABEL); // Draw a moving circle. background(200); let x = frameCount * 0.1; fill(255, 0, 0); circle(x, 20, 20); fill(0, 0, 255); square(50, 50, 50); // Add a general description of the canvas. describe('A red circle moves from left to right above a blue square.'); } `

p5

Environment

Environment

Creates a screen reader-accessible description of shapes on the canvas.
`gridOutput()` adds a general description, table of shapes, and list of shapes to the web page. The general description includes the canvas size, canvas color, and number of shapes. For example, `gray canvas, 100 by 100 pixels, contains 2 shapes: 1 circle 1 square`.
`gridOutput()` uses its table of shapes as a grid. Each shape in the grid is placed in a cell whose row and column correspond to the shape's location on the canvas. The grid cells describe the color and type of shape at that location. For example, `red circle`. These descriptions can be selected individually to get more details. This is different from textOutput(), which uses its table as a list.
A list of shapes follows the table. The list describes the color, type, location, and area of each shape. For example, `red circle, location = middle, area = 3 %`.
The `display` parameter is optional. It determines how the description is displayed. If `LABEL` is passed, as in `gridOutput(LABEL)`, the description will be visible in a div element next to the canvas. Using `LABEL` creates unhelpful duplicates for screen readers. Only use `LABEL` during development. If `FALLBACK` is passed, as in `gridOutput(FALLBACK)`, the description will only be visible to screen readers. This is the default mode.
Read Writing accessible canvas descriptions to learn more about making sketches accessible.

method

gridOutput

display

either FALLBACK or LABEL.

Constant

` function setup() { // Add the grid description. gridOutput(); // Draw a couple of shapes. background(200); fill(255, 0, 0); circle(20, 20, 20); fill(0, 0, 255); square(50, 50, 50); // Add a general description of the canvas. describe('A red circle and a blue square on a gray background.'); } `
` function setup() { // Add the grid description and // display it for debugging. gridOutput(LABEL); // Draw a couple of shapes. background(200); fill(255, 0, 0); circle(20, 20, 20); fill(0, 0, 255); square(50, 50, 50); // Add a general description of the canvas. describe('A red circle and a blue square on a gray background.'); } `
` function draw() { // Add the grid description. gridOutput(); // Draw a moving circle. background(200); let x = frameCount * 0.1; fill(255, 0, 0); circle(x, 20, 20); fill(0, 0, 255); square(50, 50, 50); // Add a general description of the canvas. describe('A red circle moves from left to right above a blue square.'); } `
` function draw() { // Add the grid description and // display it for debugging. gridOutput(LABEL); // Draw a moving circle. background(200); let x = frameCount * 0.1; fill(255, 0, 0); circle(x, 20, 20); fill(0, 0, 255); square(50, 50, 50); // Add a general description of the canvas. describe('A red circle moves from left to right above a blue square.'); } `

p5

Environment

Environment

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.

p5

Color

Color Conversion

Convert an HSBA array to HSLA.

p5

Color

Color Conversion

Convert an HSBA array to RGBA.

p5

Color

Color Conversion

Convert an HSLA array to HSBA.

p5

Color

Color Conversion

Convert an HSLA array to RGBA.
We need to change basis from HSLA to something that can be more easily be projected onto RGBA. We will choose hue and brightness as our first two components, and pick a convenient third one ('zest') so that we don't need to calculate formal HSBA saturation.

p5

Color

Color Conversion

Convert an RGBA array to HSBA.

p5

Color

Color Conversion

Convert an RGBA array to HSLA.

p5

Color

Color Conversion

Gets the alpha (transparency) value of a color.
`alpha()` extracts the alpha value from a p5.Color object, an array of color components, or a CSS color string.

method

alpha

color

p5.Color object, array of color components, or CSS color string.

p5.Color|Number[]|String

### return
the alpha value.

Number

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Color object. let c = color(0, 126, 255, 102); // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'alphaValue' to 102. let alphaValue = alpha(c); // Draw the right rectangle. fill(alphaValue); rect(50, 15, 35, 70); describe('Two rectangles. The left one is light blue and the right one is charcoal gray.'); } `

` function setup() { createCanvas(100, 100); background(200); // Create a color array. let c = [0, 126, 255, 102]; // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'alphaValue' to 102. let alphaValue = alpha(c); // Draw the left rectangle. fill(alphaValue); rect(50, 15, 35, 70); describe('Two rectangles. The left one is light blue and the right one is charcoal gray.'); } `

` function setup() { createCanvas(100, 100); background(200); // Create a CSS color string. let c = 'rgba(0, 126, 255, 0.4)'; // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'alphaValue' to 102. let alphaValue = alpha(c); // Draw the right rectangle. fill(alphaValue); rect(50, 15, 35, 70); describe('Two rectangles. The left one is light blue and the right one is charcoal gray.'); } `

p5

Color

Creating & Reading

Gets the blue value of a color.
`blue()` extracts the blue value from a p5.Color object, an array of color components, or a CSS color string.
By default, `blue()` returns a color's blue value in the range 0 to 255. If the colorMode() is set to RGB, it returns the blue value in the given range.

method

blue

color

p5.Color object, array of color components, or CSS color string.

p5.Color|Number[]|String

### return
the blue value.

Number

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Color object using RGB values. let c = color(175, 100, 220); // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'blueValue' to 220. let blueValue = blue(c); // Draw the right rectangle. fill(0, 0, blueValue); rect(50, 15, 35, 70); describe('Two rectangles. The left one is light purple and the right one is royal blue.'); } `

` function setup() { createCanvas(100, 100); background(200); // Create a color array. let c = [175, 100, 220]; // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'blueValue' to 220. let blueValue = blue(c); // Draw the right rectangle. fill(0, 0, blueValue); rect(50, 15, 35, 70); describe('Two rectangles. The left one is light purple and the right one is royal blue.'); } `

` function setup() { createCanvas(100, 100); background(200); // Create a CSS color string. let c = 'rgb(175, 100, 220)'; // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'blueValue' to 220. let blueValue = blue(c); // Draw the right rectangle. fill(0, 0, blueValue); rect(50, 15, 35, 70); describe('Two rectangles. The left one is light purple and the right one is royal blue.'); } `

` function setup() { createCanvas(100, 100); background(200); // Use RGB color with values in the range 0-100. colorMode(RGB, 100); // Create a p5.Color object using RGB values. let c = color(69, 39, 86); // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'blueValue' to 86. let blueValue = blue(c); // Draw the right rectangle. fill(0, 0, blueValue); rect(50, 15, 35, 70); describe('Two rectangles. The left one is light purple and the right one is royal blue.'); } `

p5

Color

Creating & Reading

Gets the brightness value of a color.
`brightness()` extracts the HSB brightness value from a p5.Color object, an array of color components, or a CSS color string.
By default, `brightness()` returns a color's HSB brightness in the range 0 to 100. If the colorMode() is set to HSB, it returns the brightness value in the given range.

method

brightness

color

p5.Color object, array of color components, or CSS color string.

p5.Color|Number[]|String

### return
the brightness value.

Number

` function setup() { createCanvas(100, 100); background(200); // Use HSB color. colorMode(HSB); // Create a p5.Color object. let c = color(0, 50, 100); // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'brightValue' to 100. let brightValue = brightness(c); // Draw the right rectangle. fill(brightValue); rect(50, 15, 35, 70); describe('Two rectangles. The left one is salmon pink and the right one is white.'); } `

` function setup() { createCanvas(100, 100); background(200); // Use HSB color. colorMode(HSB); // Create a color array. let c = [0, 50, 100]; // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'brightValue' to 100. let brightValue = brightness(c); // Draw the right rectangle. fill(brightValue); rect(50, 15, 35, 70); describe('Two rectangles. The left one is salmon pink and the right one is white.'); } `

` function setup() { createCanvas(100, 100); background(200); // Use HSB color. colorMode(HSB); // Create a CSS color string. let c = 'rgb(255, 128, 128)'; // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'brightValue' to 100. let brightValue = brightness(c); // Draw the right rectangle. fill(brightValue); rect(50, 15, 35, 70); describe('Two rectangles. The left one is salmon pink and the right one is white.'); } `

` function setup() { createCanvas(100, 100); background(200); // Use HSB color with values in the range 0-255. colorMode(HSB, 255); // Create a p5.Color object. let c = color(0, 127, 255); // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'brightValue' to 255. let brightValue = brightness(c); // Draw the right rectangle. fill(brightValue); rect(50, 15, 35, 70); describe('Two rectangles. The left one is salmon pink and the right one is white.'); } `

p5

Color

Creating & Reading

Creates a p5.Color object.
By default, the parameters are interpreted as RGB values. Calling `color(255, 204, 0)` will return a bright yellow color. The way these parameters are interpreted may be changed with the colorMode() function.
The version of `color()` with one parameter interprets the value one of two ways. If the parameter is a number, it's interpreted as a grayscale value. If the parameter is a string, it's interpreted as a CSS color string.
The version of `color()` with two parameters interprets the first one as a grayscale value. The second parameter sets the alpha (transparency) value.
The version of `color()` with three parameters interprets them as RGB, HSB, or HSL colors, depending on the current `colorMode()`.
The version of `color()` with four parameters interprets them as RGBA, HSBA, or HSLA colors, depending on the current `colorMode()`. The last parameter sets the alpha (transparency) value.

method

color

### return
resulting color.

p5.Color

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Color object using RGB values. let c = color(255, 204, 0); // Draw the square. fill(c); noStroke(); square(30, 20, 55); describe('A yellow square on a gray canvas.'); } `

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Color object using RGB values. let c1 = color(255, 204, 0); // Draw the left circle. fill(c1); noStroke(); circle(25, 25, 80); // Create a p5.Color object using a grayscale value. let c2 = color(65); // Draw the right circle. fill(c2); circle(75, 75, 80); describe( 'Two circles on a gray canvas. The circle in the top-left corner is yellow and the one at the bottom-right is gray.' ); } `

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Color object using a named color. let c = color('magenta'); // Draw the square. fill(c); noStroke(); square(20, 20, 60); describe('A magenta square on a gray canvas.'); } `

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Color object using a hex color code. let c1 = color('#0f0'); // Draw the left rectangle. fill(c1); noStroke(); rect(0, 10, 45, 80); // Create a p5.Color object using a hex color code. let c2 = color('#00ff00'); // Draw the right rectangle. fill(c2); rect(55, 10, 45, 80); describe('Two bright green rectangles on a gray canvas.'); } `

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Color object using a RGB color string. let c1 = color('rgb(0, 0, 255)'); // Draw the top-left square. fill(c1); square(10, 10, 35); // Create a p5.Color object using a RGB color string. let c2 = color('rgb(0%, 0%, 100%)'); // Draw the top-right square. fill(c2); square(55, 10, 35); // Create a p5.Color object using a RGBA color string. let c3 = color('rgba(0, 0, 255, 1)'); // Draw the bottom-left square. fill(c3); square(10, 55, 35); // Create a p5.Color object using a RGBA color string. let c4 = color('rgba(0%, 0%, 100%, 1)'); // Draw the bottom-right square. fill(c4); square(55, 55, 35); describe('Four blue squares in the corners of a gray canvas.'); } `

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Color object using a HSL color string. let c1 = color('hsl(160, 100%, 50%)'); // Draw the left rectangle. noStroke(); fill(c1); rect(0, 10, 45, 80); // Create a p5.Color object using a HSLA color string. let c2 = color('hsla(160, 100%, 50%, 0.5)'); // Draw the right rectangle. fill(c2); rect(55, 10, 45, 80); describe('Two sea green rectangles. A darker rectangle on the left and a brighter one on the right.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create a p5.Color object using a HSB color string. let c1 = color('hsb(160, 100%, 50%)'); // Draw the left rectangle. noStroke(); fill(c1); rect(0, 10, 45, 80); // Create a p5.Color object using a HSBA color string. let c2 = color('hsba(160, 100%, 50%, 0.5)'); // Draw the right rectangle. fill(c2); rect(55, 10, 45, 80); describe('Two green rectangles. A darker rectangle on the left and a brighter one on the right.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create a p5.Color object using RGB values. let c1 = color(50, 55, 100); // Draw the left rectangle. fill(c1); rect(0, 10, 45, 80); // Switch the color mode to HSB. colorMode(HSB, 100); // Create a p5.Color object using HSB values. let c2 = color(50, 55, 100); // Draw the right rectangle. fill(c2); rect(55, 10, 45, 80); describe('Two blue rectangles. A darker rectangle on the left and a brighter one on the right.'); } `

p5

Color

Creating & Reading

gray

number specifying value between white and black.

Number

alpha

alpha value relative to current color range (default is 0-255).

Number

##### return
resulting color.

p5.Color

v1

red or hue value relative to the current color range.

Number

v2

green or saturation value relative to the current color range.

Number

v3

blue or brightness value relative to the current color range.

Number

alpha



Number

##### return


p5.Color

value

a color string.

String

##### return


p5.Color

values

an array containing the red, green, blue, and alpha components of the color.

Number[]

##### return


p5.Color

color



p5.Color

##### return


p5.Color

Gets the green value of a color.
`green()` extracts the green value from a p5.Color object, an array of color components, or a CSS color string.
By default, `green()` returns a color's green value in the range 0 to 255. If the colorMode() is set to RGB, it returns the green value in the given range.

method

green

color

p5.Color object, array of color components, or CSS color string.

p5.Color|Number[]|String

### return
the green value.

Number

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Color object. let c = color(175, 100, 220); // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'greenValue' to 100. let greenValue = green(c); // Draw the right rectangle. fill(0, greenValue, 0); rect(50, 15, 35, 70); describe('Two rectangles. The left one is light purple and the right one is dark green.'); } `

` function setup() { createCanvas(100, 100); background(200); // Create a color array. let c = [175, 100, 220]; // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'greenValue' to 100. let greenValue = green(c); // Draw the right rectangle. fill(0, greenValue, 0); rect(50, 15, 35, 70); describe('Two rectangles. The left one is light purple and the right one is dark green.'); } `

` function setup() { createCanvas(100, 100); background(200); // Create a CSS color string. let c = 'rgb(175, 100, 220)'; // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'greenValue' to 100. let greenValue = green(c); // Draw the right rectangle. fill(0, greenValue, 0); rect(50, 15, 35, 70); describe('Two rectangles. The left one is light purple and the right one is dark green.'); } `

` function setup() { createCanvas(100, 100); background(200); // Use RGB color with values in the range 0-100. colorMode(RGB, 100); // Create a p5.Color object using RGB values. let c = color(69, 39, 86); // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'greenValue' to 39. let greenValue = green(c); // Draw the right rectangle. fill(0, greenValue, 0); rect(50, 15, 35, 70); describe('Two rectangles. The left one is light purple and the right one is dark green.'); } `

p5

Color

Creating & Reading

Gets the hue value of a color.
`hue()` extracts the hue value from a p5.Color object, an array of color components, or a CSS color string.
Hue describes a color's position on the color wheel. By default, `hue()` returns a color's HSL hue in the range 0 to 360. If the colorMode() is set to HSB or HSL, it returns the hue value in the given mode.

method

hue

color

p5.Color object, array of color components, or CSS color string.

p5.Color|Number[]|String

### return
the hue value.

Number

` function setup() { createCanvas(100, 100); background(200); // Use HSL color. colorMode(HSL); // Create a p5.Color object. let c = color(0, 50, 100); // Draw the left rectangle. noStroke(); fill(c); rect(15, 20, 35, 60); // Set 'hueValue' to 0. let hueValue = hue(c); // Draw the right rectangle. fill(hueValue); rect(50, 20, 35, 60); describe( 'Two rectangles. The rectangle on the left is salmon pink and the one on the right is black.' ); } `

` function setup() { createCanvas(100, 100); background(200); // Use HSL color. colorMode(HSL); // Create a color array. let c = [0, 50, 100]; // Draw the left rectangle. noStroke(); fill(c); rect(15, 20, 35, 60); // Set 'hueValue' to 0. let hueValue = hue(c); // Draw the right rectangle. fill(hueValue); rect(50, 20, 35, 60); describe( 'Two rectangles. The rectangle on the left is salmon pink and the one on the right is black.' ); } `

` function setup() { createCanvas(100, 100); background(200); // Use HSL color. colorMode(HSL); // Create a CSS color string. let c = 'rgb(255, 128, 128)'; // Draw the left rectangle. noStroke(); fill(c); rect(15, 20, 35, 60); // Set 'hueValue' to 0. let hueValue = hue(c); // Draw the right rectangle. fill(hueValue); rect(50, 20, 35, 60); describe( 'Two rectangles. The rectangle on the left is salmon pink and the one on the right is black.' ); } `

p5

Color

Creating & Reading

Blends two colors to find a third color between them.
The `amt` parameter specifies the amount to interpolate between the two values. 0 is equal to the first color, 0.1 is very near the first color, 0.5 is halfway between the two colors, and so on. Negative numbers are set to 0. Numbers greater than 1 are set to 1. This differs from the behavior of lerp. It's necessary because numbers outside of the interval [0, 1] will produce strange and unexpected colors.
The way that colors are interpolated depends on the current colorMode().

method

lerpColor

c1

interpolate from this color (any value created by the color() function).

p5.Color

c2

interpolate to this color (any value created by the color() function).

p5.Color

amt

number between 0 and 1.

Number

### return
interpolated color.

p5.Color

` function setup() { createCanvas(100, 100); background(200); // Create p5.Color objects to interpolate between. let from = color(218, 165, 32); let to = color(72, 61, 139); // Create intermediate colors. let interA = lerpColor(from, to, 0.33); let interB = lerpColor(from, to, 0.66); // Draw the left rectangle. noStroke(); fill(from); rect(10, 20, 20, 60); // Draw the left-center rectangle. fill(interA); rect(30, 20, 20, 60); // Draw the right-center rectangle. fill(interB); rect(50, 20, 20, 60); // Draw the right rectangle. fill(to); rect(70, 20, 20, 60); describe( 'Four rectangles. From left to right, the rectangles are tan, brown, brownish purple, and purple.' ); } `

p5

Color

Creating & Reading

Blends multiple colors to find a color between them.
The `amt` parameter specifies the amount to interpolate between the color stops which are colors at each `amt` value "location" with `amt` values that are between 2 color stops interpolating between them based on its relative distance to both.
The way that colors are interpolated depends on the current colorMode().

method

paletteLerp

colors_stops

color stops to interpolate from

[p5.Color, Number][]

amt

number to use to interpolate relative to color stops

Number

### return
interpolated color.

p5.Color

` function setup() { createCanvas(400, 400); } function draw() { // The background goes from white to red to green to blue fill background(paletteLerp([ ['white', 0], ['red', 0.05], ['green', 0.25], ['blue', 1] ], millis() / 10000 % 1)); } `

p5

Color

Creating & Reading

Gets the lightness value of a color.
`lightness()` extracts the HSL lightness value from a p5.Color object, an array of color components, or a CSS color string.
By default, `lightness()` returns a color's HSL lightness in the range 0 to 100. If the colorMode() is set to HSL, it returns the lightness value in the given range.

method

lightness

color

p5.Color object, array of color components, or CSS color string.

p5.Color|Number[]|String

### return
the lightness value.

Number

` function setup() { createCanvas(100, 100); background(50); // Use HSL color. colorMode(HSL); // Create a p5.Color object using HSL values. let c = color(0, 100, 75); // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'lightValue' to 75. let lightValue = lightness(c); // Draw the right rectangle. fill(lightValue); rect(50, 15, 35, 70); describe('Two rectangles. The left one is salmon pink and the right one is gray.'); } `

` function setup() { createCanvas(100, 100); background(50); // Use HSL color. colorMode(HSL); // Create a color array. let c = [0, 100, 75]; // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'lightValue' to 75. let lightValue = lightness(c); // Draw the right rectangle. fill(lightValue); rect(50, 15, 35, 70); describe('Two rectangles. The left one is salmon pink and the right one is gray.'); } `

` function setup() { createCanvas(100, 100); background(50); // Use HSL color. colorMode(HSL); // Create a CSS color string. let c = 'rgb(255, 128, 128)'; // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'lightValue' to 75. let lightValue = lightness(c); // Draw the right rectangle. fill(lightValue); rect(50, 15, 35, 70); describe('Two rectangles. The left one is salmon pink and the right one is gray.'); } `

` function setup() { createCanvas(100, 100); background(50); // Use HSL color with values in the range 0-255. colorMode(HSL, 255); // Create a p5.Color object using HSL values. let c = color(0, 255, 191.5); // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'lightValue' to 191.5. let lightValue = lightness(c); // Draw the right rectangle. fill(lightValue); rect(50, 15, 35, 70); describe('Two rectangles. The left one is salmon pink and the right one is gray.'); } `

p5

Color

Creating & Reading

Gets the red value of a color.
`red()` extracts the red value from a p5.Color object, an array of color components, or a CSS color string.
By default, `red()` returns a color's red value in the range 0 to 255. If the colorMode() is set to RGB, it returns the red value in the given range.

method

red

color

p5.Color object, array of color components, or CSS color string.

p5.Color|Number[]|String

### return
the red value.

Number

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Color object. let c = color(175, 100, 220); // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'redValue' to 175. let redValue = red(c); // Draw the right rectangle. fill(redValue, 0, 0); rect(50, 15, 35, 70); describe('Two rectangles. The left one is light purple and the right one is red.'); } `

` function setup() { createCanvas(100, 100); background(200); // Create a color array. let c = [175, 100, 220]; // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'redValue' to 175. let redValue = red(c); // Draw the right rectangle. fill(redValue, 0, 0); rect(50, 15, 35, 70); describe('Two rectangles. The left one is light purple and the right one is red.'); } `

` function setup() { createCanvas(100, 100); background(200); // Create a CSS color string. let c = 'rgb(175, 100, 220)'; // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'redValue' to 175. let redValue = red(c); // Draw the right rectangle. fill(redValue, 0, 0); rect(50, 15, 35, 70); describe('Two rectangles. The left one is light purple and the right one is red.'); } `

` function setup() { createCanvas(100, 100); background(200); // Use RGB color with values in the range 0-100. colorMode(RGB, 100); // Create a p5.Color object. let c = color(69, 39, 86); // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'redValue' to 69. let redValue = red(c); // Draw the right rectangle. fill(redValue, 0, 0); rect(50, 15, 35, 70); describe('Two rectangles. The left one is light purple and the right one is red.'); } `

p5

Color

Creating & Reading

Gets the saturation value of a color.
`saturation()` extracts the saturation value from a p5.Color object, an array of color components, or a CSS color string.
Saturation is scaled differently in HSB and HSL. By default, `saturation()` returns a color's HSL saturation in the range 0 to 100. If the colorMode() is set to HSB or HSL, it returns the saturation value in the given mode.

method

saturation

color

p5.Color object, array of color components, or CSS color string.

p5.Color|Number[]|String

### return
the saturation value

Number

` function setup() { createCanvas(100, 100); background(50); // Use HSB color. colorMode(HSB); // Create a p5.Color object. let c = color(0, 50, 100); // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'satValue' to 50. let satValue = saturation(c); // Draw the right rectangle. fill(satValue); rect(50, 15, 35, 70); describe('Two rectangles. The left one is salmon pink and the right one is dark gray.'); } `

` function setup() { createCanvas(100, 100); background(50); // Use HSB color. colorMode(HSB); // Create a color array. let c = [0, 50, 100]; // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'satValue' to 100. let satValue = saturation(c); // Draw the right rectangle. fill(satValue); rect(50, 15, 35, 70); describe('Two rectangles. The left one is salmon pink and the right one is gray.'); } `

` function setup() { createCanvas(100, 100); background(50); // Use HSB color. colorMode(HSB); // Create a CSS color string. let c = 'rgb(255, 128, 128)'; // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'satValue' to 100. let satValue = saturation(c); // Draw the right rectangle. fill(satValue); rect(50, 15, 35, 70); describe('Two rectangles. The left one is salmon pink and the right one is gray.'); } `

` function setup() { createCanvas(100, 100); background(50); // Use HSL color. colorMode(HSL); // Create a p5.Color object. let c = color(0, 100, 75); // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'satValue' to 100. let satValue = saturation(c); // Draw the right rectangle. fill(satValue); rect(50, 15, 35, 70); describe('Two rectangles. The left one is salmon pink and the right one is white.'); } `

` function setup() { createCanvas(100, 100); background(50); // Use HSL color with values in the range 0-255. colorMode(HSL, 255); // Create a p5.Color object. let c = color(0, 255, 191.5); // Draw the left rectangle. noStroke(); fill(c); rect(15, 15, 35, 70); // Set 'satValue' to 255. let satValue = saturation(c); // Draw the right rectangle. fill(satValue); rect(50, 15, 35, 70); describe('Two rectangles. The left one is salmon pink and the right one is white.'); } `

p5

Color

Creating & Reading

CSS named colors.

p5

Color

Creating & Reading

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.

p5

Color

Creating & Reading

Full color string patterns. The capture groups are necessary.

p5

Color

Creating & Reading

Returns the color formatted as a `String`.
Calling `myColor.toString()` can be useful for debugging, as in `print(myColor.toString())`. It's also helpful for using p5.js with other libraries.
The parameter, `format`, is optional. If a format string is passed, as in `myColor.toString('#rrggbb')`, it will determine how the color string is formatted. By default, color strings are formatted as `'rgba(r, g, b, a)'`.

method

toString

format

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.

String

### return
the formatted string.

String

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Color object. let myColor = color('darkorchid'); // Style the text. textAlign(CENTER); textSize(16); // Display the text. text(myColor.toString('#rrggbb'), 50, 50); describe('The text "#9932cc" written in purple on a gray background.'); } `

p5.Color

Color

Creating & Reading

Sets the red component of a color.
The range depends on the colorMode(). In the default RGB mode it's between 0 and 255.

method

setRed

red

the new red value.

Number

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Color object. let c = color(255, 128, 128); // Draw the left rectangle. noStroke(); fill(c); rect(15, 20, 35, 60); // Change the red value. c.setRed(64); // Draw the right rectangle. fill(c); rect(50, 20, 35, 60); describe('Two rectangles. The left one is salmon pink and the right one is teal.'); } `

p5.Color

Color

Creating & Reading

Sets the green component of a color.
The range depends on the colorMode(). In the default RGB mode it's between 0 and 255.

method

setGreen

green

the new green value.

Number

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Color object. let c = color(255, 128, 128); // Draw the left rectangle. noStroke(); fill(c); rect(15, 20, 35, 60); // Change the green value. c.setGreen(255); // Draw the right rectangle. fill(c); rect(50, 20, 35, 60); describe('Two rectangles. The left one is salmon pink and the right one is yellow.'); } `

p5.Color

Color

Creating & Reading

Sets the blue component of a color.
The range depends on the colorMode(). In the default RGB mode it's between 0 and 255.

method

setBlue

blue

the new blue value.

Number

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Color object. let c = color(255, 128, 128); // Draw the left rectangle. noStroke(); fill(c); rect(15, 20, 35, 60); // Change the blue value. c.setBlue(255); // Draw the right rectangle. fill(c); rect(50, 20, 35, 60); describe('Two rectangles. The left one is salmon pink and the right one is pale fuchsia.'); } `

p5.Color

Color

Creating & Reading

Sets the alpha (transparency) value of a color.
The range depends on the colorMode(). In the default RGB mode it's between 0 and 255.

method

setAlpha

alpha

the new alpha value.

Number

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Color object. let c = color(255, 128, 128); // Draw the left rectangle. noStroke(); fill(c); rect(15, 20, 35, 60); // Change the alpha value. c.setAlpha(128); // Draw the right rectangle. fill(c); rect(50, 20, 35, 60); describe('Two rectangles. The left one is salmon pink and the right one is faded pink.'); } `

p5.Color

Color

Creating & Reading

Hue is the same in HSB and HSL, but the maximum value may be different. This function will return the HSB-normalized saturation when supplied with an HSB color object, but will default to the HSL-normalized saturation otherwise.

p5.Color

Color

Creating & Reading

Saturation is scaled differently in HSB and HSL. This function will return the HSB saturation when supplied with an HSB color object, but will default to the HSL saturation otherwise.

p5.Color

Color

Creating & Reading

For HSB and HSL, interpret the gray level as a brightness/lightness value (they are equivalent when chroma is zero). For RGB, normalize the gray level according to the blue maximum.

p5.Color

Color

Creating & Reading

Starts defining a shape that will mask any shapes drawn afterward.
Any shapes drawn between `beginClip()` and endClip() will add to the mask shape. The mask will apply to anything drawn after endClip().
The parameter, `options`, is optional. If an object with an `invert` property is passed, as in `beginClip({ invert: true })`, it will be used to set the masking mode. `{ invert: true }` inverts the mask, creating holes in shapes that are masked. `invert` is `false` by default.
Masks can be contained between the push() and pop() functions. Doing so allows unmasked shapes to be drawn after masked shapes.
Masks can also be defined in a callback function that's passed to clip().

method

beginClip

options

an object containing clip settings.

Object

` function setup() { createCanvas(100, 100); background(200); // Create a mask. beginClip(); triangle(15, 37, 30, 13, 43, 37); circle(45, 45, 7); endClip(); // Draw a backing shape. square(5, 5, 45); describe('A white triangle and circle on a gray background.'); } `

` function setup() { createCanvas(100, 100); background(200); // Create an inverted mask. beginClip({ invert: true }); triangle(15, 37, 30, 13, 43, 37); circle(45, 45, 7); endClip(); // Draw a backing shape. square(5, 5, 45); describe('A white square at the top-left corner of a gray square. The white square has a triangle and a circle cut out of it.'); } `
` function setup() { createCanvas(100, 100); background(200); noStroke(); // Draw a masked shape. push(); // Create a mask. beginClip(); triangle(15, 37, 30, 13, 43, 37); circle(45, 45, 7); endClip(); // Draw a backing shape. square(5, 5, 45); pop(); // Translate the origin to the center. translate(50, 50); // Draw an inverted masked shape. push(); // Create an inverted mask. beginClip({ invert: true }); triangle(15, 37, 30, 13, 43, 37); circle(45, 45, 7); endClip(); // Draw a backing shape. square(5, 5, 45); pop(); describe('In the top left, a white triangle and circle. In the bottom right, a white square with a triangle and circle cut out of it.'); } `

` function setup() { createCanvas(100, 100, WEBGL); describe('A silhouette of a rotating torus colored fuchsia.'); } function draw() { background(200); // Create a mask. beginClip(); push(); rotateX(frameCount * 0.01); rotateY(frameCount * 0.01); scale(0.5); torus(30, 15); pop(); endClip(); // Draw a backing shape. noStroke(); fill('fuchsia'); plane(100); } `

` function setup() { createCanvas(100, 100, WEBGL); describe('A silhouette of a rotating torus colored with a gradient from cyan to purple.'); } function draw() { background(200); // Create a mask. beginClip(); push(); rotateX(frameCount * 0.01); rotateY(frameCount * 0.01); scale(0.5); torus(30, 15); pop(); endClip(); // Draw a backing shape. noStroke(); beginShape(QUAD_STRIP); fill(0, 255, 255); vertex(-width / 2, -height / 2); vertex(width / 2, -height / 2); fill(100, 0, 100); vertex(-width / 2, height / 2); vertex(width / 2, height / 2); endShape(); } `

p5

Color

Setting

Ends defining a mask that was started with beginClip().

method

endClip

` function setup() { createCanvas(100, 100); background(200); // Create a mask. beginClip(); triangle(15, 37, 30, 13, 43, 37); circle(45, 45, 7); endClip(); // Draw a backing shape. square(5, 5, 45); describe('A white triangle and circle on a gray background.'); } `

p5

Color

Setting

Defines a shape that will mask any shapes drawn afterward.
The first parameter, `callback`, is a function that defines the mask. Any shapes drawn in `callback` will add to the mask shape. The mask will apply to anything drawn after `clip()` is called.
The second parameter, `options`, is optional. If an object with an `invert` property is passed, as in `beginClip({ invert: true })`, it will be used to set the masking mode. `{ invert: true }` inverts the mask, creating holes in shapes that are masked. `invert` is `false` by default.
Masks can be contained between the push() and pop() functions. Doing so allows unmasked shapes to be drawn after masked shapes.
Masks can also be defined with beginClip() and endClip().

method

clip

callback

a function that draws the mask shape.

Function

options

an object containing clip settings.

Object

` function setup() { createCanvas(100, 100); background(200); // Create a mask. clip(mask); // Draw a backing shape. square(5, 5, 45); describe('A white triangle and circle on a gray background.'); } // Declare a function that defines the mask. function mask() { triangle(15, 37, 30, 13, 43, 37); circle(45, 45, 7); } `

` function setup() { createCanvas(100, 100); background(200); // Create an inverted mask. clip(mask, { invert: true }); // Draw a backing shape. square(5, 5, 45); describe('A white square at the top-left corner of a gray square. The white square has a triangle and a circle cut out of it.'); } // Declare a function that defines the mask. function mask() { triangle(15, 37, 30, 13, 43, 37); circle(45, 45, 7); } `
` function setup() { createCanvas(100, 100); background(200); noStroke(); // Draw a masked shape. push(); // Create a mask. clip(mask); // Draw a backing shape. square(5, 5, 45); pop(); // Translate the origin to the center. translate(50, 50); // Draw an inverted masked shape. push(); // Create an inverted mask. clip(mask, { invert: true }); // Draw a backing shape. square(5, 5, 45); pop(); describe('In the top left, a white triangle and circle. In the bottom right, a white square with a triangle and circle cut out of it.'); } // Declare a function that defines the mask. function mask() { triangle(15, 37, 30, 13, 43, 37); circle(45, 45, 7); } `

` function setup() { createCanvas(100, 100, WEBGL); describe('A silhouette of a rotating torus colored fuchsia.'); } function draw() { background(200); // Create a mask. clip(mask); // Draw a backing shape. noStroke(); fill('fuchsia'); plane(100); } // Declare a function that defines the mask. function mask() { push(); rotateX(frameCount * 0.01); rotateY(frameCount * 0.01); scale(0.5); torus(30, 15); pop(); } `

` function setup() { createCanvas(100, 100, WEBGL); describe('A silhouette of a rotating torus colored with a gradient from cyan to purple.'); } function draw() { background(200); // Create a mask. clip(mask); // Draw a backing shape. noStroke(); beginShape(QUAD_STRIP); fill(0, 255, 255); vertex(-width / 2, -height / 2); vertex(width / 2, -height / 2); fill(100, 0, 100); vertex(-width / 2, height / 2); vertex(width / 2, height / 2); endShape(); } // Declare a function that defines the mask. function mask() { push(); rotateX(frameCount * 0.01); rotateY(frameCount * 0.01); scale(0.5); torus(30, 15); pop(); } `

p5

Color

Setting

Sets the color used for the background of the canvas.
By default, the background is transparent. `background()` is typically used within draw() to clear the display window at the beginning of each frame. It can also be used inside setup() to set the background on the first frame of animation.
The version of `background()` with one parameter interprets the value one of four ways. If the parameter is a `Number`, it's interpreted as a grayscale value. If the parameter is a `String`, it's interpreted as a CSS color string. RGB, RGBA, HSL, HSLA, hex, and named color strings are supported. If the parameter is a p5.Color object, it will be used as the background color. If the parameter is a p5.Image object, it will be used as the background image.
The version of `background()` with two parameters interprets the first one as a grayscale value. The second parameter sets the alpha (transparency) value.
The version of `background()` with three parameters interprets them as RGB, HSB, or HSL colors, depending on the current colorMode(). By default, colors are specified in RGB values. Calling `background(255, 204, 0)` sets the background a bright yellow color.

method

background

` function setup() { createCanvas(100, 100); // A grayscale value. background(51); describe('A canvas with a dark charcoal gray background.'); } `
` function setup() { createCanvas(100, 100); // A grayscale value and an alpha value. background(51, 0.4); describe('A canvas with a transparent gray background.'); } `
` function setup() { createCanvas(100, 100); // R, G & B values. background(255, 204, 0); describe('A canvas with a yellow background.'); } `
` function setup() { createCanvas(100, 100); // Use HSB color. colorMode(HSB); // H, S & B values. background(255, 204, 100); describe('A canvas with a royal blue background.'); } `
` function setup() { createCanvas(100, 100); // A CSS named color. background('red'); describe('A canvas with a red background.'); } `
` function setup() { createCanvas(100, 100); // Three-digit hex RGB notation. background('#fae'); describe('A canvas with a pink background.'); } `
` function setup() { createCanvas(100, 100); // Six-digit hex RGB notation. background('#222222'); describe('A canvas with a black background.'); } `
` function setup() { createCanvas(100, 100); // Integer RGB notation. background('rgb(0, 255, 0)'); describe('A canvas with a bright green background.'); } `
` function setup() { createCanvas(100, 100); // Integer RGBA notation. background('rgba(0, 255, 0, 0.25)'); describe('A canvas with a transparent green background.'); } `
` function setup() { createCanvas(100, 100); // Percentage RGB notation. background('rgb(100%, 0%, 10%)'); describe('A canvas with a red background.'); } `
` function setup() { createCanvas(100, 100); // Percentage RGBA notation. background('rgba(100%, 0%, 100%, 0.5)'); describe('A canvas with a transparent purple background.'); } `
` function setup() { createCanvas(100, 100); // A p5.Color object. let c = color(0, 0, 255); background(c); describe('A canvas with a blue background.'); } `

p5

Color

Setting

color

any value created by the color() function

p5.Color

colorstring

color string, possible formats include: integer rgb() or rgba(), percentage rgb() or rgba(), 3-digit hex, 6-digit hex.

String

a

opacity of the background relative to current color range (default is 0-255).

Number

gray

specifies a value between white and black.

Number

a



Number

v1

red value if color mode is RGB, or hue value if color mode is HSB.

Number

v2

green value if color mode is RGB, or saturation value if color mode is HSB.

Number

v3

blue value if color mode is RGB, or brightness value if color mode is HSB.

Number

a



Number

values

an array containing the red, green, blue and alpha components of the color.

Number[]

image

image created with loadImage() or createImage(), to set as background. (must be same size as the sketch window).

p5.Image

a



Number

Clears the pixels on the canvas.
`clear()` makes every pixel 100% transparent. Calling `clear()` doesn't clear objects created by `createX()` functions such as createGraphics(), createVideo(), and createImg(). These objects will remain unchanged after calling `clear()` and can be redrawn.
In WebGL mode, this function can clear the screen to a specific color. It interprets four numeric parameters as normalized RGBA color values. It also clears the depth buffer. If you are not using the WebGL renderer, these parameters will have no effect.

method

clear

` function setup() { createCanvas(100, 100); background(200); describe('A gray square. White circles are drawn as the user moves the mouse. The circles disappear when the user presses the mouse.'); } function draw() { circle(mouseX, mouseY, 20); } function mousePressed() { clear(); background(200); } `
` let pg; function setup() { createCanvas(100, 100); background(200); pg = createGraphics(60, 60); pg.background(200); pg.noStroke(); pg.circle(pg.width / 2, pg.height / 2, 15); image(pg, 20, 20); describe('A white circle drawn on a gray square. The square gets smaller when the mouse is pressed.'); } function mousePressed() { clear(); image(pg, 20, 20); } `

r

normalized red value.

Number

g

normalized green value.

Number

b

normalized blue value.

Number

a

normalized alpha value.

Number

p5

Color

Setting

Changes the way color values are interpreted.
By default, the `Number` parameters for fill(), stroke(), background(), and color() are defined by values between 0 and 255 using the RGB color model. This is equivalent to calling `colorMode(RGB, 255)`. Pure red is `color(255, 0, 0)` in this model.
Calling `colorMode(RGB, 100)` sets colors to use RGB color values between 0 and 100. Pure red is `color(100, 0, 0)` in this model.
Calling `colorMode(HSB)` or `colorMode(HSL)` changes to HSB or HSL system instead of RGB. Pure red is `color(0, 100, 100)` in HSB and `color(0, 100, 50)` in HSL.
p5.Color objects remember the mode that they were created in. Changing modes doesn't affect their appearance.

method

colorMode

` function setup() { createCanvas(100, 100); background(200); // Fill with pure red. fill(255, 0, 0); circle(50, 50, 25); describe('A gray square with a red circle at its center.'); } `

` function setup() { createCanvas(100, 100); background(200); // Use RGB color with values in the range 0-100. colorMode(RGB, 100); // Fill with pure red. fill(100, 0, 0); circle(50, 50, 25); describe('A gray square with a red circle at its center.'); } `

` function setup() { createCanvas(100, 100); background(200); // Use HSB color. colorMode(HSB); // Fill with pure red. fill(0, 100, 100); circle(50, 50, 25); describe('A gray square with a red circle at its center.'); } `

` function setup() { createCanvas(100, 100); background(200); // Use HSL color. colorMode(HSL); // Fill with pure red. fill(0, 100, 50); circle(50, 50, 25); describe('A gray square with a red circle at its center.'); } `

` function setup() { createCanvas(100, 100); // Use RGB color with values in the range 0-100. colorMode(RGB, 100); for (let x = 0; x < 100; x += 1) { for (let y = 0; y < 100; y += 1) { stroke(x, y, 0); point(x, y); } } describe( 'A diagonal green to red gradient from bottom-left to top-right with shading transitioning to black at top-left corner.' ); } `
` function setup() { createCanvas(100, 100); // Use HSB color with values in the range 0-100. colorMode(HSB, 100); for (let x = 0; x < 100; x += 1) { for (let y = 0; y < 100; y += 1) { stroke(x, y, 100); point(x, y); } } describe('A rainbow gradient from left-to-right. Brightness transitions to white at the top.'); } `
` function setup() { createCanvas(100, 100); // Create a p5.Color object. let myColor = color(180, 175, 230); background(myColor); // Use RGB color with values in the range 0-1. colorMode(RGB, 1); // Get the red, green, and blue color components. let redValue = red(myColor); let greenValue = green(myColor); let blueValue = blue(myColor); // Round the color components for display. redValue = round(redValue, 2); greenValue = round(greenValue, 2); blueValue = round(blueValue, 2); // Display the color components. text(`Red: ${redValue}`, 10, 10, 80, 80); text(`Green: ${greenValue}`, 10, 40, 80, 80); text(`Blue: ${blueValue}`, 10, 70, 80, 80); describe('A purple canvas with the red, green, and blue decimal values of the color written on it.'); } `
` function setup() { createCanvas(100, 100); background(255); // Use RGB color with alpha values in the range 0-1. colorMode(RGB, 255, 255, 255, 1); noFill(); strokeWeight(4); stroke(255, 0, 10, 0.3); circle(40, 40, 50); circle(50, 60, 50); describe('Two overlapping translucent pink circle outlines.'); } `

p5

Color

Setting

mode

either RGB, HSB or HSL, corresponding to Red/Green/Blue and Hue/Saturation/Brightness (or Lightness).

Constant

max

range for all values.

Number

mode



Constant

max1

range for the red or hue depending on the current color mode.

Number

max2

range for the green or saturation depending on the current color mode.

Number

max3

range for the blue or brightness/lightness depending on the current color mode.

Number

maxA

range for the alpha.

Number

Sets the color used to fill shapes.
Calling `fill(255, 165, 0)` or `fill('orange')` means all shapes drawn after the fill command will be filled with the color orange.
The version of `fill()` with one parameter interprets the value one of three ways. If the parameter is a `Number`, it's interpreted as a grayscale value. If the parameter is a `String`, it's interpreted as a CSS color string. A p5.Color object can also be provided to set the fill color.
The version of `fill()` with three parameters interprets them as RGB, HSB, or HSL colors, depending on the current colorMode(). The default color space is RGB, with each value in the range from 0 to 255.

method

fill

` function setup() { createCanvas(100, 100); background(200); // A grayscale value. fill(51); square(20, 20, 60); describe('A dark charcoal gray square with a black outline.'); } `
` function setup() { createCanvas(100, 100); background(200); // R, G & B values. fill(255, 204, 0); square(20, 20, 60); describe('A yellow square with a black outline.'); } `
` function setup() { createCanvas(100, 100); background(100); // Use HSB color. colorMode(HSB); // H, S & B values. fill(255, 204, 100); square(20, 20, 60); describe('A royal blue square with a black outline.'); } `
` function setup() { createCanvas(100, 100); background(200); // A CSS named color. fill('red'); square(20, 20, 60); describe('A red square with a black outline.'); } `
` function setup() { createCanvas(100, 100); background(200); // Three-digit hex RGB notation. fill('#fae'); square(20, 20, 60); describe('A pink square with a black outline.'); } `
` function setup() { createCanvas(100, 100); background(200); // Six-digit hex RGB notation. fill('#A251FA'); square(20, 20, 60); describe('A purple square with a black outline.'); } `
` function setup() { createCanvas(100, 100); background(200); // Integer RGB notation. fill('rgb(0, 255, 0)'); square(20, 20, 60); describe('A bright green square with a black outline.'); } `
` function setup() { createCanvas(100, 100); background(200); // Integer RGBA notation. fill('rgba(0, 255, 0, 0.25)'); square(20, 20, 60); describe('A soft green rectange with a black outline.'); } `
` function setup() { createCanvas(100, 100); background(200); // Percentage RGB notation. fill('rgb(100%, 0%, 10%)'); square(20, 20, 60); describe('A red square with a black outline.'); } `
` function setup() { createCanvas(100, 100); background(200); // Percentage RGBA notation. fill('rgba(100%, 0%, 100%, 0.5)'); square(20, 20, 60); describe('A dark fuchsia square with a black outline.'); } `
` function setup() { createCanvas(100, 100); background(200); // A p5.Color object. let c = color(0, 0, 255); fill(c); square(20, 20, 60); describe('A blue square with a black outline.'); } `

p5

Color

Setting

v1

red value if color mode is RGB or hue value if color mode is HSB.

Number

v2

green value if color mode is RGB or saturation value if color mode is HSB.

Number

v3

blue value if color mode is RGB or brightness value if color mode is HSB.

Number

alpha

alpha value, controls transparency (0 - transparent, 255 - opaque).

Number

value

a color string.

String

gray

a grayscale value.

Number

alpha



Number

values

an array containing the red, green, blue & and alpha components of the color.

Number[]

color

the fill color.

p5.Color

Disables setting the fill color for shapes.
Calling `noFill()` is the same as making the fill completely transparent, as in `fill(0, 0)`. If both noStroke() and `noFill()` are called, nothing will be drawn to the screen.

method

noFill

` function setup() { createCanvas(100, 100); background(200); // Draw the top square. square(32, 10, 35); // Draw the bottom square. noFill(); square(32, 55, 35); describe('A white square on above an empty square. Both squares have black outlines.'); } `
` function setup() { createCanvas(100, 100, WEBGL); describe('A purple cube wireframe spinning on a black canvas.'); } function draw() { background(0); // Style the box. noFill(); stroke(100, 100, 240); // Rotate the coordinates. rotateX(frameCount * 0.01); rotateY(frameCount * 0.01); // Draw the box. box(45); } `

p5

Color

Setting

Disables drawing points, lines, and the outlines of shapes.
Calling `noStroke()` is the same as making the stroke completely transparent, as in `stroke(0, 0)`. If both `noStroke()` and noFill() are called, nothing will be drawn to the screen.

method

noStroke

` function setup() { createCanvas(100, 100); background(200); noStroke(); square(20, 20, 60); describe('A white square with no outline.'); } `
` function setup() { createCanvas(100, 100, WEBGL); describe('A pink cube with no edge outlines spinning on a black canvas.'); } function draw() { background(0); // Style the box. noStroke(); fill(240, 150, 150); // Rotate the coordinates. rotateX(frameCount * 0.01); rotateY(frameCount * 0.01); // Draw the box. box(45); } `

p5

Color

Setting

Sets the color used to draw points, lines, and the outlines of shapes.
Calling `stroke(255, 165, 0)` or `stroke('orange')` means all shapes drawn after calling `stroke()` will be filled with the color orange. The way these parameters are interpreted may be changed with the colorMode() function.
The version of `stroke()` with one parameter interprets the value one of three ways. If the parameter is a `Number`, it's interpreted as a grayscale value. If the parameter is a `String`, it's interpreted as a CSS color string. A p5.Color object can also be provided to set the stroke color.
The version of `stroke()` with two parameters interprets the first one as a grayscale value. The second parameter sets the alpha (transparency) value.
The version of `stroke()` with three parameters interprets them as RGB, HSB, or HSL colors, depending on the current `colorMode()`.
The version of `stroke()` with four parameters interprets them as RGBA, HSBA, or HSLA colors, depending on the current `colorMode()`. The last parameter sets the alpha (transparency) value.

method

stroke

` function setup() { createCanvas(100, 100); background(200); // A grayscale value. strokeWeight(4); stroke(51); square(20, 20, 60); describe('A white square with a dark charcoal gray outline.'); } `
` function setup() { createCanvas(100, 100); background(200); // R, G & B values. stroke(255, 204, 0); strokeWeight(4); square(20, 20, 60); describe('A white square with a yellow outline.'); } `
` function setup() { createCanvas(100, 100); background(200); // Use HSB color. colorMode(HSB); // H, S & B values. strokeWeight(4); stroke(255, 204, 100); square(20, 20, 60); describe('A white square with a royal blue outline.'); } `
` function setup() { createCanvas(100, 100); background(200); // A CSS named color. stroke('red'); strokeWeight(4); square(20, 20, 60); describe('A white square with a red outline.'); } `
` function setup() { createCanvas(100, 100); background(200); // Three-digit hex RGB notation. stroke('#fae'); strokeWeight(4); square(20, 20, 60); describe('A white square with a pink outline.'); } `
` function setup() { createCanvas(100, 100); background(200); // Six-digit hex RGB notation. stroke('#222222'); strokeWeight(4); square(20, 20, 60); describe('A white square with a black outline.'); } `
` function setup() { createCanvas(100, 100); background(200); // Integer RGB notation. stroke('rgb(0, 255, 0)'); strokeWeight(4); square(20, 20, 60); describe('A whiite square with a bright green outline.'); } `
` function setup() { createCanvas(100, 100); background(200); // Integer RGBA notation. stroke('rgba(0, 255, 0, 0.25)'); strokeWeight(4); square(20, 20, 60); describe('A white square with a soft green outline.'); } `
` function setup() { createCanvas(100, 100); background(200); // Percentage RGB notation. stroke('rgb(100%, 0%, 10%)'); strokeWeight(4); square(20, 20, 60); describe('A white square with a red outline.'); } `
` function setup() { createCanvas(100, 100); background(200); // Percentage RGBA notation. stroke('rgba(100%, 0%, 100%, 0.5)'); strokeWeight(4); square(20, 20, 60); describe('A white square with a dark fuchsia outline.'); } `
` function setup() { createCanvas(100, 100); background(200); // A p5.Color object. stroke(color(0, 0, 255)); strokeWeight(4); square(20, 20, 60); describe('A white square with a blue outline.'); } `

p5

Color

Setting

v1

red value if color mode is RGB or hue value if color mode is HSB.

Number

v2

green value if color mode is RGB or saturation value if color mode is HSB.

Number

v3

blue value if color mode is RGB or brightness value if color mode is HSB.

Number

alpha

alpha value, controls transparency (0 - transparent, 255 - opaque).

Number

value

a color string.

String

gray

a grayscale value.

Number

alpha



Number

values

an array containing the red, green, blue, and alpha components of the color.

Number[]

color

the stroke color.

p5.Color

Starts using shapes to erase parts of the canvas.
All drawing that follows `erase()` will subtract from the canvas, revealing the web page underneath. The erased areas will become transparent, allowing the content behind the canvas to show through. The fill(), stroke(), and blendMode() have no effect once `erase()` is called.
The `erase()` function has two optional parameters. The first parameter sets the strength of erasing by the shape's interior. A value of 0 means that no erasing will occur. A value of 255 means that the shape's interior will fully erase the content underneath. The default value is 255 (full strength).
The second parameter sets the strength of erasing by the shape's edge. A value of 0 means that no erasing will occur. A value of 255 means that the shape's edge will fully erase the content underneath. The default value is 255 (full strength).
To cancel the erasing effect, use the noErase() function.
`erase()` has no effect on drawing done with the image() and background() functions.

method

erase

strengthFill

a number (0-255) for the strength of erasing under a shape's interior. Defaults to 255, which is full strength.

Number

strengthStroke

a number (0-255) for the strength of erasing under a shape's edge. Defaults to 255, which is full strength.

Number

` function setup() { createCanvas(100, 100); background(100, 100, 250); // Draw a pink square. fill(250, 100, 100); square(20, 20, 60); // Erase a circular area. erase(); circle(25, 30, 30); noErase(); describe('A purple canvas with a pink square in the middle. A circle is erased from the top-left, leaving a hole.'); } `

` function setup() { createCanvas(100, 100); background(100, 100, 250); // Draw a pink square. fill(250, 100, 100); square(20, 20, 60); // Erase a circular area. strokeWeight(5); erase(150, 255); circle(25, 30, 30); noErase(); describe('A purple canvas with a pink square in the middle. A circle at the top-left partially erases its interior and a fully erases its outline.'); } `

p5

Color

Setting

Ends erasing that was started with erase().
The fill(), stroke(), and blendMode() settings will return to what they were prior to calling erase().

method

noErase

` function setup() { createCanvas(100, 100); background(235, 145, 15); // Draw the left rectangle. noStroke(); fill(30, 45, 220); rect(30, 10, 10, 80); // Erase a circle. erase(); circle(50, 50, 60); noErase(); // Draw the right rectangle. rect(70, 10, 10, 80); describe('An orange canvas with two tall blue rectangles. A circular hole in the center erases the rectangle on the left but not the one on the right.'); } `

p5

Color

Setting

p5

Color

Prints out all the colors in the color pallete with white text. For color blindness testing.

p5

Color

p5

Color

p5

Color

p5

Color

p5

Color

This function does 3 things:
    1. Bounds the desired start/stop angles for an arc (in radians) so that:
           0 <= start < TWO_PI ;    start <= stop < start + TWO_PI
           
This means that the arc rendering functions don't have to be concerned with what happens if stop is smaller than start, or if the arc 'goes round more than once', etc.: they can just start at start and increase until stop and the correct arc will be drawn.
    2. Optionally adjusts the angles within each quadrant to counter the naive scaling of the underlying ellipse up from the unit circle. Without this, the angles become arbitrary when width != height: 45 degrees might be drawn at 5 degrees on a 'wide' ellipse, or at 85 degrees on a 'tall' ellipse.
    3. Flags up when start and stop correspond to the same place on the underlying ellipse. This is useful if you want to do something special there (like rendering a whole ellipse instead).

p5

Shape

2D Primitives

Draws an arc.
An arc is a section of an ellipse defined by the `x`, `y`, `w`, and `h` parameters. `x` and `y` set the location of the arc's center. `w` and `h` set the arc's width and height. See ellipse() and ellipseMode() for more details.
The fifth and sixth parameters, `start` and `stop`, set the angles between which to draw the arc. Arcs are always drawn clockwise from `start` to `stop`. The fifth and sixth parameters, start and stop, set the angles between which to draw the arc. Arcs are always drawn clockwise from start to stop. By default, angles are given in radians, but if angleMode (DEGREES) is set, the function interprets the values in degrees.
The seventh parameter, `mode`, is optional. It determines the arc's fill style. The fill modes are a semi-circle (`OPEN`), a closed semi-circle (`CHORD`), or a closed pie segment (`PIE`).
The eighth parameter, `detail`, is also optional. It determines how many vertices are used to draw the arc in WebGL mode. The default value is 25.

method

arc

x

x-coordinate of the arc's ellipse.

Number

y

y-coordinate of the arc's ellipse.

Number

w

width of the arc's ellipse by default.

Number

h

height of the arc's ellipse by default.

Number

start

angle to start the arc, specified in radians.

Number

stop

angle to stop the arc, specified in radians.

Number

mode

optional parameter to determine the way of drawing the arc. either CHORD, PIE, or OPEN.

Constant

detail

optional parameter for WebGL mode only. This is to specify the number of vertices that makes up the perimeter of the arc. Default value is 25. Won't draw a stroke for a detail of more than 50.

Integer

` function setup() { createCanvas(100, 100); background(200); arc(50, 50, 80, 80, 0, PI + HALF_PI); describe('A white circle on a gray canvas. The top-right quarter of the circle is missing.'); } `

` function setup() { createCanvas(100, 100); background(200); arc(50, 50, 80, 40, 0, PI + HALF_PI); describe('A white ellipse on a gray canvas. The top-right quarter of the ellipse is missing.'); } `

` function setup() { createCanvas(100, 100); background(200); // Bottom-right. arc(50, 55, 50, 50, 0, HALF_PI); noFill(); // Bottom-left. arc(50, 55, 60, 60, HALF_PI, PI); // Top-left. arc(50, 55, 70, 70, PI, PI + QUARTER_PI); // Top-right. arc(50, 55, 80, 80, PI + QUARTER_PI, TWO_PI); describe( 'A shattered outline of an circle with a quarter of a white circle at the bottom-right.' ); } `
` function setup() { createCanvas(100, 100); background(200); // Default fill mode. arc(50, 50, 80, 80, 0, PI + QUARTER_PI); describe('A white circle with the top-right third missing. The bottom is outlined in black.'); } `
` function setup() { createCanvas(100, 100); background(200); // OPEN fill mode. arc(50, 50, 80, 80, 0, PI + QUARTER_PI, OPEN); describe( 'A white circle missing a section from the top-right. The bottom is outlined in black.' ); } `
` function setup() { createCanvas(100, 100); background(200); // CHORD fill mode. arc(50, 50, 80, 80, 0, PI + QUARTER_PI, CHORD); describe('A white circle with a black outline missing a section from the top-right.'); } `
` function setup() { createCanvas(100, 100); background(200); // PIE fill mode. arc(50, 50, 80, 80, 0, PI + QUARTER_PI, PIE); describe('A white circle with a black outline. The top-right third is missing.'); } `
` function setup() { createCanvas(100, 100, WEBGL); background(200); // PIE fill mode. arc(0, 0, 80, 80, 0, PI + QUARTER_PI, PIE); describe('A white circle with a black outline. The top-right third is missing.'); } `
` function setup() { createCanvas(100, 100, WEBGL); background(200); // PIE fill mode with 5 vertices. arc(0, 0, 80, 80, 0, PI + QUARTER_PI, PIE, 5); describe('A white circle with a black outline. The top-right third is missing.'); } `
` function setup() { createCanvas(100, 100); describe('A yellow circle on a black background. The circle opens and closes its mouth.'); } function draw() { background(0); // Style the arc. noStroke(); fill(255, 255, 0); // Update start and stop angles. let biteSize = PI / 16; let startAngle = biteSize * sin(frameCount * 0.1) + biteSize; let endAngle = TWO_PI - startAngle; // Draw the arc. arc(50, 50, 80, 80, startAngle, endAngle, PIE); } `

p5

Shape

2D Primitives

Draws an ellipse (oval).
An ellipse is a round shape defined by the `x`, `y`, `w`, and `h` parameters. `x` and `y` set the location of its center. `w` and `h` set its width and height. See ellipseMode() for other ways to set its position.
If no height is set, 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 fifth parameter, `detail`, is also optional. It determines how many vertices are used to draw the ellipse in WebGL mode. The default value is 25.

method

ellipse

` function setup() { createCanvas(100, 100); background(200); ellipse(50, 50, 80, 80); describe('A white circle on a gray canvas.'); } `

` function setup() { createCanvas(100, 100); background(200); ellipse(50, 50, 80); describe('A white circle on a gray canvas.'); } `

` function setup() { createCanvas(100, 100); background(200); ellipse(50, 50, 80, 40); describe('A white ellipse on a gray canvas.'); } `

` function setup() { createCanvas(100, 100, WEBGL); background(200); ellipse(0, 0, 80, 40); describe('A white ellipse on a gray canvas.'); } `

` function setup() { createCanvas(100, 100, WEBGL); background(200); // Use 6 vertices. ellipse(0, 0, 80, 40, 6); describe('A white hexagon on a gray canvas.'); } `

p5

Shape

2D Primitives

x

x-coordinate of the center of the ellipse.

Number

y

y-coordinate of the center of the ellipse.

Number

w

width of the ellipse.

Number

h

height of the ellipse.

Number

x



Number

y



Number

w



Number

h



Number

detail

optional parameter for WebGL mode only. This is to specify the number of vertices that makes up the perimeter of the ellipse. Default value is 25. Won't draw a stroke for a detail of more than 50.

Integer

Draws a circle.
A circle is a round shape defined by the `x`, `y`, and `d` parameters. `x` and `y` set the location of its center. `d` sets its width and height (diameter). Every point on the circle's edge is the same distance, `0.5 * d`, from its center. `0.5 * d` (half the diameter) is the circle's radius. See ellipseMode() for other ways to set its position.

method

circle

x

x-coordinate of the center of the circle.

Number

y

y-coordinate of the center of the circle.

Number

d

diameter of the circle.

Number

` function setup() { createCanvas(100, 100); background(200); circle(50, 50, 25); describe('A white circle with black outline in the middle of a gray canvas.'); } `

` function setup() { createCanvas(100, 100, WEBGL); background(200); circle(0, 0, 25); describe('A white circle with black outline in the middle of a gray canvas.'); } `

p5

Shape

2D Primitives

Draws a straight line between two points.
A line's default width is one pixel. The version of `line()` with four parameters draws the line in 2D. To color a line, use the stroke() function. To change its width, use the strokeWeight() function. A line can't be filled, so the fill() function won't affect the line's color.
The version of `line()` with six parameters allows the line to be drawn in 3D space. Doing so requires adding the `WEBGL` argument to createCanvas().

method

line

` function setup() { createCanvas(100, 100); background(200); line(30, 20, 85, 75); describe( 'A black line on a gray canvas running from top-center to bottom-right.' ); } `

` function setup() { createCanvas(100, 100); background(200); // Style the line. stroke('magenta'); strokeWeight(5); line(30, 20, 85, 75); describe( 'A thick, magenta line on a gray canvas running from top-center to bottom-right.' ); } `
` function setup() { createCanvas(100, 100); background(200); // Top. line(30, 20, 85, 20); // Right. stroke(126); line(85, 20, 85, 75); // Bottom. stroke(255); line(85, 75, 30, 75); describe( 'Three lines drawn in grayscale on a gray canvas. They form the top, right, and bottom sides of a square.' ); } `

` function setup() { createCanvas(100, 100, WEBGL); background(200); line(-20, -30, 35, 25); describe( 'A black line on a gray canvas running from top-center to bottom-right.' ); } `
` function setup() { createCanvas(100, 100, WEBGL); describe('A black line connecting two spheres. The scene spins slowly.'); } function draw() { background(200); // Rotate around the y-axis. rotateY(frameCount * 0.01); // Draw a line. line(0, 0, 0, 30, 20, -10); // Draw the center sphere. sphere(10); // Translate to the second point. translate(30, 20, -10); // Draw the bottom-right sphere. sphere(10); } `

p5

Shape

2D Primitives

x1

the x-coordinate of the first point.

Number

y1

the y-coordinate of the first point.

Number

x2

the x-coordinate of the second point.

Number

y2

the y-coordinate of the second point.

Number

x1



Number

y1



Number

z1

the z-coordinate of the first point.

Number

x2



Number

y2



Number

z2

the z-coordinate of the second point.

Number

Draws a single point in space.
A point's default width is one pixel. To color a point, use the stroke() function. To change its width, use the strokeWeight() function. A point can't be filled, so the fill() function won't affect the point's color.
The version of `point()` with two parameters allows the point's location to be set with its x- and y-coordinates, as in `point(10, 20)`.
The version of `point()` with three parameters allows the point to be drawn in 3D space with x-, y-, and z-coordinates, as in `point(10, 20, 30)`. Doing so requires adding the `WEBGL` argument to createCanvas().
The version of `point()` with one parameter allows the point's location to be set with a p5.Vector object.

method

point

` function setup() { createCanvas(100, 100); background(200); // Top-left. point(30, 20); // Top-right. point(85, 20); // Bottom-right. point(85, 75); // Bottom-left. point(30, 75); describe( 'Four small, black points drawn on a gray canvas. The points form the corners of a square.' ); } `
` function setup() { createCanvas(100, 100); background(200); // Top-left. point(30, 20); // Top-right. point(70, 20); // Style the next points. stroke('purple'); strokeWeight(10); // Bottom-right. point(70, 80); // Bottom-left. point(30, 80); describe( 'Four points drawn on a gray canvas. Two are black and two are purple. The points form the corners of a square.' ); } `
` function setup() { createCanvas(100, 100); background(200); // Top-left. let a = createVector(30, 20); point(a); // Top-right. let b = createVector(70, 20); point(b); // Bottom-right. let c = createVector(70, 80); point(c); // Bottom-left. let d = createVector(30, 80); point(d); describe( 'Four small, black points drawn on a gray canvas. The points form the corners of a square.' ); } `
` function setup() { createCanvas(100, 100, WEBGL); describe('Two purple points drawn on a gray canvas.'); } function draw() { background(200); // Style the points. stroke('purple'); strokeWeight(10); // Top-left. point(-20, -30); // Bottom-right. point(20, 30); } `
` function setup() { createCanvas(100, 100, WEBGL); describe('Two purple points drawn on a gray canvas. The scene spins slowly.'); } function draw() { background(200); // Rotate around the y-axis. rotateY(frameCount * 0.01); // Style the points. stroke('purple'); strokeWeight(10); // Top-left. point(-20, -30, 0); // Bottom-right. point(20, 30, -50); } `

p5

Shape

2D Primitives

x

the x-coordinate.

Number

y

the y-coordinate.

Number

z

the z-coordinate (for WebGL mode).

Number

coordinateVector

the coordinate vector.

p5.Vector

Draws a quadrilateral (four-sided shape).
Quadrilaterals include rectangles, squares, rhombuses, and trapezoids. The first pair of parameters `(x1, y1)` sets the quad's first point. The next three pairs of parameters set the coordinates for its next three points `(x2, y2)`, `(x3, y3)`, and `(x4, y4)`. Points should be added in either clockwise or counter-clockwise order.
The version of `quad()` with twelve parameters allows the quad to be drawn in 3D space. Doing so requires adding the `WEBGL` argument to createCanvas().
The thirteenth and fourteenth parameters are optional. In WebGL mode, they set the number of segments used to draw the quadrilateral in the x- and y-directions. They're both 2 by default.

method

quad

` function setup() { createCanvas(100, 100); background(200); quad(20, 20, 80, 20, 80, 80, 20, 80); describe('A white square with a black outline drawn on a gray canvas.'); } `
` function setup() { createCanvas(100, 100); background(200); quad(20, 30, 80, 30, 80, 70, 20, 70); describe('A white rectangle with a black outline drawn on a gray canvas.'); } `
` function setup() { createCanvas(100, 100); background(200); quad(50, 62, 86, 50, 50, 38, 14, 50); describe('A white rhombus with a black outline drawn on a gray canvas.'); } `
` function setup() { createCanvas(100, 100); background(200); quad(20, 50, 80, 30, 80, 70, 20, 70); describe('A white trapezoid with a black outline drawn on a gray canvas.'); } `
` function setup() { createCanvas(100, 100, WEBGL); background(200); quad(-30, -30, 30, -30, 30, 30, -30, 30); describe('A white square with a black outline drawn on a gray canvas.'); } `
` function setup() { createCanvas(100, 100, WEBGL); describe('A wavy white surface spins around on gray canvas.'); } function draw() { background(200); // Rotate around the y-axis. rotateY(frameCount * 0.01); // Draw the quad. quad(-30, -30, 0, 30, -30, 0, 30, 30, 20, -30, 30, -20); } `

p5

Shape

2D Primitives

x1

the x-coordinate of the first point.

Number

y1

the y-coordinate of the first point.

Number

x2

the x-coordinate of the second point.

Number

y2

the y-coordinate of the second point.

Number

x3

the x-coordinate of the third point.

Number

y3

the y-coordinate of the third point.

Number

x4

the x-coordinate of the fourth point.

Number

y4

the y-coordinate of the fourth point.

Number

detailX

number of segments in the x-direction.

Integer

detailY

number of segments in the y-direction.

Integer

x1



Number

y1



Number

z1

the z-coordinate of the first point.

Number

x2



Number

y2



Number

z2

the z-coordinate of the second point.

Number

x3



Number

y3



Number

z3

the z-coordinate of the third point.

Number

x4



Number

y4



Number

z4

the z-coordinate of the fourth point.

Number

detailX



Integer

detailY



Integer

Draws a rectangle.
A rectangle is a four-sided shape defined by the `x`, `y`, `w`, and `h` parameters. `x` and `y` set the location of its top-left corner. `w` sets its width and `h` sets its height. Every angle in the rectangle measures 90˚. See rectMode() for other ways to define rectangles.
The version of `rect()` with five parameters creates a rounded rectangle. The fifth parameter sets the radius for all four corners.
The version of `rect()` with eight parameters also creates a rounded rectangle. Each of the last four parameters set the radius of a corner. The radii start with the top-left corner and move clockwise around the rectangle. If any of these parameters are omitted, they are set to the value of the last radius that was set.

method

rect

` function setup() { createCanvas(100, 100); background(200); rect(30, 20, 55, 55); describe('A white square with a black outline on a gray canvas.'); } `
` function setup() { createCanvas(100, 100); background(200); rect(30, 20, 55, 40); describe('A white rectangle with a black outline on a gray canvas.'); } `
` function setup() { createCanvas(100, 100); background(200); // Give all corners a radius of 20. rect(30, 20, 55, 50, 20); describe('A white rectangle with a black outline and round edges on a gray canvas.'); } `
` function setup() { createCanvas(100, 100); background(200); // Give each corner a unique radius. rect(30, 20, 55, 50, 20, 15, 10, 5); describe('A white rectangle with a black outline and round edges of different radii.'); } `
` function setup() { createCanvas(100, 100, WEBGL); background(200); rect(-20, -30, 55, 55); describe('A white square with a black outline on a gray canvas.'); } `
` function setup() { createCanvas(100, 100, WEBGL); describe('A white square spins around on gray canvas.'); } function draw() { background(200); // Rotate around the y-axis. rotateY(frameCount * 0.01); // Draw the rectangle. rect(-20, -30, 55, 55); } `

p5

Shape

2D Primitives

x

x-coordinate of the rectangle.

Number

y

y-coordinate of the rectangle.

Number

w

width of the rectangle.

Number

h

height of the rectangle.

Number

tl

optional radius of top-left corner.

Number

tr

optional radius of top-right corner.

Number

br

optional radius of bottom-right corner.

Number

bl

optional radius of bottom-left corner.

Number

x



Number

y



Number

w



Number

h



Number

detailX

number of segments in the x-direction (for WebGL mode).

Integer

detailY

number of segments in the y-direction (for WebGL mode).

Integer

Draws a square.
A square is a four-sided shape defined by the `x`, `y`, and `s` parameters. `x` and `y` set the location of its top-left corner. `s` sets its width and height. Every angle in the square measures 90˚ and all its sides are the same length. See rectMode() for other ways to define squares.
The version of `square()` with four parameters creates a rounded square. The fourth parameter sets the radius for all four corners.
The version of `square()` with seven parameters also creates a rounded square. Each of the last four parameters set the radius of a corner. The radii start with the top-left corner and move clockwise around the square. If any of these parameters are omitted, they are set to the value of the last radius that was set.

method

square

x

x-coordinate of the square.

Number

y

y-coordinate of the square.

Number

s

side size of the square.

Number

tl

optional radius of top-left corner.

Number

tr

optional radius of top-right corner.

Number

br

optional radius of bottom-right corner.

Number

bl

optional radius of bottom-left corner.

Number

` function setup() { createCanvas(100, 100); background(200); square(30, 20, 55); describe('A white square with a black outline in on a gray canvas.'); } `
` function setup() { createCanvas(100, 100); background(200); // Give all corners a radius of 20. square(30, 20, 55, 20); describe( 'A white square with a black outline and round edges on a gray canvas.' ); } `
` function setup() { createCanvas(100, 100); background(200); // Give each corner a unique radius. square(30, 20, 55, 20, 15, 10, 5); describe('A white square with a black outline and round edges of different radii.'); } `
` function setup() { createCanvas(100, 100, WEBGL); background(200); square(-20, -30, 55); describe('A white square with a black outline in on a gray canvas.'); } `
` function setup() { createCanvas(100, 100, WEBGL); describe('A white square spins around on gray canvas.'); } function draw() { background(200); // Rotate around the y-axis. rotateY(frameCount * 0.01); // Draw the square. square(-20, -30, 55); } `

p5

Shape

2D Primitives

Draws a triangle.
A triangle is a three-sided shape defined by three points. The first two parameters specify the triangle's first point `(x1, y1)`. The middle two parameters specify its second point `(x2, y2)`. And the last two parameters specify its third point `(x3, y3)`.

method

triangle

x1

x-coordinate of the first point.

Number

y1

y-coordinate of the first point.

Number

x2

x-coordinate of the second point.

Number

y2

y-coordinate of the second point.

Number

x3

x-coordinate of the third point.

Number

y3

y-coordinate of the third point.

Number

` function setup() { createCanvas(100, 100); background(200); triangle(30, 75, 58, 20, 86, 75); describe('A white triangle with a black outline on a gray canvas.'); } `
` function setup() { createCanvas(100, 100, WEBGL); background(200); triangle(-20, 25, 8, -30, 36, 25); describe('A white triangle with a black outline on a gray canvas.'); } `
` function setup() { createCanvas(100, 100, WEBGL); describe('A white triangle spins around on a gray canvas.'); } function draw() { background(200); // Rotate around the y-axis. rotateY(frameCount * 0.01); // Draw the triangle. triangle(-20, 25, 8, -30, 36, 25); } `

p5

Shape

2D Primitives

Changes where ellipses, circles, and arcs are drawn.
By default, the first two parameters of ellipse(), circle(), and arc() are the x- and y-coordinates of the shape's center. The next parameters set the shape's width and height. This is the same as calling `ellipseMode(CENTER)`.
`ellipseMode(RADIUS)` also uses the first two parameters to set the x- and y-coordinates of the shape's center. The next parameters are half of the shapes's width and height. Calling `ellipse(0, 0, 10, 15)` draws a shape with a width of 20 and height of 30.
`ellipseMode(CORNER)` uses the first two parameters as the upper-left corner of the shape. The next parameters are its width and height.
`ellipseMode(CORNERS)` uses the first two parameters as the location of one corner of the ellipse's bounding box. The next parameters are the location of the opposite corner.
The argument passed to `ellipseMode()` must be written in ALL CAPS because the constants `CENTER`, `RADIUS`, `CORNER`, and `CORNERS` are defined this way. JavaScript is a case-sensitive language.

method

ellipseMode

mode

either CENTER, RADIUS, CORNER, or CORNERS

Constant

` function setup() { createCanvas(100, 100); background(200); // White ellipse. ellipseMode(RADIUS); fill(255); ellipse(50, 50, 30, 30); // Gray ellipse. ellipseMode(CENTER); fill(100); ellipse(50, 50, 30, 30); describe('A white circle with a gray circle at its center. Both circles have black outlines.'); } `
` function setup() { createCanvas(100, 100); background(200); // White ellipse. ellipseMode(CORNER); fill(255); ellipse(25, 25, 50, 50); // Gray ellipse. ellipseMode(CORNERS); fill(100); ellipse(25, 25, 50, 50); describe('A white circle with a gray circle at its top-left corner. Both circles have black outlines.'); } `

p5

Shape

Attributes

Draws certain features with jagged (aliased) edges.
smooth() is active by default. In 2D mode, `noSmooth()` is helpful for scaling up images without blurring. The functions don't affect shapes or fonts.
In WebGL mode, `noSmooth()` causes all shapes to be drawn with jagged (aliased) edges. The functions don't affect images or fonts.

method

noSmooth

` let heart; // Load a pixelated heart image from an image data string. function preload() { heart = loadImage('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAAXNSR0IArs4c6QAAAEZJREFUGFd9jcsNACAIQ9tB2MeR3YdBMBBq8CIXPi2vBICIiOwkOedatllqWO6Y8yOWoyuNf1GZwgmf+RRG2YXr+xVFmA8HZ9Mx/KGPMtcAAAAASUVORK5CYII='); } function setup() { createCanvas(100, 100); background(50); // Antialiased hearts. image(heart, 10, 10); image(heart, 20, 10, 16, 16); image(heart, 40, 10, 32, 32); // Aliased hearts. noSmooth(); image(heart, 10, 60); image(heart, 20, 60, 16, 16); image(heart, 40, 60, 32, 32); } `
` function setup() { createCanvas(100, 100, WEBGL); background(200); circle(0, 0, 80); describe('A white circle on a gray background.'); } `
` function setup() { createCanvas(100, 100, WEBGL); // Disable smoothing. noSmooth(); background(200); circle(0, 0, 80); describe('A pixelated white circle on a gray background.'); } `

p5

Shape

Attributes

Changes where rectangles and squares are drawn.
By default, the first two parameters of rect() and square(), are the x- and y-coordinates of the shape's upper left corner. The next parameters set the shape's width and height. This is the same as calling `rectMode(CORNER)`.
`rectMode(CORNERS)` also uses the first two parameters as the location of one of the corners. The next parameters are the location of the opposite corner. This mode only works for rect().
`rectMode(CENTER)` uses the first two parameters as the x- and y-coordinates of the shape's center. The next parameters are its width and height.
`rectMode(RADIUS)` also uses the first two parameters as the x- and y-coordinates of the shape's center. The next parameters are half of the shape's width and height.
The argument passed to `rectMode()` must be written in ALL CAPS because the constants `CENTER`, `RADIUS`, `CORNER`, and `CORNERS` are defined this way. JavaScript is a case-sensitive language.

method

rectMode

mode

either CORNER, CORNERS, CENTER, or RADIUS

Constant

` function setup() { createCanvas(100, 100); background(200); rectMode(CORNER); fill(255); rect(25, 25, 50, 50); rectMode(CORNERS); fill(100); rect(25, 25, 50, 50); describe('A small gray square drawn at the top-left corner of a white square.'); } `
` function setup() { createCanvas(100, 100); background(200); rectMode(RADIUS); fill(255); rect(50, 50, 30, 30); rectMode(CENTER); fill(100); rect(50, 50, 30, 30); describe('A small gray square drawn at the center of a white square.'); } `
` function setup() { createCanvas(100, 100); background(200); rectMode(CORNER); fill(255); square(25, 25, 50); describe('A white square.'); } `
` function setup() { createCanvas(100, 100); background(200); rectMode(RADIUS); fill(255); square(50, 50, 30); rectMode(CENTER); fill(100); square(50, 50, 30); describe('A small gray square drawn at the center of a white square.'); } `

p5

Shape

Attributes

Draws certain features with smooth (antialiased) edges.
`smooth()` is active by default. In 2D mode, noSmooth() is helpful for scaling up images without blurring. The functions don't affect shapes or fonts.
In WebGL mode, noSmooth() causes all shapes to be drawn with jagged (aliased) edges. The functions don't affect images or fonts.

method

smooth

` let heart; // Load a pixelated heart image from an image data string. function preload() { heart = loadImage('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAAXNSR0IArs4c6QAAAEZJREFUGFd9jcsNACAIQ9tB2MeR3YdBMBBq8CIXPi2vBICIiOwkOedatllqWO6Y8yOWoyuNf1GZwgmf+RRG2YXr+xVFmA8HZ9Mx/KGPMtcAAAAASUVORK5CYII='); } function setup() { createCanvas(100, 100); background(50); // Antialiased hearts. image(heart, 10, 10); image(heart, 20, 10, 16, 16); image(heart, 40, 10, 32, 32); // Aliased hearts. noSmooth(); image(heart, 10, 60); image(heart, 20, 60, 16, 16); image(heart, 40, 60, 32, 32); } `
` function setup() { createCanvas(100, 100, WEBGL); background(200); circle(0, 0, 80); describe('A white circle on a gray background.'); } `
` function setup() { createCanvas(100, 100, WEBGL); // Disable smoothing. noSmooth(); background(200); circle(0, 0, 80); describe('A pixelated white circle on a gray background.'); } `

p5

Shape

Attributes

Sets the style for rendering the ends of lines.
The caps for line endings are either rounded (`ROUND`), squared (`SQUARE`), or extended (`PROJECT`). The default cap is `ROUND`.
The argument passed to `strokeCap()` must be written in ALL CAPS because the constants `ROUND`, `SQUARE`, and `PROJECT` are defined this way. JavaScript is a case-sensitive language.

method

strokeCap

cap

either ROUND, SQUARE, or PROJECT

Constant

` function setup() { createCanvas(100, 100); background(200); strokeWeight(12); // Top. strokeCap(ROUND); line(20, 30, 80, 30); // Middle. strokeCap(SQUARE); line(20, 50, 80, 50); // Bottom. strokeCap(PROJECT); line(20, 70, 80, 70); describe( 'Three horizontal lines. The top line has rounded ends, the middle line has squared ends, and the bottom line has longer, squared ends.' ); } `

p5

Shape

Attributes

Sets the style of the joints that connect line segments.
Joints are either mitered (`MITER`), beveled (`BEVEL`), or rounded (`ROUND`). The default joint is `MITER` in 2D mode and `ROUND` in WebGL mode.
The argument passed to `strokeJoin()` must be written in ALL CAPS because the constants `MITER`, `BEVEL`, and `ROUND` are defined this way. JavaScript is a case-sensitive language.

method

strokeJoin

join

either MITER, BEVEL, or ROUND

Constant

` function setup() { createCanvas(100, 100); background(200); // Style the line. noFill(); strokeWeight(10); strokeJoin(MITER); // Draw the line. beginShape(); vertex(35, 20); vertex(65, 50); vertex(35, 80); endShape(); describe('A right-facing arrowhead shape with a pointed tip in center of canvas.'); } `
` function setup() { createCanvas(100, 100); background(200); // Style the line. noFill(); strokeWeight(10); strokeJoin(BEVEL); // Draw the line. beginShape(); vertex(35, 20); vertex(65, 50); vertex(35, 80); endShape(); describe('A right-facing arrowhead shape with a flat tip in center of canvas.'); } `
` function setup() { createCanvas(100, 100); background(200); // Style the line. noFill(); strokeWeight(10); strokeJoin(ROUND); // Draw the line. beginShape(); vertex(35, 20); vertex(65, 50); vertex(35, 80); endShape(); describe('A right-facing arrowhead shape with a rounded tip in center of canvas.'); } `

p5

Shape

Attributes

Sets the width of the stroke used for points, lines, and the outlines of shapes.
Note: `strokeWeight()` is affected by transformations, especially calls to scale().

method

strokeWeight

weight

the weight of the stroke (in pixels).

Number

` function setup() { createCanvas(100, 100); background(200); // Top. line(20, 20, 80, 20); // Middle. strokeWeight(4); line(20, 40, 80, 40); // Bottom. strokeWeight(10); line(20, 70, 80, 70); describe('Three horizontal black lines. The top line is thin, the middle is medium, and the bottom is thick.'); } `
` function setup() { createCanvas(100, 100); background(200); // Top. line(20, 20, 80, 20); // Scale by a factor of 5. scale(5); // Bottom. Coordinates are adjusted for scaling. line(4, 8, 16, 8); describe('Two horizontal black lines. The top line is thin and the bottom is five times thicker than the top.'); } `

p5

Shape

Attributes

Draws a Bézier curve.
Bézier curves can form shapes and curves that slope gently. They're defined by two anchor points and two control points. Bézier curves provide more control than the spline curves created with the curve() function.
The first two parameters, `x1` and `y1`, set the first anchor point. The first anchor point is where the curve starts.
The next four parameters, `x2`, `y2`, `x3`, and `y3`, set the two control points. The control points "pull" the curve towards them.
The seventh and eighth parameters, `x4` and `y4`, set the last anchor point. The last anchor point is where the curve ends.
Bézier curves can also be drawn in 3D using WebGL mode. The 3D version of `bezier()` has twelve arguments because each point has x-, y-, and z-coordinates.

method

bezier

` function setup() { createCanvas(100, 100); background(200); // Draw the anchor points in black. stroke(0); strokeWeight(5); point(85, 20); point(15, 80); // Draw the control points in red. stroke(255, 0, 0); point(10, 10); point(90, 90); // Draw a black bezier curve. noFill(); stroke(0); strokeWeight(1); bezier(85, 20, 10, 10, 90, 90, 15, 80); // Draw red lines from the anchor points to the control points. stroke(255, 0, 0); line(85, 20, 10, 10); line(15, 80, 90, 90); describe( 'A gray square with three curves. A black s-curve has two straight, red lines that extend from its ends. The endpoints of all the curves are marked with dots.' ); } `
` // Click the mouse near the red dot in the top-left corner // and drag to change the curve's shape. let x2 = 10; let y2 = 10; let isChanging = false; function setup() { createCanvas(100, 100); describe( 'A gray square with three curves. A black s-curve has two straight, red lines that extend from its ends. The endpoints of all the curves are marked with dots.' ); } function draw() { background(200); // Draw the anchor points in black. stroke(0); strokeWeight(5); point(85, 20); point(15, 80); // Draw the control points in red. stroke(255, 0, 0); point(x2, y2); point(90, 90); // Draw a black bezier curve. noFill(); stroke(0); strokeWeight(1); bezier(85, 20, x2, y2, 90, 90, 15, 80); // Draw red lines from the anchor points to the control points. stroke(255, 0, 0); line(85, 20, x2, y2); line(15, 80, 90, 90); } // Start changing the first control point if the user clicks near it. function mousePressed() { if (dist(mouseX, mouseY, x2, y2) < 20) { isChanging = true; } } // Stop changing the first control point when the user releases the mouse. function mouseReleased() { isChanging = false; } // Update the first control point while the user drags the mouse. function mouseDragged() { if (isChanging === true) { x2 = mouseX; y2 = mouseY; } } `
` function setup() { createCanvas(100, 100); background('skyblue'); // Draw the red balloon. fill('red'); bezier(50, 60, 5, 15, 95, 15, 50, 60); // Draw the balloon string. line(50, 60, 50, 80); describe('A red balloon in a blue sky.'); } `
` function setup() { createCanvas(100, 100, WEBGL); describe('A red balloon in a blue sky. The balloon rotates slowly, revealing that it is flat.'); } function draw() { background('skyblue'); // Rotate around the y-axis. rotateY(frameCount * 0.01); // Draw the red balloon. fill('red'); bezier(0, 0, 0, -45, -45, 0, 45, -45, 0, 0, 0, 0); // Draw the balloon string. line(0, 0, 0, 0, 20, 0); } `

p5

Shape

Curves

x1

x-coordinate of the first anchor point.

Number

y1

y-coordinate of the first anchor point.

Number

x2

x-coordinate of the first control point.

Number

y2

y-coordinate of the first control point.

Number

x3

x-coordinate of the second control point.

Number

y3

y-coordinate of the second control point.

Number

x4

x-coordinate of the second anchor point.

Number

y4

y-coordinate of the second anchor point.

Number

x1



Number

y1



Number

z1

z-coordinate of the first anchor point.

Number

x2



Number

y2



Number

z2

z-coordinate of the first control point.

Number

x3



Number

y3



Number

z3

z-coordinate of the second control point.

Number

x4



Number

y4



Number

z4

z-coordinate of the second anchor point.

Number

Sets the number of segments used to draw Bézier curves in WebGL mode.
In WebGL mode, smooth shapes are drawn using many flat segments. Adding more flat segments makes shapes appear smoother.
The parameter, `detail`, is the number of segments to use while drawing a Bézier curve. For example, calling `bezierDetail(5)` will use 5 segments to draw curves with the bezier() function. By default,`detail` is 20.
Note: `bezierDetail()` has no effect in 2D mode.

method

bezierDetail

detail

number of segments to use. Defaults to 20.

Number

` // Draw the original curve. function setup() { createCanvas(100, 100); background(200); // Draw the anchor points in black. stroke(0); strokeWeight(5); point(85, 20); point(15, 80); // Draw the control points in red. stroke(255, 0, 0); point(10, 10); point(90, 90); // Draw a black bezier curve. noFill(); stroke(0); strokeWeight(1); bezier(85, 20, 10, 10, 90, 90, 15, 80); // Draw red lines from the anchor points to the control points. stroke(255, 0, 0); line(85, 20, 10, 10); line(15, 80, 90, 90); describe( 'A gray square with three curves. A black s-curve has two straight, red lines that extend from its ends. The endpoints of all the curves are marked with dots.' ); } `
` // Draw the curve with less detail. function setup() { createCanvas(100, 100, WEBGL); background(200); // Set the curveDetail() to 5. bezierDetail(5); // Draw the anchor points in black. stroke(0); strokeWeight(5); point(35, -30, 0); point(-35, 30, 0); // Draw the control points in red. stroke(255, 0, 0); point(-40, -40, 0); point(40, 40, 0); // Draw a black bezier curve. noFill(); stroke(0); strokeWeight(1); bezier(35, -30, 0, -40, -40, 0, 40, 40, 0, -35, 30, 0); // Draw red lines from the anchor points to the control points. stroke(255, 0, 0); line(35, -30, -40, -40); line(-35, 30, 40, 40); describe( 'A gray square with three curves. A black s-curve is drawn with jagged segments. Two straight, red lines that extend from its ends. The endpoints of all the curves are marked with dots.' ); } `

p5

Shape

Curves

Calculates coordinates along a Bézier curve using interpolation.
`bezierPoint()` calculates coordinates along a Bézier curve using the anchor and control points. It expects points in the same order as the bezier() function. `bezierPoint()` works one axis at a time. Passing the anchor and control points' x-coordinates will calculate the x-coordinate of a point on the curve. Passing the anchor and control points' y-coordinates will calculate the y-coordinate of a point on the curve.
The first parameter, `a`, is the coordinate of the first anchor point.
The second and third parameters, `b` and `c`, are the coordinates of the control points.
The fourth parameter, `d`, is the coordinate of the last anchor point.
The fifth parameter, `t`, is the amount to interpolate along the curve. 0 is the first anchor point, 1 is the second anchor point, and 0.5 is halfway between them.

method

bezierPoint

a

coordinate of first anchor point.

Number

b

coordinate of first control point.

Number

c

coordinate of second control point.

Number

d

coordinate of second anchor point.

Number

t

amount to interpolate between 0 and 1.

Number

### return
coordinate of the point on the curve.

Number

` function setup() { createCanvas(100, 100); background(200); // Set the coordinates for the curve's anchor and control points. let x1 = 85; let x2 = 10; let x3 = 90; let x4 = 15; let y1 = 20; let y2 = 10; let y3 = 90; let y4 = 80; // Style the curve. noFill(); // Draw the curve. bezier(x1, y1, x2, y2, x3, y3, x4, y4); // Draw circles along the curve's path. fill(255); // Top-right. let x = bezierPoint(x1, x2, x3, x4, 0); let y = bezierPoint(y1, y2, y3, y4, 0); circle(x, y, 5); // Center. x = bezierPoint(x1, x2, x3, x4, 0.5); y = bezierPoint(y1, y2, y3, y4, 0.5); circle(x, y, 5); // Bottom-left. x = bezierPoint(x1, x2, x3, x4, 1); y = bezierPoint(y1, y2, y3, y4, 1); circle(x, y, 5); describe('A black s-curve on a gray square. The endpoints and center of the curve are marked with white circles.'); } `
` function setup() { createCanvas(100, 100); describe('A black s-curve on a gray square. A white circle moves back and forth along the curve.'); } function draw() { background(200); // Set the coordinates for the curve's anchor and control points. let x1 = 85; let x2 = 10; let x3 = 90; let x4 = 15; let y1 = 20; let y2 = 10; let y3 = 90; let y4 = 80; // Draw the curve. noFill(); bezier(x1, y1, x2, y2, x3, y3, x4, y4); // Calculate the circle's coordinates. let t = 0.5 * sin(frameCount * 0.01) + 0.5; let x = bezierPoint(x1, x2, x3, x4, t); let y = bezierPoint(y1, y2, y3, y4, t); // Draw the circle. fill(255); circle(x, y, 5); } `

p5

Shape

Curves

Calculates coordinates along a line that's tangent to a Bézier curve.
Tangent lines skim the surface of a curve. A tangent line's slope equals the curve's slope at the point where it intersects.
`bezierTangent()` calculates coordinates along a tangent line using the Bézier curve's anchor and control points. It expects points in the same order as the bezier() function. `bezierTangent()` works one axis at a time. Passing the anchor and control points' x-coordinates will calculate the x-coordinate of a point on the tangent line. Passing the anchor and control points' y-coordinates will calculate the y-coordinate of a point on the tangent line.
The first parameter, `a`, is the coordinate of the first anchor point.
The second and third parameters, `b` and `c`, are the coordinates of the control points.
The fourth parameter, `d`, is the coordinate of the last anchor point.
The fifth parameter, `t`, is the amount to interpolate along the curve. 0 is the first anchor point, 1 is the second anchor point, and 0.5 is halfway between them.

method

bezierTangent

a

coordinate of first anchor point.

Number

b

coordinate of first control point.

Number

c

coordinate of second control point.

Number

d

coordinate of second anchor point.

Number

t

amount to interpolate between 0 and 1.

Number

### return
coordinate of a point on the tangent line.

Number

` function setup() { createCanvas(100, 100); background(200); // Set the coordinates for the curve's anchor and control points. let x1 = 85; let x2 = 10; let x3 = 90; let x4 = 15; let y1 = 20; let y2 = 10; let y3 = 90; let y4 = 80; // Style the curve. noFill(); // Draw the curve. bezier(x1, y1, x2, y2, x3, y3, x4, y4); // Draw tangents along the curve's path. fill(255); // Top-right circle. stroke(0); let x = bezierPoint(x1, x2, x3, x4, 0); let y = bezierPoint(y1, y2, y3, y4, 0); circle(x, y, 5); // Top-right tangent line. // Scale the tangent point to draw a shorter line. stroke(255, 0, 0); let tx = 0.1 * bezierTangent(x1, x2, x3, x4, 0); let ty = 0.1 * bezierTangent(y1, y2, y3, y4, 0); line(x + tx, y + ty, x - tx, y - ty); // Center circle. stroke(0); x = bezierPoint(x1, x2, x3, x4, 0.5); y = bezierPoint(y1, y2, y3, y4, 0.5); circle(x, y, 5); // Center tangent line. // Scale the tangent point to draw a shorter line. stroke(255, 0, 0); tx = 0.1 * bezierTangent(x1, x2, x3, x4, 0.5); ty = 0.1 * bezierTangent(y1, y2, y3, y4, 0.5); line(x + tx, y + ty, x - tx, y - ty); // Bottom-left circle. stroke(0); x = bezierPoint(x1, x2, x3, x4, 1); y = bezierPoint(y1, y2, y3, y4, 1); circle(x, y, 5); // Bottom-left tangent. // Scale the tangent point to draw a shorter line. stroke(255, 0, 0); tx = 0.1 * bezierTangent(x1, x2, x3, x4, 1); ty = 0.1 * bezierTangent(y1, y2, y3, y4, 1); line(x + tx, y + ty, x - tx, y - ty); describe( 'A black s-curve on a gray square. The endpoints and center of the curve are marked with white circles. Red tangent lines extend from the white circles.' ); } `

p5

Shape

Curves

Draws a curve using a Catmull-Rom spline.
Spline curves can form shapes and curves that slope gently. They’re like cables that are attached to a set of points. Splines are defined by two anchor points and two control points.
The first two parameters, `x1` and `y1`, set the first control point. This point isn’t drawn and can be thought of as the curve’s starting point.
The next four parameters, `x2`, `y2`, `x3`, and `y3`, set the two anchor points. The anchor points are the start and end points of the curve’s visible segment.
The seventh and eighth parameters, `x4` and `y4`, set the last control point. This point isn’t drawn and can be thought of as the curve’s ending point.
Spline curves can also be drawn in 3D using WebGL mode. The 3D version of `curve()` has twelve arguments because each point has x-, y-, and z-coordinates.

method

curve

` function setup() { createCanvas(100, 100); background(200); // Draw a black spline curve. noFill(); strokeWeight(1); stroke(0); curve(5, 26, 73, 24, 73, 61, 15, 65); // Draw red spline curves from the anchor points to the control points. stroke(255, 0, 0); curve(5, 26, 5, 26, 73, 24, 73, 61); curve(73, 24, 73, 61, 15, 65, 15, 65); // Draw the anchor points in black. strokeWeight(5); stroke(0); point(73, 24); point(73, 61); // Draw the control points in red. stroke(255, 0, 0); point(5, 26); point(15, 65); describe( 'A gray square with a curve drawn in three segments. The curve is a sideways U shape with red segments on top and bottom, and a black segment on the right. The endpoints of all the segments are marked with dots.' ); } `
` let x1 = 5; let y1 = 26; let isChanging = false; function setup() { createCanvas(100, 100); describe( 'A gray square with a curve drawn in three segments. The curve is a sideways U shape with red segments on top and bottom, and a black segment on the right. The endpoints of all the segments are marked with dots.' ); } function draw() { background(200); // Draw a black spline curve. noFill(); strokeWeight(1); stroke(0); curve(x1, y1, 73, 24, 73, 61, 15, 65); // Draw red spline curves from the anchor points to the control points. stroke(255, 0, 0); curve(x1, y1, x1, y1, 73, 24, 73, 61); curve(73, 24, 73, 61, 15, 65, 15, 65); // Draw the anchor points in black. strokeWeight(5); stroke(0); point(73, 24); point(73, 61); // Draw the control points in red. stroke(255, 0, 0); point(x1, y1); point(15, 65); } // Start changing the first control point if the user clicks near it. function mousePressed() { if (dist(mouseX, mouseY, x1, y1) < 20) { isChanging = true; } } // Stop changing the first control point when the user releases the mouse. function mouseReleased() { isChanging = false; } // Update the first control point while the user drags the mouse. function mouseDragged() { if (isChanging === true) { x1 = mouseX; y1 = mouseY; } } `
` function setup() { createCanvas(100, 100); background('skyblue'); // Draw the red balloon. fill('red'); curve(-150, 275, 50, 60, 50, 60, 250, 275); // Draw the balloon string. line(50, 60, 50, 80); describe('A red balloon in a blue sky.'); } `
` function setup() { createCanvas(100, 100, WEBGL); describe('A red balloon in a blue sky.'); } function draw() { background('skyblue'); // Rotate around the y-axis. rotateY(frameCount * 0.01); // Draw the red balloon. fill('red'); curve(-200, 225, 0, 0, 10, 0, 0, 10, 0, 200, 225, 0); // Draw the balloon string. line(0, 10, 0, 0, 30, 0); } `

p5

Shape

Curves

x1

x-coordinate of the first control point.

Number

y1

y-coordinate of the first control point.

Number

x2

x-coordinate of the first anchor point.

Number

y2

y-coordinate of the first anchor point.

Number

x3

x-coordinate of the second anchor point.

Number

y3

y-coordinate of the second anchor point.

Number

x4

x-coordinate of the second control point.

Number

y4

y-coordinate of the second control point.

Number

x1



Number

y1



Number

z1

z-coordinate of the first control point.

Number

x2



Number

y2



Number

z2

z-coordinate of the first anchor point.

Number

x3



Number

y3



Number

z3

z-coordinate of the second anchor point.

Number

x4



Number

y4



Number

z4

z-coordinate of the second control point.

Number

Sets the number of segments used to draw spline curves in WebGL mode.
In WebGL mode, smooth shapes are drawn using many flat segments. Adding more flat segments makes shapes appear smoother.
The parameter, `detail`, is the number of segments to use while drawing a spline curve. For example, calling `curveDetail(5)` will use 5 segments to draw curves with the curve() function. By default,`detail` is 20.
Note: `curveDetail()` has no effect in 2D mode.

method

curveDetail

resolution

number of segments to use. Defaults to 20.

Number

` function setup() { createCanvas(100, 100); background(200); // Draw a black spline curve. noFill(); strokeWeight(1); stroke(0); curve(5, 26, 73, 24, 73, 61, 15, 65); // Draw red spline curves from the anchor points to the control points. stroke(255, 0, 0); curve(5, 26, 5, 26, 73, 24, 73, 61); curve(73, 24, 73, 61, 15, 65, 15, 65); // Draw the anchor points in black. strokeWeight(5); stroke(0); point(73, 24); point(73, 61); // Draw the control points in red. stroke(255, 0, 0); point(5, 26); point(15, 65); describe( 'A gray square with a curve drawn in three segments. The curve is a sideways U shape with red segments on top and bottom, and a black segment on the right. The endpoints of all the segments are marked with dots.' ); } `
` function setup() { createCanvas(100, 100, WEBGL); background(200); // Set the curveDetail() to 3. curveDetail(3); // Draw a black spline curve. noFill(); strokeWeight(1); stroke(0); curve(-45, -24, 0, 23, -26, 0, 23, 11, 0, -35, 15, 0); // Draw red spline curves from the anchor points to the control points. stroke(255, 0, 0); curve(-45, -24, 0, -45, -24, 0, 23, -26, 0, 23, 11, 0); curve(23, -26, 0, 23, 11, 0, -35, 15, 0, -35, 15, 0); // Draw the anchor points in black. strokeWeight(5); stroke(0); point(23, -26); point(23, 11); // Draw the control points in red. stroke(255, 0, 0); point(-45, -24); point(-35, 15); describe( 'A gray square with a jagged curve drawn in three segments. The curve is a sideways U shape with red segments on top and bottom, and a black segment on the right. The endpoints of all the segments are marked with dots.' ); } `

p5

Shape

Curves

Adjusts the way curve() and curveVertex() draw.
Spline curves are like cables that are attached to a set of points. `curveTightness()` adjusts how tightly the cable is attached to the points.
The parameter, `tightness`, determines how the curve fits to the vertex points. By default, `tightness` is set to 0. Setting tightness to 1, as in `curveTightness(1)`, connects the curve's points using straight lines. Values in the range from –5 to 5 deform curves while leaving them recognizable.

method

curveTightness

amount

amount of tightness.

Number

` // Move the mouse left and right to see the curve change. function setup() { createCanvas(100, 100); describe('A black curve forms a sideways U shape. The curve deforms as the user moves the mouse from left to right'); } function draw() { background(200); // Set the curve's tightness using the mouse. let t = map(mouseX, 0, 100, -5, 5, true); curveTightness(t); // Draw the curve. noFill(); beginShape(); curveVertex(10, 26); curveVertex(10, 26); curveVertex(83, 24); curveVertex(83, 61); curveVertex(25, 65); curveVertex(25, 65); endShape(); } `

p5

Shape

Curves

Calculates coordinates along a spline curve using interpolation.
`curvePoint()` calculates coordinates along a spline curve using the anchor and control points. It expects points in the same order as the curve() function. `curvePoint()` works one axis at a time. Passing the anchor and control points' x-coordinates will calculate the x-coordinate of a point on the curve. Passing the anchor and control points' y-coordinates will calculate the y-coordinate of a point on the curve.
The first parameter, `a`, is the coordinate of the first control point.
The second and third parameters, `b` and `c`, are the coordinates of the anchor points.
The fourth parameter, `d`, is the coordinate of the last control point.
The fifth parameter, `t`, is the amount to interpolate along the curve. 0 is the first anchor point, 1 is the second anchor point, and 0.5 is halfway between them.

method

curvePoint

a

coordinate of first control point.

Number

b

coordinate of first anchor point.

Number

c

coordinate of second anchor point.

Number

d

coordinate of second control point.

Number

t

amount to interpolate between 0 and 1.

Number

### return
coordinate of a point on the curve.

Number

` function setup() { createCanvas(100, 100); background(200); // Set the coordinates for the curve's anchor and control points. let x1 = 5; let y1 = 26; let x2 = 73; let y2 = 24; let x3 = 73; let y3 = 61; let x4 = 15; let y4 = 65; // Draw the curve. noFill(); curve(x1, y1, x2, y2, x3, y3, x4, y4); // Draw circles along the curve's path. fill(255); // Top. let x = curvePoint(x1, x2, x3, x4, 0); let y = curvePoint(y1, y2, y3, y4, 0); circle(x, y, 5); // Center. x = curvePoint(x1, x2, x3, x4, 0.5); y = curvePoint(y1, y2, y3, y4, 0.5); circle(x, y, 5); // Bottom. x = curvePoint(x1, x2, x3, x4, 1); y = curvePoint(y1, y2, y3, y4, 1); circle(x, y, 5); describe('A black curve on a gray square. The endpoints and center of the curve are marked with white circles.'); } `
` function setup() { createCanvas(100, 100); describe('A black curve on a gray square. A white circle moves back and forth along the curve.'); } function draw() { background(200); // Set the coordinates for the curve's anchor and control points. let x1 = 5; let y1 = 26; let x2 = 73; let y2 = 24; let x3 = 73; let y3 = 61; let x4 = 15; let y4 = 65; // Draw the curve. noFill(); curve(x1, y1, x2, y2, x3, y3, x4, y4); // Calculate the circle's coordinates. let t = 0.5 * sin(frameCount * 0.01) + 0.5; let x = curvePoint(x1, x2, x3, x4, t); let y = curvePoint(y1, y2, y3, y4, t); // Draw the circle. fill(255); circle(x, y, 5); } `

p5

Shape

Curves

Calculates coordinates along a line that's tangent to a spline curve.
Tangent lines skim the surface of a curve. A tangent line's slope equals the curve's slope at the point where it intersects.
`curveTangent()` calculates coordinates along a tangent line using the spline curve's anchor and control points. It expects points in the same order as the curve() function. `curveTangent()` works one axis at a time. Passing the anchor and control points' x-coordinates will calculate the x-coordinate of a point on the tangent line. Passing the anchor and control points' y-coordinates will calculate the y-coordinate of a point on the tangent line.
The first parameter, `a`, is the coordinate of the first control point.
The second and third parameters, `b` and `c`, are the coordinates of the anchor points.
The fourth parameter, `d`, is the coordinate of the last control point.
The fifth parameter, `t`, is the amount to interpolate along the curve. 0 is the first anchor point, 1 is the second anchor point, and 0.5 is halfway between them.

method

curveTangent

a

coordinate of first control point.

Number

b

coordinate of first anchor point.

Number

c

coordinate of second anchor point.

Number

d

coordinate of second control point.

Number

t

amount to interpolate between 0 and 1.

Number

### return
coordinate of a point on the tangent line.

Number

` function setup() { createCanvas(100, 100); background(200); // Set the coordinates for the curve's anchor and control points. let x1 = 5; let y1 = 26; let x2 = 73; let y2 = 24; let x3 = 73; let y3 = 61; let x4 = 15; let y4 = 65; // Draw the curve. noFill(); curve(x1, y1, x2, y2, x3, y3, x4, y4); // Draw tangents along the curve's path. fill(255); // Top circle. stroke(0); let x = curvePoint(x1, x2, x3, x4, 0); let y = curvePoint(y1, y2, y3, y4, 0); circle(x, y, 5); // Top tangent line. // Scale the tangent point to draw a shorter line. stroke(255, 0, 0); let tx = 0.2 * curveTangent(x1, x2, x3, x4, 0); let ty = 0.2 * curveTangent(y1, y2, y3, y4, 0); line(x + tx, y + ty, x - tx, y - ty); // Center circle. stroke(0); x = curvePoint(x1, x2, x3, x4, 0.5); y = curvePoint(y1, y2, y3, y4, 0.5); circle(x, y, 5); // Center tangent line. // Scale the tangent point to draw a shorter line. stroke(255, 0, 0); tx = 0.2 * curveTangent(x1, x2, x3, x4, 0.5); ty = 0.2 * curveTangent(y1, y2, y3, y4, 0.5); line(x + tx, y + ty, x - tx, y - ty); // Bottom circle. stroke(0); x = curvePoint(x1, x2, x3, x4, 1); y = curvePoint(y1, y2, y3, y4, 1); circle(x, y, 5); // Bottom tangent line. // Scale the tangent point to draw a shorter line. stroke(255, 0, 0); tx = 0.2 * curveTangent(x1, x2, x3, x4, 1); ty = 0.2 * curveTangent(y1, y2, y3, y4, 1); line(x + tx, y + ty, x - tx, y - ty); describe( 'A black curve on a gray square. A white circle moves back and forth along the curve.' ); } `

p5

Shape

Curves

Begins creating a hole within a flat shape.
The `beginContour()` and endContour() functions allow for creating negative space within custom shapes that are flat. `beginContour()` begins adding vertices to a negative space and endContour() stops adding them. `beginContour()` and endContour() must be called between beginShape() and endShape().
Transformations such as translate(), rotate(), and scale() don't work between `beginContour()` and endContour(). It's also not possible to use other shapes, such as ellipse() or rect(), between `beginContour()` and endContour().
Note: The vertices that define a negative space must "wind" in the opposite direction from the outer shape. First, draw vertices for the outer shape clockwise order. Then, draw vertices for the negative space in counter-clockwise order.

method

beginContour

` function setup() { createCanvas(100, 100); background(200); // Start drawing the shape. beginShape(); // Exterior vertices, clockwise winding. vertex(10, 10); vertex(90, 10); vertex(90, 90); vertex(10, 90); // Interior vertices, counter-clockwise winding. beginContour(); vertex(30, 30); vertex(30, 70); vertex(70, 70); vertex(70, 30); endContour(); // Stop drawing the shape. endShape(CLOSE); describe('A white square with a square hole in its center drawn on a gray background.'); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white square with a square hole in its center drawn on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Start drawing the shape. beginShape(); // Exterior vertices, clockwise winding. vertex(-40, -40); vertex(40, -40); vertex(40, 40); vertex(-40, 40); // Interior vertices, counter-clockwise winding. beginContour(); vertex(-20, -20); vertex(-20, 20); vertex(20, 20); vertex(20, -20); endContour(); // Stop drawing the shape. endShape(CLOSE); } `

p5

Shape

Vertex

Begins adding vertices to a custom shape.
The `beginShape()` and endShape() functions allow for creating custom shapes in 2D or 3D. `beginShape()` begins adding vertices to a custom shape and endShape() stops adding them.
The parameter, `kind`, sets the kind of shape to make. By default, any irregular polygon can be drawn. The available modes for kind are:
    * `POINTS` to draw a series of points.
    * `LINES` to draw a series of unconnected line segments.
    * `TRIANGLES` to draw a series of separate triangles.
    * `TRIANGLE_FAN` to draw a series of connected triangles sharing the first vertex in a fan-like fashion.
    * `TRIANGLE_STRIP` to draw a series of connected triangles in strip fashion.
    * `QUADS` to draw a series of separate quadrilaterals (quads).
    * `QUAD_STRIP` to draw quad strip using adjacent edges to form the next quad.
    * `TESS` to create a filling curve by explicit tessellation (WebGL only).
After calling `beginShape()`, shapes can be built by calling vertex(), bezierVertex(), quadraticVertex(), and/or curveVertex(). Calling endShape() will stop adding vertices to the shape. Each shape will be outlined with the current stroke color and filled with the current fill color.
Transformations such as translate(), rotate(), and scale() don't work between `beginShape()` and endShape(). It's also not possible to use other shapes, such as ellipse() or rect(), between `beginShape()` and endShape().

method

beginShape

kind

either POINTS, LINES, TRIANGLES, TRIANGLE_FAN TRIANGLE_STRIP, QUADS, QUAD_STRIP or TESS.

Constant

` function setup() { createCanvas(100, 100); background(200); // Start drawing the shape. beginShape(); // Add vertices. vertex(30, 20); vertex(85, 20); vertex(85, 75); vertex(30, 75); // Stop drawing the shape. endShape(CLOSE); describe('A white square on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Start drawing the shape. // Only draw the vertices (points). beginShape(POINTS); // Add vertices. vertex(30, 20); vertex(85, 20); vertex(85, 75); vertex(30, 75); // Stop drawing the shape. endShape(); describe('Four black dots that form a square are drawn on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Start drawing the shape. // Only draw lines between alternating pairs of vertices. beginShape(LINES); // Add vertices. vertex(30, 20); vertex(85, 20); vertex(85, 75); vertex(30, 75); // Stop drawing the shape. endShape(); describe('Two horizontal black lines on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Style the shape. noFill(); // Start drawing the shape. beginShape(); // Add vertices. vertex(30, 20); vertex(85, 20); vertex(85, 75); vertex(30, 75); // Stop drawing the shape. endShape(); describe('Three black lines form a sideways U shape on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Style the shape. noFill(); // Start drawing the shape. beginShape(); // Add vertices. vertex(30, 20); vertex(85, 20); vertex(85, 75); vertex(30, 75); // Stop drawing the shape. // Connect the first and last vertices. endShape(CLOSE); describe('A black outline of a square drawn on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Start drawing the shape. // Draw a series of triangles. beginShape(TRIANGLES); // Left triangle. vertex(30, 75); vertex(40, 20); vertex(50, 75); // Right triangle. vertex(60, 20); vertex(70, 75); vertex(80, 20); // Stop drawing the shape. endShape(); describe('Two white triangles drawn on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Start drawing the shape. // Draw a series of triangles. beginShape(TRIANGLE_STRIP); // Add vertices. vertex(30, 75); vertex(40, 20); vertex(50, 75); vertex(60, 20); vertex(70, 75); vertex(80, 20); vertex(90, 75); // Stop drawing the shape. endShape(); describe('Five white triangles that are interleaved drawn on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Start drawing the shape. // Draw a series of triangles that share their first vertex. beginShape(TRIANGLE_FAN); // Add vertices. vertex(57.5, 50); vertex(57.5, 15); vertex(92, 50); vertex(57.5, 85); vertex(22, 50); vertex(57.5, 15); // Stop drawing the shape. endShape(); describe('Four white triangles form a square are drawn on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Start drawing the shape. // Draw a series of quadrilaterals. beginShape(QUADS); // Left rectangle. vertex(30, 20); vertex(30, 75); vertex(50, 75); vertex(50, 20); // Right rectangle. vertex(65, 20); vertex(65, 75); vertex(85, 75); vertex(85, 20); // Stop drawing the shape. endShape(); describe('Two white rectangles drawn on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Start drawing the shape. // Draw a series of quadrilaterals. beginShape(QUAD_STRIP); // Add vertices. vertex(30, 20); vertex(30, 75); vertex(50, 20); vertex(50, 75); vertex(65, 20); vertex(65, 75); vertex(85, 20); vertex(85, 75); // Stop drawing the shape. endShape(); describe('Three white rectangles that share edges are drawn on a gray background.'); } `
` function setup() { createCanvas(100, 100, WEBGL); background(200); // Start drawing the shape. // Draw a series of quadrilaterals. beginShape(TESS); // Add the vertices. vertex(-30, -30, 0); vertex(30, -30, 0); vertex(30, -10, 0); vertex(-10, -10, 0); vertex(-10, 10, 0); vertex(30, 10, 0); vertex(30, 30, 0); vertex(-30, 30, 0); // Stop drawing the shape. // Connect the first and last vertices. endShape(CLOSE); describe('A blocky C shape drawn in white on a gray background.'); } `
` // Click and drag with the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A blocky C shape drawn in red, blue, and green on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Start drawing the shape. // Draw a series of quadrilaterals. beginShape(TESS); // Add the vertices. fill('red'); stroke('red'); vertex(-30, -30, 0); vertex(30, -30, 0); vertex(30, -10, 0); fill('green'); stroke('green'); vertex(-10, -10, 0); vertex(-10, 10, 0); vertex(30, 10, 0); fill('blue'); stroke('blue'); vertex(30, 30, 0); vertex(-30, 30, 0); // Stop drawing the shape. // Connect the first and last vertices. endShape(CLOSE); } `

p5

Shape

Vertex

Adds a Bézier curve segment to a custom shape.
`bezierVertex()` adds a curved segment to custom shapes. The Bézier curves it creates are defined like those made by the bezier() function. `bezierVertex()` must be called between the beginShape() and endShape() functions. The curved segment uses the previous vertex as the first anchor point, so there must be at least one call to vertex() before `bezierVertex()` can be used.
The first four parameters, `x2`, `y2`, `x3`, and `y3`, set the curve’s two control points. The control points "pull" the curve towards them.
The fifth and sixth parameters, `x4`, and `y4`, set the last anchor point. The last anchor point is where the curve ends.
Bézier curves can also be drawn in 3D using WebGL mode. The 3D version of `bezierVertex()` has eight arguments because each point has x-, y-, and z-coordinates.
Note: `bezierVertex()` won’t work when an argument is passed to beginShape().

method

bezierVertex

` function setup() { createCanvas(100, 100); background(200); // Style the shape. noFill(); // Start drawing the shape. beginShape(); // Add the first anchor point. vertex(30, 20); // Add the Bézier vertex. bezierVertex(80, 0, 80, 75, 30, 75); // Stop drawing the shape. endShape(); describe('A black C curve on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Draw the anchor points in black. stroke(0); strokeWeight(5); point(30, 20); point(30, 75); // Draw the control points in red. stroke(255, 0, 0); point(80, 0); point(80, 75); // Style the shape. noFill(); stroke(0); strokeWeight(1); // Start drawing the shape. beginShape(); // Add the first anchor point. vertex(30, 20); // Add the Bézier vertex. bezierVertex(80, 0, 80, 75, 30, 75); // Stop drawing the shape. endShape(); // Draw red lines from the anchor points to the control points. stroke(255, 0, 0); line(30, 20, 80, 0); line(30, 75, 80, 75); describe( 'A gray square with three curves. A black curve has two straight, red lines that extend from its ends. The endpoints of all the curves are marked with dots.' ); } `
` // Click the mouse near the red dot in the top-right corner // and drag to change the curve's shape. let x2 = 80; let y2 = 0; let isChanging = false; function setup() { createCanvas(100, 100); describe( 'A gray square with three curves. A black curve has two straight, red lines that extend from its ends. The endpoints of all the curves are marked with dots.' ); } function draw() { background(200); // Draw the anchor points in black. stroke(0); strokeWeight(5); point(30, 20); point(30, 75); // Draw the control points in red. stroke(255, 0, 0); point(x2, y2); point(80, 75); // Style the shape. noFill(); stroke(0); strokeWeight(1); // Start drawing the shape. beginShape(); // Add the first anchor point. vertex(30, 20); // Add the Bézier vertex. bezierVertex(x2, y2, 80, 75, 30, 75); // Stop drawing the shape. endShape(); // Draw red lines from the anchor points to the control points. stroke(255, 0, 0); line(30, 20, x2, y2); line(30, 75, 80, 75); } // Start changing the first control point if the user clicks near it. function mousePressed() { if (dist(mouseX, mouseY, x2, y2) < 20) { isChanging = true; } } // Stop changing the first control point when the user releases the mouse. function mouseReleased() { isChanging = false; } // Update the first control point while the user drags the mouse. function mouseDragged() { if (isChanging === true) { x2 = mouseX; y2 = mouseY; } } `
` function setup() { createCanvas(100, 100); background(200); // Start drawing the shape. beginShape(); // Add the first anchor point. vertex(30, 20); // Add the Bézier vertices. bezierVertex(80, 0, 80, 75, 30, 75); bezierVertex(50, 80, 60, 25, 30, 20); // Stop drawing the shape. endShape(); describe('A crescent moon shape drawn in white on a gray background.'); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A crescent moon shape drawn in white on a blue background. When the user drags the mouse, the scene rotates and a second moon is revealed.'); } function draw() { background('midnightblue'); // Enable orbiting with the mouse. orbitControl(); // Style the moons. noStroke(); fill('lemonchiffon'); // Draw the first moon. beginShape(); vertex(-20, -30, 0); bezierVertex(30, -50, 0, 30, 25, 0, -20, 25, 0); bezierVertex(0, 30, 0, 10, -25, 0, -20, -30, 0); endShape(); // Draw the second moon. beginShape(); vertex(-20, -30, -20); bezierVertex(30, -50, -20, 30, 25, -20, -20, 25, -20); bezierVertex(0, 30, -20, 10, -25, -20, -20, -30, -20); endShape(); } `

p5

Shape

Vertex

x2

x-coordinate of the first control point.

Number

y2

y-coordinate of the first control point.

Number

x3

x-coordinate of the second control point.

Number

y3

y-coordinate of the second control point.

Number

x4

x-coordinate of the anchor point.

Number

y4

y-coordinate of the anchor point.

Number

x2



Number

y2



Number

z2

z-coordinate of the first control point.

Number

x3



Number

y3



Number

z3

z-coordinate of the second control point.

Number

x4



Number

y4



Number

z4

z-coordinate of the anchor point.

Number

Adds a spline curve segment to a custom shape.
`curveVertex()` adds a curved segment to custom shapes. The spline curves it creates are defined like those made by the curve() function. `curveVertex()` must be called between the beginShape() and endShape() functions.
Spline curves can form shapes and curves that slope gently. They’re like cables that are attached to a set of points. Splines are defined by two anchor points and two control points. `curveVertex()` must be called at least four times between beginShape() and endShape() in order to draw a curve:
    beginShape();
    
    // Add the first control point.
    curveVertex(84, 91);
    
    // Add the anchor points to draw between.
    curveVertex(68, 19);
    curveVertex(21, 17);
    
    // Add the second control point.
    curveVertex(32, 91);
    
    endShape();
    
The code snippet above would only draw the curve between the anchor points, similar to the curve() function. The segments between the control and anchor points can be drawn by calling `curveVertex()` with the coordinates of the control points:
    beginShape();
    
    // Add the first control point and draw a segment to it.
    curveVertex(84, 91);
    curveVertex(84, 91);
    
    // Add the anchor points to draw between.
    curveVertex(68, 19);
    curveVertex(21, 17);
    
    // Add the second control point.
    curveVertex(32, 91);
    
    // Uncomment the next line to draw the segment to the second control point.
    // curveVertex(32, 91);
    
    endShape();
    
The first two parameters, `x` and `y`, set the vertex’s location. For example, calling `curveVertex(10, 10)` adds a point to the curve at `(10, 10)`.
Spline curves can also be drawn in 3D using WebGL mode. The 3D version of `curveVertex()` has three arguments because each point has x-, y-, and z-coordinates. By default, the vertex’s z-coordinate is set to 0.
Note: `curveVertex()` won’t work when an argument is passed to beginShape().

method

curveVertex

` function setup() { createCanvas(100, 100); background(200); // Style the shape. noFill(); strokeWeight(1); // Start drawing the shape. beginShape(); // Add the first control point. curveVertex(32, 91); // Add the anchor points. curveVertex(21, 17); curveVertex(68, 19); // Add the second control point. curveVertex(84, 91); // Stop drawing the shape. endShape(); // Style the anchor and control points. strokeWeight(5); // Draw the anchor points in black. stroke(0); point(21, 17); point(68, 19); // Draw the control points in red. stroke(255, 0, 0); point(32, 91); point(84, 91); describe( 'A black curve drawn on a gray background. The curve has black dots at its ends. Two red dots appear near the bottom of the canvas.' ); } `
` function setup() { createCanvas(100, 100); background(200); // Style the shape. noFill(); strokeWeight(1); // Start drawing the shape. beginShape(); // Add the first control point and draw a segment to it. curveVertex(32, 91); curveVertex(32, 91); // Add the anchor points. curveVertex(21, 17); curveVertex(68, 19); // Add the second control point. curveVertex(84, 91); // Stop drawing the shape. endShape(); // Style the anchor and control points. strokeWeight(5); // Draw the anchor points in black. stroke(0); point(21, 17); point(68, 19); // Draw the control points in red. stroke(255, 0, 0); point(32, 91); point(84, 91); describe( 'A black curve drawn on a gray background. The curve passes through one red dot and two black dots. Another red dot appears near the bottom of the canvas.' ); } `
` function setup() { createCanvas(100, 100); background(200); // Style the shape. noFill(); strokeWeight(1); // Start drawing the shape. beginShape(); // Add the first control point and draw a segment to it. curveVertex(32, 91); curveVertex(32, 91); // Add the anchor points. curveVertex(21, 17); curveVertex(68, 19); // Add the second control point and draw a segment to it. curveVertex(84, 91); curveVertex(84, 91); // Stop drawing the shape. endShape(); // Style the anchor and control points. strokeWeight(5); // Draw the anchor points in black. stroke(0); point(21, 17); point(68, 19); // Draw the control points in red. stroke(255, 0, 0); point(32, 91); point(84, 91); describe( 'A black U curve drawn upside down on a gray background. The curve passes from one red dot through two black dots and ends at another red dot.' ); } `
` // Click the mouse near the red dot in the bottom-left corner // and drag to change the curve's shape. let x1 = 32; let y1 = 91; let isChanging = false; function setup() { createCanvas(100, 100); describe( 'A black U curve drawn upside down on a gray background. The curve passes from one red dot through two black dots and ends at another red dot.' ); } function draw() { background(200); // Style the shape. noFill(); stroke(0); strokeWeight(1); // Start drawing the shape. beginShape(); // Add the first control point and draw a segment to it. curveVertex(x1, y1); curveVertex(x1, y1); // Add the anchor points. curveVertex(21, 17); curveVertex(68, 19); // Add the second control point and draw a segment to it. curveVertex(84, 91); curveVertex(84, 91); // Stop drawing the shape. endShape(); // Style the anchor and control points. strokeWeight(5); // Draw the anchor points in black. stroke(0); point(21, 17); point(68, 19); // Draw the control points in red. stroke(255, 0, 0); point(x1, y1); point(84, 91); } // Start changing the first control point if the user clicks near it. function mousePressed() { if (dist(mouseX, mouseY, x1, y1) < 20) { isChanging = true; } } // Stop changing the first control point when the user releases the mouse. function mouseReleased() { isChanging = false; } // Update the first control point while the user drags the mouse. function mouseDragged() { if (isChanging === true) { x1 = mouseX; y1 = mouseY; } } `
` function setup() { createCanvas(100, 100); background(200); // Start drawing the shape. beginShape(); // Add the first control point and draw a segment to it. curveVertex(32, 91); curveVertex(32, 91); // Add the anchor points. curveVertex(21, 17); curveVertex(68, 19); // Add the second control point. curveVertex(84, 91); curveVertex(84, 91); // Stop drawing the shape. endShape(); describe('A ghost shape drawn in white on a gray background.'); } `

p5

Shape

Vertex

x

x-coordinate of the vertex

Number

y

y-coordinate of the vertex

Number

x



Number

y



Number

z

z-coordinate of the vertex.

Number

Stops creating a hole within a flat shape.
The beginContour() and `endContour()` functions allow for creating negative space within custom shapes that are flat. beginContour() begins adding vertices to a negative space and `endContour()` stops adding them. beginContour() and `endContour()` must be called between beginShape() and endShape().
Transformations such as translate(), rotate(), and scale() don't work between beginContour() and `endContour()`. It's also not possible to use other shapes, such as ellipse() or rect(), between beginContour() and `endContour()`.
Note: The vertices that define a negative space must "wind" in the opposite direction from the outer shape. First, draw vertices for the outer shape clockwise order. Then, draw vertices for the negative space in counter-clockwise order.

method

endContour

` function setup() { createCanvas(100, 100); background(200); // Start drawing the shape. beginShape(); // Exterior vertices, clockwise winding. vertex(10, 10); vertex(90, 10); vertex(90, 90); vertex(10, 90); // Interior vertices, counter-clockwise winding. beginContour(); vertex(30, 30); vertex(30, 70); vertex(70, 70); vertex(70, 30); endContour(); // Stop drawing the shape. endShape(CLOSE); describe('A white square with a square hole in its center drawn on a gray background.'); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white square with a square hole in its center drawn on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Start drawing the shape. beginShape(); // Exterior vertices, clockwise winding. vertex(-40, -40); vertex(40, -40); vertex(40, 40); vertex(-40, 40); // Interior vertices, counter-clockwise winding. beginContour(); vertex(-20, -20); vertex(-20, 20); vertex(20, 20); vertex(20, -20); endContour(); // Stop drawing the shape. endShape(CLOSE); } `

p5

Shape

Vertex

Begins adding vertices to a custom shape.
The beginShape() and `endShape()` functions allow for creating custom shapes in 2D or 3D. beginShape() begins adding vertices to a custom shape and `endShape()` stops adding them.
The first parameter, `mode`, is optional. By default, the first and last vertices of a shape aren't connected. If the constant `CLOSE` is passed, as in `endShape(CLOSE)`, then the first and last vertices will be connected.
The second parameter, `count`, is also optional. In WebGL mode, it’s more efficient to draw many copies of the same shape using a technique called instancing. The `count` parameter tells WebGL mode how many copies to draw. For example, calling `endShape(CLOSE, 400)` after drawing a custom shape will make it efficient to draw 400 copies. This feature requires writing a custom shader.
After calling beginShape(), shapes can be built by calling vertex(), bezierVertex(), quadraticVertex(), and/or curveVertex(). Calling `endShape()` will stop adding vertices to the shape. Each shape will be outlined with the current stroke color and filled with the current fill color.
Transformations such as translate(), rotate(), and scale() don't work between beginShape() and `endShape()`. It's also not possible to use other shapes, such as ellipse() or rect(), between beginShape() and `endShape()`.

method

endShape

mode

use CLOSE to close the shape

Constant

count

number of times you want to draw/instance the shape (for WebGL mode).

Integer

` function setup() { createCanvas(100, 100); background(200); // Style the shapes. noFill(); // Left triangle. beginShape(); vertex(20, 20); vertex(45, 20); vertex(45, 80); endShape(CLOSE); // Right triangle. beginShape(); vertex(50, 20); vertex(75, 20); vertex(75, 80); endShape(); describe( 'Two sets of black lines drawn on a gray background. The three lines on the left form a right triangle. The two lines on the right form a right angle.' ); } `
` // Note: A "uniform" is a global variable within a shader program. // Create a string with the vertex shader program. // The vertex shader is called for each vertex. let vertSrc = `#version 300 es precision mediump float; in vec3 aPosition; flat out int instanceID; uniform mat4 uModelViewMatrix; uniform mat4 uProjectionMatrix; void main() { // Copy the instance ID to the fragment shader. instanceID = gl_InstanceID; vec4 positionVec4 = vec4(aPosition, 1.0); // gl_InstanceID represents a numeric value for each instance. // Using gl_InstanceID allows us to move each instance separately. // Here we move each instance horizontally by ID * 23. float xOffset = float(gl_InstanceID) * 23.0; // Apply the offset to the final position. gl_Position = uProjectionMatrix * uModelViewMatrix * (positionVec4 - vec4(xOffset, 0.0, 0.0, 0.0)); } `; // Create a string with the fragment shader program. // The fragment shader is called for each pixel. let fragSrc = `#version 300 es precision mediump float; out vec4 outColor; flat in int instanceID; uniform float numInstances; void main() { vec4 red = vec4(1.0, 0.0, 0.0, 1.0); vec4 blue = vec4(0.0, 0.0, 1.0, 1.0); // Normalize the instance ID. float normId = float(instanceID) / numInstances; // Mix between two colors using the normalized instance ID. outColor = mix(red, blue, normId); } `; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Shader object. let myShader = createShader(vertSrc, fragSrc); background(220); // Compile and apply the p5.Shader. shader(myShader); // Set the numInstances uniform. myShader.setUniform('numInstances', 4); // Translate the origin to help align the drawing. translate(25, -10); // Style the shapes. noStroke(); // Draw the shapes. beginShape(); vertex(0, 0); vertex(0, 20); vertex(20, 20); vertex(20, 0); vertex(0, 0); endShape(CLOSE, 4); describe('A row of four squares. Their colors transition from purple on the left to red on the right'); } `

p5

Shape

Vertex

Adds a quadratic Bézier curve segment to a custom shape.
`quadraticVertex()` adds a curved segment to custom shapes. The Bézier curve segments it creates are similar to those made by the bezierVertex() function. `quadraticVertex()` must be called between the beginShape() and endShape() functions. The curved segment uses the previous vertex as the first anchor point, so there must be at least one call to vertex() before `quadraticVertex()` can be used.
The first two parameters, `cx` and `cy`, set the curve’s control point. The control point "pulls" the curve towards its.
The last two parameters, `x3`, and `y3`, set the last anchor point. The last anchor point is where the curve ends.
Bézier curves can also be drawn in 3D using WebGL mode. The 3D version of `bezierVertex()` has eight arguments because each point has x-, y-, and z-coordinates.
Note: `quadraticVertex()` won’t work when an argument is passed to beginShape().

method

quadraticVertex

` function setup() { createCanvas(100, 100); background(200); // Style the curve. noFill(); // Draw the curve. beginShape(); vertex(20, 20); quadraticVertex(80, 20, 50, 50); endShape(); describe('A black curve drawn on a gray square. The curve starts at the top-left corner and ends at the center.'); } `
` function setup() { createCanvas(100, 100); background(200); // Draw the curve. noFill(); beginShape(); vertex(20, 20); quadraticVertex(80, 20, 50, 50); endShape(); // Draw red lines from the anchor points to the control point. stroke(255, 0, 0); line(20, 20, 80, 20); line(50, 50, 80, 20); // Draw the anchor points in black. strokeWeight(5); stroke(0); point(20, 20); point(50, 50); // Draw the control point in red. stroke(255, 0, 0); point(80, 20); describe('A black curve that starts at the top-left corner and ends at the center. Its anchor and control points are marked with dots. Red lines connect both anchor points to the control point.'); } `
` // Click the mouse near the red dot in the top-right corner // and drag to change the curve's shape. let x2 = 80; let y2 = 20; let isChanging = false; function setup() { createCanvas(100, 100); describe('A black curve that starts at the top-left corner and ends at the center. Its anchor and control points are marked with dots. Red lines connect both anchor points to the control point.'); } function draw() { background(200); // Style the curve. noFill(); strokeWeight(1); stroke(0); // Draw the curve. beginShape(); vertex(20, 20); quadraticVertex(x2, y2, 50, 50); endShape(); // Draw red lines from the anchor points to the control point. stroke(255, 0, 0); line(20, 20, x2, y2); line(50, 50, x2, y2); // Draw the anchor points in black. strokeWeight(5); stroke(0); point(20, 20); point(50, 50); // Draw the control point in red. stroke(255, 0, 0); point(x2, y2); } // Start changing the first control point if the user clicks near it. function mousePressed() { if (dist(mouseX, mouseY, x2, y2) < 20) { isChanging = true; } } // Stop changing the first control point when the user releases the mouse. function mouseReleased() { isChanging = false; } // Update the first control point while the user drags the mouse. function mouseDragged() { if (isChanging === true) { x2 = mouseX; y2 = mouseY; } } `
` function setup() { createCanvas(100, 100); background(200); // Start drawing the shape. beginShape(); // Add the curved segments. vertex(20, 20); quadraticVertex(80, 20, 50, 50); quadraticVertex(20, 80, 80, 80); // Add the straight segments. vertex(80, 10); vertex(20, 10); vertex(20, 20); // Stop drawing the shape. endShape(); describe('A white puzzle piece drawn on a gray background.'); } `
` // Click the and drag the mouse to view the scene from a different angle. function setup() { createCanvas(100, 100, WEBGL); describe('A white puzzle piece on a dark gray background. When the user clicks and drags the scene, the outline of a second puzzle piece is revealed.'); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Style the first puzzle piece. noStroke(); fill(255); // Draw the first puzzle piece. beginShape(); vertex(-30, -30, 0); quadraticVertex(30, -30, 0, 0, 0, 0); quadraticVertex(-30, 30, 0, 30, 30, 0); vertex(30, -40, 0); vertex(-30, -40, 0); vertex(-30, -30, 0); endShape(); // Style the second puzzle piece. stroke(255); noFill(); // Draw the second puzzle piece. beginShape(); vertex(-30, -30, -20); quadraticVertex(30, -30, -20, 0, 0, -20); quadraticVertex(-30, 30, -20, 30, 30, -20); vertex(30, -40, -20); vertex(-30, -40, -20); vertex(-30, -30, -20); endShape(); } `

p5

Shape

Vertex

cx

x-coordinate of the control point.

Number

cy

y-coordinate of the control point.

Number

x3

x-coordinate of the anchor point.

Number

y3

y-coordinate of the anchor point.

Number

cx



Number

cy



Number

cz

z-coordinate of the control point.

Number

x3



Number

y3



Number

z3

z-coordinate of the anchor point.

Number

Adds a vertex to a custom shape.
`vertex()` sets the coordinates of vertices drawn between the beginShape() and endShape() functions.
The first two parameters, `x` and `y`, set the x- and y-coordinates of the vertex.
The third parameter, `z`, is optional. It sets the z-coordinate of the vertex in WebGL mode. By default, `z` is 0.
The fourth and fifth parameters, `u` and `v`, are also optional. They set the u- and v-coordinates for the vertex’s texture when used with endShape(). By default, `u` and `v` are both 0.

method

vertex

` function setup() { createCanvas(100, 100); background(200); // Style the shape. strokeWeight(3); // Start drawing the shape. // Only draw the vertices. beginShape(POINTS); // Add the vertices. vertex(30, 20); vertex(85, 20); vertex(85, 75); vertex(30, 75); // Stop drawing the shape. endShape(); describe('Four black dots that form a square are drawn on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Start drawing the shape. beginShape(); // Add vertices. vertex(30, 20); vertex(85, 20); vertex(85, 75); vertex(30, 75); // Stop drawing the shape. endShape(CLOSE); describe('A white square on a gray background.'); } `
` function setup() { createCanvas(100, 100, WEBGL); background(200); // Start drawing the shape. beginShape(); // Add vertices. vertex(-20, -30, 0); vertex(35, -30, 0); vertex(35, 25, 0); vertex(-20, 25, 0); // Stop drawing the shape. endShape(CLOSE); describe('A white square on a gray background.'); } `
` function setup() { createCanvas(100, 100, WEBGL); describe('A white square spins around slowly on a gray background.'); } function draw() { background(200); // Rotate around the y-axis. rotateY(frameCount * 0.01); // Start drawing the shape. beginShape(); // Add vertices. vertex(-20, -30, 0); vertex(35, -30, 0); vertex(35, 25, 0); vertex(-20, 25, 0); // Stop drawing the shape. endShape(CLOSE); } `
` let img; // Load an image to apply as a texture. function preload() { img = loadImage('assets/laDefense.jpg'); } function setup() { createCanvas(100, 100, WEBGL); describe('A photograph of a ceiling rotates slowly against a gray background.'); } function draw() { background(200); // Rotate around the y-axis. rotateY(frameCount * 0.01); // Style the shape. noStroke(); // Apply the texture. texture(img); textureMode(NORMAL); // Start drawing the shape beginShape(); // Add vertices. vertex(-20, -30, 0, 0, 0); vertex(35, -30, 0, 1, 0); vertex(35, 25, 0, 1, 1); vertex(-20, 25, 0, 0, 1); // Stop drawing the shape. endShape(); } `

p5

Shape

Vertex

x

x-coordinate of the vertex.

Number

y

y-coordinate of the vertex.

Number

x



Number

y



Number

z

z-coordinate of the vertex. Defaults to 0.

Number

x



Number

y



Number

z



Number

u

u-coordinate of the vertex's texture. Defaults to 0.

Number

v

v-coordinate of the vertex's texture. Defaults to 0.

Number

Sets the normal vector for vertices in a custom 3D shape.
3D shapes created with beginShape() and endShape() are made by connecting sets of points called vertices. Each vertex added with vertex() has a normal vector that points away from it. The normal vector controls how light reflects off the shape.
`normal()` can be called two ways with different parameters to define the normal vector's components.
The first way to call `normal()` has three parameters, `x`, `y`, and `z`. If `Number`s are passed, as in `normal(1, 2, 3)`, they set the x-, y-, and z-components of the normal vector.
The second way to call `normal()` has one parameter, `vector`. If a p5.Vector object is passed, as in `normal(myVector)`, its components will be used to set the normal vector.
`normal()` changes the normal vector of vertices added to a custom shape with vertex(). `normal()` must be called between the beginShape() and endShape() functions, just like vertex(). The normal vector set by calling `normal()` will affect all following vertices until `normal()` is called again:
    beginShape();
    
    // Set the vertex normal.
    normal(-0.4, -0.4, 0.8);
    
    // Add a vertex.
    vertex(-30, -30, 0);
    
    // Set the vertex normal.
    normal(0, 0, 1);
    
    // Add vertices.
    vertex(30, -30, 0);
    vertex(30, 30, 0);
    
    // Set the vertex normal.
    normal(0.4, -0.4, 0.8);
    
    // Add a vertex.
    vertex(-30, 30, 0);
    
    endShape();
    

method

normal

` // Click the and drag the mouse to view the scene from a different angle. function setup() { createCanvas(100, 100, WEBGL); describe( 'A colorful square on a black background. The square changes color and rotates when the user drags the mouse. Parts of its surface reflect light in different directions.' ); } function draw() { background(0); // Enable orbiting with the mouse. orbitControl(); // Style the shape. normalMaterial(); noStroke(); // Draw the shape. beginShape(); vertex(-30, -30, 0); vertex(30, -30, 0); vertex(30, 30, 0); vertex(-30, 30, 0); endShape(); } `
` // Click the and drag the mouse to view the scene from a different angle. function setup() { createCanvas(100, 100, WEBGL); describe( 'A colorful square on a black background. The square changes color and rotates when the user drags the mouse. Parts of its surface reflect light in different directions.' ); } function draw() { background(0); // Enable orbiting with the mouse. orbitControl(); // Style the shape. normalMaterial(); noStroke(); // Draw the shape. // Use normal() to set vertex normals. beginShape(); normal(-0.4, -0.4, 0.8); vertex(-30, -30, 0); normal(0, 0, 1); vertex(30, -30, 0); vertex(30, 30, 0); normal(0.4, -0.4, 0.8); vertex(-30, 30, 0); endShape(); } `
` // Click the and drag the mouse to view the scene from a different angle. function setup() { createCanvas(100, 100, WEBGL); describe( 'A colorful square on a black background. The square changes color and rotates when the user drags the mouse. Parts of its surface reflect light in different directions.' ); } function draw() { background(0); // Enable orbiting with the mouse. orbitControl(); // Style the shape. normalMaterial(); noStroke(); // Create p5.Vector objects. let n1 = createVector(-0.4, -0.4, 0.8); let n2 = createVector(0, 0, 1); let n3 = createVector(0.4, -0.4, 0.8); // Draw the shape. // Use normal() to set vertex normals. beginShape(); normal(n1); vertex(-30, -30, 0); normal(n2); vertex(30, -30, 0); vertex(30, 30, 0); normal(n3); vertex(-30, 30, 0); endShape(); } `

p5

Shape

Vertex

vector

vertex normal as a p5.Vector object.

p5.Vector

x

x-component of the vertex normal.

Number

y

y-component of the vertex normal.

Number

z

z-component of the vertex normal.

Number

Version of this p5.js.

property

VERSION

String

p5

Constants

Constants

The default, two-dimensional renderer.

property

P2D

String

p5

Constants

Constants

One of the two render modes in p5.js, used for computationally intensive tasks like 3D rendering and shaders.
`WEBGL` differs from the default `P2D` renderer in the following ways:
    * Coordinate System \- When drawing in `WEBGL` mode, the origin point (0,0,0) is located at the center of the screen, not the top-left corner. See the tutorial page about coordinates and transformations.
    * 3D Shapes \- `WEBGL` mode can be used to draw 3-dimensional shapes like box(), sphere(), cone(), and more. See the tutorial page about custom geometry to make more complex objects.
    * Shape Detail \- When drawing in `WEBGL` mode, you can specify how smooth curves should be drawn by using a `detail` parameter. See the wiki section about shapes for a more information and an example.
    * Textures \- A texture is like a skin that wraps onto a shape. See the wiki section about textures for examples of mapping images onto surfaces with textures.
    * Materials and Lighting \- `WEBGL` offers different types of lights like ambientLight() to place around a scene. Materials like specularMaterial() reflect the lighting to convey shape and depth. See the tutorial page for styling and appearance to experiment with different combinations.
    * Camera \- The viewport of a `WEBGL` sketch can be adjusted by changing camera attributes. See the tutorial page section about cameras for an explanation of camera controls.
    * Text \- `WEBGL` requires opentype/truetype font files to be preloaded using loadFont(). See the wiki section about text for details, along with a workaround.
    * Shaders \- Shaders are hardware accelerated programs that can be used for a variety of effects and graphics. See the introduction to shaders to get started with shaders in p5.js.
    * Graphics Acceleration \- `WEBGL` mode uses the graphics card instead of the CPU, so it may help boost the performance of your sketch (example: drawing more shapes on the screen at once).
To learn more about WEBGL mode, check out all the interactive WEBGL tutorials in the "Tutorials" section of this website, or read the wiki article "Getting started with WebGL in p5".

property

WEBGL

String

p5

Constants

Constants

One of the two possible values of a WebGL canvas (either WEBGL or WEBGL2), which can be used to determine what capabilities the rendering environment has.

property

WEBGL2

String

p5

Constants

Constants

property

ARROW

String

p5

Constants

Constants

property

CROSS

String

p5

Constants

Constants

property

HAND

String

p5

Constants

Constants

property

MOVE

String

p5

Constants

Constants

property

TEXT

String

p5

Constants

Constants

property

WAIT

String

p5

Constants

Constants

A `Number` constant that's approximately 1.5708.
`HALF_PI` is half the value of the mathematical constant π. It's useful for many tasks that involve rotation and oscillation. For example, calling `rotate(HALF_PI)` rotates the coordinate system `HALF_PI` radians, which is a quarter turn (90˚).
Note: `TWO_PI` radians equals 360˚, `PI` radians equals 180˚, `HALF_PI` radians equals 90˚, and `QUARTER_PI` radians equals 45˚.

property

HALF_PI

Number

` function setup() { createCanvas(100, 100); background(200); // Draw an arc from 0 to HALF_PI. arc(50, 50, 80, 80, 0, HALF_PI); describe('The bottom-right quarter of a circle drawn in white on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Translate the origin to the center. translate(50, 50); // Draw a line. line(0, 0, 40, 0); // Rotate a quarter turn. rotate(HALF_PI); // Draw the same line, rotated. line(0, 0, 40, 0); describe('Two black lines on a gray background. One line extends from the center to the right. The other line extends from the center to the bottom.'); } `
` function setup() { createCanvas(100, 100); describe( 'A red circle and a blue circle oscillate from left to right on a gray background. The red circle appears to chase the blue circle.' ); } function draw() { background(200); // Translate the origin to the center. translate(50, 50); // Calculate the x-coordinates. let x1 = 40 * sin(frameCount * 0.05); let x2 = 40 * sin(frameCount * 0.05 + HALF_PI); // Style the oscillators. noStroke(); // Draw the red oscillator. fill(255, 0, 0); circle(x1, 0, 20); // Draw the blue oscillator. fill(0, 0, 255); circle(x2, 0, 20); } `

p5

Constants

Constants

A `Number` constant that's approximately 3.1416.
`PI` is the mathematical constant π. It's useful for many tasks that involve rotation and oscillation. For example, calling `rotate(PI)` rotates the coordinate system `PI` radians, which is a half turn (180˚).
Note: `TWO_PI` radians equals 360˚, `PI` radians equals 180˚, `HALF_PI` radians equals 90˚, and `QUARTER_PI` radians equals 45˚.

property

PI

Number

` function setup() { createCanvas(100, 100); background(200); // Draw an arc from 0 to PI. arc(50, 50, 80, 80, 0, PI); describe('The bottom half of a circle drawn in white on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Translate the origin to the center. translate(50, 50); // Draw a line. line(0, 0, 40, 0); // Rotate a half turn. rotate(PI); // Draw the same line, rotated. line(0, 0, 40, 0); describe('A horizontal black line on a gray background.'); } `
` function setup() { createCanvas(100, 100); describe( 'A red circle and a blue circle oscillate from left to right on a gray background. The circles drift apart, then meet in the middle, over and over again.' ); } function draw() { background(200); // Translate the origin to the center. translate(50, 50); // Calculate the x-coordinates. let x1 = 40 * sin(frameCount * 0.05); let x2 = 40 * sin(frameCount * 0.05 + PI); // Style the oscillators. noStroke(); // Draw the red oscillator. fill(255, 0, 0); circle(x1, 0, 20); // Draw the blue oscillator. fill(0, 0, 255); circle(x2, 0, 20); } `

p5

Constants

Constants

A `Number` constant that's approximately 0.7854.
`QUARTER_PI` is one-fourth the value of the mathematical constant π. It's useful for many tasks that involve rotation and oscillation. For example, calling `rotate(QUARTER_PI)` rotates the coordinate system `QUARTER_PI` radians, which is an eighth of a turn (45˚).
Note: `TWO_PI` radians equals 360˚, `PI` radians equals 180˚, `HALF_PI` radians equals 90˚, and `QUARTER_PI` radians equals 45˚.

property

QUARTER_PI

Number

` function setup() { createCanvas(100, 100); background(200); // Draw an arc from 0 to QUARTER_PI. arc(50, 50, 80, 80, 0, QUARTER_PI); describe('A one-eighth slice of a circle drawn in white on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Translate the origin to the center. translate(50, 50); // Draw a line. line(0, 0, 40, 0); // Rotate an eighth turn. rotate(QUARTER_PI); // Draw the same line, rotated. line(0, 0, 40, 0); describe('Two black lines that form a "V" opening towards the bottom-right corner of a gray square.'); } `
` function setup() { createCanvas(100, 100); describe( 'A red circle and a blue circle oscillate from left to right on a gray background. The red circle appears to chase the blue circle.' ); } function draw() { background(200); // Translate the origin to the center. translate(50, 50); // Calculate the x-coordinates. let x1 = 40 * sin(frameCount * 0.05); let x2 = 40 * sin(frameCount * 0.05 + QUARTER_PI); // Style the oscillators. noStroke(); // Draw the red oscillator. fill(255, 0, 0); circle(x1, 0, 20); // Draw the blue oscillator. fill(0, 0, 255); circle(x2, 0, 20); } `

p5

Constants

Constants

A `Number` constant that's approximately 6.2382.
`TAU` is twice the value of the mathematical constant π. It's useful for many tasks that involve rotation and oscillation. For example, calling `rotate(TAU)` rotates the coordinate system `TAU` radians, which is one full turn (360˚). `TAU` and `TWO_PI` are equal.
Note: `TAU` radians equals 360˚, `PI` radians equals 180˚, `HALF_PI` radians equals 90˚, and `QUARTER_PI` radians equals 45˚.

property

TAU

Number

` function setup() { createCanvas(100, 100); background(200); // Draw an arc from 0 to TAU. arc(50, 50, 80, 80, 0, TAU); describe('A white circle drawn on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Translate the origin to the center. translate(50, 50); // Draw a line. line(0, 0, 40, 0); // Rotate a full turn. rotate(TAU); // Style the second line. strokeWeight(5); // Draw the same line, shorter and rotated. line(0, 0, 20, 0); describe( 'Two horizontal black lines on a gray background. A thick line extends from the center toward the right. A thin line extends from the end of the thick line.' ); } `
` function setup() { createCanvas(100, 100); describe( 'A red circle with a blue center oscillates from left to right on a gray background.' ); } function draw() { background(200); // Translate the origin to the center. translate(50, 50); // Calculate the x-coordinates. let x1 = 40 * sin(frameCount * 0.05); let x2 = 40 * sin(frameCount * 0.05 + TAU); // Style the oscillators. noStroke(); // Draw the red oscillator. fill(255, 0, 0); circle(x1, 0, 20); // Draw the blue oscillator, smaller. fill(0, 0, 255); circle(x2, 0, 10); } `

p5

Constants

Constants

A `Number` constant that's approximately 6.2382.
`TWO_PI` is twice the value of the mathematical constant π. It's useful for many tasks that involve rotation and oscillation. For example, calling `rotate(TWO_PI)` rotates the coordinate system `TWO_PI` radians, which is one full turn (360˚). `TWO_PI` and `TAU` are equal.
Note: `TWO_PI` radians equals 360˚, `PI` radians equals 180˚, `HALF_PI` radians equals 90˚, and `QUARTER_PI` radians equals 45˚.

property

TWO_PI

Number

` function setup() { createCanvas(100, 100); background(200); // Draw an arc from 0 to TWO_PI. arc(50, 50, 80, 80, 0, TWO_PI); describe('A white circle drawn on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Translate the origin to the center. translate(50, 50); // Draw a line. line(0, 0, 40, 0); // Rotate a full turn. rotate(TWO_PI); // Style the second line. strokeWeight(5); // Draw the same line, shorter and rotated. line(0, 0, 20, 0); describe( 'Two horizontal black lines on a gray background. A thick line extends from the center toward the right. A thin line extends from the end of the thick line.' ); } `
` function setup() { createCanvas(100, 100); describe( 'A red circle with a blue center oscillates from left to right on a gray background.' ); } function draw() { background(200); // Translate the origin to the center. translate(50, 50); // Calculate the x-coordinates. let x1 = 40 * sin(frameCount * 0.05); let x2 = 40 * sin(frameCount * 0.05 + TWO_PI); // Style the oscillators. noStroke(); // Draw the red oscillator. fill(255, 0, 0); circle(x1, 0, 20); // Draw the blue oscillator, smaller. fill(0, 0, 255); circle(x2, 0, 10); } `

p5

Constants

Constants

A `String` constant that's used to set the angleMode().
By default, functions such as rotate() and sin() expect angles measured in units of radians. Calling `angleMode(DEGREES)` ensures that angles are measured in units of degrees.
Note: `TWO_PI` radians equals 360˚.

property

DEGREES

String

` function setup() { createCanvas(100, 100); background(200); // Draw a red arc from 0 to HALF_PI radians. fill(255, 0, 0); arc(50, 50, 80, 80, 0, HALF_PI); // Use degrees. angleMode(DEGREES); // Draw a blue arc from 90˚ to 180˚. fill(0, 0, 255); arc(50, 50, 80, 80, 90, 180); describe('The bottom half of a circle drawn on a gray background. The bottom-right quarter is red. The bottom-left quarter is blue.'); } `

p5

Constants

Constants

A `String` constant that's used to set the angleMode().
By default, functions such as rotate() and sin() expect angles measured in units of radians. Calling `angleMode(RADIANS)` ensures that angles are measured in units of radians. Doing so can be useful if the angleMode() has been set to DEGREES.
Note: `TWO_PI` radians equals 360˚.

property

RADIANS

String

` function setup() { createCanvas(100, 100); background(200); // Use degrees. angleMode(DEGREES); // Draw a red arc from 0˚ to 90˚. fill(255, 0, 0); arc(50, 50, 80, 80, 0, 90); // Use radians. angleMode(RADIANS); // Draw a blue arc from HALF_PI to PI. fill(0, 0, 255); arc(50, 50, 80, 80, HALF_PI, PI); describe('The bottom half of a circle drawn on a gray background. The bottom-right quarter is red. The bottom-left quarter is blue.'); } `

p5

Constants

Constants

property

CORNER

String

p5

Constants

Constants

property

CORNERS

String

p5

Constants

Constants

property

RADIUS

String

p5

Constants

Constants

property

RIGHT

String

p5

Constants

Constants

property

LEFT

String

p5

Constants

Constants

property

CENTER

String

p5

Constants

Constants

property

TOP

String

p5

Constants

Constants

property

BOTTOM

String

p5

Constants

Constants

property

BASELINE

String

alphabetic

p5

Constants

Constants

property

POINTS

Number

0x0000

p5

Constants

Constants

property

LINES

Number

0x0001

p5

Constants

Constants

property

LINE_STRIP

Number

0x0003

p5

Constants

Constants

property

LINE_LOOP

Number

0x0002

p5

Constants

Constants

property

TRIANGLES

Number

0x0004

p5

Constants

Constants

property

TRIANGLE_FAN

Number

0x0006

p5

Constants

Constants

property

TRIANGLE_STRIP

Number

0x0005

p5

Constants

Constants

property

QUADS

String

p5

Constants

Constants

property

QUAD_STRIP

String

quad_strip

p5

Constants

Constants

property

TESS

String

tess

p5

Constants

Constants

property

CLOSE

String

p5

Constants

Constants

property

OPEN

String

p5

Constants

Constants

property

CHORD

String

p5

Constants

Constants

property

PIE

String

p5

Constants

Constants

property

PROJECT

String

square

p5

Constants

Constants

property

SQUARE

String

butt

p5

Constants

Constants

property

ROUND

String

p5

Constants

Constants

property

BEVEL

String

p5

Constants

Constants

property

MITER

String

p5

Constants

Constants

property

RGB

String

p5

Constants

Constants

HSB (hue, saturation, brightness) is a type of color model. You can learn more about it at HSB.

property

HSB

String

p5

Constants

Constants

property

HSL

String

p5

Constants

Constants

AUTO allows us to automatically set the width or height of an element (but not both), based on the current height and width of the element. Only one parameter can be passed to the size function as AUTO, at a time.

property

AUTO

String

p5

Constants

Constants

property

ALT

Number

p5

Constants

Constants

property

BACKSPACE

Number

p5

Constants

Constants

property

CONTROL

Number

p5

Constants

Constants

property

DELETE

Number

p5

Constants

Constants

property

DOWN_ARROW

Number

p5

Constants

Constants

property

ENTER

Number

p5

Constants

Constants

property

ESCAPE

Number

p5

Constants

Constants

property

LEFT_ARROW

Number

p5

Constants

Constants

property

OPTION

Number

p5

Constants

Constants

property

RETURN

Number

p5

Constants

Constants

property

RIGHT_ARROW

Number

p5

Constants

Constants

property

SHIFT

Number

p5

Constants

Constants

property

TAB

Number

p5

Constants

Constants

property

UP_ARROW

Number

p5

Constants

Constants

property

BLEND

String

source-over

p5

Constants

Constants

property

REMOVE

String

destination-out

p5

Constants

Constants

property

ADD

String

lighter

p5

Constants

Constants

property

DARKEST

String

p5

Constants

Constants

property

LIGHTEST

String

lighten

p5

Constants

Constants

property

DIFFERENCE

String

p5

Constants

Constants

property

SUBTRACT

String

p5

Constants

Constants

property

EXCLUSION

String

p5

Constants

Constants

property

MULTIPLY

String

p5

Constants

Constants

property

SCREEN

String

p5

Constants

Constants

property

REPLACE

String

copy

p5

Constants

Constants

property

OVERLAY

String

p5

Constants

Constants

property

HARD_LIGHT

String

p5

Constants

Constants

property

SOFT_LIGHT

String

p5

Constants

Constants

property

DODGE

String

color-dodge

p5

Constants

Constants

property

BURN

String

color-burn

p5

Constants

Constants

property

THRESHOLD

String

p5

Constants

Constants

property

GRAY

String

p5

Constants

Constants

property

OPAQUE

String

p5

Constants

Constants

property

INVERT

String

p5

Constants

Constants

property

POSTERIZE

String

p5

Constants

Constants

property

DILATE

String

p5

Constants

Constants

property

ERODE

String

p5

Constants

Constants

property

BLUR

String

p5

Constants

Constants

property

NORMAL

String

p5

Constants

Constants

property

ITALIC

String

p5

Constants

Constants

property

BOLD

String

p5

Constants

Constants

property

BOLDITALIC

String

p5

Constants

Constants

property

CHAR

String

p5

Constants

Constants

property

WORD

String

p5

Constants

Constants

property

LINEAR

String

p5

Constants

Constants

property

QUADRATIC

String

p5

Constants

Constants

property

BEZIER

String

p5

Constants

Constants

property

CURVE

String

p5

Constants

Constants

property

STROKE

String

p5

Constants

Constants

property

FILL

String

p5

Constants

Constants

property

TEXTURE

String

p5

Constants

Constants

property

IMMEDIATE

String

p5

Constants

Constants

property

IMAGE

String

p5

Constants

Constants

property

NEAREST

String

p5

Constants

Constants

property

REPEAT

String

p5

Constants

Constants

property

CLAMP

String

p5

Constants

Constants

property

MIRROR

String

p5

Constants

Constants

property

FLAT

String

p5

Constants

Constants

property

SMOOTH

String

p5

Constants

Constants

property

LANDSCAPE

String

p5

Constants

Constants

property

PORTRAIT

String

p5

Constants

Constants

property

GRID

String

p5

Constants

Constants

property

AXES

String

p5

Constants

Constants

property

LABEL

String

p5

Constants

Constants

property

FALLBACK

String

p5

Constants

Constants

property

CONTAIN

String

p5

Constants

Constants

property

COVER

String

p5

Constants

Constants

property

UNSIGNED_BYTE

String

p5

Constants

Constants

property

UNSIGNED_INT

String

p5

Constants

Constants

property

FLOAT

String

p5

Constants

Constants

property

HALF_FLOAT

String

p5

Constants

Constants

property

RGBA

String

p5

Constants

Constants

Displays text in the web browser's console.
`print()` is helpful for printing values while debugging. Each call to `print()` creates a new line of text.
Note: Call `print(' ')` to print a blank line. Calling `print()` without an argument opens the browser's dialog for printing documents.

method

print

contents

content to print to the console.

Any

` function setup() { // Prints "hello, world" to the console. print('hello, world'); } `
` function setup() { let name = 'ada'; // Prints "hello, ada" to the console. print(`hello, ${name}`); } `

p5

Environment

Environment

A `Number` variable that tracks the number of frames drawn since the sketch started.
`frameCount`'s value is 0 inside setup(). It increments by 1 each time the code in draw() finishes executing.

property

frameCount

Integer



` function setup() { createCanvas(100, 100); background(200); // Display the value of // frameCount. textSize(30); textAlign(CENTER, CENTER); text(frameCount, 50, 50); describe('The number 0 written in black in the middle of a gray square.'); } `
` function setup() { createCanvas(100, 100); // Set the frameRate to 30. frameRate(30); textSize(30); textAlign(CENTER, CENTER); describe('A number written in black in the middle of a gray square. Its value increases rapidly.'); } function draw() { background(200); // Display the value of // frameCount. text(frameCount, 50, 50); } `

p5

Environment

Environment

A `Number` variable that tracks the number of milliseconds it took to draw the last frame.
`deltaTime` contains the amount of time it took draw() to execute during the previous frame. It's useful for simulating physics.

property

deltaTime

Integer



` let x = 0; let speed = 0.05; function setup() { createCanvas(100, 100); // Set the frameRate to 30. frameRate(30); describe('A white circle moves from left to right on a gray background. It reappears on the left side when it reaches the right side.'); } function draw() { background(200); // Use deltaTime to calculate // a change in position. let deltaX = speed * deltaTime; // Update the x variable. x += deltaX; // Reset x to 0 if it's // greater than 100. if (x > 100) { x = 0; } // Use x to set the circle's // position. circle(x, 50, 20); } `

p5

Environment

Environment

A `Boolean` variable that's `true` if the browser is focused and `false` if not.
Note: The browser window can only receive input if it's focused.

property

focused

Boolean



` // Open this example in two separate browser // windows placed side-by-side to demonstrate. function setup() { createCanvas(100, 100); describe('A square changes color from green to red when the browser window is out of focus.'); } function draw() { // Change the background color // when the browser window // goes in/out of focus. if (focused === true) { background(0, 255, 0); } else { background(255, 0, 0); } } `

p5

Environment

Environment

Changes the cursor's appearance.
The first parameter, `type`, sets the type of cursor to display. The built-in options are `ARROW`, `CROSS`, `HAND`, `MOVE`, `TEXT`, and `WAIT`. `cursor()` also recognizes standard CSS cursor properties passed as strings: `'help'`, `'wait'`, `'crosshair'`, `'not-allowed'`, `'zoom-in'`, and `'grab'`. If the path to an image is passed, as in `cursor('assets/target.png')`, then the image will be used as the cursor. Images must be in .cur, .gif, .jpg, .jpeg, or .png format and should be at most 32 by 32 pixels large.
The parameters `x` and `y` are optional. If an image is used for the cursor, `x` and `y` set the location pointed to within the image. They are both 0 by default, so the cursor points to the image's top-left corner. `x` and `y` must be less than the image's width and height, respectively.

method

cursor

type

Built-in: either ARROW, CROSS, HAND, MOVE, TEXT, or WAIT. Native CSS properties: 'grab', 'progress', and so on. Path to cursor image.

String|Constant

x

horizontal active spot of the cursor.

Number

y

vertical active spot of the cursor.

Number

` function setup() { createCanvas(100, 100); describe('A gray square. The cursor appears as crosshairs.'); } function draw() { background(200); // Set the cursor to crosshairs: + cursor(CROSS); } `
` function setup() { createCanvas(100, 100); describe('A gray square divided into quadrants. The cursor image changes when the mouse moves to each quadrant.'); } function draw() { background(200); // Divide the canvas into quadrants. line(50, 0, 50, 100); line(0, 50, 100, 50); // Change cursor based on mouse position. if (mouseX < 50 && mouseY < 50) { cursor(CROSS); } else if (mouseX > 50 && mouseY < 50) { cursor('progress'); } else if (mouseX > 50 && mouseY > 50) { cursor('https://avatars0.githubusercontent.com/u/1617169?s=16'); } else { cursor('grab'); } } `
` function setup() { createCanvas(100, 100); describe('An image of three purple curves follows the mouse. The image shifts when the mouse is pressed.'); } function draw() { background(200); // Change the cursor's active spot // when the mouse is pressed. if (mouseIsPressed === true) { cursor('https://avatars0.githubusercontent.com/u/1617169?s=16', 8, 8); } else { cursor('https://avatars0.githubusercontent.com/u/1617169?s=16'); } } `

p5

Environment

Environment

Sets the number of frames to draw per second.
Calling `frameRate()` with one numeric argument, as in `frameRate(30)`, attempts to draw 30 frames per second (FPS). The target frame rate may not be achieved depending on the sketch's processing needs. Most computers default to a frame rate of 60 FPS. Frame rates of 24 FPS and above are fast enough for smooth animations.
Calling `frameRate()` without an argument returns the current frame rate. The value returned is an approximation.

method

frameRate

` function setup() { createCanvas(100, 100); describe('A white circle on a gray background. The circle moves from left to right in a loop. It slows down when the mouse is pressed.'); } function draw() { background(200); // Set the x variable based // on the current frameCount. let x = frameCount % 100; // If the mouse is pressed, // decrease the frame rate. if (mouseIsPressed === true) { frameRate(10); } else { frameRate(60); } // Use x to set the circle's // position. circle(x, 50, 20); } `
` function setup() { createCanvas(100, 100); describe('A number written in black on a gray background. The number decreases when the mouse is pressed.'); } function draw() { background(200); // If the mouse is pressed, do lots // of math to slow down drawing. if (mouseIsPressed === true) { for (let i = 0; i < 1000000; i += 1) { random(); } } // Get the current frame rate // and display it. let fps = frameRate(); text(fps, 50, 50); } `

p5

Environment

Environment

fps

number of frames to draw per second.

Number

##### return
current frame rate.

Number

Returns the target frame rate.
The value is either the system frame rate or the last value passed to frameRate().

method

getTargetFrameRate

### return
_targetFrameRate

Number

` function setup() { createCanvas(100, 100); describe('The number 20 written in black on a gray background.'); } function draw() { background(200); // Set the frame rate to 20. frameRate(20); // Get the target frame rate and // display it. let fps = getTargetFrameRate(); text(fps, 43, 54); } `

p5

Environment

Environment

Hides the cursor from view.

method

noCursor

` function setup() { // Hide the cursor. noCursor(); } function draw() { background(200); circle(mouseX, mouseY, 10); describe('A white circle on a gray background. The circle follows the mouse as it moves. The cursor is hidden.'); } `

p5

Environment

Environment

A `String` variable with the WebGL version in use.
`webglVersion`'s value equals one of the following string constants:
    * `WEBGL2` whose value is `'webgl2'`,
    * `WEBGL` whose value is `'webgl'`, or
    * `P2D` whose value is `'p2d'`. This is the default for 2D sketches.
See setAttributes() for ways to set the WebGL version.

property

webglVersion

String



` function setup() { background(200); // Display the current WebGL version. text(webglVersion, 42, 54); describe('The text "p2d" written in black on a gray background.'); } `
` let font; function preload() { // Load a font to use. font = loadFont('assets/inconsolata.otf'); } function setup() { // Create a canvas using WEBGL mode. createCanvas(100, 50, WEBGL); background(200); // Display the current WebGL version. fill(0); textFont(font); text(webglVersion, -15, 5); describe('The text "webgl2" written in black on a gray background.'); } `
` let font; function preload() { // Load a font to use. font = loadFont('assets/inconsolata.otf'); } function setup() { // Create a canvas using WEBGL mode. createCanvas(100, 50, WEBGL); // Set WebGL to version 1. setAttributes({ version: 1 }); background(200); // Display the current WebGL version. fill(0); textFont(font); text(webglVersion, -14, 5); describe('The text "webgl" written in black on a gray background.'); } `

p5

Environment

Environment

A `Number` variable that stores the width of the screen display.
`displayWidth` is useful for running full-screen programs. Its value depends on the current pixelDensity().
Note: The actual screen width can be computed as `displayWidth * pixelDensity()`.

property

displayWidth

Number



` function setup() { // Set the canvas' width and height // using the display's dimensions. createCanvas(displayWidth, displayHeight); background(200); describe('A gray canvas that is the same size as the display.'); } `

This example does not render anything.

p5

Environment

Environment

A `Number` variable that stores the height of the screen display.
`displayHeight` is useful for running full-screen programs. Its value depends on the current pixelDensity().
Note: The actual screen height can be computed as `displayHeight * pixelDensity()`.

property

displayHeight

Number



` function setup() { // Set the canvas' width and height // using the display's dimensions. createCanvas(displayWidth, displayHeight); background(200); describe('A gray canvas that is the same size as the display.'); } `

This example does not render anything.

p5

Environment

Environment

A `Number` variable that stores the width of the browser's viewport.
The layout viewport is the area within the browser that's available for drawing.

property

windowWidth

Number



` function setup() { // Set the canvas' width and height // using the browser's dimensions. createCanvas(windowWidth, windowHeight); background(200); describe('A gray canvas that takes up the entire browser window.'); } `

This example does not render anything.

p5

Environment

Environment

A `Number` variable that stores the height of the browser's viewport.
The layout viewport is the area within the browser that's available for drawing.

property

windowHeight

Number



` function setup() { // Set the canvas' width and height // using the browser's dimensions. createCanvas(windowWidth, windowHeight); background(200); describe('A gray canvas that takes up the entire browser window.'); } `

This example does not render anything.

p5

Environment

Environment

A function that's called when the browser window is resized.
Code placed in the body of `windowResized()` will run when the browser window's size changes. It's a good place to call resizeCanvas() or make other adjustments to accommodate the new window size.
The `event` parameter is optional. If added to the function declaration, it can be used for debugging or other purposes.

method

windowResized

event

optional resize Event.

UIEvent

` function setup() { createCanvas(windowWidth, windowHeight); describe('A gray canvas with a white circle at its center. The canvas takes up the entire browser window. It changes size to match the browser window.'); } function draw() { background(200); // Draw a circle at the center. circle(width / 2, height / 2, 50); } // Resize the canvas when the // browser's size changes. function windowResized() { resizeCanvas(windowWidth, windowHeight); } `

This example does not render anything.

p5

Environment

Environment

Called upon each p5 instantiation instead of module import due to the possibility of the window being resized when no sketch is active.

p5

Environment

Environment

A `Number` variable that stores the width of the canvas in pixels.
`width`'s default value is 100. Calling createCanvas() or resizeCanvas() changes the value of `width`. Calling noCanvas() sets its value to 0.

` function setup() { background(200); // Display the canvas' width. text(width, 42, 54); describe('The number 100 written in black on a gray square.'); } `
` function setup() { createCanvas(50, 100); background(200); // Display the canvas' width. text(width, 21, 54); describe('The number 50 written in black on a gray rectangle.'); } `
` function setup() { createCanvas(100, 100); background(200); // Display the canvas' width. text(width, 42, 54); describe('The number 100 written in black on a gray square. When the mouse is pressed, the square becomes a rectangle and the number becomes 50.'); } // If the mouse is pressed, reisze // the canvas and display its new // width. function mousePressed() { if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { resizeCanvas(50, 100); background(200); text(width, 21, 54); } } `

property

width

Number



p5

Environment

Environment

A `Number` variable that stores the height of the canvas in pixels.
`height`'s default value is 100. Calling createCanvas() or resizeCanvas() changes the value of `height`. Calling noCanvas() sets its value to 0.

` function setup() { background(200); // Display the canvas' height. text(height, 42, 54); describe('The number 100 written in black on a gray square.'); } `
` function setup() { createCanvas(100, 50); background(200); // Display the canvas' height. text(height, 42, 27); describe('The number 50 written in black on a gray rectangle.'); } `
` function setup() { createCanvas(100, 100); background(200); // Display the canvas' height. text(height, 42, 54); describe('The number 100 written in black on a gray square. When the mouse is pressed, the square becomes a rectangle and the number becomes 50.'); } // If the mouse is pressed, reisze // the canvas and display its new // height. function mousePressed() { if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { resizeCanvas(100, 50); background(200); text(height, 42, 27); } } `

property

height

Number



p5

Environment

Environment

Toggles full-screen mode or returns the current mode.
Calling `fullscreen(true)` makes the sketch full-screen. Calling `fullscreen(false)` makes the sketch its original size.
Calling `fullscreen()` without an argument returns `true` if the sketch is in full-screen mode and `false` if not.
Note: Due to browser restrictions, `fullscreen()` can only be called with user input such as a mouse press.

method

fullscreen

val

whether the sketch should be in fullscreen mode.

Boolean

### return
current fullscreen state.

Boolean

` function setup() { background(200); describe('A gray canvas that switches between default and full-screen display when clicked.'); } // If the mouse is pressed, // toggle full-screen mode. function mousePressed() { if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { let fs = fullscreen(); fullscreen(!fs); } } `

p5

Environment

Environment

Sets the pixel density or returns the current density.
Computer displays are grids of little lights called pixels. A display's pixel density describes how many pixels it packs into an area. Displays with smaller pixels have a higher pixel density and create sharper images.
`pixelDensity()` sets the pixel scaling for high pixel density displays. By default, the pixel density is set to match the display's density. Calling `pixelDensity(1)` turn this off.
Calling `pixelDensity()` without an argument returns the current pixel density.

method

pixelDensity

` function setup() { // Set the pixel density to 1. pixelDensity(1); // Create a canvas and draw // a circle. createCanvas(100, 100); background(200); circle(50, 50, 70); describe('A fuzzy white circle on a gray canvas.'); } `
` function setup() { // Set the pixel density to 3. pixelDensity(3); // Create a canvas, paint the // background, and draw a // circle. createCanvas(100, 100); background(200); circle(50, 50, 70); describe('A sharp white circle on a gray canvas.'); } `

p5

Environment

Environment

val

desired pixel density.

Number

##### return
current pixel density of the sketch.

Number

Returns the display's current pixel density.

method

displayDensity

### return
current pixel density of the display.

Number

` function setup() { // Set the pixel density to 1. pixelDensity(1); // Create a canvas and draw // a circle. createCanvas(100, 100); background(200); circle(50, 50, 70); describe('A fuzzy white circle drawn on a gray background. The circle becomes sharper when the mouse is pressed.'); } function mousePressed() { // Get the current display density. let d = displayDensity(); // Use the display density to set // the sketch's pixel density. pixelDensity(d); // Paint the background and // draw a circle. background(200); circle(50, 50, 70); } `

p5

Environment

Environment

Returns the sketch's current URL as a `String`.

method

getURL

### return
url

String

` function setup() { background(200); // Get the sketch's URL // and display it. let url = getURL(); textWrap(CHAR); text(url, 0, 40, 100); describe('The URL "https://p5js.org/reference/p5/getURL" written in black on a gray background.'); } `

p5

Environment

Environment

Returns the current URL path as an `Array` of `String`s.
For example, consider a sketch hosted at the URL `https://example.com/sketchbook`. Calling `getURLPath()` returns `['sketchbook']`. For a sketch hosted at the URL `https://example.com/sketchbook/monday`, `getURLPath()` returns `['sketchbook', 'monday']`.

method

getURLPath

### return
path components.

String[]

` function setup() { background(200); // Get the sketch's URL path // and display the first // part. let path = getURLPath(); text(path[0], 25, 54); describe('The word "reference" written in black on a gray background.'); } `

p5

Environment

Environment

Returns the current URL parameters in an `Object`.
For example, calling `getURLParams()` in a sketch hosted at the URL `https://p5js.org?year=2014&month;=May&day;=15` returns `{ year: 2014, month: 'May', day: 15 }`.

method

getURLParams

### return
URL params

Object

` // Imagine this sketch is hosted at the following URL: // https://p5js.org?year=2014&month;=May&day;=15 function setup() { background(200); // Get the sketch's URL // parameters and display // them. let params = getURLParams(); text(params.day, 10, 20); text(params.month, 10, 40); text(params.year, 10, 60); describe('The text "15", "May", and "2014" written in black on separate lines.'); } `

This example does not render anything.

p5

Environment

Environment

p5

Environment

This is our i18next "backend" plugin. It tries to fetch languages from a CDN.

p5

Environment

Set up our translation function, with loaded languages

p5

Environment

Returns a list of languages we have translations loaded for

p5

Environment

Returns the current language selected for translation

p5

Environment

Sets the current language for translation Returns a promise that resolved when loading is finished, or rejects if it fails.

p5

Environment

p5

Environment

A function that's called once to load assets before the sketch runs.
Declaring the function `preload()` sets a code block to run once automatically before setup() or draw(). It's used to load assets including multimedia files, fonts, data, and 3D models:
    function preload() {
      // Code to run before the rest of the sketch.
    }
    
Functions such as loadImage(), loadFont(), loadJSON(), and loadModel() are guaranteed to either finish loading or raise an error if they're called within `preload()`. Doing so ensures that assets are available when the sketch begins running.

method

preload

` let img; // Load an image and create a p5.Image object. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); // Draw the image. image(img, 0, 0); describe('A red brick wall.'); } `

p5

Structure

Structure

A function that's called once when the sketch begins running.
Declaring the function `setup()` sets a code block to run once automatically when the sketch starts running. It's used to perform setup tasks such as creating the canvas and initializing variables:
    function setup() {
      // Code to run once at the start of the sketch.
    }
    
Code placed in `setup()` will run once before code placed in draw() begins looping. If the preload() is declared, then `setup()` will run immediately after preload() finishes loading assets.
Note: `setup()` doesn’t have to be declared, but it’s common practice to do so.

method

setup

` function setup() { createCanvas(100, 100); background(200); // Draw the circle. circle(50, 50, 40); describe('A white circle on a gray background.'); } `
` function setup() { createCanvas(100, 100); // Paint the background once. background(200); describe( 'A white circle on a gray background. The circle follows the mouse as the user moves, leaving a trail.' ); } function draw() { // Draw circles repeatedly. circle(mouseX, mouseY, 40); } `
` let img; function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); // Draw the image. image(img, 0, 0); describe( 'A white circle on a brick wall. The circle follows the mouse as the user moves, leaving a trail.' ); } function draw() { // Style the circle. noStroke(); // Draw the circle. circle(mouseX, mouseY, 10); } `

p5

Structure

Structure

A function that's called repeatedly while the sketch runs.
Declaring the function `draw()` sets a code block to run repeatedly once the sketch starts. It’s used to create animations and respond to user inputs:
    function draw() {
      // Code to run repeatedly.
    }
    
This is often called the "draw loop" because p5.js calls the code in `draw()` in a loop behind the scenes. By default, `draw()` tries to run 60 times per second. The actual rate depends on many factors. The drawing rate, called the "frame rate", can be controlled by calling frameRate(). The number of times `draw()` has run is stored in the system variable frameCount().
Code placed within `draw()` begins looping after setup() runs. `draw()` will run until the user closes the sketch. `draw()` can be stopped by calling the noLoop() function. `draw()` can be resumed by calling the loop() function.

method

draw

` function setup() { createCanvas(100, 100); // Paint the background once. background(200); describe( 'A white circle on a gray background. The circle follows the mouse as the user moves, leaving a trail.' ); } function draw() { // Draw circles repeatedly. circle(mouseX, mouseY, 40); } `
` function setup() { createCanvas(100, 100); describe( 'A white circle on a gray background. The circle follows the mouse as the user moves.' ); } function draw() { // Paint the background repeatedly. background(200); // Draw circles repeatedly. circle(mouseX, mouseY, 40); } `
` // Double-click the canvas to change the circle's color. function setup() { createCanvas(100, 100); describe( 'A white circle on a gray background. The circle follows the mouse as the user moves. The circle changes color to pink when the user double-clicks.' ); } function draw() { // Paint the background repeatedly. background(200); // Draw circles repeatedly. circle(mouseX, mouseY, 40); } // Change the fill color when the user double-clicks. function doubleClicked() { fill('deeppink'); } `

p5

Structure

Structure

Removes the sketch from the web page.
Calling `remove()` stops the draw loop and removes any HTML elements created by the sketch, including the canvas. A new sketch can be created by using the p5() constructor, as in `new p5()`.

method

remove

` // Double-click to remove the canvas. function setup() { createCanvas(100, 100); describe( 'A white circle on a gray background. The circle follows the mouse as the user moves. The sketch disappears when the user double-clicks.' ); } function draw() { // Paint the background repeatedly. background(200); // Draw circles repeatedly. circle(mouseX, mouseY, 40); } // Remove the sketch when the user double-clicks. function doubleClicked() { remove(); } `

p5

Structure

Structure

Turns off the parts of the Friendly Error System (FES) that impact performance.
The FES can cause sketches to draw slowly because it does extra work behind the scenes. For example, the FES checks the arguments passed to functions, which takes time to process. Disabling the FES can significantly improve performance by turning off these checks.

property

disableFriendlyErrors

Boolean

` // Disable the FES. p5.disableFriendlyErrors = true; function setup() { createCanvas(100, 100); background(200); // The circle() function requires three arguments. The // next line would normally display a friendly error that // points this out. Instead, nothing happens and it fails // silently. circle(50, 50); describe('A gray square.'); } `

p5

Structure

Structure

The element's underlying `HTMLElement` object.
The HTMLElement object's properties and methods can be used directly.

` function setup() { // Create a canvas element and // assign it to cnv. let cnv = createCanvas(100, 100); background(200); // Set the border style for the // canvas. cnv.elt.style.border = '5px dashed deeppink'; describe('A gray square with a pink border drawn with dashed lines.'); } `

property

elt



p5.Element

DOM

DOM

A `Number` property that stores the element's width.

{Number}

property

width

p5.Element

DOM

DOM

A `Number` property that stores the element's height.

{Number}

property

height

p5.Element

DOM

DOM

Attaches the element to a parent element.
For example, a `<div></div>` element may be used as a box to hold two pieces of text, a header and a paragraph. The `<div></div>` is the parent element of both the header and paragraph.
The parameter `parent` can have one of three types. `parent` can be a string with the parent element's ID, as in `myElement.parent('container')`. It can also be another p5.Element object, as in `myElement.parent(myDiv)`. Finally, `parent` can be an `HTMLElement` object, as in `myElement.parent(anotherElement)`.
Calling `myElement.parent()` without an argument returns the element's parent.

method

parent

` function setup() { background(200); // Create a div element. let div = createDiv(); // Place the div in the top-left corner. div.position(10, 20); // Set its width and height. div.size(80, 60); // Set its background color to white div.style('background-color', 'white'); // Align any text to the center. div.style('text-align', 'center'); // Set its ID to "container". div.id('container'); // Create a paragraph element. let p = createP('p5*js'); // Make the div its parent // using its ID "container". p.parent('container'); describe('The text "p5*js" written in black at the center of a white rectangle. The rectangle is inside a gray square.'); } `
` function setup() { background(200); // Create rectangular div element. let div = createDiv(); // Place the div in the top-left corner. div.position(10, 20); // Set its width and height. div.size(80, 60); // Set its background color and align // any text to the center. div.style('background-color', 'white'); div.style('text-align', 'center'); // Create a paragraph element. let p = createP('p5*js'); // Make the div its parent. p.parent(div); describe('The text "p5*js" written in black at the center of a white rectangle. The rectangle is inside a gray square.'); } `
` function setup() { background(200); // Create rectangular div element. let div = createDiv(); // Place the div in the top-left corner. div.position(10, 20); // Set its width and height. div.size(80, 60); // Set its background color and align // any text to the center. div.style('background-color', 'white'); div.style('text-align', 'center'); // Create a paragraph element. let p = createP('p5*js'); // Make the div its parent // using the underlying // HTMLElement. p.parent(div.elt); describe('The text "p5*js" written in black at the center of a white rectangle. The rectangle is inside a gray square.'); } `

p5.Element

DOM

DOM

parent

ID, p5.Element, or HTMLElement of desired parent element.

String|p5.Element|Object

##### return


p5.Element

Sets the element's ID using a given string.
Calling `myElement.id()` without an argument returns its ID as a string.

method

id

` function setup() { // Create a canvas element and // assign it to cnv. let cnv = createCanvas(100, 100); background(200); // Set the canvas' ID // to "mycanvas". cnv.id('mycanvas'); // Get the canvas' ID. let id = cnv.id(); text(id, 24, 54); describe('The text "mycanvas" written in black on a gray background.'); } `

p5.Element

DOM

DOM

id

ID of the element.

String

##### return
ID of the element.

String

Adds a class attribute to the element using a given string.
Calling `myElement.class()` without an argument returns a string with its current classes.

method

class

` function setup() { // Create a canvas element and // assign it to cnv. let cnv = createCanvas(100, 100); background(200); // Add the class "small" to the // canvas element. cnv.class('small'); // Get the canvas element's class // and display it. let c = cnv.class(); text(c, 35, 54); describe('The word "small" written in black on a gray canvas.'); } `

p5.Element

DOM

DOM

class

class to add.

String

##### return
element's classes, if any.

String

Calls a function when the mouse is pressed over the element.
Calling `myElement.mousePressed(false)` disables the function.
Note: Some mobile browsers may also trigger this event when the element receives a quick tap.

method

mousePressed

fxn

function to call when the mouse is pressed over the element. `false` disables the function.

Function|Boolean

` function setup() { // Create a canvas element and // assign it to cnv. let cnv = createCanvas(100, 100); background(200); // Call randomColor() when the canvas // is pressed. cnv.mousePressed(randomColor); describe('A gray square changes color when the mouse is pressed.'); } // Paint the background either // red, yellow, blue, or green. function randomColor() { let c = random(['red', 'yellow', 'blue', 'green']); background(c); } `

p5.Element

DOM

DOM

Calls a function when the mouse is pressed twice over the element.
Calling `myElement.doubleClicked(false)` disables the function.

method

doubleClicked

fxn

function to call when the mouse is double clicked over the element. `false` disables the function.

Function|Boolean

` function setup() { // Create a canvas element and // assign it to cnv. let cnv = createCanvas(100, 100); background(200); // Call randomColor() when the // canvas is double-clicked. cnv.doubleClicked(randomColor); describe('A gray square changes color when the user double-clicks the canvas.'); } // Paint the background either // red, yellow, blue, or green. function randomColor() { let c = random(['red', 'yellow', 'blue', 'green']); background(c); } `

p5.Element

DOM

DOM

Calls a function when the mouse wheel scrolls over the element.
The callback function, `fxn`, is passed an `event` object. `event` has two numeric properties, `deltaY` and `deltaX`. `event.deltaY` is negative if the mouse wheel rotates away from the user. It's positive if the mouse wheel rotates toward the user. `event.deltaX` is positive if the mouse wheel moves to the right. It's negative if the mouse wheel moves to the left.
Calling `myElement.mouseWheel(false)` disables the function.

method

mouseWheel

fxn

function to call when the mouse wheel is scrolled over the element. `false` disables the function.

Function|Boolean

` function setup() { // Create a canvas element and // assign it to cnv. let cnv = createCanvas(100, 100); background(200); // Call randomColor() when the // mouse wheel moves. cnv.mouseWheel(randomColor); describe('A gray square changes color when the user scrolls the mouse wheel over the canvas.'); } // Paint the background either // red, yellow, blue, or green. function randomColor() { let c = random(['red', 'yellow', 'blue', 'green']); background(c); } `
` function setup() { // Create a canvas element and // assign it to cnv. let cnv = createCanvas(100, 100); background(200); // Call changeBackground() when the // mouse wheel moves. cnv.mouseWheel(changeBackground); describe('A gray square. When the mouse wheel scrolls over the square, it changes color and displays shapes.'); } function changeBackground(event) { // Change the background color // based on deltaY. if (event.deltaY > 0) { background('deeppink'); } else if (event.deltaY < 0) { background('cornflowerblue'); } else { background(200); } // Draw a shape based on deltaX. if (event.deltaX > 0) { circle(50, 50, 20); } else if (event.deltaX < 0) { square(40, 40, 20); } } `

p5.Element

DOM

DOM

Calls a function when the mouse is released over the element.
Calling `myElement.mouseReleased(false)` disables the function.
Note: Some mobile browsers may also trigger this event when the element receives a quick tap.

method

mouseReleased

fxn

function to call when the mouse is pressed over the element. `false` disables the function.

Function|Boolean

` function setup() { // Create a canvas element and // assign it to cnv. let cnv = createCanvas(100, 100); background(200); // Call randomColor() when a // mouse press ends. cnv.mouseReleased(randomColor); describe('A gray square changes color when the user releases a mouse press.'); } // Paint the background either // red, yellow, blue, or green. function randomColor() { let c = random(['red', 'yellow', 'blue', 'green']); background(c); } `

p5.Element

DOM

DOM

Calls a function when the mouse is pressed and released over the element.
Calling `myElement.mouseReleased(false)` disables the function.
Note: Some mobile browsers may also trigger this event when the element receives a quick tap.

method

mouseClicked

fxn

function to call when the mouse is pressed and released over the element. `false` disables the function.

Function|Boolean

` function setup() { // Create a canvas element and // assign it to cnv. let cnv = createCanvas(100, 100); background(200); // Call randomColor() when a // mouse press ends. cnv.mouseClicked(randomColor); describe('A gray square changes color when the user releases a mouse press.'); } // Paint the background either // red, yellow, blue, or green. function randomColor() { let c = random(['red', 'yellow', 'blue', 'green']); background(c); } `

p5.Element

DOM

DOM

Calls a function when the mouse moves over the element.
Calling `myElement.mouseMoved(false)` disables the function.

method

mouseMoved

fxn

function to call when the mouse moves over the element. `false` disables the function.

Function|Boolean

` function setup() { // Create a canvas element and // assign it to cnv. let cnv = createCanvas(100, 100); background(200); // Call randomColor() when the // mouse moves. cnv.mouseMoved(randomColor); describe('A gray square changes color when the mouse moves over the canvas.'); } // Paint the background either // red, yellow, blue, or green. function randomColor() { let c = random(['red', 'yellow', 'blue', 'green']); background(c); } `

p5.Element

DOM

DOM

Calls a function when the mouse moves onto the element.
Calling `myElement.mouseOver(false)` disables the function.

method

mouseOver

fxn

function to call when the mouse moves onto the element. `false` disables the function.

Function|Boolean

` function setup() { // Create a canvas element and // assign it to cnv. let cnv = createCanvas(100, 100); background(200); // Call randomColor() when the // mouse moves onto the canvas. cnv.mouseOver(randomColor); describe('A gray square changes color when the mouse moves onto the canvas.'); } // Paint the background either // red, yellow, blue, or green. function randomColor() { let c = random(['red', 'yellow', 'blue', 'green']); background(c); } `

p5.Element

DOM

DOM

Calls a function when the mouse moves off the element.
Calling `myElement.mouseOut(false)` disables the function.

method

mouseOut

fxn

function to call when the mouse moves off the element. `false` disables the function.

Function|Boolean

` function setup() { // Create a canvas element and // assign it to cnv. let cnv = createCanvas(100, 100); background(200); // Call randomColor() when the // mouse moves off the canvas. cnv.mouseOut(randomColor); describe('A gray square changes color when the mouse moves off the canvas.'); } // Paint the background either // red, yellow, blue, or green. function randomColor() { let c = random(['red', 'yellow', 'blue', 'green']); background(c); } `

p5.Element

DOM

DOM

Calls a function when the element is touched.
Calling `myElement.touchStarted(false)` disables the function.
Note: Touch functions only work on mobile devices.

method

touchStarted

fxn

function to call when the touch starts. `false` disables the function.

Function|Boolean

` function setup() { // Create a canvas element and // assign it to cnv. let cnv = createCanvas(100, 100); background(200); // Call randomColor() when the // user touches the canvas. cnv.touchStarted(randomColor); describe('A gray square changes color when the user touches the canvas.'); } // Paint the background either // red, yellow, blue, or green. function randomColor() { let c = random(['red', 'yellow', 'blue', 'green']); background(c); } `

p5.Element

DOM

DOM

Calls a function when the user touches the element and moves.
Calling `myElement.touchMoved(false)` disables the function.
Note: Touch functions only work on mobile devices.

method

touchMoved

fxn

function to call when the touch moves over the element. `false` disables the function.

Function|Boolean

` function setup() { // Create a canvas element and // assign it to cnv. let cnv = createCanvas(100, 100); background(200); // Call randomColor() when the // user touches the canvas // and moves. cnv.touchMoved(randomColor); describe('A gray square changes color when the user touches the canvas and moves.'); } // Paint the background either // red, yellow, blue, or green. function randomColor() { let c = random(['red', 'yellow', 'blue', 'green']); background(c); } `

p5.Element

DOM

DOM

Calls a function when the user stops touching the element.
Calling `myElement.touchMoved(false)` disables the function.
Note: Touch functions only work on mobile devices.

method

touchEnded

fxn

function to call when the touch ends. `false` disables the function.

Function|Boolean

` function setup() { // Create a canvas element and // assign it to cnv. let cnv = createCanvas(100, 100); background(200); // Call randomColor() when the // user touches the canvas, // then lifts their finger. cnv.touchEnded(randomColor); describe('A gray square changes color when the user touches the canvas, then lifts their finger.'); } // Paint the background either // red, yellow, blue, or green. function randomColor() { let c = random(['red', 'yellow', 'blue', 'green']); background(c); } `

p5.Element

DOM

DOM

Calls a function when a file is dragged over the element.
Calling `myElement.dragOver(false)` disables the function.

method

dragOver

fxn

function to call when the file is dragged over the element. `false` disables the function.

Function|Boolean

` // Drag a file over the canvas to test. function setup() { // Create a canvas element and // assign it to cnv. let cnv = createCanvas(100, 100); background(200); // Call helloFile() when a // file is dragged over // the canvas. cnv.dragOver(helloFile); describe('A gray square. The text "hello, file" appears when a file is dragged over the square.'); } function helloFile() { text('hello, file', 50, 50); } `

p5.Element

DOM

DOM

Calls a function when a file is dragged off the element.
Calling `myElement.dragLeave(false)` disables the function.

method

dragLeave

fxn

function to call when the file is dragged off the element. `false` disables the function.

Function|Boolean

` // Drag a file over, then off // the canvas to test. function setup() { // Create a canvas element and // assign it to cnv. let cnv = createCanvas(100, 100); background(200); // Call byeFile() when a // file is dragged over, // then off the canvas. cnv.dragLeave(byeFile); describe('A gray square. The text "bye, file" appears when a file is dragged over, then off the square.'); } function byeFile() { text('bye, file', 50, 50); } `

p5.Element

DOM

DOM

Helper fxn for sharing pixel methods

p5.Element

DOM

DOM

Resets the graphics buffer's transformations and lighting.
By default, the main canvas resets certain transformation and lighting values each time draw() executes. `p5.Graphics` objects must reset these values manually by calling `myGraphics.reset()`.

method

reset

` let pg; function setup() { createCanvas(100, 100); // Create a p5.Graphics object. pg = createGraphics(60, 60); describe('A white circle moves downward slowly within a dark square. The circle resets at the top of the dark square when the user presses the mouse.'); } function draw() { background(200); // Translate the p5.Graphics object's coordinate system. // The translation accumulates; the white circle moves. pg.translate(0, 0.1); // Draw to the p5.Graphics object. pg.background(100); pg.circle(30, 0, 10); // Display the p5.Graphics object. image(pg, 20, 20); // Translate the main canvas' coordinate system. // The translation doesn't accumulate; the dark // square is always in the same place. translate(0, 0.1); // Reset the p5.Graphics object when the // user presses the mouse. if (mouseIsPressed === true) { pg.reset(); } } `
` let pg; function setup() { createCanvas(100, 100); // Create a p5.Graphics object. pg = createGraphics(60, 60); describe('A white circle at the center of a dark gray square. The image is drawn on a light gray background.'); } function draw() { background(200); // Translate the p5.Graphics object's coordinate system. pg.translate(30, 30); // Draw to the p5.Graphics object. pg.background(100); pg.circle(0, 0, 10); // Display the p5.Graphics object. image(pg, 20, 20); // Reset the p5.Graphics object automatically. pg.reset(); } `
` let pg; function setup() { createCanvas(100, 100); // Create a p5.Graphics object using WebGL mode. pg = createGraphics(100, 100, WEBGL); describe("A sphere lit from above with a red light. The sphere's surface becomes glossy while the user clicks and holds the mouse."); } function draw() { background(200); // Add a red point light from the top-right. pg.pointLight(255, 0, 0, 50, -100, 50); // Style the sphere. // It should appear glossy when the // lighting values are reset. pg.noStroke(); pg.specularMaterial(255); pg.shininess(100); // Draw the sphere. pg.sphere(30); // Display the p5.Graphics object. image(pg, -50, -50); // Reset the p5.Graphics object when // the user presses the mouse. if (mouseIsPressed === true) { pg.reset(); } } `
` let pg; function setup() { createCanvas(100, 100); // Create a p5.Graphics object using WebGL mode. pg = createGraphics(100, 100, WEBGL); describe('A sphere with a glossy surface is lit from the top-right by a red light.'); } function draw() { background(200); // Add a red point light from the top-right. pg.pointLight(255, 0, 0, 50, -100, 50); // Style the sphere. pg.noStroke(); pg.specularMaterial(255); pg.shininess(100); // Draw the sphere. pg.sphere(30); // Display the p5.Graphics object. image(pg, 0, 0); // Reset the p5.Graphics object automatically. pg.reset(); } `

p5.Graphics

Rendering

Rendering

Removes the graphics buffer from the web page.
Calling `myGraphics.remove()` removes the graphics buffer's `<canvas>` element from the web page. The graphics buffer also uses a bit of memory on the CPU that can be freed like so:
    // Remove the graphics buffer from the web page.
    myGraphics.remove();
    
    // Delete the graphics buffer from CPU memory.
    myGraphics = undefined;
    
Note: All variables that reference the graphics buffer must be assigned the value `undefined` to delete the graphics buffer from CPU memory. If any variable still refers to the graphics buffer, then it won't be garbage collected.

method

remove

` // Double-click to remove the p5.Graphics object. let pg; function setup() { createCanvas(100, 100); // Create a p5.Graphics object. pg = createGraphics(60, 60); // Draw to the p5.Graphics object. pg.background(100); pg.circle(30, 30, 20); describe('A white circle at the center of a dark gray square disappears when the user double-clicks.'); } function draw() { background(200); // Display the p5.Graphics object if // it's available. if (pg) { image(pg, 20, 20); } } // Remove the p5.Graphics object when the // the user double-clicks. function doubleClicked() { // Remove the p5.Graphics object from the web page. pg.remove(); pg = undefined; } `

p5.Graphics

Rendering

Rendering

Creates a new p5.Framebuffer object with the same WebGL context as the graphics buffer.
p5.Framebuffer objects are separate drawing surfaces that can be used as textures in WebGL mode. They're similar to p5.Graphics objects and generally run much faster when used as textures. Creating a p5.Framebuffer object in the same context as the graphics buffer makes this speedup possible.
The parameter, `options`, is optional. An object can be passed to configure the p5.Framebuffer object. The available properties are:
    * `format`: data format of the texture, either `UNSIGNED_BYTE`, `FLOAT`, or `HALF_FLOAT`. Default is `UNSIGNED_BYTE`.
    * `channels`: whether to store `RGB` or `RGBA` color channels. Default is to match the graphics buffer which is `RGBA`.
    * `depth`: whether to include a depth buffer. Default is `true`.
    * `depthFormat`: data format of depth information, either `UNSIGNED_INT` or `FLOAT`. Default is `FLOAT`.
    * `stencil`: whether to include a stencil buffer for masking. `depth` must be `true` for this feature to work. Defaults to the value of `depth` which is `true`.
    * `antialias`: whether to perform anti-aliasing. If set to `true`, as in `{ antialias: true }`, 2 samples will be used by default. The number of samples can also be set, as in `{ antialias: 4 }`. Default is to match setAttributes() which is `false` (`true` in Safari).
    * `width`: width of the p5.Framebuffer object. Default is to always match the graphics buffer width.
    * `height`: height of the p5.Framebuffer object. Default is to always match the graphics buffer height.
    * `density`: pixel density of the p5.Framebuffer object. Default is to always match the graphics buffer pixel density.
    * `textureFiltering`: how to read values from the p5.Framebuffer object. Either `LINEAR` (nearby pixels will be interpolated) or `NEAREST` (no interpolation). Generally, use `LINEAR` when using the texture as an image and `NEAREST` if reading the texture as data. Default is `LINEAR`.
If the `width`, `height`, or `density` attributes are set, they won't automatically match the graphics buffer and must be changed manually.

method

createFramebuffer

options

configuration options.

Object

### return
new framebuffer.

p5.Framebuffer

` // Click and hold a mouse button to change shapes. let pg; let torusLayer; let boxLayer; function setup() { createCanvas(100, 100); // Create a p5.Graphics object using WebGL mode. pg = createGraphics(100, 100, WEBGL); // Create the p5.Framebuffer objects. torusLayer = pg.createFramebuffer(); boxLayer = pg.createFramebuffer(); describe('A grid of white toruses rotating against a dark gray background. The shapes become boxes while the user holds a mouse button.'); } function draw() { // Update and draw the layers offscreen. drawTorus(); drawBox(); // Choose the layer to display. let layer; if (mouseIsPressed === true) { layer = boxLayer; } else { layer = torusLayer; } // Draw to the p5.Graphics object. pg.background(50); // Iterate from left to right. for (let x = -50; x < 50; x += 25) { // Iterate from top to bottom. for (let y = -50; y < 50; y += 25) { // Draw the layer to the p5.Graphics object pg.image(layer, x, y, 25, 25); } } // Display the p5.Graphics object. image(pg, 0, 0); } // Update and draw the torus layer offscreen. function drawTorus() { // Start drawing to the torus p5.Framebuffer. torusLayer.begin(); // Clear the drawing surface. pg.clear(); // Turn on the lights. pg.lights(); // Rotate the coordinate system. pg.rotateX(frameCount * 0.01); pg.rotateY(frameCount * 0.01); // Style the torus. pg.noStroke(); // Draw the torus. pg.torus(20); // Start drawing to the torus p5.Framebuffer. torusLayer.end(); } // Update and draw the box layer offscreen. function drawBox() { // Start drawing to the box p5.Framebuffer. boxLayer.begin(); // Clear the drawing surface. pg.clear(); // Turn on the lights. pg.lights(); // Rotate the coordinate system. pg.rotateX(frameCount * 0.01); pg.rotateY(frameCount * 0.01); // Style the box. pg.noStroke(); // Draw the box. pg.box(30); // Start drawing to the box p5.Framebuffer. boxLayer.end(); } `
` // Click and hold a mouse button to change shapes. let pg; let torusLayer; let boxLayer; function setup() { createCanvas(100, 100); // Create an options object. let options = { width: 25, height: 25 }; // Create a p5.Graphics object using WebGL mode. pg = createGraphics(100, 100, WEBGL); // Create the p5.Framebuffer objects. // Use options for configuration. torusLayer = pg.createFramebuffer(options); boxLayer = pg.createFramebuffer(options); describe('A grid of white toruses rotating against a dark gray background. The shapes become boxes while the user holds a mouse button.'); } function draw() { // Update and draw the layers offscreen. drawTorus(); drawBox(); // Choose the layer to display. let layer; if (mouseIsPressed === true) { layer = boxLayer; } else { layer = torusLayer; } // Draw to the p5.Graphics object. pg.background(50); // Iterate from left to right. for (let x = -50; x < 50; x += 25) { // Iterate from top to bottom. for (let y = -50; y < 50; y += 25) { // Draw the layer to the p5.Graphics object pg.image(layer, x, y); } } // Display the p5.Graphics object. image(pg, 0, 0); } // Update and draw the torus layer offscreen. function drawTorus() { // Start drawing to the torus p5.Framebuffer. torusLayer.begin(); // Clear the drawing surface. pg.clear(); // Turn on the lights. pg.lights(); // Rotate the coordinate system. pg.rotateX(frameCount * 0.01); pg.rotateY(frameCount * 0.01); // Style the torus. pg.noStroke(); // Draw the torus. pg.torus(5, 2.5); // Start drawing to the torus p5.Framebuffer. torusLayer.end(); } // Update and draw the box layer offscreen. function drawBox() { // Start drawing to the box p5.Framebuffer. boxLayer.begin(); // Clear the drawing surface. pg.clear(); // Turn on the lights. pg.lights(); // Rotate the coordinate system. pg.rotateX(frameCount * 0.01); pg.rotateY(frameCount * 0.01); // Style the box. pg.noStroke(); // Draw the box. pg.box(7.5); // Start drawing to the box p5.Framebuffer. boxLayer.end(); } `

p5.Graphics

Rendering

Rendering

Resize our canvas element.

p5.Renderer

Rendering

Rendering

Helper function to check font type (system or otf)

p5.Renderer

Rendering

Rendering

Helper fxn to measure ascent and descent. Adapted from http://stackoverflow.com/a/25355178

p5.Renderer

Rendering

Rendering

p5.Renderer2D The 2D graphics canvas renderer class. extends p5.Renderer

p5

Rendering

Declares a new variable.
A variable is a container for a value. For example, a variable might contain a creature's x-coordinate as a `Number` or its name as a `String`. Variables can change value by reassigning them as follows:
    // Declare the variable x and assign it the value 10.
    let x = 10;
    
    // Reassign x to 50.
    x = 50;
    
Variables have block scope. When a variable is declared between curly braces `{}`, it only exists within the block defined by those braces. For example, the following code would throw a `ReferenceError` because `x` is declared within the `setup()` function's block:
    function setup() {
      createCanvas(100, 100);
    
      let x = 50;
    }
    
    function draw() {
      background(200);
    
      // x was declared in setup(), so it can't be referenced here.
      circle(x, 50, 20);
    }
    
Variables declared outside of all curly braces `{}` are in the global scope. A variable that's in the global scope can be used and changed anywhere in a sketch:
    let x = 50;
    
    function setup() {
      createCanvas(100, 100);
    }
    
    function draw() {
      background(200);
    
      // Change the value of x.
      x += 10;
    
      circle(x, 50, 20);
    }
    

property

let

` function setup() { createCanvas(100, 100); background(220); // Style the text. textAlign(CENTER); textSize(16); // Create the message variable. let message = 'Hello, 🌍!'; // Display the message. text(message, 50, 50); describe('The text "Hello, 🌍!" written on a gray background.'); } `
` let x = 0; function setup() { createCanvas(100, 100); describe('A white circle moves from left to right against a gray background.'); } function draw() { background(220); // Change the value of x. x += 1; circle(x, 50, 20); } `

p5

Foundation

Foundation

A way to choose whether to run a block of code.
`if` statements are helpful for running a block of code based on a condition. For example, an `if` statement makes it easy to express the idea "Draw a circle if the mouse is pressed.":
    if (mouseIsPressed === true) {
      circle(mouseX, mouseY, 20);
    }
    
The statement header begins with the keyword `if`. The expression in parentheses `mouseIsPressed === true` is a `Boolean` expression that's either `true` or `false`. The code between the curly braces `{}` is the if statement's body. The body only runs if the `Boolean` expression is `true`.
The mouseIsPressed system variable is always `true` or `false`, so the code snippet above could also be written as follows:
    if (mouseIsPressed) {
      circle(mouseX, mouseY, 20);
    }
    
An `if`-`else` statement adds a block of code that runs if the `Boolean` expression is `false`. For example, here's an `if`-`else` statement that expresses the idea "Draw a circle if the mouse is pressed. Otherwise, display a message.":
    if (mouseIsPressed === true) {
      // When true.
      circle(mouseX, mouseY, 20);
    } else {
      // When false.
      text('Click me!', 50, 50);
    }
    
There are two possible paths, or branches, in this code snippet. The program must follow one branch or the other.
An `else`-`if` statement makes it possible to add more branches. `else`-`if` statements run different blocks of code under different conditions. For example, an `else`-`if` statement makes it easy to express the idea "If the mouse is on the left, paint the canvas white. If the mouse is in the middle, paint the canvas gray. Otherwise, paint the canvas black.":
    if (mouseX < 33) {
      background(255);
    } else if (mouseX < 67) {
      background(200);
    } else {
      background(0);
    }
    
`if` statements can add as many `else`-`if` statements as needed. However, there can only be one `else` statement and it must be last.
`if` statements can also check for multiple conditions at once. For example, the `Boolean` operator `&&` (AND) checks whether two expressions are both `true`:
    if (keyIsPressed === true && key === 'p') {
      text('You pressed the "p" key!', 50, 50);
    }
    
If the user is pressing a key AND that key is `'p'`, then a message will display.
The `Boolean` operator `||` (OR) checks whether at least one of two expressions is `true`:
    if (keyIsPressed === true || mouseIsPressed === true) {
      text('You did something!', 50, 50);
    }
    
If the user presses a key, or presses a mouse button, or both, then a message will display.
The body of an `if` statement can contain another `if` statement. This is called a "nested `if` statement." For example, nested `if` statements make it easy to express the idea "If a key is pressed, then check if the key is `'r'`. If it is, then set the fill to red.":
    if (keyIsPressed === true) {
      if (key === 'r') {
        fill('red');
      }
    }
    
See Boolean and Number to learn more about these data types and the operations they support.

property

if

` // Click the mouse to show the circle. function setup() { createCanvas(100, 100); describe( 'A white circle on a gray background. The circle follows the mouse user clicks on the canvas.' ); } function draw() { background(200); if (mouseIsPressed === true) { circle(mouseX, mouseY, 20); } } `
` // Click the mouse to show different shapes. function setup() { createCanvas(100, 100); describe( 'A white ellipse on a gray background. The ellipse becomes a circle when the user presses the mouse.' ); } function draw() { background(200); if (mouseIsPressed === true) { circle(50, 50, 20); } else { ellipse(50, 50, 20, 50); } } `
` // Move the mouse to change the background color. function setup() { createCanvas(100, 100); describe( 'A square changes color from white to black as the user moves the mouse from left to right.' ); } function draw() { if (mouseX < 33) { background(255); } else if (mouseX < 67) { background(200); } else { background(0); } } `
` // Click on the canvas to begin detecting key presses. function setup() { createCanvas(100, 100); describe( 'A white circle drawn on a gray background. The circle changes color to red when the user presses the "r" key.' ); } function draw() { background(200); if (keyIsPressed === true) { if (key === 'r') { fill('red'); } } circle(50, 50, 40); } `

p5

Foundation

Foundation

A named group of statements.
Functions help with organizing and reusing code. For example, functions make it easy to express the idea "Draw a flower.":
    function drawFlower() {
      // Style the text.
      textAlign(CENTER, CENTER);
      textSize(20);
    
      // Draw a flower emoji.
      text('🌸', 50, 50);
    }
    
The function header begins with the keyword `function`. The function's name, `drawFlower`, is followed by parentheses `()` and curly braces `{}`. The code between the curly braces is called the function's body. The function's body runs when the function is called like so:
    drawFlower();
    
Functions can accept inputs by adding parameters to their headers. Parameters are placeholders for values that will be provided when the function is called. For example, the `drawFlower()` function could include a parameter for the flower's size:
    function drawFlower(size) {
      // Style the text.
      textAlign(CENTER, CENTER);
    
      // Use the size parameter.
      textSize(size);
    
      // Draw a flower emoji.
      text('🌸', 50, 50);
    }
    
Parameters are part of the function's declaration. Arguments are provided by the code that calls a function. When a function is called, arguments are assigned to parameters:
    // The argument 20 is assigned to the parameter size.
    drawFlower(20);
    
Functions can have multiple parameters separated by commas. Parameters can have any type. For example, the `drawFlower()` function could accept `Number` parameters for the flower's x- and y-coordinates along with its size:
    function drawFlower(x, y, size) {
      // Style the text.
      textAlign(CENTER, CENTER);
    
      // Use the size parameter.
      textSize(size);
    
      // Draw a flower emoji.
      // Use the x and y parameters.
      text('🌸', x, y);
    }
    
Functions can also produce outputs by adding a `return` statement:
    function double(x) {
      let answer = 2 * x;
      return answer;
    }
    
The expression following `return` can produce an output that's used elsewhere. For example, the output of the `double()` function can be assigned to a variable:
    let six = double(3);
    text(`3 x 2 = ${six}`, 50, 50);
    

property

function

` function setup() { createCanvas(100, 100); describe('A pink flower on a gray background.'); } function draw() { background(200); // Call the drawFlower() function. drawFlower(); } // Declare a function that draws a flower at the // center of the canvas. function drawFlower() { // Style the text. textAlign(CENTER, CENTER); textSize(20); // Draw a flower emoji. text('🌸', 50, 50); } `
` function setup() { createCanvas(100, 100); describe('A pink flower on a gray background.'); } function draw() { background(200); // Call the drawFlower() function and pass values for // its position and size. drawFlower(50, 50, 20); } // Declare a function that draws a flower at the // center of the canvas. function drawFlower(x, y, size) { // Style the text. textAlign(CENTER, CENTER); // Use the size parameter. textSize(size); // Draw a flower emoji. // Use the x and y parameters. text('🌸', x, y); } `
` function setup() { createCanvas(100, 100); describe('The message "Hello, 🌍!" written on a gray background.'); } function draw() { background(200); // Create a greeting. let greeting = createGreeting('🌍'); // Style the text. textAlign(CENTER, CENTER); textSize(16); // Display the greeting. text(greeting, 50, 50); } // Return a string with a personalized greeting. function createGreeting(name) { let message = `Hello, ${name}!`; return message; } `

p5

Foundation

Foundation

A value that's either `true` or `false`.
`Boolean` values help to make decisions in code. They appear any time a logical condition is checked. For example, the condition "Is a mouse button being pressed?" must be either `true` or `false`:
    // If the user presses the mouse, draw a circle at
    // the mouse's location.
    if (mouseIsPressed === true) {
      circle(mouseX, mouseY, 20);
    }
    
The `if` statement checks whether mouseIsPressed is `true` and draws a circle if it is. `Boolean` expressions such as `mouseIsPressed === true` evaluate to one of the two possible `Boolean` values: `true` or `false`.
The `===` operator (EQUAL) checks whether two values are equal. If they are, the expression evaluates to `true`. Otherwise, it evaluates to `false`.
Note: There's also a `==` operator with two `=` instead of three. Don't use it.
The mouseIsPressed system variable is always `true` or `false`, so the code snippet above could also be written as follows:
    if (mouseIsPressed) {
      circle(mouseX, mouseY, 20);
    }
    
The `!==` operator (NOT EQUAL) checks whether two values are not equal, as in the following example:
    if (2 + 2 !== 4) {
      text('War is peace.', 50, 50);
    }
    
Starting from the left, the arithmetic expression `2 + 2` produces the value `4`. The `Boolean` expression `4 !== 4` evaluates to `false` because `4` is equal to itself. As a result, the `if` statement's body is skipped.
Note: There's also a `!=` operator with one `=` instead of two. Don't use it.
The `Boolean` operator `&&` (AND) checks whether two expressions are both `true`:
    if (keyIsPressed === true && key === 'p') {
      text('You pressed the "p" key!', 50, 50);
    }
    
If the user is pressing a key AND that key is `'p'`, then a message will display.
The `Boolean` operator `||` (OR) checks whether at least one of two expressions is `true`:
    if (keyIsPressed === true || mouseIsPressed === true) {
      text('You did something!', 50, 50);
    }
    
If the user presses a key, or presses a mouse button, or both, then a message will display.
The following truth table summarizes a few common scenarios with `&&` and `||`:
    true && true  // true
    true && false // false
    false && false // false
    true || true  // true
    true || false // true
    false || false // false
    
The relational operators `>`, `<`, `>=`, and `<=` also produce `Boolean` values:
    2 > 1 // true
    2 < 1 // false
    2 >= 2 // true
    2 <= 2 // true
    
See if for more information about `if` statements and Number for more information about `Number`s.

property

Boolean

` function setup() { createCanvas(100, 100); describe('A gray square. When the user presses the mouse, a circle appears at that location.'); } function draw() { background(200); // If the user presses the mouse, draw a circle at that location. if (mouseIsPressed) { circle(mouseX, mouseY, 20); } } `
` function setup() { createCanvas(100, 100); describe('A gray square. When the user presses the mouse, a circle appears at that location.'); } function draw() { background(200); // If the user presses the mouse, draw a circle at that location. if (mouseIsPressed === true) { circle(mouseX, mouseY, 20); } } `
` // Click on the canvas to begin detecting key presses. function setup() { createCanvas(100, 100); describe('A gray square that turns pink when the user presses the mouse or a key.'); } function draw() { background(200); // If the user presses the mouse, change the background color. if (mouseIsPressed === true || keyIsPressed === true) { background('deeppink'); } } `
` // Click the canvas to begin detecting key presses. // Create a Boolean variable. let isPlaying = false; function setup() { createCanvas(100, 100); describe( 'The message "Begin? Y or N" written in green on a black background. The message "Good luck!" appears when they press the "y" key.' ); } function draw() { background(0); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(16); fill(0, 255, 0); // Display a different message when the user begins playing. if (isPlaying === false) { text('Begin?', 50, 40); text('Y or N', 50, 60); } else { text('Good luck!', 50, 50); } } // Start playing when the user presses the 'y' key. function keyPressed() { if (key === 'y') { isPlaying = true; } } `

p5

Foundation

Foundation

A sequence of text characters.
The `String` data type is helpful for working with text. For example, a string could contain a welcome message:
    // Use a string literal.
    text('Hello!', 10, 10);
    
    // Create a string variable.
    let message = 'Hello!';
    
    // Use the string variable.
    text(message, 10, 10);
    
The most common way to create strings is to use some form of quotations as follows:
    text("hi", 50, 50);
    
    text('hi', 50, 50);
    
    text(`hi`, 50, 50);
    
`"hi"`, `'hi'`, and `hi` are all string literals. A "literal" means a value was actually written, as in `text('hi', 50, 50)`. By contrast, `text(message, 50, 50)` uses the variable `message`, so it isn't a string literal.
Single quotes `''` and double quotes `""` mean the same thing. It's nice to have the option for cases when a string contains one type of quote:
    text("What's up?", 50, 50);
    
    text('Air quotes make you look "cool."', 50, 50);
    
Backticks ```` create template literals. Template literals have many uses. For example, they can contain both single and double quotes as needed:
    text(`"Don't you forget about me"`,  10, 10);
    
Template literals are helpful when strings are created from variables like so:
    let size = random(10, 20);
    circle(50, 50, size);
    
    text(`The circle's diameter is ${size} pixels.`,  10, 10);
    
The `size` variable's value will replace `${size}` when the string is created. `${}` is a placeholder for any value. That means an expression can be used, as in `${round(PI, 3)}`. All of the following are valid template literals:
    text(`π is about ${round(PI, 2)} pixels.`,  10, 10);
    text(`It's ${mouseX < width / 2} that I'm on the left half of the canvas.`,  10, 30);
    
Template literals can include several variables:
    let x = random(0, 100);
    let y = random(0, 100);
    let size = random(10, 20);
    circle(x, y, size);
    
    text(`The circle at (${x}, ${y}) has a diameter of ${size} pixels.`,  10, 10);
    
Template literals are also helpful for creating multi-line text like so:
    let poem = `My sketch doesn't run;
    it waits for me patiently
    while bugs point the way.`;
    
    text(poem, 10, 10);
    

property

String

` function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(CENTER, CENTER); textSize(20); // Display a welcome message. text('Hello!', 50, 50); describe('The text "Hello!" written on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(CENTER, CENTER); textSize(20); // Create a string variable. let world = '🌍'; // Display a welcome message using a template string. text(`Hello, ${world}!`, 50, 50); describe('The text "Hello, 🌍!" written on a gray background.'); } `

p5

Foundation

Foundation

A number that can be positive, negative, or zero.
The `Number` data type is useful for describing values such as position, size, and color. A number can be an integer such as 20 or a decimal number such as 12.34. For example, a circle's position and size can be described by three numbers:
    circle(50, 50, 20);
    
    circle(50, 50, 12.34);
    
Numbers support basic arithmetic and follow the standard order of operations: Parentheses, Exponents, Multiplication, Division, Addition, and Subtraction (PEMDAS). For example, it's common to use arithmetic operators with p5.js' system variables that are numbers:
    // Draw a circle at the center.
    circle(width / 2, height / 2, 20);
    
    // Draw a circle that moves from left to right.
    circle(frameCount * 0.01, 50, 20);
    
Here's a quick overview of the arithmetic operators:
    1 + 2 // Add
    1 - 2 // Subtract
    1 * 2 // Multiply
    1 / 2 // Divide
    1 % 2 // Remainder
    1 ** 2 // Exponentiate
    
It's common to update a number variable using arithmetic. For example, an object's location can be updated like so:
    x = x + 1;
    
The statement above adds 1 to a variable `x` using the `+` operator. The addition assignment operator `+=` expresses the same idea:
    x += 1;
    
Here's a quick overview of the assignment operators:
    x += 2 // Addition assignment
    x -= 2 // Subtraction assignment
    x *= 2 // Multiplication assignment
    x /= 2 // Division assignment
    x %= 2 // Remainder assignment
    
Numbers can be compared using the relational operators `>`, `<`, `>=`, `<=`, `===`, and `!==`. For example, a sketch's frameCount can be used as a timer:
    if (frameCount > 1000) {
      text('Game over!', 50, 50);
    }
    
An expression such as `frameCount > 1000` evaluates to a `Boolean` value that's either `true` or `false`. The relational operators all produce `Boolean` values:
    2 > 1 // true
    2 < 1 // false
    2 >= 2 // true
    2 <= 2 // true
    2 === 2 // true
    2 !== 2 // false
    
See Boolean for more information about comparisons and conditions.
Note: There are also `==` and `!=` operators with one fewer `=`. Don't use them.
Expressions with numbers can also produce special values when something goes wrong:
    sqrt(-1) // NaN
    1 / 0 // Infinity
    
The value `NaN` stands for Not-A-Number. `NaN` appears when calculations or conversions don't work. `Infinity` is a value that's larger than any number. It appears during certain calculations.

property

Number

` function setup() { createCanvas(100, 100); background(200); // Draw a circle at the center. circle(50, 50, 70); // Draw a smaller circle at the center. circle(width / 2, height / 2, 30); describe('Two concentric, white circles drawn on a gray background.'); } `
` function setup() { createCanvas(100, 100); describe('A white circle travels from left to right on a gray background.'); } function draw() { background(200); circle(frameCount * 0.05, 50, 20); } `

p5

Foundation

Foundation

A container for data that's stored as key-value pairs.
Objects help to organize related data of any type, including other objects. A value stored in an object can be accessed by name, called its key. Each key-value pair is called a "property." Objects are similar to dictionaries in Python and maps in Java and Ruby.
For example, an object could contain the location, size, and appearance of a dog:
    // Declare the dog variable and assign it an object.
    let dog = { x: 50, y: 50, size: 20, emoji: '🐶' };
    
    // Style the text.
    textAlign(CENTER, CENTER);
    textSize(dog.size);
    
    // Draw the dog.
    text(dog.emoji, dog.x, dog.y);
    
The variable `dog` is assigned an object with four properties. Objects are declared with curly braces `{}`. Values can be accessed using the dot operator, as in `dog.size`. In the example above, the key `size` corresponds to the value `20`. Objects can also be empty to start:
    // Declare a cat variable and assign it an empty object.
    let cat = {};
    
    // Add properties to the object.
    cat.x = 50;
    cat.y = 50;
    cat.size = 20;
    cat.emoji = '🐱';
    
    // Style the text.
    textAlign(CENTER, CENTER);
    textSize(cat.size);
    
    // Draw the cat.
    text(cat.emoji, cat.x, cat.y);
    
An object's data can be updated while a sketch runs. For example, the `cat` could run away from the `dog` by updating its location:
    // Run to the right.
    cat.x += 5;
    
If needed, an object's values can be accessed using square brackets `[]` and strings instead of dot notation:
    // Run to the right.
    cat["x"] += 5;
    
This syntax can be helpful when the key's name has spaces, as in `cat['height (m)']`.

property

Object

` // Declare the variable data and assign it an object with three properties. let data = { x: 50, y: 50, d: 20 }; function setup() { createCanvas(100, 100); describe('A white circle on a gray background.'); } function draw() { background(200); // Access the object's values using the . operator. circle(data.x, data.y, data.d); } `
` // Declare the variable data and assign it an object with three properties. let data = { x: 50, y: 50, d: 20 }; // Add another property for color. data.color = 'deeppink'; function setup() { createCanvas(100, 100); describe('A pink circle on a gray background.'); } function draw() { background(200); // Access the object's values using the . operator. fill(data.color); circle(data.x, data.y, data.d); } `
` // Declare the variable data and assign it an object with three properties. let data = { x: 50, y: 50, d: 20 }; // Add another property for color. data.color = 'deeppink'; function setup() { createCanvas(100, 100); describe('A white circle on a gray background.'); } function draw() { background(200); // Access the object's values using the . operator. fill(data.color); circle(data.x, data.y, data.d); // Update the object's x and y properties. data.x += random(-1, 1); data.y += random(-1, 1); } `

p5

Foundation

Foundation

A list that keeps several pieces of data in order.
Arrays are helpful for storing related data. They can contain data of any type. For example, an array could contain a list of someone's favorite colors as strings. Arrays are created as follows:
    let myArray = ['deeppink', 'darkorchid', 'magenta'];
    
Each piece of data in an array is called an element. Each element has an address, or index, within its array. The variable `myArray` refers to an array with three String elements, `'deeppink'`, `'darkorchid'`, and `'magenta'`. Arrays are zero-indexed, which means that `'deeppink'` is at index 0, `'darkorchid'` is at index 1, and '`magenta'` is at index 2. Array elements can be accessed using their indices as follows:
    let zeroth = myArray[0]; // 'deeppink'
    let first = myArray[1]; // 'darkorchid'
    let second = myArray[2]; // 'magenta'
    
Elements can be added to the end of an array by calling the push() method as follows:
    myArray.push('lavender');
    
    let third = myArray[3]; // 'lavender'
    
See MDN for more information about arrays.

property

Array

` // Declare the variable xCoordinates and assign it an array // with three numeric elements. let xCoordinates = [25, 50, 75]; function setup() { createCanvas(100, 100); describe( 'Three white circles drawn in a horizontal line on a gray background.' ); } function draw() { background(200); // Access the element at index 0, which is 25. circle(xCoordinates[0], 50, 20); // Access the element at index 1, which is 50. circle(xCoordinates[1], 50, 20); // Access the element at index 2, which is 75. circle(xCoordinates[2], 50, 20); } `
` // Declare the variable xCoordinates and assign it an array with three numeric elements. let xCoordinates = [20, 40, 60]; // Add another element to the end of the array. xCoordinates.push(80); function setup() { createCanvas(100, 100); describe('Four white circles drawn in a horizontal line on a gray background.'); } function draw() { background(200); // Access the element at index 0, which is 20. circle(xCoordinates[0], 50, 20); // Access the element at index 1, which is 40. circle(xCoordinates[1], 50, 20); // Access the element at index 2, which is 60. circle(xCoordinates[2], 50, 20); // Access the element at index 3, which is 80. circle(xCoordinates[3], 50, 20); } `
` // Declare the variable xCoordinates and assign it an empty array. let xCoordinates = []; function setup() { createCanvas(100, 100); // Add elements to the array using a loop. for (let x = 20; x < 100; x += 20) { xCoordinates.push(x); } describe('Four white circles drawn in a horizontal line on a gray background.'); } function draw() { background(200); // Access the element at index i and use it to draw a circle. for (let i = 0; i < xCoordinates.length; i += 1) { circle(xCoordinates[i], 50, 20); } } `
` // Declare the variable xCoordinates and assign it an empty array. let xCoordinates = []; function setup() { createCanvas(100, 100); // Add elements to the array using a loop. for (let x = 20; x < 100; x += 20) { xCoordinates.push(x); } describe('Four white circles drawn in a horizontal line on a gray background.'); } function draw() { background(200); // Access each element of the array and use it to draw a circle. for (let x of xCoordinates) { circle(x, 50, 20); } } `
` // Declare the variable xCoordinates and assign it an empty array. let xCoordinates = []; function setup() { createCanvas(100, 100); // Add elements to the array using a loop. for (let x = 20; x < 100; x += 20) { xCoordinates.push(x); } describe( 'Four white circles in a horizontal line on a gray background. The circles move randomly.' ); } function draw() { background(200); for (let i = 0; i < xCoordinates.length; i += 1) { // Update the element at index i. xCoordinates[i] += random(-1, 1); // Use the element at index i to draw a circle. circle(xCoordinates[i], 50, 20); } } `

p5

Foundation

Foundation

A template for creating objects of a particular type.
Classes can make it easier to program with objects. For example, a `Frog` class could create objects that behave like frogs. Each object created using a class is called an instance of that class. All instances of a class are the same type. Here's an example of creating an instance of a `Frog` class:
    let fifi = new Frog(50, 50, 20);
    
The variable `fifi` refers to an instance of the `Frog` class. The keyword `new` is used to call the `Frog` class' constructor in the statement `new Frog()`. Altogether, a new `Frog` object was created and assigned to the variable `fifi`. Classes are templates, so they can be used to create more than one instance:
    // First Frog instance.
    let frog1 = new Frog(25, 50, 10);
    
    // Second Frog instance.
    let frog2 = new Frog(75, 50, 10);
    
A simple `Frog` class could be declared as follows:
    class Frog {
      constructor(x, y, size) {
        // This code runs once when an instance is created.
        this.x = x;
        this.y = y;
        this.size = size;
      }
    
      show() {
        // This code runs once when myFrog.show() is called.
        textAlign(CENTER, CENTER);
        textSize(this.size);
        text('🐸', this.x, this.y);
      }
    
      hop() {
        // This code runs once when myFrog.hop() is called.
        this.x += random(-10, 10);
        this.y += random(-10, 10);
      }
    }
    
Class declarations begin with the keyword `class` followed by the class name, such as `Frog`, and curly braces `{}`. Class names should use `PascalCase` and can't have spaces in their names. For example, naming a class `Kermit The Frog` with spaces between each word would throw a `SyntaxError`. The code between the curly braces `{}` defines the class.
Functions that belong to a class are called methods. `constructor()`, `show()`, and `hop()` are methods in the `Frog` class. Methods define an object's behavior. Methods can accept parameters and return values, just like functions. Note that methods don't use the `function` keyword.
`constructor()` is a special method that's called once when an instance of the class is created. The statement `new Frog()` calls the `Frog` class' `constructor()` method.
A class definition is a template for instances. The keyword `this` refers to an instance's data and methods. For example, each `Frog` instance has unique coordinates stored in `this.x` and `this.y`. The `show()` method uses those coordinates to draw the frog. The `hop()` method updates those coordinates when called. Once a `Frog` instance is created, its data and methods can be accessed using the dot operator `.` as follows:
    // Draw a lily pad.
    fill('green');
    stroke('green');
    circle(fifi.x, fifi.y, 2 * fifi.size);
    
    // Show the Frog.
    fifi.show();
    
    // Hop.
    fifi.hop();
    

property

class

` // Declare a frog variable. let fifi; function setup() { createCanvas(100, 100); // Assign the frog variable a new Frog object. fifi = new Frog(50, 50, 20); describe('A frog face drawn on a blue background.'); } function draw() { background('cornflowerblue'); // Show the frog. fifi.show(); } class Frog { constructor(x, y, size) { this.x = x; this.y = y; this.size = size; } show() { textAlign(CENTER, CENTER); textSize(this.size); text('🐸', this.x, this.y); } } `
` // Declare two frog variables. let frog1; let frog2; function setup() { createCanvas(100, 100); // Assign the frog variables a new Frog object. frog1 = new Frog(25, 50, 10); frog2 = new Frog(75, 50, 20); describe('Two frog faces drawn next to each other on a blue background.'); } function draw() { background('cornflowerblue'); // Show the frogs. frog1.show(); frog2.show(); } class Frog { constructor(x, y, size) { this.x = x; this.y = y; this.size = size; } show() { textAlign(CENTER, CENTER); textSize(this.size); text('🐸', this.x, this.y); } } `
` // Declare two frog variables. let frog1; let frog2; function setup() { createCanvas(100, 100); // Assign the frog variables a new Frog object. frog1 = new Frog(25, 50, 10); frog2 = new Frog(75, 50, 20); // Slow the frame rate. frameRate(1); describe('Two frog faces on a blue background. The frogs hop around randomly.'); } function draw() { background('cornflowerblue'); // Show the frogs. frog1.show(); frog2.show(); // Move the frogs. frog1.hop(); frog2.hop(); // Wrap around if they've hopped off the edge. frog1.checkEdges(); frog2.checkEdges(); } class Frog { constructor(x, y, size) { this.x = x; this.y = y; this.size = size; } show() { textAlign(CENTER, CENTER); textSize(this.size); text('🐸', this.x, this.y); } hop() { this.x += random(-10, 10); this.y += random(-10, 10); } checkEdges() { if (this.x > width) { this.x = this.x - width; } else if (this.x < 0) { this.x = width - this.x; } if (this.y > height) { this.y = this.y - height; } else if (this.y < 0) { this.y = height - this.y; } } } `
` // Create an array that will hold frogs. let frogs = []; function setup() { createCanvas(100, 100); // Add Frog objects to the array. for (let i = 0; i < 5; i += 1) { // Calculate random coordinates and size. let x = random(0, 100); let y = random(0, 100); let s = random(2, 20); // Create a new Frog object. let frog = new Frog(x, y, s); // Add the Frog to the array. frogs.push(frog); } // Slow the frame rate. frameRate(1); describe( 'Five frog faces on a blue background. The frogs hop around randomly.' ); } function draw() { background('cornflowerblue'); for (let frog of frogs) { // Show the frog. frog.show(); // Move the frog. frog.hop(); // Wrap around if they've hopped off the edge. frog.checkEdges(); } } class Frog { constructor(x, y, size) { this.x = x; this.y = y; this.size = size; } show() { textAlign(CENTER, CENTER); textSize(this.size); text('🐸', this.x, this.y); } hop() { this.x += random(-10, 10); this.y += random(-10, 10); } checkEdges() { if (this.x > width) { this.x = this.x - width; } else if (this.x < 0) { this.x = width - this.x; } if (this.y > height) { this.y = this.y - height; } else if (this.y < 0) { this.y = height - this.y; } } } `

p5

Foundation

Foundation

A way to repeat a block of code when the number of iterations is known.
`for` loops are helpful for repeating statements a certain number of times. For example, a `for` loop makes it easy to express the idea "draw five lines" like so:
    for (let x = 10; x < 100; x += 20) {
      line(x, 25, x, 75);
    }
    
The loop's header begins with the keyword `for`. Loops generally count up or count down as they repeat, or iterate. The statements in parentheses `let x = 10; x < 100; x += 20` tell the loop how it should repeat:
    * `let x = 10` tells the loop to start counting at `10` and keep track of iterations using the variable `x`.
    * `x < 100` tells the loop to count up to, but not including, `100`.
    * `x += 20` tells the loop to count up by `20` at the end of each iteration.
The code between the curly braces `{}` is the loop's body. Statements in the loop body are repeated during each iteration of the loop.
It's common to create infinite loops accidentally. When this happens, sketches may become unresponsive and the web browser may display a warning. For example, the following loop never stops iterating because it doesn't count up:
    for (let x = 10; x < 100; x = 20) {
      line(x, 25, x, 75);
    }
    
The statement `x = 20` keeps the variable `x` stuck at `20`, which is always less than `100`.
`for` loops can also count down:
    for (let d = 100; d > 0; d -= 10) {
      circle(50, 50, d);
    }
    
`for` loops can also contain other loops. The following nested loop draws a grid of points:
    // Loop from left to right.
    for (let x = 10; x < 100; x += 10) {
    
      // Loop from top to bottom.
      for (let y = 10; y < 100; y += 10) {
        point(x, y);
      }
    
    }
    
`for` loops are also helpful for iterating through the elements of an array. For example, it's common to iterate through an array that contains information about where or what to draw:
    // Create an array of x-coordinates.
    let xCoordinates = [20, 40, 60];
    
    for (let i = 0; i < xCoordinates.length; i += 1) {
      // Update the element.
      xCoordinates[i] += random(-1, 1);
    
      // Draw a circle.
      circle(xCoordinates[i], 50, 20);
    }
    
If the array's values aren't modified, the `for...of` statement can simplify the code. They're similar to `for` loops in Python and `for-each` loops in C++ and Java. The following loops have the same effect:
    // Draw circles with a for loop.
    let xCoordinates = [20, 40, 60];
    
    for (let i = 0; i < xCoordinates.length; i += 1) {
      circle(xCoordinates[i], 50, 20);
    }
    
    // Draw circles with a for...of statement.
    let xCoordinates = [20, 40, 60];
    
    for (let x of xCoordinates) {
      circle(x, 50, 20);
    }
    
In the code snippets above, the variables `i` and `x` have different roles.
In the first snippet, `i` counts from `0` up to `2`, which is one less than `xCoordinates.length`. `i` is used to access the element in `xCoordinates` at index `i`.
In the second code snippet, `x` isn't keeping track of the loop's progress or an index. During each iteration, `x` contains the next element of `xCoordinates`. `x` starts from the beginning of `xCoordinates` (`20`) and updates its value to `40` and then `60` during the next iterations.

property

for

` function setup() { createCanvas(100, 100); describe('Five black vertical lines on a gray background.'); } function draw() { background(200); // Draw vertical lines using a loop. for (let x = 10; x < 100; x += 20) { line(x, 25, x, 75); } } `
` function setup() { createCanvas(100, 100); describe('Five white concentric circles drawn on a gray background.'); } function draw() { background(200); // Draw concentric circles using a loop. for (let d = 100; d > 0; d -= 20) { circle(50, 50, d); } } `
` function setup() { createCanvas(100, 100); describe('A grid of black dots on a gray background.'); } function draw() { background(200); // Set the spacing for points on the grid. let space = 10; // Increase the stroke weight. strokeWeight(3); // Loop from the left to the right. for (let x = space; x < 100; x += space) { // Loop from the top to the bottom. for (let y = space; y < 100; y += space) { point(x, y); } } } `
` // Declare the variable xCoordinates and assign it an array of numbers. let xCoordinates = [20, 40, 60, 80]; function setup() { createCanvas(100, 100); describe('Four white circles drawn in a horizontal line on a gray background.'); } function draw() { background(200); // Access the element at index i and use it to draw a circle. for (let i = 0; i < xCoordinates.length; i += 1) { circle(xCoordinates[i], 50, 20); } } `
` // Declare the variable xCoordinates and assign it an array of numbers. let xCoordinates = [20, 40, 60, 80]; function setup() { createCanvas(100, 100); describe('Four white circles drawn in a horizontal line on a gray background.'); } function draw() { background(200); // Access each element of the array and use it to draw a circle. for (let x of xCoordinates) { circle(x, 50, 20); } } `

p5

Foundation

Foundation

A way to repeat a block of code.
`while` loops are helpful for repeating statements while a condition is `true`. They're like `if` statements that repeat. For example, a `while` loop makes it easy to express the idea "draw several lines" like so:
    // Declare a variable to keep track of iteration.
    let x = 10;
    
    // Repeat as long as x < 100
    while (x < 100) {
      line(x, 25, x, 75);
    
      // Increment by 20.
      x += 20;
    }
    
The loop's header begins with the keyword `while`. Loops generally count up or count down as they repeat, or iterate. The statement in parentheses `x < 100` is a condition the loop checks each time it iterates. If the condition is `true`, the loop runs the code between the curly braces `{}`, The code between the curly braces is called the loop's body. If the condition is `false`, the body is skipped and the loop is stopped.
It's common to create infinite loops accidentally. For example, the following loop never stops iterating because it doesn't count up:
    // Declare a variable to keep track of iteration.
    let x = 10;
    
    // Repeat as long as x < 100
    while (x < 100) {
      line(x, 25, x, 75);
    }
    
    // This should be in the loop's body!
    x += 20;
    
The statement `x += 20` appears after the loop's body. That means the variable `x` is stuck at `10`, which is always less than `100`.
`while` loops are useful when the number of iterations isn't known in advance. For example, concentric circles could be drawn at random increments:
    let d = 100;
    let minSize = 5;
    
    while (d > minSize) {
      circle(50, 50, d);
      d -= random(10);
    }
    

property

while

` function setup() { createCanvas(100, 100); describe('Five black vertical lines on a gray background.'); } function draw() { background(200); // Declare a variable to keep track of iteration. let x = 10; // Repeat as long as x < 100 while (x < 100) { line(x, 25, x, 75); // Increment by 20. x += 20; } } `
` function setup() { createCanvas(100, 100); // Slow the frame rate. frameRate(5); describe( "A gray square with several concentric circles at the center. The circles' sizes decrease at random increments." ); } function draw() { background(200); let d = 100; let minSize = 5; while (d > minSize) { circle(50, 50, d); d -= random(5, 15); } } `

p5

Foundation

Foundation

Prints a message to the web browser's console.
The console object is helpful for printing messages while debugging. For example, it's common to add a `console.log()` statement while studying how a section of code works:
    if (isPlaying === true) {
      // Add a console.log() statement to make sure this block of code runs.
      console.log('Got here!');
    
      // Game logic.
    }
    
`console.error()` is helpful for tracking errors because it prints formatted messages. For example, it's common to encounter errors when loading media assets:
    // Logs an error message with special formatting.
    function handleFailure(error) {
      console.error('Oops!', error);
    }
    
    // Try to load an image and call handleError() if it fails.
    loadImage('https://example.com/cat.jpg', handleImage, handleError);
    

property

console

` function setup() { noCanvas(); // Prints "Hello!" to the console. console.log('Hello!'); } `
` function setup() { createCanvas(100, 100); background(200); // Try to load an image from a fake URL. // Call handleError() if the image fails to load. loadImage('https://example.com/cat.jpg', handleImage, handleError); } // Displays the image. function handleImage(img) { image(img, 0, 0); describe('A cat on a gray background.'); } // Prints the error. function handleError(error) { console.error('Oops!', error); describe('A gray square.'); } `

p5

Foundation

Foundation

Creates a canvas element on the web page.
`createCanvas()` creates the main drawing canvas for a sketch. It should only be called once at the beginning of setup(). Calling `createCanvas()` more than once causes unpredictable behavior.
The first two parameters, `width` and `height`, are optional. They set the dimensions of the canvas and the values of the width and height system variables. For example, calling `createCanvas(900, 500)` creates a canvas that's 900×500 pixels. By default, `width` and `height` are both 100.
The third parameter is also optional. If either of the constants `P2D` or `WEBGL` is passed, as in `createCanvas(900, 500, WEBGL)`, then it will set the sketch's rendering mode. If an existing HTMLCanvasElement is passed, as in `createCanvas(900, 500, myCanvas)`, then it will be used by the sketch.
The fourth parameter is also optional. If an existing HTMLCanvasElement is passed, as in `createCanvas(900, 500, WEBGL, myCanvas)`, then it will be used by the sketch.
Note: In WebGL mode, the canvas will use a WebGL2 context if it's supported by the browser. Check the webglVersion system variable to check what version is being used, or call `setAttributes({ version: 1 })` to create a WebGL1 context.

method

createCanvas

### return
new `p5.Renderer` that holds the canvas.

p5.Renderer

` function setup() { createCanvas(100, 100); background(180); // Draw a diagonal line. line(0, 0, width, height); describe('A diagonal line drawn from top-left to bottom-right on a gray background.'); } `
` function setup() { createCanvas(100, 50); background(180); // Draw a diagonal line. line(0, 0, width, height); describe('A diagonal line drawn from top-left to bottom-right on a gray background.'); } `
` // Use WebGL mode. function setup() { createCanvas(100, 100, WEBGL); background(180); // Draw a diagonal line. line(-width / 2, -height / 2, width / 2, height / 2); describe('A diagonal line drawn from top-left to bottom-right on a gray background.'); } `
` function setup() { // Create a p5.Render object. let cnv = createCanvas(50, 50); // Position the canvas. cnv.position(10, 20); background(180); // Draw a diagonal line. line(0, 0, width, height); describe('A diagonal line drawn from top-left to bottom-right on a gray background.'); } `

p5

Rendering

Rendering

width

width of the canvas. Defaults to 100.

Number

height

height of the canvas. Defaults to 100.

Number

renderer

either P2D or WEBGL. Defaults to `P2D`.

Constant

canvas

existing canvas element that should be used for the sketch.

HTMLCanvasElement

##### return
new `p5.Renderer` that holds the canvas.

p5.Renderer

width



Number

height



Number

canvas



HTMLCanvasElement

##### return


p5.Renderer

Resizes the canvas to a given width and height.
`resizeCanvas()` immediately clears the canvas and calls redraw(). It's common to call `resizeCanvas()` within the body of windowResized() like so:
    function windowResized() {
      resizeCanvas(windowWidth, windowHeight);
    }
    
The first two parameters, `width` and `height`, set the dimensions of the canvas. They also the values of the width and height system variables. For example, calling `resizeCanvas(300, 500)` resizes the canvas to 300×500 pixels, then sets width to 300 and height 500.
The third parameter, `noRedraw`, is optional. If `true` is passed, as in `resizeCanvas(300, 500, true)`, then the canvas will be canvas to 300×500 pixels but the redraw() function won't be called immediately. By default, redraw() is called immediately when `resizeCanvas()` finishes executing.

method

resizeCanvas

width

width of the canvas.

Number

height

height of the canvas.

Number

noRedraw

whether to delay calling redraw(). Defaults to `false`.

Boolean

` // Double-click to resize the canvas. function setup() { createCanvas(100, 100); describe( 'A white circle drawn on a gray background. The canvas shrinks by half the first time the user double-clicks.' ); } function draw() { background(180); // Draw a circle at the center of the canvas. circle(width / 2, height / 2, 20); } // Resize the canvas when the user double-clicks. function doubleClicked() { resizeCanvas(50, 50); } `
` // Resize the web browser to change the canvas size. function setup() { createCanvas(windowWidth, windowHeight); describe('A white circle drawn on a gray background.'); } function draw() { background(180); // Draw a circle at the center of the canvas. circle(width / 2, height / 2, 20); } // Always resize the canvas to fill the browser window. function windowResized() { resizeCanvas(windowWidth, windowHeight); } `

p5

Rendering

Rendering

Removes the default canvas.
By default, a 100×100 pixels canvas is created without needing to call createCanvas(). `noCanvas()` removes the default canvas for sketches that don't need it.

method

noCanvas

` function setup() { noCanvas(); } `

p5

Rendering

Rendering

Creates a p5.Graphics object.
`createGraphics()` creates an offscreen drawing canvas (graphics buffer) and returns it as a p5.Graphics object. Drawing to a separate graphics buffer can be helpful for performance and for organizing code.
The first two parameters, `width` and `height`, are optional. They set the dimensions of the p5.Graphics object. For example, calling `createGraphics(900, 500)` creates a graphics buffer that's 900×500 pixels.
The third parameter is also optional. If either of the constants `P2D` or `WEBGL` is passed, as in `createGraphics(900, 500, WEBGL)`, then it will set the p5.Graphics object's rendering mode. If an existing HTMLCanvasElement is passed, as in `createGraphics(900, 500, myCanvas)`, then it will be used by the graphics buffer.
The fourth parameter is also optional. If an existing HTMLCanvasElement is passed, as in `createGraphics(900, 500, WEBGL, myCanvas)`, then it will be used by the graphics buffer.
Note: In WebGL mode, the p5.Graphics object will use a WebGL2 context if it's supported by the browser. Check the webglVersion system variable to check what version is being used, or call `setAttributes({ version: 1 })` to create a WebGL1 context.

method

createGraphics

### return
new graphics buffer.

p5.Graphics

` // Double-click to draw the contents of the graphics buffer. let pg; function setup() { createCanvas(100, 100); background(180); // Create the p5.Graphics object. pg = createGraphics(50, 50); // Draw to the graphics buffer. pg.background(100); pg.circle(pg.width / 2, pg.height / 2, 20); describe('A gray square. A smaller, darker square with a white circle at its center appears when the user double-clicks.'); } // Display the graphics buffer when the user double-clicks. function doubleClicked() { if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { image(pg, 25, 25); } } `
` // Double-click to draw the contents of the graphics buffer. let pg; function setup() { createCanvas(100, 100); background(180); // Create the p5.Graphics object in WebGL mode. pg = createGraphics(50, 50, WEBGL); // Draw to the graphics buffer. pg.background(100); pg.lights(); pg.noStroke(); pg.rotateX(QUARTER_PI); pg.rotateY(QUARTER_PI); pg.torus(15, 5); describe('A gray square. A smaller, darker square with a white torus at its center appears when the user double-clicks.'); } // Display the graphics buffer when the user double-clicks. function doubleClicked() { if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { image(pg, 25, 25); } } `

p5

Rendering

Rendering

width

width of the graphics buffer.

Number

height

height of the graphics buffer.

Number

renderer

either P2D or WEBGL. Defaults to P2D.

Constant

canvas

existing canvas element that should be used for the graphics buffer..

HTMLCanvasElement

##### return
new graphics buffer.

p5.Graphics

width



Number

height



Number

canvas



HTMLCanvasElement

##### return


p5.Graphics

args[0] is expected to be renderer args[1] is expected to be canvas

p5

Rendering

Rendering

Creates and a new p5.Framebuffer object.
p5.Framebuffer objects are separate drawing surfaces that can be used as textures in WebGL mode. They're similar to p5.Graphics objects and generally run much faster when used as textures.
The parameter, `options`, is optional. An object can be passed to configure the p5.Framebuffer object. The available properties are:
    * `format`: data format of the texture, either `UNSIGNED_BYTE`, `FLOAT`, or `HALF_FLOAT`. Default is `UNSIGNED_BYTE`.
    * `channels`: whether to store `RGB` or `RGBA` color channels. Default is to match the main canvas which is `RGBA`.
    * `depth`: whether to include a depth buffer. Default is `true`.
    * `depthFormat`: data format of depth information, either `UNSIGNED_INT` or `FLOAT`. Default is `FLOAT`.
    * `stencil`: whether to include a stencil buffer for masking. `depth` must be `true` for this feature to work. Defaults to the value of `depth` which is `true`.
    * `antialias`: whether to perform anti-aliasing. If set to `true`, as in `{ antialias: true }`, 2 samples will be used by default. The number of samples can also be set, as in `{ antialias: 4 }`. Default is to match setAttributes() which is `false` (`true` in Safari).
    * `width`: width of the p5.Framebuffer object. Default is to always match the main canvas width.
    * `height`: height of the p5.Framebuffer object. Default is to always match the main canvas height.
    * `density`: pixel density of the p5.Framebuffer object. Default is to always match the main canvas pixel density.
    * `textureFiltering`: how to read values from the p5.Framebuffer object. Either `LINEAR` (nearby pixels will be interpolated) or `NEAREST` (no interpolation). Generally, use `LINEAR` when using the texture as an image and `NEAREST` if reading the texture as data. Default is `LINEAR`.
If the `width`, `height`, or `density` attributes are set, they won't automatically match the main canvas and must be changed manually.
Note: `createFramebuffer()` can only be used in WebGL mode.

method

createFramebuffer

options

configuration options.

Object

### return
new framebuffer.

p5.Framebuffer

` let myBuffer; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Framebuffer object. myBuffer = createFramebuffer(); describe('A grid of white toruses rotating against a dark gray background.'); } function draw() { background(50); // Start drawing to the p5.Framebuffer object. myBuffer.begin(); // Clear the drawing surface. clear(); // Turn on the lights. lights(); // Rotate the coordinate system. rotateX(frameCount * 0.01); rotateY(frameCount * 0.01); // Style the torus. noStroke(); // Draw the torus. torus(20); // Stop drawing to the p5.Framebuffer object. myBuffer.end(); // Iterate from left to right. for (let x = -50; x < 50; x += 25) { // Iterate from top to bottom. for (let y = -50; y < 50; y += 25) { // Draw the p5.Framebuffer object to the canvas. image(myBuffer, x, y, 25, 25); } } } `
` let myBuffer; function setup() { createCanvas(100, 100, WEBGL); // Create an options object. let options = { width: 25, height: 25 }; // Create a p5.Framebuffer object. // Use options for configuration. myBuffer = createFramebuffer(options); describe('A grid of white toruses rotating against a dark gray background.'); } function draw() { background(50); // Start drawing to the p5.Framebuffer object. myBuffer.begin(); // Clear the drawing surface. clear(); // Turn on the lights. lights(); // Rotate the coordinate system. rotateX(frameCount * 0.01); rotateY(frameCount * 0.01); // Style the torus. noStroke(); // Draw the torus. torus(5, 2.5); // Stop drawing to the p5.Framebuffer object. myBuffer.end(); // Iterate from left to right. for (let x = -50; x < 50; x += 25) { // Iterate from top to bottom. for (let y = -50; y < 50; y += 25) { // Draw the p5.Framebuffer object to the canvas. image(myBuffer, x, y); } } } `

p5

Rendering

Rendering

Clears the depth buffer in WebGL mode.
`clearDepth()` clears information about how far objects are from the camera in 3D space. This information is stored in an object called the depth buffer. Clearing the depth buffer ensures new objects aren't drawn behind old ones. Doing so can be useful for feedback effects in which the previous frame serves as the background for the current frame.
The parameter, `depth`, is optional. If a number is passed, as in `clearDepth(0.5)`, it determines the range of objects to clear from the depth buffer. 0 doesn't clear any depth information, 0.5 clears depth information halfway between the near and far clipping planes, and 1 clears depth information all the way to the far clipping plane. By default, `depth` is 1.
Note: `clearDepth()` can only be used in WebGL mode.

method

clearDepth

depth

amount of the depth buffer to clear between 0 (none) and 1 (far clipping plane). Defaults to 1.

Number

` let previous; let current; function setup() { createCanvas(100, 100, WEBGL); // Create the p5.Framebuffer objects. previous = createFramebuffer({ format: FLOAT }); current = createFramebuffer({ format: FLOAT }); describe( 'A multicolor box drifts from side to side on a white background. It leaves a trail that fades over time.' ); } function draw() { // Swap the previous p5.Framebuffer and the // current one so it can be used as a texture. [previous, current] = [current, previous]; // Start drawing to the current p5.Framebuffer. current.begin(); // Paint the background. background(255); // Draw the previous p5.Framebuffer. // Clear the depth buffer so the previous // frame doesn't block the current one. push(); tint(255, 250); image(previous, -50, -50); clearDepth(); pop(); // Draw the box on top of the previous frame. push(); let x = 25 * sin(frameCount * 0.01); let y = 25 * sin(frameCount * 0.02); translate(x, y, 0); rotateX(frameCount * 0.01); rotateY(frameCount * 0.01); normalMaterial(); box(12); pop(); // Stop drawing to the current p5.Framebuffer. current.end(); // Display the current p5.Framebuffer. image(current, -50, -50); } `

p5

Rendering

Rendering

Sets the way colors blend when added to the canvas.
By default, drawing with a solid color paints over the current pixel values on the canvas. `blendMode()` offers many options for blending colors.
Shapes, images, and text can be used as sources for drawing to the canvas. A source pixel changes the color of the canvas pixel where it's drawn. The final color results from blending the source pixel's color with the canvas pixel's color. RGB color values from the source and canvas pixels are compared, added, subtracted, multiplied, and divided to create different effects. Red values with red values, greens with greens, and blues with blues.
The parameter, `mode`, sets the blend mode. For example, calling `blendMode(ADD)` sets the blend mode to `ADD`. The following blend modes are available in both 2D and WebGL mode:
    * `BLEND`: color values from the source overwrite the canvas. This is the default mode.
    * `ADD`: color values from the source are added to values from the canvas.
    * `DARKEST`: keeps the darkest color value.
    * `LIGHTEST`: keeps the lightest color value.
    * `EXCLUSION`: similar to `DIFFERENCE` but with less contrast.
    * `MULTIPLY`: color values from the source are multiplied with values from the canvas. The result is always darker.
    * `SCREEN`: all color values are inverted, then multiplied, then inverted again. The result is always lighter. (Opposite of `MULTIPLY`)
    * `REPLACE`: the last source drawn completely replaces the rest of the canvas.
    * `REMOVE`: overlapping pixels are removed by making them completely transparent.
The following blend modes are only available in 2D mode:
    * `DIFFERENCE`: color values from the source are subtracted from the values from the canvas. If the difference is a negative number, it's made positive.
    * `OVERLAY`: combines `MULTIPLY` and `SCREEN`. Dark values in the canvas get darker and light values get lighter.
    * `HARD_LIGHT`: combines `MULTIPLY` and `SCREEN`. Dark values in the source get darker and light values get lighter.
    * `SOFT_LIGHT`: a softer version of `HARD_LIGHT`.
    * `DODGE`: lightens light tones and increases contrast. Divides the canvas color values by the inverted color values from the source.
    * `BURN`: darkens dark tones and increases contrast. Divides the source color values by the inverted color values from the canvas, then inverts the result.
The following blend modes are only available in WebGL mode:
    * `SUBTRACT`: RGB values from the source are subtracted from the values from the canvas. If the difference is a negative number, it's made positive. Alpha (transparency) values from the source and canvas are added.

method

blendMode

mode

blend mode to set. either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN, ADD, REMOVE or SUBTRACT

Constant

` function setup() { createCanvas(100, 100); background(180); // Use the default blend mode. blendMode(BLEND); // Style the lines. strokeWeight(30); // Draw the first line. stroke('#1a85ff'); line(25, 25, 75, 75); // Draw the second line. stroke('#d41159'); line(75, 25, 25, 75); describe('A Sky Blue line and a Deep Rose line form an X on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(180); // Set the blend mode. blendMode(HARD_LIGHT); // Style the lines. strokeWeight(30); // Draw the first line. stroke('#1a85ff'); line(25, 25, 75, 75); // Draw the second line. stroke('#d41159'); line(75, 25, 25, 75); describe('An ocean blue line and a hot pink line form an X on a gray background. The area where they overlap is Magenta purple.'); } `
` function setup() { createCanvas(100, 100); background(180); // Set the blend mode. blendMode(ADD); // Style the lines. strokeWeight(30); // Draw the first line. stroke('#1a85ff'); line(25, 25, 75, 75); // Draw the second line. stroke('#d41159'); line(75, 25, 25, 75); describe('An icy blue line and a light lavender line form an X on a gray background. The area where they overlap is white.'); } `
` function setup() { createCanvas(100, 100); background(180); // Set the blend mode. blendMode(DARKEST); // Style the lines. strokeWeight(30); // Draw the first line. stroke('#1a85ff'); line(25, 25, 75, 75); // Draw the second line. stroke('#d41159'); line(75, 25, 25, 75); describe('A steel blue line and a cranberry line form an X on a gray background. The area where they overlap is deep purple.'); } `
` function setup() { createCanvas(100, 100); background(180); // Set the blend mode. blendMode(BURN); // Style the lines. strokeWeight(30); // Draw the first line. stroke('#1a85ff'); line(25, 25, 75, 75); // Draw the second line. stroke('#d41159'); line(75, 25, 25, 75); describe('A cobalt blue line and a burgundy line form an X on a gray background. The area where they overlap is black.'); } `
` function setup() { createCanvas(100, 100); background(180); // Set the blend mode. blendMode(LIGHTEST); // Style the lines. strokeWeight(30); // Draw the first line. stroke('#1a85ff'); line(25, 25, 75, 75); // Draw the second line. stroke('#d41159'); line(75, 25, 25, 75); describe('A pale lavender line and a soft beige line form an X on a gray background. The area where they overlap is pale lilac.'); } `
` function setup() { createCanvas(100, 100); background(180); // Set the blend mode. blendMode(EXCLUSION); // Style the lines. strokeWeight(30); // Draw the first line. stroke('#1a85ff'); line(25, 25, 75, 75); // Draw the second line. stroke('#d41159'); line(75, 25, 25, 75); describe('An earthy brown line and a muted sage line form an X on a gray background. The area where they overlap is sage green.'); } `
` function setup() { createCanvas(100, 100); background(180); // Set the blend mode. blendMode(MULTIPLY); // Style the lines. strokeWeight(30); // Draw the first line. stroke('#1a85ff'); line(25, 25, 75, 75); // Draw the second line. stroke('#d41159'); line(75, 25, 25, 75); describe('A slate blue line and a plum line form an X on a gray background. The area where they overlap is dark Indigo.'); } `
` function setup() { createCanvas(100, 100); background(180); // Set the blend mode. blendMode(SCREEN); // Style the lines. strokeWeight(30); // Draw the first line. stroke('#1a85ff'); line(25, 25, 75, 75); // Draw the second line. stroke('#d41159'); line(75, 25, 25, 75); describe('A baby blue line and a peach pink line form an X on a gray background. The area where they overlap is misty lilac.'); } `
` function setup() { createCanvas(100, 100); background(180); // Set the blend mode. blendMode(REPLACE); // Style the lines. strokeWeight(30); // Draw the first line. stroke('#1a85ff'); line(25, 25, 75, 75); // Draw the second line. stroke('#d41159'); line(75, 25, 25, 75); describe('A diagonal deep rose line.'); } `
` function setup() { createCanvas(100, 100); background(180); // Set the blend mode. blendMode(REMOVE); // Style the lines. strokeWeight(30); // Draw the first line. stroke('#1a85ff'); line(25, 25, 75, 75); // Draw the second line. stroke('#d41159'); line(75, 25, 25, 75); describe('The silhouette of an X is missing from a gray background.'); } `
` function setup() { createCanvas(100, 100); background(180); // Set the blend mode. blendMode(DIFFERENCE); // Style the lines. strokeWeight(30); // Draw the first line. stroke('#1a85ff'); line(25, 25, 75, 75); // Draw the second line. stroke('#d41159'); line(75, 25, 25, 75); describe('A light burgundy line and a forest green line form an X on a gray background. The area where they overlap is dark cocoa.'); } `
` function setup() { createCanvas(100, 100); background(180); // Set the blend mode. blendMode(OVERLAY); // Style the lines. strokeWeight(30); // Draw the first line. stroke('#1a85ff'); line(25, 25, 75, 75); // Draw the second line. stroke('#d41159'); line(75, 25, 25, 75); describe('A cornflower blue line and a light rose line form an X on a gray background. The area where they overlap is violet.'); } `
` function setup() { createCanvas(100, 100); background(180); // Set the blend mode. blendMode(SOFT_LIGHT); // Style the lines. strokeWeight(30); // Draw the first line. stroke('#1a85ff'); line(25, 25, 75, 75); // Draw the second line. stroke('#d41159'); line(75, 25, 25, 75); describe('A pale sky line and a rose blush line form an X on a gray background. The area where they overlap is lavender.'); } `
` function setup() { createCanvas(100, 100); background(180); // Set the blend mode. blendMode(DODGE); // Style the lines. strokeWeight(30); // Draw the first line. stroke('#1a85ff'); line(25, 25, 75, 75); // Draw the second line. stroke('#d41159'); line(75, 25, 25, 75); describe('An aqua blue line and a light pink line form an X on a gray background. The area where they overlap is white.'); } `
` function setup() { // Create a canvas with WEBGL mode. createCanvas(100, 100, WEBGL); // Set the background color. background(180); // Set the blend mode to SUBTRACT. blendMode(SUBTRACT); // Style the lines. strokeWeight(30); // Draw the blue line. stroke('#1a85ff'); line(-25, -25, 25, 25); // Draw the red line. stroke('#d41159'); line(25, -25, -25, 25); describe('A burnt orange and a sea green line form an X on a gray background. The area where they overlap is forest green.'); } `

p5

Rendering

Rendering

A system variable that provides direct access to the sketch's `<canvas>` element.
The `<canvas>` element provides many specialized features that aren't included in the p5.js library. The `drawingContext` system variable provides access to these features by exposing the sketch's CanvasRenderingContext2D object.

property

drawingContext

` function setup() { createCanvas(100, 100); background(180); // Style the circle using shadows. drawingContext.shadowOffsetX = 5; drawingContext.shadowOffsetY = -5; drawingContext.shadowBlur = 10; drawingContext.shadowColor = 'black'; // Draw the circle. circle(50, 50, 40); describe("A white circle on a gray background. The circle's edges are shadowy."); } `
` function setup() { createCanvas(100, 100); background('skyblue'); // Style the circle using a color gradient. let myGradient = drawingContext.createRadialGradient(50, 50, 3, 50, 50, 40); myGradient.addColorStop(0, 'yellow'); myGradient.addColorStop(0.6, 'orangered'); myGradient.addColorStop(1, 'yellow'); drawingContext.fillStyle = myGradient; drawingContext.strokeStyle = 'rgba(0, 0, 0, 0)'; // Draw the circle. circle(50, 50, 40); describe('A fiery sun drawn on a light blue background.'); } `

p5

Rendering

Rendering

Stops the code in draw() from running repeatedly.
By default, draw() tries to run 60 times per second. Calling `noLoop()` stops draw() from repeating. The draw loop can be restarted by calling loop(). draw() can be run once by calling redraw().
The isLooping() function can be used to check whether a sketch is looping, as in `isLooping() === true`.

method

noLoop

` function setup() { createCanvas(100, 100); // Turn off the draw loop. noLoop(); describe('A white half-circle on the left edge of a gray square.'); } function draw() { background(200); // Calculate the circle's x-coordinate. let x = frameCount; // Draw the circle. // Normally, the circle would move from left to right. circle(x, 50, 20); } `
` // Double-click to stop the draw loop. function setup() { createCanvas(100, 100); // Slow the frame rate. frameRate(5); describe('A white circle moves randomly on a gray background. It stops moving when the user double-clicks.'); } function draw() { background(200); // Calculate the circle's coordinates. let x = random(0, 100); let y = random(0, 100); // Draw the circle. // Normally, the circle would move from left to right. circle(x, y, 20); } // Stop the draw loop when the user double-clicks. function doubleClicked() { noLoop(); } `
` let startButton; let stopButton; function setup() { createCanvas(100, 100); // Create the button elements and place them // beneath the canvas. startButton = createButton('▶'); startButton.position(0, 100); startButton.size(50, 20); stopButton = createButton('◾'); stopButton.position(50, 100); stopButton.size(50, 20); // Set functions to call when the buttons are pressed. startButton.mousePressed(loop); stopButton.mousePressed(noLoop); // Slow the frame rate. frameRate(5); describe( 'A white circle moves randomly on a gray background. Play and stop buttons are shown beneath the canvas. The circle stops or starts moving when the user presses a button.' ); } function draw() { background(200); // Calculate the circle's coordinates. let x = random(0, 100); let y = random(0, 100); // Draw the circle. // Normally, the circle would move from left to right. circle(x, y, 20); } `

p5

Structure

Structure

Resumes the draw loop after noLoop() has been called.
By default, draw() tries to run 60 times per second. Calling noLoop() stops draw() from repeating. The draw loop can be restarted by calling `loop()`.
The isLooping() function can be used to check whether a sketch is looping, as in `isLooping() === true`.

method

loop

` function setup() { createCanvas(100, 100); // Turn off the draw loop. noLoop(); describe( 'A white half-circle on the left edge of a gray square. The circle starts moving to the right when the user double-clicks.' ); } function draw() { background(200); // Calculate the circle's x-coordinate. let x = frameCount; // Draw the circle. circle(x, 50, 20); } // Resume the draw loop when the user double-clicks. function doubleClicked() { loop(); } `
` let startButton; let stopButton; function setup() { createCanvas(100, 100); // Create the button elements and place them // beneath the canvas. startButton = createButton('▶'); startButton.position(0, 100); startButton.size(50, 20); stopButton = createButton('◾'); stopButton.position(50, 100); stopButton.size(50, 20); // Set functions to call when the buttons are pressed. startButton.mousePressed(loop); stopButton.mousePressed(noLoop); // Slow the frame rate. frameRate(5); describe( 'A white circle moves randomly on a gray background. Play and stop buttons are shown beneath the canvas. The circle stops or starts moving when the user presses a button.' ); } function draw() { background(200); // Calculate the circle's coordinates. let x = random(0, 100); let y = random(0, 100); // Draw the circle. // Normally, the circle would move from left to right. circle(x, y, 20); } `

p5

Structure

Structure

Returns `true` if the draw loop is running and `false` if not.
By default, draw() tries to run 60 times per second. Calling noLoop() stops draw() from repeating. The draw loop can be restarted by calling loop().
The `isLooping()` function can be used to check whether a sketch is looping, as in `isLooping() === true`.

method

isLooping

### return


Boolean

` function setup() { createCanvas(100, 100); describe('A white circle drawn against a gray background. When the user double-clicks, the circle stops or resumes following the mouse.'); } function draw() { background(200); // Draw the circle at the mouse's position. circle(mouseX, mouseY, 20); } // Toggle the draw loop when the user double-clicks. function doubleClicked() { if (isLooping() === true) { noLoop(); } else { loop(); } } `

p5

Structure

Structure

Begins a drawing group that contains its own styles and transformations.
By default, styles such as fill() and transformations such as rotate() are applied to all drawing that follows. The `push()` and pop() functions can limit the effect of styles and transformations to a specific group of shapes, images, and text. For example, a group of shapes could be translated to follow the mouse without affecting the rest of the sketch:
    // Begin the drawing group.
    push();
    
    // Translate the origin to the mouse's position.
    translate(mouseX, mouseY);
    
    // Style the face.
    noStroke();
    fill('green');
    
    // Draw the face.
    circle(0, 0, 60);
    
    // Style the eyes.
    fill('white');
    
    // Draw the left eye.
    ellipse(-20, -20, 30, 20);
    
    // Draw the right eye.
    ellipse(20, -20, 30, 20);
    
    // End the drawing group.
    pop();
    
    // Draw a bug.
    let x = random(0, 100);
    let y = random(0, 100);
    text('🦟', x, y);
    
In the code snippet above, the bug's position isn't affected by `translate(mouseX, mouseY)` because that transformation is contained between `push()` and pop(). The bug moves around the entire canvas as expected.
Note: `push()` and pop() are always called as a pair. Both functions are required to begin and end a drawing group.
`push()` and pop() can also be nested to create subgroups. For example, the code snippet above could be changed to give more detail to the frog’s eyes:
    // Begin the drawing group.
    push();
    
    // Translate the origin to the mouse's position.
    translate(mouseX, mouseY);
    
    // Style the face.
    noStroke();
    fill('green');
    
    // Draw a face.
    circle(0, 0, 60);
    
    // Style the eyes.
    fill('white');
    
    // Draw the left eye.
    push();
    translate(-20, -20);
    ellipse(0, 0, 30, 20);
    fill('black');
    circle(0, 0, 8);
    pop();
    
    // Draw the right eye.
    push();
    translate(20, -20);
    ellipse(0, 0, 30, 20);
    fill('black');
    circle(0, 0, 8);
    pop();
    
    // End the drawing group.
    pop();
    
    // Draw a bug.
    let x = random(0, 100);
    let y = random(0, 100);
    text('🦟', x, y);
    
In this version, the code to draw each eye is contained between its own `push()` and pop() functions. Doing so makes it easier to add details in the correct part of a drawing.
`push()` and pop() contain the effects of the following functions:
    * fill()
    * noFill()
    * noStroke()
    * stroke()
    * tint()
    * noTint()
    * strokeWeight()
    * strokeCap()
    * strokeJoin()
    * imageMode()
    * rectMode()
    * ellipseMode()
    * colorMode()
    * textAlign()
    * textFont()
    * textSize()
    * textLeading()
    * applyMatrix()
    * resetMatrix()
    * rotate()
    * scale()
    * shearX()
    * shearY()
    * translate()
In WebGL mode, `push()` and pop() contain the effects of a few additional styles:
    * setCamera()
    * ambientLight()
    * directionalLight()
    * pointLight() texture()
    * specularMaterial()
    * shininess()
    * normalMaterial()
    * shader()

method

push

` function setup() { createCanvas(100, 100); background(200); // Draw the left circle. circle(25, 50, 20); // Begin the drawing group. push(); // Translate the origin to the center. translate(50, 50); // Style the circle. strokeWeight(5); stroke('royalblue'); fill('orange'); // Draw the circle. circle(0, 0, 20); // End the drawing group. pop(); // Draw the right circle. circle(75, 50, 20); describe( 'Three circles drawn in a row on a gray background. The left and right circles are white with thin, black borders. The middle circle is orange with a thick, blue border.' ); } `
` function setup() { createCanvas(100, 100); // Slow the frame rate. frameRate(24); describe('A mosquito buzzes in front of a green frog. The frog follows the mouse as the user moves.'); } function draw() { background(200); // Begin the drawing group. push(); // Translate the origin to the mouse's position. translate(mouseX, mouseY); // Style the face. noStroke(); fill('green'); // Draw a face. circle(0, 0, 60); // Style the eyes. fill('white'); // Draw the left eye. push(); translate(-20, -20); ellipse(0, 0, 30, 20); fill('black'); circle(0, 0, 8); pop(); // Draw the right eye. push(); translate(20, -20); ellipse(0, 0, 30, 20); fill('black'); circle(0, 0, 8); pop(); // End the drawing group. pop(); // Draw a bug. let x = random(0, 100); let y = random(0, 100); text('🦟', x, y); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe( 'Two spheres drawn on a gray background. The sphere on the left is red and lit from the front. The sphere on the right is a blue wireframe.' ); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the red sphere. push(); translate(-25, 0, 0); noStroke(); directionalLight(255, 0, 0, 0, 0, -1); sphere(20); pop(); // Draw the blue sphere. push(); translate(25, 0, 0); strokeWeight(0.3); stroke(0, 0, 255); noFill(); sphere(20); pop(); } `

p5

Structure

Structure

Ends a drawing group that contains its own styles and transformations.
By default, styles such as fill() and transformations such as rotate() are applied to all drawing that follows. The push() and `pop()` functions can limit the effect of styles and transformations to a specific group of shapes, images, and text. For example, a group of shapes could be translated to follow the mouse without affecting the rest of the sketch:
    // Begin the drawing group.
    push();
    
    // Translate the origin to the mouse's position.
    translate(mouseX, mouseY);
    
    // Style the face.
    noStroke();
    fill('green');
    
    // Draw the face.
    circle(0, 0, 60);
    
    // Style the eyes.
    fill('white');
    
    // Draw the left eye.
    ellipse(-20, -20, 30, 20);
    
    // Draw the right eye.
    ellipse(20, -20, 30, 20);
    
    // End the drawing group.
    pop();
    
    // Draw a bug.
    let x = random(0, 100);
    let y = random(0, 100);
    text('🦟', x, y);
    
In the code snippet above, the bug's position isn't affected by `translate(mouseX, mouseY)` because that transformation is contained between push() and `pop()`. The bug moves around the entire canvas as expected.
Note: push() and `pop()` are always called as a pair. Both functions are required to begin and end a drawing group.
push() and `pop()` can also be nested to create subgroups. For example, the code snippet above could be changed to give more detail to the frog’s eyes:
    // Begin the drawing group.
    push();
    
    // Translate the origin to the mouse's position.
    translate(mouseX, mouseY);
    
    // Style the face.
    noStroke();
    fill('green');
    
    // Draw a face.
    circle(0, 0, 60);
    
    // Style the eyes.
    fill('white');
    
    // Draw the left eye.
    push();
    translate(-20, -20);
    ellipse(0, 0, 30, 20);
    fill('black');
    circle(0, 0, 8);
    pop();
    
    // Draw the right eye.
    push();
    translate(20, -20);
    ellipse(0, 0, 30, 20);
    fill('black');
    circle(0, 0, 8);
    pop();
    
    // End the drawing group.
    pop();
    
    // Draw a bug.
    let x = random(0, 100);
    let y = random(0, 100);
    text('🦟', x, y);
    
In this version, the code to draw each eye is contained between its own push() and `pop()` functions. Doing so makes it easier to add details in the correct part of a drawing.
push() and `pop()` contain the effects of the following functions:
    * fill()
    * noFill()
    * noStroke()
    * stroke()
    * tint()
    * noTint()
    * strokeWeight()
    * strokeCap()
    * strokeJoin()
    * imageMode()
    * rectMode()
    * ellipseMode()
    * colorMode()
    * textAlign()
    * textFont()
    * textSize()
    * textLeading()
    * applyMatrix()
    * resetMatrix()
    * rotate()
    * scale()
    * shearX()
    * shearY()
    * translate()
In WebGL mode, push() and `pop()` contain the effects of a few additional styles:
    * setCamera()
    * ambientLight()
    * directionalLight()
    * pointLight() texture()
    * specularMaterial()
    * shininess()
    * normalMaterial()
    * shader()

method

pop

` function setup() { createCanvas(100, 100); background(200); // Draw the left circle. circle(25, 50, 20); // Begin the drawing group. push(); // Translate the origin to the center. translate(50, 50); // Style the circle. strokeWeight(5); stroke('royalblue'); fill('orange'); // Draw the circle. circle(0, 0, 20); // End the drawing group. pop(); // Draw the right circle. circle(75, 50, 20); describe( 'Three circles drawn in a row on a gray background. The left and right circles are white with thin, black borders. The middle circle is orange with a thick, blue border.' ); } `
` function setup() { createCanvas(100, 100); // Slow the frame rate. frameRate(24); describe('A mosquito buzzes in front of a green frog. The frog follows the mouse as the user moves.'); } function draw() { background(200); // Begin the drawing group. push(); // Translate the origin to the mouse's position. translate(mouseX, mouseY); // Style the face. noStroke(); fill('green'); // Draw a face. circle(0, 0, 60); // Style the eyes. fill('white'); // Draw the left eye. push(); translate(-20, -20); ellipse(0, 0, 30, 20); fill('black'); circle(0, 0, 8); pop(); // Draw the right eye. push(); translate(20, -20); ellipse(0, 0, 30, 20); fill('black'); circle(0, 0, 8); pop(); // End the drawing group. pop(); // Draw a bug. let x = random(0, 100); let y = random(0, 100); text('🦟', x, y); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe( 'Two spheres drawn on a gray background. The sphere on the left is red and lit from the front. The sphere on the right is a blue wireframe.' ); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the red sphere. push(); translate(-25, 0, 0); noStroke(); directionalLight(255, 0, 0, 0, 0, -1); sphere(20); pop(); // Draw the blue sphere. push(); translate(25, 0, 0); strokeWeight(0.3); stroke(0, 0, 255); noFill(); sphere(20); pop(); } `

p5

Structure

Structure

Runs the code in draw() once.
By default, draw() tries to run 60 times per second. Calling noLoop() stops draw() from repeating. Calling `redraw()` will execute the code in the draw() function a set number of times.
The parameter, `n`, is optional. If a number is passed, as in `redraw(5)`, then the draw loop will run the given number of times. By default, `n` is 1.

method

redraw

n

number of times to run draw(). Defaults to 1.

Integer

` // Double-click the canvas to move the circle. let x = 0; function setup() { createCanvas(100, 100); // Turn off the draw loop. noLoop(); describe( 'A white half-circle on the left edge of a gray square. The circle moves a little to the right when the user double-clicks.' ); } function draw() { background(200); // Draw the circle. circle(x, 50, 20); // Increment x. x += 5; } // Run the draw loop when the user double-clicks. function doubleClicked() { redraw(); } `
` // Double-click the canvas to move the circle. let x = 0; function setup() { createCanvas(100, 100); // Turn off the draw loop. noLoop(); describe( 'A white half-circle on the left edge of a gray square. The circle hops to the right when the user double-clicks.' ); } function draw() { background(200); // Draw the circle. circle(x, 50, 20); // Increment x. x += 5; } // Run the draw loop three times when the user double-clicks. function doubleClicked() { redraw(3); } `

p5

Structure

Structure

Creates a new sketch in "instance" mode.
All p5.js sketches are instances of the `p5` class. Put another way, all p5.js sketches are objects with methods including `pInst.setup()`, `pInst.draw()`, `pInst.circle()`, and `pInst.fill()`. By default, sketches run in "global mode" to hide some of this complexity.
In global mode, a default instance of the `p5` class is created automatically. The default `p5` instance searches the web page's source code for declarations of system functions such as `setup()`, `draw()`, and `mousePressed()`, then attaches those functions to itself as methods. Calling a function such as `circle()` in global mode actually calls the default `p5` object's `pInst.circle()` method.
It's often helpful to isolate the code within sketches from the rest of the code on a web page. Two common use cases are web pages that use other JavaScript libraries and web pages with multiple sketches. "Instance mode" makes it easy to support both of these scenarios.
Instance mode sketches support the same API as global mode sketches. They use a function to bundle, or encapsulate, an entire sketch. The function containing the sketch is then passed to the `p5()` constructor.
The first parameter, `sketch`, is a function that contains the sketch. For example, the statement `new p5(mySketch)` would create a new instance mode sketch from a function named `mySketch`. The function should have one parameter, `p`, that's a `p5` object.
The second parameter, `node`, is optional. If a string is passed, as in `new p5(mySketch, 'sketch-one')` the new instance mode sketch will become a child of the HTML element with the id `sketch-one`. If an HTML element is passed, as in `new p5(mySketch, myElement)`, then the new instance mode sketch will become a child of the `Element` object called `myElement`.

method

p5

sketch

function containing the sketch.

Object

node

ID or reference to the HTML element that will contain the sketch.

String|HTMLElement

` // Declare the function containing the sketch. function sketch(p) { // Declare the setup() method. p.setup = function () { p.createCanvas(100, 100); p.describe('A white circle drawn on a gray background.'); }; // Declare the draw() method. p.draw = function () { p.background(200); // Draw the circle. p.circle(50, 50, 20); }; } // Initialize the sketch. new p5(sketch); `
` // Declare the function containing the sketch. function sketch(p) { // Create the sketch's variables within its scope. let x = 50; let y = 50; // Declare the setup() method. p.setup = function () { p.createCanvas(100, 100); p.describe('A white circle moves randomly on a gray background.'); }; // Declare the draw() method. p.draw = function () { p.background(200); // Update x and y. x += p.random(-1, 1); y += p.random(-1, 1); // Draw the circle. p.circle(x, y, 20); }; } // Initialize the sketch. new p5(sketch); `
` // Declare the function containing the sketch. function sketch(p) { // Declare the setup() method. p.setup = function () { p.createCanvas(100, 100); p.describe('A white circle drawn on a gray background.'); }; // Declare the draw() method. p.draw = function () { p.background(200); // Draw the circle. p.circle(50, 50, 20); }; } // Select the web page's body element. let body = document.querySelector('body'); // Initialize the sketch and attach it to the web page's body. new p5(sketch, body); `
` // Declare the function containing the sketch. function sketch(p) { // Declare the setup() method. p.setup = function () { p.createCanvas(100, 100); p.describe( 'A white circle drawn on a gray background. The circle follows the mouse as the user moves.' ); }; // Declare the draw() method. p.draw = function () { p.background(200); // Draw the circle. p.circle(p.mouseX, p.mouseY, 20); }; } // Initialize the sketch. new p5(sketch); `
` // Declare the function containing the sketch. function sketch(p) { // Declare the setup() method. p.setup = function () { p.createCanvas(100, 100); p.describe( 'A white circle drawn on a gray background. The circle follows the mouse as the user moves. The circle becomes black when the user double-clicks.' ); }; // Declare the draw() method. p.draw = function () { p.background(200); // Draw the circle. p.circle(p.mouseX, p.mouseY, 20); }; // Declare the doubleClicked() method. p.doubleClicked = function () { // Change the fill color when the user double-clicks. p.fill(0); }; } // Initialize the sketch. new p5(sketch); `

p5

Structure

Structure

Applies a transformation matrix to the coordinate system.
Transformations such as translate(), rotate(), and scale() use matrix-vector multiplication behind the scenes. A table of numbers, called a matrix, encodes each transformation. The values in the matrix then multiply each point on the canvas, which is represented by a vector.
`applyMatrix()` allows for many transformations to be applied at once. See Wikipedia and MDN for more details about transformations.
There are two ways to call `applyMatrix()` in two and three dimensions.
In 2D mode, the parameters `a`, `b`, `c`, `d`, `e`, and `f`, correspond to elements in the following transformation matrix:
> The numbers can be passed individually, as in `applyMatrix(2, 0, 0, 0, 2, 0)`. They can also be passed in an array, as in `applyMatrix([2, 0, 0, 0, 2, 0])`.
In 3D mode, the parameters `a`, `b`, `c`, `d`, `e`, `f`, `g`, `h`, `i`, `j`, `k`, `l`, `m`, `n`, `o`, and `p` correspond to elements in the following transformation matrix:
The numbers can be passed individually, as in `applyMatrix(2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1)`. They can also be passed in an array, as in `applyMatrix([2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1])`.
By default, transformations accumulate. The push() and pop() functions can be used to isolate transformations within distinct drawing groups.
Note: Transformations are reset at the beginning of the draw loop. Calling `applyMatrix()` inside the draw() function won't cause shapes to transform continuously.

method

applyMatrix

` function setup() { createCanvas(100, 100); describe('A white circle on a gray background.'); } function draw() { background(200); // Translate the origin to the center. applyMatrix(1, 0, 0, 1, 50, 50); // Draw the circle at coordinates (0, 0). circle(0, 0, 40); } `
` function setup() { createCanvas(100, 100); describe('A white circle on a gray background.'); } function draw() { background(200); // Translate the origin to the center. let m = [1, 0, 0, 1, 50, 50]; applyMatrix(m); // Draw the circle at coordinates (0, 0). circle(0, 0, 40); } `
` function setup() { createCanvas(100, 100); describe("A white rectangle on a gray background. The rectangle's long axis runs from top-left to bottom-right."); } function draw() { background(200); // Rotate the coordinate system 1/8 turn. let angle = QUARTER_PI; let ca = cos(angle); let sa = sin(angle); applyMatrix(ca, sa, -sa, ca, 0, 0); // Draw a rectangle at coordinates (50, 0). rect(50, 0, 40, 20); } `
` function setup() { createCanvas(100, 100); describe( 'Two white squares on a gray background. The larger square appears at the top-center. The smaller square appears at the top-left.' ); } function draw() { background(200); // Draw a square at (30, 20). square(30, 20, 40); // Scale the coordinate system by a factor of 0.5. applyMatrix(0.5, 0, 0, 0.5, 0, 0); // Draw a square at (30, 20). // It appears at (15, 10) after scaling. square(30, 20, 40); } `
` function setup() { createCanvas(100, 100); describe('A white quadrilateral on a gray background.'); } function draw() { background(200); // Calculate the shear factor. let angle = QUARTER_PI; let shearFactor = 1 / tan(HALF_PI - angle); // Shear the coordinate system along the x-axis. applyMatrix(1, 0, shearFactor, 1, 0, 0); // Draw the square. square(0, 0, 50); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white cube rotates slowly against a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Rotate the coordinate system a little more each frame. let angle = frameCount * 0.01; let ca = cos(angle); let sa = sin(angle); applyMatrix(ca, 0, sa, 0, 0, 1, 0, 0, -sa, 0, ca, 0, 0, 0, 0, 1); // Draw a box. box(); } `

p5

Transform

Transform

arr

an array containing the elements of the transformation matrix. Its length should be either 6 (2D) or 16 (3D).

Array

a

an element of the transformation matrix.

Number

b

an element of the transformation matrix.

Number

c

an element of the transformation matrix.

Number

d

an element of the transformation matrix.

Number

e

an element of the transformation matrix.

Number

f

an element of the transformation matrix.

Number

a



Number

b



Number

c



Number

d



Number

e



Number

f



Number

g

an element of the transformation matrix.

Number

h

an element of the transformation matrix.

Number

i

an element of the transformation matrix.

Number

j

an element of the transformation matrix.

Number

k

an element of the transformation matrix.

Number

l

an element of the transformation matrix.

Number

m

an element of the transformation matrix.

Number

n

an element of the transformation matrix.

Number

o

an element of the transformation matrix.

Number

p

an element of the transformation matrix.

Number

Clears all transformations applied to the coordinate system.

method

resetMatrix

` function setup() { createCanvas(100, 100); describe( 'Two circles drawn on a gray background. A blue circle is at the top-left and a red circle is at the bottom-right.' ); } function draw() { background(200); // Translate the origin to the center. translate(50, 50); // Draw a blue circle at the coordinates (25, 25). fill('blue'); circle(25, 25, 20); // Clear all transformations. // The origin is now at the top-left corner. resetMatrix(); // Draw a red circle at the coordinates (25, 25). fill('red'); circle(25, 25, 20); } `

p5

Transform

Transform

Rotates the coordinate system.
By default, the positive x-axis points to the right and the positive y-axis points downward. The `rotate()` function changes this orientation by rotating the coordinate system about the origin. Everything drawn after `rotate()` is called will appear to be rotated.
The first parameter, `angle`, is the amount to rotate. For example, calling `rotate(1)` rotates the coordinate system clockwise 1 radian which is nearly 57˚. `rotate()` interprets angle values using the current angleMode().
The second parameter, `axis`, is optional. It's used to orient 3D rotations in WebGL mode. If a p5.Vector is passed, as in `rotate(QUARTER_PI, myVector)`, then the coordinate system will rotate `QUARTER_PI` radians about `myVector`. If an array of vector components is passed, as in `rotate(QUARTER_PI, [1, 0, 0])`, then the coordinate system will rotate `QUARTER_PI` radians about a vector with the components `[1, 0, 0]`.
By default, transformations accumulate. For example, calling `rotate(1)` twice has the same effect as calling `rotate(2)` once. The push() and pop() functions can be used to isolate transformations within distinct drawing groups.
Note: Transformations are reset at the beginning of the draw loop. Calling `rotate(1)` inside the draw() function won't cause shapes to spin.

method

rotate

angle

angle of rotation in the current angleMode().

Number

axis

axis to rotate about in 3D.

p5.Vector|Number[]

` function setup() { createCanvas(100, 100); describe( "A white rectangle on a gray background. The rectangle's long axis runs from top-left to bottom-right." ); } function draw() { background(200); // Rotate the coordinate system 1/8 turn. rotate(QUARTER_PI); // Draw a rectangle at coordinates (50, 0). rect(50, 0, 40, 20); } `
` function setup() { createCanvas(100, 100); describe( "A white rectangle on a gray background. The rectangle's long axis runs from top-left to bottom-right." ); } function draw() { background(200); // Rotate the coordinate system 1/16 turn. rotate(QUARTER_PI / 2); // Rotate the coordinate system another 1/16 turn. rotate(QUARTER_PI / 2); // Draw a rectangle at coordinates (50, 0). rect(50, 0, 40, 20); } `
` function setup() { createCanvas(100, 100); // Use degrees. angleMode(DEGREES); describe( "A white rectangle on a gray background. The rectangle's long axis runs from top-left to bottom-right." ); } function draw() { background(200); // Rotate the coordinate system 1/8 turn. rotate(45); // Draw a rectangle at coordinates (50, 0). rect(50, 0, 40, 20); } `
` function setup() { createCanvas(100, 100); describe( 'A white rectangle on a gray background. The rectangle rotates slowly about the top-left corner. It disappears and reappears periodically.' ); } function draw() { background(200); // Rotate the coordinate system a little more each frame. let angle = frameCount * 0.01; rotate(angle); // Draw a rectangle at coordinates (50, 0). rect(50, 0, 40, 20); } `
` function setup() { createCanvas(100, 100, WEBGL); describe("A cube on a gray background. The cube's front face points to the top-right."); } function draw() { background(200); // Rotate the coordinate system 1/8 turn about // the axis [1, 1, 0]. let axis = createVector(1, 1, 0); rotate(QUARTER_PI, axis); // Draw a box. box(); } `
` function setup() { createCanvas(100, 100, WEBGL); describe("A cube on a gray background. The cube's front face points to the top-right."); } function draw() { background(200); // Rotate the coordinate system 1/8 turn about // the axis [1, 1, 0]. let axis = [1, 1, 0]; rotate(QUARTER_PI, axis); // Draw a box. box(); } `

p5

Transform

Transform

Rotates the coordinate system about the x-axis in WebGL mode.
The parameter, `angle`, is the amount to rotate. For example, calling `rotateX(1)` rotates the coordinate system about the x-axis by 1 radian. `rotateX()` interprets angle values using the current angleMode().
By default, transformations accumulate. For example, calling `rotateX(1)` twice has the same effect as calling `rotateX(2)` once. The push() and pop() functions can be used to isolate transformations within distinct drawing groups.
Note: Transformations are reset at the beginning of the draw loop. Calling `rotateX(1)` inside the draw() function won't cause shapes to spin.

method

rotateX

angle

angle of rotation in the current angleMode().

Number

` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white cube on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Rotate the coordinate system 1/8 turn. rotateX(QUARTER_PI); // Draw a box. box(); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white cube on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Rotate the coordinate system 1/16 turn. rotateX(QUARTER_PI / 2); // Rotate the coordinate system 1/16 turn. rotateX(QUARTER_PI / 2); // Draw a box. box(); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); // Use degrees. angleMode(DEGREES); describe('A white cube on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Rotate the coordinate system 1/8 turn. rotateX(45); // Draw a box. box(); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white cube rotates slowly against a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Rotate the coordinate system a little more each frame. let angle = frameCount * 0.01; rotateX(angle); // Draw a box. box(); } `

p5

Transform

Transform

Rotates the coordinate system about the y-axis in WebGL mode.
The parameter, `angle`, is the amount to rotate. For example, calling `rotateY(1)` rotates the coordinate system about the y-axis by 1 radian. `rotateY()` interprets angle values using the current angleMode().
By default, transformations accumulate. For example, calling `rotateY(1)` twice has the same effect as calling `rotateY(2)` once. The push() and pop() functions can be used to isolate transformations within distinct drawing groups.
Note: Transformations are reset at the beginning of the draw loop. Calling `rotateY(1)` inside the draw() function won't cause shapes to spin.

method

rotateY

angle

angle of rotation in the current angleMode().

Number

` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white cube on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Rotate the coordinate system 1/8 turn. rotateY(QUARTER_PI); // Draw a box. box(); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white cube on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Rotate the coordinate system 1/16 turn. rotateY(QUARTER_PI / 2); // Rotate the coordinate system 1/16 turn. rotateY(QUARTER_PI / 2); // Draw a box. box(); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); // Use degrees. angleMode(DEGREES); describe('A white cube on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Rotate the coordinate system 1/8 turn. rotateY(45); // Draw a box. box(); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white cube rotates slowly against a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Rotate the coordinate system a little more each frame. let angle = frameCount * 0.01; rotateY(angle); // Draw a box. box(); } `

p5

Transform

Transform

Rotates the coordinate system about the z-axis in WebGL mode.
The parameter, `angle`, is the amount to rotate. For example, calling `rotateZ(1)` rotates the coordinate system about the z-axis by 1 radian. `rotateZ()` interprets angle values using the current angleMode().
By default, transformations accumulate. For example, calling `rotateZ(1)` twice has the same effect as calling `rotateZ(2)` once. The push() and pop() functions can be used to isolate transformations within distinct drawing groups.
Note: Transformations are reset at the beginning of the draw loop. Calling `rotateZ(1)` inside the draw() function won't cause shapes to spin.

method

rotateZ

angle

angle of rotation in the current angleMode().

Number

` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white cube on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Rotate the coordinate system 1/8 turn. rotateZ(QUARTER_PI); // Draw a box. box(); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white cube on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Rotate the coordinate system 1/16 turn. rotateZ(QUARTER_PI / 2); // Rotate the coordinate system 1/16 turn. rotateZ(QUARTER_PI / 2); // Draw a box. box(); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); // Use degrees. angleMode(DEGREES); describe('A white cube on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Rotate the coordinate system 1/8 turn. rotateZ(45); // Draw a box. box(); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white cube rotates slowly against a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Rotate the coordinate system a little more each frame. let angle = frameCount * 0.01; rotateZ(angle); // Draw a box. box(); } `

p5

Transform

Transform

Scales the coordinate system.
By default, shapes are drawn at their original scale. A rectangle that's 50 pixels wide appears to take up half the width of a 100 pixel-wide canvas. The `scale()` function can shrink or stretch the coordinate system so that shapes appear at different sizes. There are two ways to call `scale()` with parameters that set the scale factor(s).
The first way to call `scale()` uses numbers to set the amount of scaling. The first parameter, `s`, sets the amount to scale each axis. For example, calling `scale(2)` stretches the x-, y-, and z-axes by a factor of 2. The next two parameters, `y` and `z`, are optional. They set the amount to scale the y- and z-axes. For example, calling `scale(2, 0.5, 1)` stretches the x-axis by a factor of 2, shrinks the y-axis by a factor of 0.5, and leaves the z-axis unchanged.
The second way to call `scale()` uses a p5.Vector object to set the scale factors. For example, calling `scale(myVector)` uses the x-, y-, and z-components of `myVector` to set the amount of scaling along the x-, y-, and z-axes. Doing so is the same as calling `scale(myVector.x, myVector.y, myVector.z)`.
By default, transformations accumulate. For example, calling `scale(1)` twice has the same effect as calling `scale(2)` once. The push() and pop() functions can be used to isolate transformations within distinct drawing groups.
Note: Transformations are reset at the beginning of the draw loop. Calling `scale(2)` inside the draw() function won't cause shapes to grow continuously.

method

scale

` function setup() { createCanvas(100, 100); describe( 'Two white squares on a gray background. The larger square appears at the top-center. The smaller square appears at the top-left.' ); } function draw() { background(200); // Draw a square at (30, 20). square(30, 20, 40); // Scale the coordinate system by a factor of 0.5. scale(0.5); // Draw a square at (30, 20). // It appears at (15, 10) after scaling. square(30, 20, 40); } `
` function setup() { createCanvas(100, 100); describe('A rectangle and a square drawn in white on a gray background.'); } function draw() { background(200); // Draw a square at (30, 20). square(30, 20, 40); // Scale the coordinate system by factors of // 0.5 along the x-axis and // 1.3 along the y-axis. scale(0.5, 1.3); // Draw a square at (30, 20). // It appears as a rectangle at (15, 26) after scaling. square(30, 20, 40); } `
` function setup() { createCanvas(100, 100); describe('A rectangle and a square drawn in white on a gray background.'); } function draw() { background(200); // Draw a square at (30, 20). square(30, 20, 40); // Create a p5.Vector object. let v = createVector(0.5, 1.3); // Scale the coordinate system by factors of // 0.5 along the x-axis and // 1.3 along the y-axis. scale(v); // Draw a square at (30, 20). // It appears as a rectangle at (15, 26) after scaling. square(30, 20, 40); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe( 'A red box and a blue box drawn on a gray background. The red box appears embedded in the blue box.' ); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Style the spheres. noStroke(); // Draw the red sphere. fill('red'); box(); // Scale the coordinate system by factors of // 0.5 along the x-axis and // 1.3 along the y-axis and // 2 along the z-axis. scale(0.5, 1.3, 2); // Draw the blue sphere. fill('blue'); box(); } `

p5

Transform

Transform

s

amount to scale along the positive x-axis.

Number|p5.Vector|Number[]

y

amount to scale along the positive y-axis. Defaults to `s`.

Number

z

amount to scale along the positive z-axis. Defaults to `y`.

Number

scales

vector whose components should be used to scale.

p5.Vector|Number[]

Shears the x-axis so that shapes appear skewed.
By default, the x- and y-axes are perpendicular. The `shearX()` function transforms the coordinate system so that x-coordinates are translated while y-coordinates are fixed.
The first parameter, `angle`, is the amount to shear. For example, calling `shearX(1)` transforms all x-coordinates using the formula `x = x + y * tan(angle)`. `shearX()` interprets angle values using the current angleMode().
By default, transformations accumulate. For example, calling `shearX(1)` twice has the same effect as calling `shearX(2)` once. The push() and pop() functions can be used to isolate transformations within distinct drawing groups.
Note: Transformations are reset at the beginning of the draw loop. Calling `shearX(1)` inside the draw() function won't cause shapes to shear continuously.

method

shearX

angle

angle to shear by in the current angleMode().

Number

` function setup() { createCanvas(100, 100); describe('A white quadrilateral on a gray background.'); } function draw() { background(200); // Shear the coordinate system along the x-axis. shearX(QUARTER_PI); // Draw the square. square(0, 0, 50); } `
` function setup() { createCanvas(100, 100); // Use degrees. angleMode(DEGREES); describe('A white quadrilateral on a gray background.'); } function draw() { background(200); // Shear the coordinate system along the x-axis. shearX(45); // Draw the square. square(0, 0, 50); } `

p5

Transform

Transform

Shears the y-axis so that shapes appear skewed.
By default, the x- and y-axes are perpendicular. The `shearY()` function transforms the coordinate system so that y-coordinates are translated while x-coordinates are fixed.
The first parameter, `angle`, is the amount to shear. For example, calling `shearY(1)` transforms all y-coordinates using the formula `y = y + x * tan(angle)`. `shearY()` interprets angle values using the current angleMode().
By default, transformations accumulate. For example, calling `shearY(1)` twice has the same effect as calling `shearY(2)` once. The push() and pop() functions can be used to isolate transformations within distinct drawing groups.
Note: Transformations are reset at the beginning of the draw loop. Calling `shearY(1)` inside the draw() function won't cause shapes to shear continuously.

method

shearY

angle

angle to shear by in the current angleMode().

Number

` function setup() { createCanvas(100, 100); describe('A white quadrilateral on a gray background.'); } function draw() { background(200); // Shear the coordinate system along the x-axis. shearY(QUARTER_PI); // Draw the square. square(0, 0, 50); } `
` function setup() { createCanvas(100, 100); // Use degrees. angleMode(DEGREES); describe('A white quadrilateral on a gray background.'); } function draw() { background(200); // Shear the coordinate system along the x-axis. shearY(45); // Draw the square. square(0, 0, 50); } `

p5

Transform

Transform

Translates the coordinate system.
By default, the origin `(0, 0)` is at the sketch's top-left corner in 2D mode and center in WebGL mode. The `translate()` function shifts the origin to a different position. Everything drawn after `translate()` is called will appear to be shifted. There are two ways to call `translate()` with parameters that set the origin's position.
The first way to call `translate()` uses numbers to set the amount of translation. The first two parameters, `x` and `y`, set the amount to translate along the positive x- and y-axes. For example, calling `translate(20, 30)` translates the origin 20 pixels along the x-axis and 30 pixels along the y-axis. The third parameter, `z`, is optional. It sets the amount to translate along the positive z-axis. For example, calling `translate(20, 30, 40)` translates the origin 20 pixels along the x-axis, 30 pixels along the y-axis, and 40 pixels along the z-axis.
The second way to call `translate()` uses a p5.Vector object to set the amount of translation. For example, calling `translate(myVector)` uses the x-, y-, and z-components of `myVector` to set the amount to translate along the x-, y-, and z-axes. Doing so is the same as calling `translate(myVector.x, myVector.y, myVector.z)`.
By default, transformations accumulate. For example, calling `translate(10, 0)` twice has the same effect as calling `translate(20, 0)` once. The push() and pop() functions can be used to isolate transformations within distinct drawing groups.
Note: Transformations are reset at the beginning of the draw loop. Calling `translate(10, 0)` inside the draw() function won't cause shapes to move continuously.

method

translate

` function setup() { createCanvas(100, 100); describe('A white circle on a gray background.'); } function draw() { background(200); // Translate the origin to the center. translate(50, 50); // Draw a circle at coordinates (0, 0). circle(0, 0, 40); } `
` function setup() { createCanvas(100, 100); describe( 'Two circles drawn on a gray background. The blue circle on the right overlaps the red circle at the center.' ); } function draw() { background(200); // Translate the origin to the center. translate(50, 50); // Draw the red circle. fill('red'); circle(0, 0, 40); // Translate the origin to the right. translate(25, 0); // Draw the blue circle. fill('blue'); circle(0, 0, 40); } `
` function setup() { createCanvas(100, 100); describe('A white circle moves slowly from left to right on a gray background.'); } function draw() { background(200); // Calculate the x-coordinate. let x = frameCount * 0.2; // Translate the origin. translate(x, 50); // Draw a circle at coordinates (0, 0). circle(0, 0, 40); } `
` function setup() { createCanvas(100, 100); describe('A white circle on a gray background.'); } function draw() { background(200); // Create a p5.Vector object. let v = createVector(50, 50); // Translate the origin by the vector. translate(v); // Draw a circle at coordinates (0, 0). circle(0, 0, 40); } `
` function setup() { createCanvas(100, 100, WEBGL); describe( 'Two spheres sitting side-by-side on gray background. The sphere at the center is red. The sphere on the right is blue.' ); } function draw() { background(200); // Turn on the lights. lights(); // Style the spheres. noStroke(); // Draw the red sphere. fill('red'); sphere(10); // Translate the origin to the right. translate(30, 0, 0); // Draw the blue sphere. fill('blue'); sphere(10); } `

p5

Transform

Transform

x

amount to translate along the positive x-axis.

Number

y

amount to translate along the positive y-axis.

Number

z

amount to translate along the positive z-axis.

Number

vector

vector by which to translate.

p5.Vector

Stores a value in the web browser's local storage.
Web browsers can save small amounts of data using the built-in localStorage object. Data stored in `localStorage` can be retrieved at any point, even after refreshing a page or restarting the browser. Data are stored as key-value pairs.
`storeItem()` makes it easy to store values in `localStorage` and getItem() makes it easy to retrieve them.
The first parameter, `key`, is the name of the value to be stored as a string.
The second parameter, `value`, is the value to be stored. Values can have any type.
Note: Sensitive data such as passwords or personal information shouldn't be stored in `localStorage`.

method

storeItem

key

name of the value.

String

value

value to be stored.

String|Number|Boolean|Object|Array

` function setup() { createCanvas(100, 100); // Store the player's name. storeItem('name', 'Feist'); // Store the player's score. storeItem('score', 1234); describe('The text "Feist: 1234" written in black on a gray background.'); } function draw() { background(200); // Style the text. textAlign(CENTER, CENTER); textSize(14); // Retrieve the name. let name = getItem('name'); // Retrieve the score. let score = getItem('score'); // Display the score. text(`${name}: ${score}`, 50, 50); } `
` function setup() { createCanvas(100, 100); // Create an object. let p = { x: 50, y: 50 }; // Store the object. storeItem('position', p); describe('A white circle on a gray background.'); } function draw() { background(200); // Retrieve the object. let p = getItem('position'); // Draw the circle. circle(p.x, p.y, 30); } `
function setup() { createCanvas(100, 100); // Create a p5.Color object. let c = color('deeppink'); // Store the object. storeItem('color', c); describe('A pink circle on a gray background.'); } function draw() { background(200); // Retrieve the object. let c = getItem('color'); // Style the circle. fill(c); // Draw the circle. circle(50, 50, 30); } `

p5

Data

LocalStorage

Returns a value in the web browser's local storage.
Web browsers can save small amounts of data using the built-in localStorage object. Data stored in `localStorage` can be retrieved at any point, even after refreshing a page or restarting the browser. Data are stored as key-value pairs.
storeItem() makes it easy to store values in `localStorage` and `getItem()` makes it easy to retrieve them.
The first parameter, `key`, is the name of the value to be stored as a string.
The second parameter, `value`, is the value to be retrieved a string. For example, calling `getItem('size')` retrieves the value with the key `size`.
Note: Sensitive data such as passwords or personal information shouldn't be stored in `localStorage`.

method

getItem

key

name of the value.

String

### return
stored item.

String|Number|Boolean|Object|Array

` function setup() { createCanvas(100, 100); // Store the player's name. storeItem('name', 'Feist'); // Store the player's score. storeItem('score', 1234); describe('The text "Feist: 1234" written in black on a gray background.'); } function draw() { background(200); // Style the text. textAlign(CENTER, CENTER); textSize(14); // Retrieve the name. let name = getItem('name'); // Retrieve the score. let score = getItem('score'); // Display the score. text(`${name}: ${score}`, 50, 50); } `
` function setup() { createCanvas(100, 100); // Create an object. let p = { x: 50, y: 50 }; // Store the object. storeItem('position', p); describe('A white circle on a gray background.'); } function draw() { background(200); // Retrieve the object. let p = getItem('position'); // Draw the circle. circle(p.x, p.y, 30); } `
` function setup() { createCanvas(100, 100); // Create a p5.Color object. let c = color('deeppink'); // Store the object. storeItem('color', c); describe('A pink circle on a gray background.'); } function draw() { background(200); // Retrieve the object. let c = getItem('color'); // Style the circle. fill(c); // Draw the circle. circle(50, 50, 30); } `

p5

Data

LocalStorage

Removes all items in the web browser's local storage.
Web browsers can save small amounts of data using the built-in localStorage object. Data stored in `localStorage` can be retrieved at any point, even after refreshing a page or restarting the browser. Data are stored as key-value pairs. Calling `clearStorage()` removes all data from `localStorage`.
Note: Sensitive data such as passwords or personal information shouldn't be stored in `localStorage`.

method

clearStorage

` // Double-click to clear localStorage. function setup() { createCanvas(100, 100); // Store the player's name. storeItem('name', 'Feist'); // Store the player's score. storeItem('score', 1234); describe( 'The text "Feist: 1234" written in black on a gray background. The text "null: null" appears when the user double-clicks.' ); } function draw() { background(200); // Style the text. textAlign(CENTER, CENTER); textSize(14); // Retrieve the name. let name = getItem('name'); // Retrieve the score. let score = getItem('score'); // Display the score. text(`${name}: ${score}`, 50, 50); } // Clear localStorage when the user double-clicks. function doubleClicked() { clearStorage(); } `

p5

Data

LocalStorage

Removes an item from the web browser's local storage.
Web browsers can save small amounts of data using the built-in localStorage object. Data stored in `localStorage` can be retrieved at any point, even after refreshing a page or restarting the browser. Data are stored as key-value pairs.
storeItem() makes it easy to store values in `localStorage` and `removeItem()` makes it easy to delete them.
The parameter, `key`, is the name of the value to remove as a string. For example, calling `removeItem('size')` removes the item with the key `size`.
Note: Sensitive data such as passwords or personal information shouldn't be stored in `localStorage`.

method

removeItem

key

name of the value to remove.

String

` // Double-click to remove an item from localStorage. function setup() { createCanvas(100, 100); // Store the player's name. storeItem('name', 'Feist'); // Store the player's score. storeItem('score', 1234); describe( 'The text "Feist: 1234" written in black on a gray background. The text "Feist: null" appears when the user double-clicks.' ); } function draw() { background(200); // Style the text. textAlign(CENTER, CENTER); textSize(14); // Retrieve the name. let name = getItem('name'); // Retrieve the score. let score = getItem('score'); // Display the score. text(`${name}: ${score}`, 50, 50); } // Remove the word from localStorage when the user double-clicks. function doubleClicked() { removeItem('score'); } `

p5

Data

LocalStorage

Creates a new instance of p5.StringDict using the key-value pair or the object you provide.

method

createStringDict

### return


p5.StringDict

` 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 } `

p5

Data

Dictionary

key



String

value



String

##### return


p5.StringDict

object

object

Object

##### return


p5.StringDict

Creates a new instance of p5.NumberDict using the key-value pair or object you provide.

method

createNumberDict

### return


p5.NumberDict

` 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 } `

p5

Data

Dictionary

key



Number

value



Number

##### return


p5.NumberDict

object

object

Object

##### return


p5.NumberDict

Returns the number of key-value pairs currently stored in the Dictionary.

method

size

### return
the number of key-value pairs in the Dictionary

Integer

` function setup() { let myDictionary = createNumberDict(1, 10); myDictionary.create(2, 20); myDictionary.create(3, 30); print(myDictionary.size()); // logs 3 to the console } `

p5.TypedDict

Data

Dictionary

Returns true if the given key exists in the Dictionary, otherwise returns false.

method

hasKey

key

that you want to look up

Number|String

### return
whether that key exists in Dictionary

Boolean

` function setup() { let myDictionary = createStringDict('p5', 'js'); print(myDictionary.hasKey('p5')); // logs true to console } `

p5.TypedDict

Data

Dictionary

Returns the value stored at the given key.

method

get

the

key you want to access

Number|String

### return
the value stored at that key

Number|String

` function setup() { let myDictionary = createStringDict('p5', 'js'); let myValue = myDictionary.get('p5'); print(myValue === 'js'); // logs true to console } `

p5.TypedDict

Data

Dictionary

Updates the value associated with the given key in case it already exists in the Dictionary. Otherwise a new key-value pair is added.

method

set

key



Number|String

value



Number|String

` function setup() { let myDictionary = createStringDict('p5', 'js'); myDictionary.set('p5', 'JS'); myDictionary.print(); // logs "key: p5 - value: JS" to console } `

p5.TypedDict

Data

Dictionary

private helper function to handle the user passing in objects during construction or calls to create()

p5.TypedDict

Data

Dictionary

Creates a new key-value pair in the Dictionary.

method

create

` function setup() { let myDictionary = createStringDict('p5', 'js'); myDictionary.create('happy', 'coding'); myDictionary.print(); // above logs "key: p5 - value: js, key: happy - value: coding" to console } `

p5.TypedDict

Data

Dictionary

key



Number|String

value



Number|String

obj

key/value pair

Object

Removes all previously stored key-value pairs from the Dictionary.

method

clear

` function setup() { let myDictionary = createStringDict('p5', 'js'); print(myDictionary.hasKey('p5')); // prints 'true' myDictionary.clear(); print(myDictionary.hasKey('p5')); // prints 'false' } `

p5.TypedDict

Data

Dictionary

Removes the key-value pair stored at the given key from the Dictionary.

method

remove

key

for the pair to remove

Number|String

` function setup() { let myDictionary = createStringDict('p5', 'js'); myDictionary.create('happy', 'coding'); myDictionary.print(); // above logs "key: p5 - value: js, key: happy - value: coding" to console myDictionary.remove('p5'); myDictionary.print(); // above logs "key: happy value: coding" to console } `

p5.TypedDict

Data

Dictionary

Logs the set of items currently stored in the Dictionary to the console.

method

print

` function setup() { let myDictionary = createStringDict('p5', 'js'); myDictionary.create('happy', 'coding'); myDictionary.print(); // above logs "key: p5 - value: js, key: happy - value: coding" to console } `

p5.TypedDict

Data

Dictionary

Converts the Dictionary into a CSV file for local download.

method

saveTable

` 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) { createStringDict({ john: 1940, paul: 1942, george: 1943, ringo: 1940 }).saveTable('beatles'); } } `

p5.TypedDict

Data

Dictionary

Converts the Dictionary into a JSON file for local download.

method

saveJSON

` 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) { createStringDict({ john: 1940, paul: 1942, george: 1943, ringo: 1940 }).saveJSON('beatles'); } } `

p5.TypedDict

Data

Dictionary

private helper function to ensure that the user passed in valid values for the Dictionary type

p5.TypedDict

Data

Dictionary

private helper function to ensure that the user passed in valid values for the Dictionary type

p5.NumberDict

Data

Dictionary

Add the given number to the value currently stored at the given key. The sum then replaces the value previously stored in the Dictionary.

method

add

Key

for the value you wish to add to

Number

Number

to add to the value

Number

` function setup() { let myDictionary = createNumberDict(2, 5); myDictionary.add(2, 2); print(myDictionary.get(2)); // logs 7 to console. } `

p5.NumberDict

Data

Dictionary

Subtract the given number from the value currently stored at the given key. The difference then replaces the value previously stored in the Dictionary.

method

sub

Key

for the value you wish to subtract from

Number

Number

to subtract from the value

Number

` function setup() { let myDictionary = createNumberDict(2, 5); myDictionary.sub(2, 2); print(myDictionary.get(2)); // logs 3 to console. } `

p5.NumberDict

Data

Dictionary

Multiply the given number with the value currently stored at the given key. The product then replaces the value previously stored in the Dictionary.

method

mult

Key

for value you wish to multiply

Number

Amount

to multiply the value by

Number

` function setup() { let myDictionary = createNumberDict(2, 4); myDictionary.mult(2, 2); print(myDictionary.get(2)); // logs 8 to console. } `

p5.NumberDict

Data

Dictionary

Divide the given number with the value currently stored at the given key. The quotient then replaces the value previously stored in the Dictionary.

method

div

Key

for value you wish to divide

Number

Amount

to divide the value by

Number

` function setup() { let myDictionary = createNumberDict(2, 8); myDictionary.div(2, 2); print(myDictionary.get(2)); // logs 4 to console. } `

p5.NumberDict

Data

Dictionary

private helper function for finding lowest or highest value the argument 'flip' is used to flip the comparison arrow from 'less than' to 'greater than'

p5.NumberDict

Data

Dictionary

Return the lowest number currently stored in the Dictionary.

method

minValue

### return


Number

` function setup() { let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 }); let lowestValue = myDictionary.minValue(); // value is -10 print(lowestValue); } `

p5.NumberDict

Data

Dictionary

Return the highest number currently stored in the Dictionary.

method

maxValue

### return


Number

` function setup() { let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 }); let highestValue = myDictionary.maxValue(); // value is 3 print(highestValue); } `

p5.NumberDict

Data

Dictionary

private helper function for finding lowest or highest key the argument 'flip' is used to flip the comparison arrow from 'less than' to 'greater than'

p5.NumberDict

Data

Dictionary

Return the lowest key currently used in the Dictionary.

method

minKey

### return


Number

` function setup() { let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 }); let lowestKey = myDictionary.minKey(); // value is 1.2 print(lowestKey); } `

p5.NumberDict

Data

Dictionary

Return the highest key currently used in the Dictionary.

method

maxKey

### return


Number

` function setup() { let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 }); let highestKey = myDictionary.maxKey(); // value is 4 print(highestKey); } `

p5.NumberDict

Data

Dictionary

Searches the page for the first element that matches the given CSS selector string.
The selector string can be an ID, class, tag name, or a combination. `select()` returns a p5.Element object if it finds a match and `null` if not.
The second parameter, `container`, is optional. It specifies a container to search within. `container` can be CSS selector string, a p5.Element object, or an HTMLElement object.

method

select

selectors

CSS selector string of element to search for.

String

container

CSS selector string, p5.Element, or HTMLElement to search within.

String|p5.Element|HTMLElement

### return
p5.Element containing the element.

p5.Element|null

` function setup() { createCanvas(100, 100); background(200); // Select the canvas by its tag. let cnv = select('canvas'); cnv.style('border', '5px deeppink dashed'); describe('A gray square with a dashed pink border.'); } `
` function setup() { let cnv = createCanvas(100, 100); // Add a class attribute to the canvas. cnv.class('pinkborder'); background(200); // Select the canvas by its class. cnv = select('.pinkborder'); // Style its border. cnv.style('border', '5px deeppink dashed'); describe('A gray square with a dashed pink border.'); } `
` function setup() { let cnv = createCanvas(100, 100); // Set the canvas' ID. cnv.id('mycanvas'); background(200); // Select the canvas by its ID. cnv = select('#mycanvas'); // Style its border. cnv.style('border', '5px deeppink dashed'); describe('A gray square with a dashed pink border.'); } `

p5

DOM

DOM

Searches the page for all elements that matches the given CSS selector string.
The selector string can be an ID, class, tag name, or a combination. `selectAll()` returns an array of p5.Element objects if it finds any matches and an empty array if none are found.
The second parameter, `container`, is optional. It specifies a container to search within. `container` can be CSS selector string, a p5.Element object, or an HTMLElement object.

method

selectAll

selectors

CSS selector string of element to search for.

String

container

CSS selector string, p5.Element, or HTMLElement to search within.

String|p5.Element|HTMLElement

### return
array of p5.Elements containing any elements found.

p5.Element[]

` function setup() { createCanvas(100, 100); // Create three buttons. createButton('1'); createButton('2'); createButton('3'); // Select the buttons by their tag. let buttons = selectAll('button'); // Position the buttons. for (let i = 0; i < 3; i += 1) { buttons[i].position(0, i * 30); } describe('Three buttons stacked vertically. The buttons are labeled, "1", "2", and "3".'); } `
` function setup() { // Create three buttons and position them. let b1 = createButton('1'); b1.position(0, 0); let b2 = createButton('2'); b2.position(0, 30); let b3 = createButton('3'); b3.position(0, 60); // Add a class attribute to each button. b1.class('btn'); b2.class('btn btn-pink'); b3.class('btn'); // Select the buttons by their class. let buttons = selectAll('.btn'); let pinkButtons = selectAll('.btn-pink'); // Style the selected buttons. buttons.forEach(setFont); pinkButtons.forEach(setColor); describe('Three buttons stacked vertically. The buttons are labeled, "1", "2", and "3". Buttons "1" and "3" are gray. Button "2" is pink.'); } // Set a button's font to Comic Sans MS. function setFont(btn) { btn.style('font-family', 'Comic Sans MS'); } // Set a button's background and font color. function setColor(btn) { btn.style('background', 'deeppink'); btn.style('color', 'white'); } `

p5

DOM

DOM

Helper function for select and selectAll

p5

DOM

DOM

Helper function for getElement and getElements.

p5

DOM

DOM

Removes all elements created by p5.js, including any event handlers.
There are two exceptions: canvas elements created by createCanvas() and p5.Render objects created by createGraphics().

method

removeElements

` function setup() { createCanvas(100, 100); background(200); // Create a paragraph element and place // it in the middle of the canvas. let p = createP('p5*js'); p.position(25, 25); describe('A gray square with the text "p5*js" written in its center. The text disappears when the mouse is pressed.'); } // Remove all elements when the mouse is pressed. function mousePressed() { removeElements(); } `
` let slider; function setup() { createCanvas(100, 100); // Create a paragraph element and place // it at the top of the canvas. let p = createP('p5*js'); p.position(25, 25); // Create a slider element and place it // beneath the canvas. slider = createSlider(0, 255, 200); slider.position(0, 100); describe('A gray square with the text "p5*js" written in its center and a range slider beneath it. The square changes color when the slider is moved. The text and slider disappear when the square is double-clicked.'); } function draw() { // Use the slider value to change the background color. let g = slider.value(); background(g); } // Remove all elements when the mouse is double-clicked. function doubleClicked() { removeElements(); } `

p5

DOM

DOM

Calls a function when the element changes.
Calling `myElement.changed(false)` disables the function.

method

changed

fxn

function to call when the element changes. `false` disables the function.

Function|Boolean

` let dropdown; function setup() { createCanvas(100, 100); background(200); // Create a dropdown menu and add a few color options. dropdown = createSelect(); dropdown.position(0, 0); dropdown.option('red'); dropdown.option('green'); dropdown.option('blue'); // Call paintBackground() when the color option changes. dropdown.changed(paintBackground); describe('A gray square with a dropdown menu at the top. The square changes color when an option is selected.'); } // Paint the background with the selected color. function paintBackground() { let c = dropdown.value(); background(c); } `
` let checkbox; function setup() { createCanvas(100, 100); background(200); // Create a checkbox and place it beneath the canvas. checkbox = createCheckbox(' circle'); checkbox.position(0, 100); // Call repaint() when the checkbox changes. checkbox.changed(repaint); describe('A gray square with a checkbox underneath it that says "circle". A white circle appears when the box is checked and disappears otherwise.'); } // Paint the background gray and determine whether to draw a circle. function repaint() { background(200); if (checkbox.checked() === true) { circle(50, 50, 30); } } `

p5

DOM

DOM

Calls a function when the element receives input.
`myElement.input()` is often used to with text inputs and sliders. Calling `myElement.input(false)` disables the function.

method

input

fxn

function to call when input is detected within the element. `false` disables the function.

Function|Boolean

` let slider; function setup() { createCanvas(100, 100); background(200); // Create a slider and place it beneath the canvas. slider = createSlider(0, 255, 200); slider.position(0, 100); // Call repaint() when the slider changes. slider.input(repaint); describe('A gray square with a range slider underneath it. The background changes shades of gray when the slider is moved.'); } // Paint the background using slider's value. function repaint() { let g = slider.value(); background(g); } `
` let input; function setup() { createCanvas(100, 100); background(200); // Create an input and place it beneath the canvas. input = createInput(''); input.position(0, 100); // Call repaint() when input is detected. input.input(repaint); describe('A gray square with a text input bar beneath it. Any text written in the input appears in the middle of the square.'); } // Paint the background gray and display the input's value. function repaint() { background(200); let msg = input.value(); text(msg, 5, 50); } `

p5

DOM

DOM

Helpers for create methods.

p5

DOM

DOM

Creates a `<div></div>` element.
`<div></div>` elements are commonly used as containers for other elements.
The parameter `html` is optional. It accepts a string that sets the inner HTML of the new `<div></div>`.

method

createDiv

html

inner HTML for the new `<div></div>` element.

String

### return
new p5.Element object.

p5.Element

` function setup() { createCanvas(100, 100); background(200); // Create a div element and set its position. let div = createDiv('p5*js'); div.position(25, 35); describe('A gray square with the text "p5*js" written in its center.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create an h3 element within the div. let div = createDiv('
### p5*js
'); div.position(20, 5); describe('A gray square with the text "p5*js" written in its center.'); } `

p5

DOM

DOM

Creates a paragraph element.
`<p></p>` elements are commonly used for paragraph-length text.
The parameter `html` is optional. It accepts a string that sets the inner HTML of the new `<p></p>`.

method

createP

html

inner HTML for the new `<p></p>` element.

String

### return
new p5.Element object.

p5.Element

` function setup() { createCanvas(100, 100); background(200); // Create a paragraph element and set its position. let p = createP('Tell me a story.'); p.position(5, 0); describe('A gray square displaying the text "Tell me a story." written in black.'); } `

p5

DOM

DOM

Creates a `<span></span>` element.
`<span></span>` elements are commonly used as containers for inline elements. For example, a `<span></span>` can hold part of a sentence that's a different style.
The parameter `html` is optional. It accepts a string that sets the inner HTML of the new `<span></span>`.

method

createSpan

html

inner HTML for the new `<span></span>` element.

String

### return
new p5.Element object.

p5.Element

` function setup() { createCanvas(100, 100); background(200); // Create a span element and set its position. let span = createSpan('p5*js'); span.position(25, 35); describe('A gray square with the text "p5*js" written in its center.'); } `
` function setup() { background(200); // Create a div element as a container. let div = createDiv(); // Place the div at the center. div.position(25, 35); // Create a span element. let s1 = createSpan('p5'); // Create a second span element. let s2 = createSpan('*'); // Set the second span's font color. s2.style('color', 'deeppink'); // Create a third span element. let s3 = createSpan('js'); // Add all the spans to the container div. s1.parent(div); s2.parent(div); s3.parent(div); describe('A gray square with the text "p5*js" written in black at its center. The asterisk is pink.'); } `

p5

DOM

DOM

Creates an `<img>` element that can appear outside of the canvas.
The first parameter, `src`, is a string with the path to the image file. `src` should be a relative path, as in `'assets/image.png'`, or a URL, as in `'https://example.com/image.png'`.
The second parameter, `alt`, is a string with the alternate text for the image. An empty string `''` can be used for images that aren't displayed.
The third parameter, `crossOrigin`, is optional. It's a string that sets the crossOrigin property of the image. Use `'anonymous'` or `'use-credentials'` to fetch the image with cross-origin access.
The fourth parameter, `callback`, is also optional. It sets a function to call after the image loads. The new image is passed to the callback function as a p5.Element object.

method

createImg

### return
new p5.Element object.

p5.Element

` function setup() { createCanvas(100, 100); background(200); let img = createImg( 'https://p5js.org/assets/img/asterisk-01.png', 'The p5.js magenta asterisk.' ); img.position(0, -10); describe('A gray square with a magenta asterisk in its center.'); } `

p5

DOM

DOM

src

relative path or URL for the image.

String

alt

alternate text for the image.

String

##### return
new p5.Element object.

p5.Element

src



String

alt



String

crossOrigin

crossOrigin property to use when fetching the image.

String

successCallback

function to call once the image loads. The new image will be passed to the function as a p5.Element object.

Function

##### return
new p5.Element object.

p5.Element

Creates an `<a></a>` element that links to another web page.
The first parmeter, `href`, is a string that sets the URL of the linked page.
The second parameter, `html`, is a string that sets the inner HTML of the link. It's common to use text, images, or buttons as links.
The third parameter, `target`, is optional. It's a string that tells the web browser where to open the link. By default, links open in the current browser tab. Passing `'_blank'` will cause the link to open in a new browser tab. MDN describes a few other options.

method

createA

href

URL of linked page.

String

html

inner HTML of link element to display.

String

target

target where the new link should open, either `'_blank'`, `'_self'`, `'_parent'`, or `'_top'`.

String

### return
new p5.Element object.

p5.Element

` function setup() { createCanvas(100, 100); background(200); // Create an anchor element that links to p5js.org. let a = createA('https://p5js.org/', 'p5*js'); a.position(25, 35); describe('The text "p5*js" written at the center of a gray square.'); } `
` function setup() { background(200); // Create an anchor tag that links to p5js.org. // Open the link in a new tab. let a = createA('https://p5js.org/', 'p5*js', '_blank'); a.position(25, 35); describe('The text "p5*js" written at the center of a gray square.'); } `

p5

DOM

DOM

p5

DOM

DOM

Creates a slider `<input></input>` element.
Range sliders are useful for quickly selecting numbers from a given range.
The first two parameters, `min` and `max`, are numbers that set the slider's minimum and maximum.
The third parameter, `value`, is optional. It's a number that sets the slider's default value.
The fourth parameter, `step`, is also optional. It's a number that sets the spacing between each value in the slider's range. Setting `step` to 0 allows the slider to move smoothly from `min` to `max`.

method

createSlider

min

minimum value of the slider.

Number

max

maximum value of the slider.

Number

value

default value of the slider.

Number

step

size for each step in the slider's range.

Number

### return
new p5.Element object.

p5.Element

` let slider; function setup() { createCanvas(100, 100); // Create a slider and place it at the top of the canvas. slider = createSlider(0, 255); slider.position(10, 10); slider.size(80); describe('A dark gray square with a range slider at the top. The square changes color when the slider is moved.'); } function draw() { // Use the slider as a grayscale value. let g = slider.value(); background(g); } `
` let slider; function setup() { createCanvas(100, 100); // Create a slider and place it at the top of the canvas. // Set its default value to 0. slider = createSlider(0, 255, 0); slider.position(10, 10); slider.size(80); describe('A black square with a range slider at the top. The square changes color when the slider is moved.'); } function draw() { // Use the slider as a grayscale value. let g = slider.value(); background(g); } `
` let slider; function setup() { createCanvas(100, 100); // Create a slider and place it at the top of the canvas. // Set its default value to 0. // Set its step size to 50. slider = createSlider(0, 255, 0, 50); slider.position(10, 10); slider.size(80); describe('A black square with a range slider at the top. The square changes color when the slider is moved.'); } function draw() { // Use the slider as a grayscale value. let g = slider.value(); background(g); } `
` let slider; function setup() { createCanvas(100, 100); // Create a slider and place it at the top of the canvas. // Set its default value to 0. // Set its step size to 0 so that it moves smoothly. slider = createSlider(0, 255, 0, 0); slider.position(10, 10); slider.size(80); describe('A black square with a range slider at the top. The square changes color when the slider is moved.'); } function draw() { // Use the slider as a grayscale value. let g = slider.value(); background(g); } `

p5

DOM

DOM

Creates a `<button></button>` element.
The first parameter, `label`, is a string that sets the label displayed on the button.
The second parameter, `value`, is optional. It's a string that sets the button's value. See MDN for more details.

method

createButton

label

label displayed on the button.

String

value

value of the button.

String

### return
new p5.Element object.

p5.Element

` function setup() { createCanvas(100, 100); background(200); // Create a button and place it beneath the canvas. let button = createButton('click me'); button.position(0, 100); // Call repaint() when the button is pressed. button.mousePressed(repaint); describe('A gray square with a button that says "click me" beneath it. The square changes color when the button is clicked.'); } // Change the background color. function repaint() { let g = random(255); background(g); } `
` let button; function setup() { createCanvas(100, 100); background(200); // Create a button and set its value to 0. // Place the button beneath the canvas. button = createButton('click me', 'red'); button.position(0, 100); // Call randomColor() when the button is pressed. button.mousePressed(randomColor); describe('A red square with a button that says "click me" beneath it. The square changes color when the button is clicked.'); } function draw() { // Use the button's value to set the background color. let c = button.value(); background(c); } // Set the button's value to a random color. function randomColor() { let c = random(['red', 'green', 'blue', 'yellow']); button.value(c); } `

p5

DOM

DOM

Creates a checkbox `<input></input>` element.
Checkboxes extend the p5.Element class with a `checked()` method. Calling `myBox.checked()` returns `true` if it the box is checked and `false` if not.
The first parameter, `label`, is optional. It's a string that sets the label to display next to the checkbox.
The second parameter, `value`, is also optional. It's a boolean that sets the checkbox's value.

method

createCheckbox

label

label displayed after the checkbox.

String

value

value of the checkbox. Checked is `true` and unchecked is `false`.

Boolean

### return
new p5.Element object.

p5.Element

` let checkbox; function setup() { createCanvas(100, 100); // Create a checkbox and place it beneath the canvas. checkbox = createCheckbox(); checkbox.position(0, 100); describe('A black square with a checkbox beneath it. The square turns white when the box is checked.'); } function draw() { // Use the checkbox to set the background color. if (checkbox.checked()) { background(255); } else { background(0); } } `
` let checkbox; function setup() { createCanvas(100, 100); // Create a checkbox and place it beneath the canvas. // Label the checkbox "white". checkbox = createCheckbox(' white'); checkbox.position(0, 100); describe('A black square with a checkbox labeled "white" beneath it. The square turns white when the box is checked.'); } function draw() { // Use the checkbox to set the background color. if (checkbox.checked()) { background(255); } else { background(0); } } `
` let checkbox; function setup() { createCanvas(100, 100); // Create a checkbox and place it beneath the canvas. // Label the checkbox "white" and set its value to true. checkbox = createCheckbox(' white', true); checkbox.position(0, 100); describe('A white square with a checkbox labeled "white" beneath it. The square turns black when the box is unchecked.'); } function draw() { // Use the checkbox to set the background color. if (checkbox.checked()) { background(255); } else { background(0); } } `

p5

DOM

DOM

Creates a dropdown menu `<select></select>` element.
The parameter is optional. If `true` is passed, as in `let mySelect = createSelect(true)`, then the dropdown will support multiple selections. If an existing `<select></select>` element is passed, as in `let mySelect = createSelect(otherSelect)`, the existing element will be wrapped in a new p5.Element object.
Dropdowns extend the p5.Element class with a few helpful methods for managing options:
    * `mySelect.option(name, [value])` adds an option to the menu. The first paremeter, `name`, is a string that sets the option's name and value. The second parameter, `value`, is optional. If provided, it sets the value that corresponds to the key `name`. If an option with `name` already exists, its value is changed to `value`.
    * `mySelect.value()` returns the currently-selected option's value.
    * `mySelect.selected()` returns the currently-selected option.
    * `mySelect.selected(option)` selects the given option by default.
    * `mySelect.disable()` marks the whole dropdown element as disabled.
    * `mySelect.disable(option)` marks a given option as disabled.
    * `mySelect.enable()` marks the whole dropdown element as enabled.
    * `mySelect.enable(option)` marks a given option as enabled.

method

createSelect

### return
new p5.Element object.

p5.Element

` let mySelect; function setup() { createCanvas(100, 100); // Create a dropdown and place it beneath the canvas. mySelect = createSelect(); mySelect.position(0, 100); // Add color options. mySelect.option('red'); mySelect.option('green'); mySelect.option('blue'); mySelect.option('yellow'); // Set the selected option to "red". mySelect.selected('red'); describe('A red square with a dropdown menu beneath it. The square changes color when a new color is selected.'); } function draw() { // Use the selected value to paint the background. let c = mySelect.selected(); background(c); } `
` let mySelect; function setup() { createCanvas(100, 100); // Create a dropdown and place it beneath the canvas. mySelect = createSelect(); mySelect.position(0, 100); // Add color options. mySelect.option('red'); mySelect.option('green'); mySelect.option('blue'); mySelect.option('yellow'); // Set the selected option to "red". mySelect.selected('red'); // Disable the "yellow" option. mySelect.disable('yellow'); describe('A red square with a dropdown menu beneath it. The square changes color when a new color is selected.'); } function draw() { // Use the selected value to paint the background. let c = mySelect.selected(); background(c); } `
` let mySelect; function setup() { createCanvas(100, 100); // Create a dropdown and place it beneath the canvas. mySelect = createSelect(); mySelect.position(0, 100); // Add color options with names and values. mySelect.option('one', 'red'); mySelect.option('two', 'green'); mySelect.option('three', 'blue'); mySelect.option('four', 'yellow'); // Set the selected option to "one". mySelect.selected('one'); describe('A red square with a dropdown menu beneath it. The square changes color when a new color is selected.'); } function draw() { // Use the selected value to paint the background. let c = mySelect.selected(); background(c); } `
` // Hold CTRL to select multiple options on Windows and Linux. // Hold CMD to select multiple options on macOS. let mySelect; function setup() { createCanvas(100, 100); // Create a dropdown and allow multiple selections. // Place it beneath the canvas. mySelect = createSelect(true); mySelect.position(0, 100); // Add color options. mySelect.option('red'); mySelect.option('green'); mySelect.option('blue'); mySelect.option('yellow'); describe('A gray square with a dropdown menu beneath it. Colorful circles appear when their color is selected.'); } function draw() { background(200); // Use the selected value(s) to draw circles. let colors = mySelect.selected(); for (let i = 0; i < colors.length; i += 1) { // Calculate the x-coordinate. let x = 10 + i * 20; // Access the color. let c = colors[i]; // Draw the circle. fill(c); circle(x, 50, 20); } } `

p5

DOM

DOM

multiple

support multiple selections.

Boolean

##### return
new p5.Element object.

p5.Element

existing

select element to wrap, either as a p5.Element or a HTMLSelectElement.

Object

##### return


p5.Element

Creates a radio button element.
The parameter is optional. If a string is passed, as in `let myRadio = createSelect('food')`, then each radio option will have `"food"` as its `name` parameter: `<input name="food">`. If an existing `<div></div>` or `<span></span>` element is passed, as in `let myRadio = createSelect(container)`, it will become the radio button's parent element.
Radio buttons extend the p5.Element class with a few helpful methods for managing options:
    * `myRadio.option(value, [label])` adds an option to the menu. The first parameter, `value`, is a string that sets the option's value and label. The second parameter, `label`, is optional. If provided, it sets the label displayed for the `value`. If an option with `value` already exists, its label is changed and its value is returned.
    * `myRadio.value()` returns the currently-selected option's value.
    * `myRadio.selected()` returns the currently-selected option.
    * `myRadio.selected(value)` selects the given option and returns it as an `HTMLInputElement`.
    * `myRadio.disable(shouldDisable)` Disables the radio button if `true` is passed, and enables it if `false` is passed.

method

createRadio

### return
new p5.Element object.

p5.Element

` let style = document.createElement('style'); style.innerHTML = ` .p5-radio label { display: flex; align-items: center; } .p5-radio input { margin-right: 5px; } `; document.head.appendChild(style); let myRadio; function setup() { createCanvas(100, 100); // Create a radio button element and place it // in the top-left corner. myRadio = createRadio(); myRadio.position(0, 0); myRadio.class('p5-radio'); myRadio.size(60); // Add a few color options. myRadio.option('red'); myRadio.option('yellow'); myRadio.option('blue'); // Choose a default option. myRadio.selected('yellow'); describe('A yellow square with three color options listed, "red", "yellow", and "blue". The square changes color when the user selects a new option.'); } function draw() { // Set the background color using the radio button. let g = myRadio.value(); background(g); } `
` let myRadio; function setup() { createCanvas(100, 100); // Create a radio button element and place it // in the top-left corner. myRadio = createRadio(); myRadio.position(0, 0); myRadio.size(50); // Add a few color options. // Color values are labeled with // emotions they evoke. myRadio.option('red', 'love'); myRadio.option('yellow', 'joy'); myRadio.option('blue', 'trust'); // Choose a default option. myRadio.selected('yellow'); describe('A yellow square with three options listed, "love", "joy", and "trust". The square changes color when the user selects a new option.'); } function draw() { // Set the background color using the radio button. let c = myRadio.value(); background(c); } `
` let myRadio; function setup() { createCanvas(100, 100); // Create a radio button element and place it // in the top-left corner. myRadio = createRadio(); myRadio.position(0, 0); myRadio.class('p5-radio'); myRadio.size(50); // Add a few color options. myRadio.option('red'); myRadio.option('yellow'); myRadio.option('blue'); // Choose a default option. myRadio.selected('yellow'); // Create a button and place it beneath the canvas. let btn = createButton('disable'); btn.position(0, 100); // Call disableRadio() when btn is pressed. btn.mousePressed(disableRadio); describe('A yellow square with three options listed, "red", "yellow", and "blue". The square changes color when the user selects a new option. A "disable" button beneath the canvas disables the color options when pressed.'); } function draw() { // Set the background color using the radio button. let c = myRadio.value(); background(c); } // Disable myRadio. function disableRadio() { myRadio.disable(true); } `

p5

DOM

DOM

containerElement

container HTML Element, either a `<div></div>` or `<span></span>`.

Object

##### return
new p5.Element object.

p5.Element

name

name parameter assigned to each option's `<input></input>` element.

String

##### return
new p5.Element object.

p5.Element

##### return
new p5.Element object.

p5.Element

Creates a color picker element.
The parameter, `value`, is optional. If a color string or p5.Color object is passed, it will set the default color.
Color pickers extend the p5.Element class with a couple of helpful methods for managing colors:
    * `myPicker.value()` returns the current color as a hex string in the format `'#rrggbb'`.
    * `myPicker.color()` returns the current color as a p5.Color object.

method

createColorPicker

value

default color as a CSS color string.

String|p5.Color

### return
new p5.Element object.

p5.Element

` let myPicker; function setup() { createCanvas(100, 100); // Create a color picker and set its position. myPicker = createColorPicker('deeppink'); myPicker.position(0, 100); describe('A pink square with a color picker beneath it. The square changes color when the user picks a new color.'); } function draw() { // Use the color picker to paint the background. let c = myPicker.color(); background(c); } `
` let myPicker; function setup() { createCanvas(100, 100); // Create a color picker and set its position. myPicker = createColorPicker('deeppink'); myPicker.position(0, 100); describe('A number with the format "#rrggbb" is displayed on a pink canvas. The background color and number change when the user picks a new color.'); } function draw() { // Use the color picker to paint the background. let c = myPicker.value(); background(c); // Display the current color as a hex string. text(c, 25, 55); } `

p5

DOM

DOM

Creates a text `<input></input>` element.
Call `myInput.size()` to set the length of the text box.
The first parameter, `value`, is optional. It's a string that sets the input's default value. The input is blank by default.
The second parameter, `type`, is also optional. It's a string that specifies the type of text being input. See MDN for a full list of options. The default is `'text'`.

method

createInput

### return
new p5.Element object.

p5.Element

` let myInput; function setup() { createCanvas(100, 100); // Create an input element and place it // beneath the canvas. myInput = createInput(); myInput.position(0, 100); describe('A gray square with a text box beneath it. The text in the square changes when the user types something new in the input bar.'); } function draw() { background(200); // Use the input to display a message. let msg = myInput.value(); text(msg, 25, 55); } `
` let myInput; function setup() { createCanvas(100, 100); // Create an input element and place it // beneath the canvas. Set its default // text to "hello!". myInput = createInput('hello!'); myInput.position(0, 100); describe('The text "hello!" written at the center of a gray square. A text box beneath the square also says "hello!". The text in the square changes when the user types something new in the input bar.'); } function draw() { background(200); // Use the input to display a message. let msg = myInput.value(); text(msg, 25, 55); } `

p5

DOM

DOM

value

default value of the input box. Defaults to an empty string `''`.

String

type

type of input. Defaults to `'text'`.

String

##### return
new p5.Element object.

p5.Element

value



String

##### return


p5.Element

Creates an `<input></input>` element of type `'file'`.
`createFileInput()` allows users to select local files for use in a sketch. It returns a p5.File object.
The first parameter, `callback`, is a function that's called when the file loads. The callback function should have one parameter, `file`, that's a p5.File object.
The second parameter, `multiple`, is optional. It's a boolean value that allows loading multiple files if set to `true`. If `true`, `callback` will be called once per file.

method

createFileInput

callback

function to call once the file loads.

Function

multiple

allow multiple files to be selected.

Boolean

### return
new p5.File object.

p5.File

` // Use the file input to select an image to // load and display. let input; let img; function setup() { createCanvas(100, 100); // Create a file input and place it beneath // the canvas. input = createFileInput(handleImage); input.position(0, 100); describe('A gray square with a file input beneath it. If the user selects an image file to load, it is displayed on the square.'); } function draw() { background(200); // Draw the image if loaded. if (img) { image(img, 0, 0, width, height); } } // Create an image if the file is an image. function handleImage(file) { if (file.type === 'image') { img = createImg(file.data, ''); img.hide(); } else { img = null; } } `
` // Use the file input to select multiple images // to load and display. let input; let images = []; function setup() { // Create a file input and place it beneath // the canvas. Allow it to load multiple files. input = createFileInput(handleImage, true); input.position(0, 100); } function draw() { background(200); // Draw the images if loaded. Each image // is drawn 20 pixels lower than the // previous image. for (let i = 0; i < images.length; i += 1) { // Calculate the y-coordinate. let y = i * 20; // Draw the image. image(images[i], 0, y, 100, 100); } describe('A gray square with a file input beneath it. If the user selects multiple image files to load, they are displayed on the square.'); } // Create an image if the file is an image, // then add it to the images array. function handleImage(file) { if (file.type === 'image') { let img = createImg(file.data, ''); img.hide(); images.push(img); } } `

p5

DOM

DOM

p5

DOM

DOM

Creates a `<video>` element for simple audio/video playback.
`createVideo()` returns a new p5.MediaElement object. Videos are shown by default. They can be hidden by calling `video.hide()` and drawn to the canvas using image().
The first parameter, `src`, is the path the video. If a single string is passed, as in `'assets/topsecret.mp4'`, a single video is loaded. An array of strings can be used to load the same video in different formats. For example, `['assets/topsecret.mp4', 'assets/topsecret.ogv', 'assets/topsecret.webm']`. This is useful for ensuring that the video can play across different browsers with different capabilities. See MDN for more information about supported formats.
The second parameter, `callback`, is optional. It's a function to call once the video is ready to play.

method

createVideo

src

path to a video file, or an array of paths for supporting different browsers.

String|String[]

callback

function to call once the video is ready to play.

Function

### return
new p5.MediaElement object.

p5.MediaElement

` function setup() { noCanvas(); // Load a video and add it to the page. // Note: this may not work in some browsers. let video = createVideo('assets/small.mp4'); // Show the default video controls. video.showControls(); describe('A video of a toy robot with playback controls beneath it.'); } `
` function setup() { noCanvas(); // Load a video and add it to the page. // Provide an array options for different file formats. let video = createVideo( ['assets/small.mp4', 'assets/small.ogv', 'assets/small.webm'] ); // Show the default video controls. video.showControls(); describe('A video of a toy robot with playback controls beneath it.'); } `
` let video; function setup() { noCanvas(); // Load a video and add it to the page. // Provide an array options for different file formats. // Call mute() once the video loads. video = createVideo( ['assets/small.mp4', 'assets/small.ogv', 'assets/small.webm'], muteVideo ); // Show the default video controls. video.showControls(); describe('A video of a toy robot with playback controls beneath it.'); } // Mute the video once it loads. function muteVideo() { video.volume(0); } `

p5

DOM

DOM

p5

DOM

DOM

Creates a hidden `<audio>` element for simple audio playback.
`createAudio()` returns a new p5.MediaElement object.
The first parameter, `src`, is the path the video. If a single string is passed, as in `'assets/video.mp4'`, a single video is loaded. An array of strings can be used to load the same video in different formats. For example, `['assets/video.mp4', 'assets/video.ogv', 'assets/video.webm']`. This is useful for ensuring that the video can play across different browsers with different capabilities. See MDN for more information about supported formats.
The second parameter, `callback`, is optional. It's a function to call once the audio is ready to play.

method

createAudio

src

path to an audio file, or an array of paths for supporting different browsers.

String|String[]

callback

function to call once the audio is ready to play.

Function

### return
new p5.MediaElement object.

p5.MediaElement

` function setup() { noCanvas(); // Load the audio. let beat = createAudio('assets/beat.mp3'); // Show the default audio controls. beat.showControls(); describe('An audio beat plays when the user double-clicks the square.'); } `

p5

DOM

DOM

p5

DOM

DOM

Creates a `<video>` element that "captures" the audio/video stream from the webcam and microphone.
`createCapture()` returns a new p5.MediaElement object. Videos are shown by default. They can be hidden by calling `capture.hide()` and drawn to the canvas using image().
The first parameter, `type`, is optional. It sets the type of capture to use. By default, `createCapture()` captures both audio and video. If `VIDEO` is passed, as in `createCapture(VIDEO)`, only video will be captured. If `AUDIO` is passed, as in `createCapture(AUDIO)`, only audio will be captured. A constraints object can also be passed to customize the stream. See the  W3C documentation for possible properties. Different browsers support different properties.
The 'flipped' property is an optional property which can be set to `{flipped:true}` to mirror the video output.If it is true then it means that video will be mirrored or flipped and if nothing is mentioned then by default it will be `false`.
The second parameter,`callback`, is optional. It's a function to call once the capture is ready for use. The callback function should have one parameter, `stream`, that's a MediaStream object.
Note: `createCapture()` only works when running a sketch locally or using HTTPS. Learn more here and here.

method

createCapture

type

type of capture, either AUDIO or VIDEO, or a constraints object. Both video and audio audio streams are captured by default.

String|Constant|Object

flipped

flip the capturing video and mirror the output with `{flipped:true}`. By default it is false.

Object

callback

function to call once the stream has loaded.

Function

### return
new p5.MediaElement object.

p5.MediaElement

` function setup() { noCanvas(); // Create the video capture. createCapture(VIDEO); describe('A video stream from the webcam.'); } `
` let capture; function setup() { createCanvas(100, 100); // Create the video capture and hide the element. capture = createCapture(VIDEO); capture.hide(); describe('A video stream from the webcam with inverted colors.'); } function draw() { // Draw the video capture within the canvas. image(capture, 0, 0, width, width * capture.height / capture.width); // Invert the colors in the stream. filter(INVERT); } `
` let capture; function setup() { createCanvas(100, 100); // Create the video capture with mirrored output. capture = createCapture(VIDEO,{ flipped:true }); capture.size(100,100); describe('A video stream from the webcam with flipped or mirrored output.'); } `
` function setup() { createCanvas(480, 120); // Create a constraints object. let constraints = { video: { mandatory: { minWidth: 1280, minHeight: 720 }, optional: [{ maxFrameRate: 10 }] }, audio: false }; // Create the video capture. createCapture(constraints); describe('A video stream from the webcam.'); } `

p5

DOM

DOM

Creates a new p5.Element object.
The first parameter, `tag`, is a string an HTML tag such as `'h5'`.
The second parameter, `content`, is optional. It's a string that sets the HTML content to insert into the new element. New elements have no content by default.

method

createElement

tag

tag for the new element.

String

content

HTML content to insert into the element.

String

### return
new p5.Element object.

p5.Element

` function setup() { createCanvas(100, 100); background(200); // Create an h5 element with nothing in it. createElement('h5'); describe('A gray square.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create an h5 element with the content "p5*js". let h5 = createElement('h5', 'p5*js'); // Set the element's style and position. h5.style('color', 'deeppink'); h5.position(30, 15); describe('The text "p5*js" written in pink in the middle of a gray square.'); } `

p5

DOM

DOM

Adds a class to the element.

method

addClass

class

name of class to add.

String

` function setup() { createCanvas(100, 100); background(200); // Create a div element. let div = createDiv('div'); // Add a class to the div. div.addClass('myClass'); describe('A gray square.'); } `

p5.Element

DOM

DOM

Removes a class from the element.

method

removeClass

class

name of class to remove.

String

` // In this example, a class is set when the div is created // and removed when mouse is pressed. This could link up // with a CSS style rule to toggle style properties. let div; function setup() { createCanvas(100, 100); background(200); // Create a div element. div = createDiv('div'); // Add a class to the div. div.addClass('myClass'); describe('A gray square.'); } // Remove 'myClass' from the div when the user presses the mouse. function mousePressed() { div.removeClass('myClass'); } `

p5.Element

DOM

DOM

Checks if a class is already applied to element.

method

hasClass

### return
a boolean value if element has specified class.

Boolean

c

name of class to check.

String

` let div; function setup() { createCanvas(100, 100); background(200); // Create a div element. div = createDiv('div'); // Add the class 'show' to the div. div.addClass('show'); describe('A gray square.'); } // Toggle the class 'show' when the mouse is pressed. function mousePressed() { if (div.hasClass('show')) { div.addClass('show'); } else { div.removeClass('show'); } } `

p5.Element

DOM

DOM

Toggles whether a class is applied to the element.

method

toggleClass

c

class name to toggle.

String

` let div; function setup() { createCanvas(100, 100); background(200); // Create a div element. div = createDiv('div'); // Add the 'show' class to the div. div.addClass('show'); describe('A gray square.'); } // Toggle the 'show' class when the mouse is pressed. function mousePressed() { div.toggleClass('show'); } `

p5.Element

DOM

DOM

Attaches the element as a child of another element.
`myElement.child()` accepts either a string ID, DOM node, or p5.Element. For example, `myElement.child(otherElement)`. If no argument is provided, an array of children DOM nodes is returned.

method

child

### return
an array of child nodes.

Node[]

` function setup() { createCanvas(100, 100); background(200); // Create the div elements. let div0 = createDiv('Parent'); let div1 = createDiv('Child'); // Make div1 the child of div0 // using the p5.Element. div0.child(div1); describe('A gray square with the words "Parent" and "Child" written beneath it.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create the div elements. let div0 = createDiv('Parent'); let div1 = createDiv('Child'); // Give div1 an ID. div1.id('apples'); // Make div1 the child of div0 // using its ID. div0.child('apples'); describe('A gray square with the words "Parent" and "Child" written beneath it.'); } `
` // This example assumes there is a div already on the page // with id "myChildDiv". function setup() { createCanvas(100, 100); background(200); // Create the div elements. let div0 = createDiv('Parent'); // Select the child element by its ID. let elt = document.getElementById('myChildDiv'); // Make div1 the child of div0 // using its HTMLElement object. div0.child(elt); describe('A gray square with the words "Parent" and "Child" written beneath it.'); } `

p5.Element

DOM

DOM

##### return
an array of child nodes.

Node[]

child

the ID, DOM node, or p5.Element to add to the current element

String|p5.Element

Centers the element either vertically, horizontally, or both.
`center()` will center the element relative to its parent or according to the page's body if the element has no parent.
If no argument is passed, as in `myElement.center()` the element is aligned both vertically and horizontally.

method

center

align

passing 'vertical', 'horizontal' aligns element accordingly

String

` function setup() { createCanvas(100, 100); background(200); // Create the div element and style it. let div = createDiv(''); div.size(10, 10); div.style('background-color', 'orange'); // Center the div relative to the page's body. div.center(); describe('A gray square and an orange rectangle. The rectangle is at the center of the page.'); } `

p5.Element

DOM

DOM

Sets the inner HTML of the element, replacing any existing HTML.
The second parameter, `append`, is optional. If `true` is passed, as in `myElement.html('hi', true)`, the HTML is appended instead of replacing existing HTML.
If no arguments are passed, as in `myElement.html()`, the element's inner HTML is returned.

method

html

### return
the inner HTML of the element

String

` function setup() { createCanvas(100, 100); // Create the div element and set its size. let div = createDiv(''); div.size(100, 100); // Set the inner HTML to "hi". div.html('hi'); describe('A gray square with the word "hi" written beneath it.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create the div element and set its size. let div = createDiv('Hello '); div.size(100, 100); // Append "World" to the div's HTML. div.html('World', true); describe('A gray square with the text "Hello World" written beneath it.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create the div element. let div = createDiv('Hello'); // Prints "Hello" to the console. print(div.html()); describe('A gray square with the word "Hello!" written beneath it.'); } `

p5.Element

DOM

DOM

##### return
the inner HTML of the element

String

html

the HTML to be placed inside the element

String

append

whether to append HTML to existing

Boolean

Sets the element's position.
The first two parameters, `x` and `y`, set the element's position relative to the top-left corner of the web page.
The third parameter, `positionType`, is optional. It sets the element's positioning scheme. `positionType` is a string that can be either `'static'`, `'fixed'`, `'relative'`, `'sticky'`, `'initial'`, or `'inherit'`.
If no arguments passed, as in `myElement.position()`, the method returns the element's position in an object, as in `{ x: 0, y: 0 }`.

method

position

### return
object of form `{ x: 0, y: 0 }` containing the element's position.

Object

` function setup() { let cnv = createCanvas(100, 100); background(200); // Positions the canvas 50px to the right and 100px // below the top-left corner of the window. cnv.position(50, 100); describe('A gray square that is 50 pixels to the right and 100 pixels down from the top-left corner of the web page.'); } `
` function setup() { let cnv = createCanvas(100, 100); background(200); // Positions the canvas at the top-left corner // of the window with a 'fixed' position type. cnv.position(0, 0, 'fixed'); describe('A gray square in the top-left corner of the web page.'); } `

p5.Element

DOM

DOM

##### return
object of form `{ x: 0, y: 0 }` containing the element's position.

Object

x

x-position relative to top-left of window (optional)

Number

y

y-position relative to top-left of window (optional)

Number

positionType

it can be static, fixed, relative, sticky, initial or inherit (optional)

String

Applies a style to the element by adding a CSS declaration.
The first parameter, `property`, is a string. If the name of a style property is passed, as in `myElement.style('color')`, the method returns the current value as a string or `null` if it hasn't been set. If a `property:style` string is passed, as in `myElement.style('color:deeppink')`, the method sets the style `property` to `value`.
The second parameter, `value`, is optional. It sets the property's value. `value` can be a string, as in `myElement.style('color', 'deeppink')`, or a p5.Color object, as in `myElement.style('color', myColor)`.

method

style

### return
value of the property.

String

` function setup() { createCanvas(100, 100); background(200); // Create a paragraph element and set its font color to "deeppink". let p = createP('p5*js'); p.position(25, 20); p.style('color', 'deeppink'); describe('The text p5*js written in pink on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create a p5.Color object. let c = color('deeppink'); // Create a paragraph element and set its font color using a p5.Color object. let p = createP('p5*js'); p.position(25, 20); p.style('color', c); describe('The text p5*js written in pink on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create a paragraph element and set its font color to "deeppink" // using property:value syntax. let p = createP('p5*js'); p.position(25, 20); p.style('color:deeppink'); describe('The text p5*js written in pink on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create an empty paragraph element and set its font color to "deeppink". let p = createP(); p.position(5, 5); p.style('color', 'deeppink'); // Get the element's color as an RGB color string. let c = p.style('color'); // Set the element's inner HTML using the RGB color string. p.html(c); describe('The text "rgb(255, 20, 147)" written in pink on a gray background.'); } `

p5.Element

DOM

DOM

property

style property to set.

String

##### return
value of the property.

String

property



String

value

value to assign to the property.

String|p5.Color

##### return
value of the property.

String

Adds an attribute to the element.
This method is useful for advanced tasks. Most commonly-used attributes, such as `id`, can be set with their dedicated methods. For example, `nextButton.id('next')` sets an element's `id` attribute. Calling `nextButton.attribute('id', 'next')` has the same effect.
The first parameter, `attr`, is the attribute's name as a string. Calling `myElement.attribute('align')` returns the attribute's current value as a string or `null` if it hasn't been set.
The second parameter, `value`, is optional. It's a string used to set the attribute's value. For example, calling `myElement.attribute('align', 'center')` sets the element's horizontal alignment to `center`.

method

attribute

### return
value of the attribute.

String

` function setup() { createCanvas(100, 100); // Create a container div element and place it at the top-left corner. let container = createDiv(); container.position(0, 0); // Create a paragraph element and place it within the container. // Set its horizontal alignment to "left". let p1 = createP('hi'); p1.parent(container); p1.attribute('align', 'left'); // Create a paragraph element and place it within the container. // Set its horizontal alignment to "center". let p2 = createP('hi'); p2.parent(container); p2.attribute('align', 'center'); // Create a paragraph element and place it within the container. // Set its horizontal alignment to "right". let p3 = createP('hi'); p3.parent(container); p3.attribute('align', 'right'); describe('A gray square with the text "hi" written on three separate lines, each placed further to the right.'); } `

p5.Element

DOM

DOM

##### return
value of the attribute.

String

attr

attribute to set.

String

value

value to assign to the attribute.

String

Removes an attribute from the element.
The parameter `attr` is the attribute's name as a string. For example, calling `myElement.removeAttribute('align')` removes its `align` attribute if it's been set.

method

removeAttribute

attr

attribute to remove.

String

` let p; function setup() { createCanvas(100, 100); background(200); // Create a paragraph element and place it in the center of the canvas. // Set its "align" attribute to "center". p = createP('hi'); p.position(0, 20); p.attribute('align', 'center'); describe('The text "hi" written in black at the center of a gray square. The text moves to the left edge when double-clicked.'); } // Remove the 'align' attribute when the user double-clicks the paragraph. function doubleClicked() { p.removeAttribute('align'); } `

p5.Element

DOM

DOM

Returns or sets the element's value.
Calling `myElement.value()` returns the element's current value.
The parameter, `value`, is an optional number or string. If provided, as in `myElement.value(123)`, it's used to set the element's value.

method

value

### return
value of the element.

String|Number

` let input; function setup() { createCanvas(100, 100); // Create a text input and place it beneath the canvas. // Set its default value to "hello". input = createInput('hello'); input.position(0, 100); describe('The text from an input box is displayed on a gray square.'); } function draw() { background(200); // Use the input's value to display a message. let msg = input.value(); text(msg, 0, 55); } `
` let input; function setup() { createCanvas(100, 100); // Create a text input and place it beneath the canvas. // Set its default value to "hello". input = createInput('hello'); input.position(0, 100); describe('The text from an input box is displayed on a gray square. The text resets to "hello" when the user double-clicks the square.'); } function draw() { background(200); // Use the input's value to display a message. let msg = input.value(); text(msg, 0, 55); } // Reset the input's value. function doubleClicked() { input.value('hello'); } `

p5.Element

DOM

DOM

##### return
value of the element.

String|Number

value



String|Number

Shows the current element.

method

show

` let p; function setup() { createCanvas(100, 100); background(200); // Create a paragraph element and hide it. p = createP('p5*js'); p.position(10, 10); p.hide(); describe('A gray square. The text "p5*js" appears when the user double-clicks the square.'); } // Show the paragraph when the user double-clicks. function doubleClicked() { p.show(); } `

p5.Element

DOM

DOM

Hides the current element.

method

hide

let p; function setup() { createCanvas(100, 100); background(200); // Create a paragraph element. p = createP('p5*js'); p.position(10, 10); describe('The text "p5*js" at the center of a gray square. The text disappears when the user double-clicks the square.'); } // Hide the paragraph when the user double-clicks. function doubleClicked() { p.hide(); } `

p5.Element

DOM

DOM

Sets the element's width and height.
Calling `myElement.size()` without an argument returns the element's size as an object with the properties `width` and `height`. For example, `{ width: 20, height: 10 }`.
The first parameter, `width`, is optional. It's a number used to set the element's width. Calling `myElement.size(10)`
The second parameter, 'height`, is also optional. It's a number used to set the element's height. For example, calling `myElement.size(20, 10)` sets the element's width to 20 pixels and height to 10 pixels.
The constant `AUTO` can be used to adjust one dimension at a time while maintaining the aspect ratio, which is `width / height`. For example, consider an element that's 200 pixels wide and 100 pixels tall. Calling `myElement.size(20, AUTO)` sets the width to 20 pixels and height to 10 pixels.
Note: In the case of elements that need to load data, such as images, wait to call `myElement.size()` until after the data loads.

method

size

### return
width and height of the element in an object.

Object

` function setup() { createCanvas(100, 100); background(200); // Create a pink div element and place it at the top-left corner. let div = createDiv(); div.position(10, 10); div.style('background-color', 'deeppink'); // Set the div's width to 80 pixels and height to 20 pixels. div.size(80, 20); describe('A gray square with a pink rectangle near its top.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create a pink div element and place it at the top-left corner. let div = createDiv(); div.position(10, 10); div.style('background-color', 'deeppink'); // Set the div's width to 80 pixels and height to 40 pixels. div.size(80, 40); // Get the div's size as an object. let s = div.size(); // Display the div's dimensions. div.html(`${s.width} x ${s.height}`); describe('A gray square with a pink rectangle near its top. The text "80 x 40" is written within the rectangle.'); } `
` let img1; let img2; function setup() { createCanvas(100, 100); background(200); // Load an image of an astronaut on the moon // and place it at the top-left of the canvas. img1 = createImg( 'assets/moonwalk.jpg', 'An astronaut walking on the moon', '' ); img1.position(0, 0); // Load an image of an astronaut on the moon // and place it at the top-left of the canvas. // Resize the image once it's loaded. img2 = createImg( 'assets/moonwalk.jpg', 'An astronaut walking on the moon', '', resizeImage ); img2.position(0, 0); describe('A gray square two copies of a space image at the top-left. The copy in front is smaller.'); } // Resize img2 and keep its aspect ratio. function resizeImage() { img2.size(50, AUTO); } `

p5.Element

DOM

DOM

##### return
width and height of the element in an object.

Object

w

width of the element, either AUTO, or a number.

Number|Constant

h

height of the element, either AUTO, or a number.

Number|Constant

Removes the element, stops all audio/video streams, and removes all callback functions.

method

remove

` let p; function setup() { createCanvas(100, 100); background(200); // Create a paragraph element. p = createP('p5*js'); p.position(10, 10); describe('The text "p5*js" written at the center of a gray square. '); } // Remove the paragraph when the user double-clicks. function doubleClicked() { p.remove(); } `

p5.Element

DOM

DOM

Calls a function when the user drops a file on the element.
The first parameter, `callback`, is a function to call once the file loads. The callback function should have one parameter, `file`, that's a p5.File object. If the user drops multiple files on the element, `callback`, is called once for each file.
The second parameter, `fxn`, is a function to call when the browser detects one or more dropped files. The callback function should have one parameter, `event`, that's a DragEvent.

method

drop

callback

called when a file loads. Called once for each file dropped.

Function

fxn

called once when any files are dropped.

Function

` // Drop an image on the canvas to view // this example. let img; function setup() { let c = createCanvas(100, 100); background(200); // Call handleFile() when a file that's dropped on the canvas has loaded. c.drop(handleFile); describe('A gray square. When the user drops an image on the square, it is displayed.'); } // Remove the existing image and display the new one. function handleFile(file) { // Remove the current image, if any. if (img) { img.remove(); } // Create an  element with the // dropped file. img = createImg(file.data, ''); img.hide(); // Draw the image. image(img, 0, 0, width, height); } `
` // Drop an image on the canvas to view // this example. let img; let msg; function setup() { let c = createCanvas(100, 100); background(200); // Call functions when the user drops a file on the canvas // and when the file loads. c.drop(handleFile, handleDrop); describe('A gray square. When the user drops an image on the square, it is displayed. The id attribute of canvas element is also displayed.'); } // Display the image when it loads. function handleFile(file) { // Remove the current image, if any. if (img) { img.remove(); } // Create an img element with the dropped file. img = createImg(file.data, ''); img.hide(); // Draw the image. image(img, 0, 0, width, height); } // Display the file's name when it loads. function handleDrop(event) { // Remove current paragraph, if any. if (msg) { msg.remove(); } // Use event to get the drop target's id. let id = event.target.id; // Write the canvas' id beneath it. msg = createP(id); msg.position(0, 100); // Set the font color randomly for each drop. let c = random(['red', 'green', 'blue']); msg.style('color', c); msg.style('font-size', '12px'); } `

p5.Element

DOM

DOM

Makes the element draggable.
The parameter, `elmnt`, is optional. If another p5.Element object is passed, as in `myElement.draggable(otherElement)`, the other element will become draggable.

method

draggable

elmnt

another p5.Element.

p5.Element

` let stickyNote; let textInput; function setup() { createCanvas(100, 100); background(200); // Create a div element and style it. stickyNote = createDiv('Note'); stickyNote.position(5, 5); stickyNote.size(80, 20); stickyNote.style('font-size', '16px'); stickyNote.style('font-family', 'Comic Sans MS'); stickyNote.style('background', 'orchid'); stickyNote.style('padding', '5px'); // Make the note draggable. stickyNote.draggable(); // Create a panel div and style it. let panel = createDiv(''); panel.position(5, 40); panel.size(80, 50); panel.style('background', 'orchid'); panel.style('font-size', '16px'); panel.style('padding', '5px'); panel.style('text-align', 'center'); // Make the panel draggable. panel.draggable(); // Create a text input and style it. textInput = createInput('Note'); textInput.size(70); // Add the input to the panel. textInput.parent(panel); // Call handleInput() when text is input. textInput.input(handleInput); describe( 'A gray square with two purple rectangles that move when dragged. The top rectangle displays the text that is typed into the bottom rectangle.' ); } // Update stickyNote's HTML when text is input. function handleInput() { stickyNote.html(textInput.value()); } `

p5.Element

DOM

DOM

p5.Element

DOM

DOM

Path to the media element's source as a string.

property

src

### return
src

String

` let beat; function setup() { createCanvas(100, 100); // Create a p5.MediaElement using createAudio(). beat = createAudio('assets/beat.mp3'); describe('The text "https://p5js.org/reference/assets/beat.mp3" written in black on a gray background.'); } function draw() { background(200); textWrap(CHAR); text(beat.src, 10, 10, 80, 80); } `

p5.MediaElement

DOM

DOM

Plays audio or video from a media element.

method

play

` let beat; function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(CENTER); textSize(16); // Display a message. text('Click to play', 50, 50); // Create a p5.MediaElement using createAudio(). beat = createAudio('assets/beat.mp3'); describe('The text "Click to play" written in black on a gray background. A beat plays when the user clicks the square.'); } // Play the beat when the user presses the mouse. function mousePressed() { beat.play(); } `

p5.MediaElement

DOM

DOM

Stops a media element and sets its current time to 0.
Calling `media.play()` will restart playing audio/video from the beginning.

method

stop

` let beat; let isStopped = true; function setup() { createCanvas(100, 100); // Create a p5.MediaElement using createAudio(). beat = createAudio('assets/beat.mp3'); describe('The text "Click to start" written in black on a gray background. The beat starts or stops when the user presses the mouse.'); } function draw() { background(200); // Style the text. textAlign(CENTER); textSize(16); // Display different instructions based on playback. if (isStopped === true) { text('Click to start', 50, 50); } else { text('Click to stop', 50, 50); } } // Adjust playback when the user presses the mouse. function mousePressed() { if (isStopped === true) { // If the beat is stopped, play it. beat.play(); isStopped = false; } else { // If the beat is playing, stop it. beat.stop(); isStopped = true; } } `

p5.MediaElement

DOM

DOM

Pauses a media element.
Calling `media.play()` will resume playing audio/video from the moment it paused.

method

pause

` let beat; let isPaused = true; function setup() { createCanvas(100, 100); // Create a p5.MediaElement using createAudio(). beat = createAudio('assets/beat.mp3'); describe('The text "Click to play" written in black on a gray background. The beat plays or pauses when the user clicks the square.'); } function draw() { background(200); // Style the text. textAlign(CENTER); textSize(16); // Display different instructions based on playback. if (isPaused === true) { text('Click to play', 50, 50); } else { text('Click to pause', 50, 50); } } // Adjust playback when the user presses the mouse. function mousePressed() { if (isPaused === true) { // If the beat is paused, // play it. beat.play(); isPaused = false; } else { // If the beat is playing, // pause it. beat.pause(); isPaused = true; } } `

p5.MediaElement

DOM

DOM

Plays the audio/video repeatedly in a loop.

method

loop

` let beat; let isLooping = false; function setup() { createCanvas(100, 100); background(200); // Create a p5.MediaElement using createAudio(). beat = createAudio('assets/beat.mp3'); describe('The text "Click to loop" written in black on a gray background. A beat plays repeatedly in a loop when the user clicks. The beat stops when the user clicks again.'); } function draw() { background(200); // Style the text. textAlign(CENTER); textSize(16); // Display different instructions based on playback. if (isLooping === true) { text('Click to stop', 50, 50); } else { text('Click to loop', 50, 50); } } // Adjust playback when the user presses the mouse. function mousePressed() { if (isLooping === true) { // If the beat is looping, stop it. beat.stop(); isLooping = false; } else { // If the beat is stopped, loop it. beat.loop(); isLooping = true; } } `

p5.MediaElement

DOM

DOM

Stops the audio/video from playing in a loop.
The media will stop when it finishes playing.

method

noLoop

` let beat; let isPlaying = false; function setup() { createCanvas(100, 100); background(200); // Create a p5.MediaElement using createAudio(). beat = createAudio('assets/beat.mp3'); describe('The text "Click to play" written in black on a gray background. A beat plays when the user clicks. The beat stops when the user clicks again.'); } function draw() { background(200); // Style the text. textAlign(CENTER); textSize(16); // Display different instructions based on playback. if (isPlaying === true) { text('Click to stop', 50, 50); } else { text('Click to play', 50, 50); } } // Adjust playback when the user presses the mouse. function mousePressed() { if (isPlaying === true) { // If the beat is playing, stop it. beat.stop(); isPlaying = false; } else { // If the beat is stopped, play it. beat.play(); isPlaying = true; } } `

p5.MediaElement

DOM

DOM

Sets the audio/video to play once it's loaded.
The parameter, `shouldAutoplay`, is optional. Calling `media.autoplay()` without an argument causes the media to play automatically. If `true` is passed, as in `media.autoplay(true)`, the media will automatically play. If `false` is passed, as in `media.autoPlay(false)`, it won't play automatically.

method

autoplay

shouldAutoplay

whether the element should autoplay.

Boolean

` let video; function setup() { noCanvas(); // Call handleVideo() once the video loads. video = createVideo('assets/fingers.mov', handleVideo); describe('A video of fingers walking on a treadmill.'); } // Set the video's size and play it. function handleVideo() { video.size(100, 100); video.autoplay(); } `
` function setup() { noCanvas(); // Load a video, but don't play it automatically. let video = createVideo('assets/fingers.mov', handleVideo); // Play the video when the user clicks on it. video.mousePressed(handlePress); describe('An image of fingers on a treadmill. They start walking when the user double-clicks on them.'); } `
// Set the video's size and playback mode. function handleVideo() { video.size(100, 100); video.autoplay(false); } // Play the video. function handleClick() { video.play(); }

p5.MediaElement

DOM

DOM

Sets the audio/video volume.
Calling `media.volume()` without an argument returns the current volume as a number in the range 0 (off) to 1 (maximum).
The parameter, `val`, is optional. It's a number that sets the volume from 0 (off) to 1 (maximum). For example, calling `media.volume(0.5)` sets the volume to half of its maximum.

method

volume

### return
current volume.

Number

` let dragon; function setup() { createCanvas(100, 100); // Create a p5.MediaElement using createAudio(). dragon = createAudio('assets/lucky_dragons.mp3'); // Show the default media controls. dragon.showControls(); describe('The text "Volume: V" on a gray square with media controls beneath it. The number "V" oscillates between 0 and 1 as the music plays.'); } function draw() { background(200); // Produce a number between 0 and 1. let n = 0.5 * sin(frameCount * 0.01) + 0.5; // Use n to set the volume. dragon.volume(n); // Get the current volume and display it. let v = dragon.volume(); // Round v to 1 decimal place for display. v = round(v, 1); // Style the text. textAlign(CENTER); textSize(16); // Display the volume. text(`Volume: ${v}`, 50, 50); } `

p5.MediaElement

DOM

DOM

##### return
current volume.

Number

val

volume between 0.0 and 1.0.

Number

Sets the audio/video playback speed.
The parameter, `val`, is optional. It's a number that sets the playback speed. 1 plays the media at normal speed, 0.5 plays it at half speed, 2 plays it at double speed, and so on. -1 plays the media at normal speed in reverse.
Calling `media.speed()` returns the current speed as a number.
Note: Not all browsers support backward playback. Even if they do, playback might not be smooth.

method

speed

### return
current playback speed.

Number

` let dragon; function setup() { createCanvas(100, 100); // Create a p5.MediaElement using createAudio(). dragon = createAudio('assets/lucky_dragons.mp3'); // Show the default media controls. dragon.showControls(); describe('The text "Speed: S" on a gray square with media controls beneath it. The number "S" oscillates between 0 and 1 as the music plays.'); } function draw() { background(200); // Produce a number between 0 and 2. let n = sin(frameCount * 0.01) + 1; // Use n to set the playback speed. dragon.speed(n); // Get the current speed and display it. let s = dragon.speed(); // Round s to 1 decimal place for display. s = round(s, 1); // Style the text. textAlign(CENTER); textSize(16); // Display the speed. text(`Speed: ${s}`, 50, 50); } `

p5.MediaElement

DOM

DOM

##### return
current playback speed.

Number

speed

speed multiplier for playback.

Number

Sets the media element's playback time.
The parameter, `time`, is optional. It's a number that specifies the time, in seconds, to jump to when playback begins.
Calling `media.time()` without an argument returns the number of seconds the audio/video has played.
Note: Time resets to 0 when looping media restarts.

method

time

### return
current time (in seconds).

Number

` let dragon; function setup() { createCanvas(100, 100); // Create a p5.MediaElement using createAudio(). dragon = createAudio('assets/lucky_dragons.mp3'); // Show the default media controls. dragon.showControls(); describe('The text "S seconds" on a gray square with media controls beneath it. The number "S" increases as the song plays.'); } function draw() { background(200); // Get the current playback time. let s = dragon.time(); // Round s to 1 decimal place for display. s = round(s, 1); // Style the text. textAlign(CENTER); textSize(16); // Display the playback time. text(`${s} seconds`, 50, 50); } `
` let dragon; function setup() { createCanvas(100, 100); // Create a p5.MediaElement using createAudio(). dragon = createAudio('assets/lucky_dragons.mp3'); // Show the default media controls. dragon.showControls(); // Jump to 2 seconds to start. dragon.time(2); describe('The text "S seconds" on a gray square with media controls beneath it. The number "S" increases as the song plays.'); } function draw() { background(200); // Get the current playback time. let s = dragon.time(); // Round s to 1 decimal place for display. s = round(s, 1); // Style the text. textAlign(CENTER); textSize(16); // Display the playback time. text(`${s} seconds`, 50, 50); } `

p5.MediaElement

DOM

DOM

##### return
current time (in seconds).

Number

time

time to jump to (in seconds).

Number

Returns the audio/video's duration in seconds.

method

duration

### return
duration (in seconds).

Number

` let dragon; function setup() { createCanvas(100, 100); background(200); // Create a p5.MediaElement using createAudio(). dragon = createAudio('assets/lucky_dragons.mp3'); // Show the default media controls. dragon.showControls(); describe('The text "S seconds left" on a gray square with media controls beneath it. The number "S" decreases as the song plays.'); } function draw() { background(200); // Calculate the time remaining. let s = dragon.duration() - dragon.time(); // Round s to 1 decimal place for display. s = round(s, 1); // Style the text. textAlign(CENTER); textSize(16); // Display the time remaining. text(`${s} seconds left`, 50, 50); } `

p5.MediaElement

DOM

DOM

Calls a function when the audio/video reaches the end of its playback.
The element is passed as an argument to the callback function.
Note: The function won't be called if the media is looping.

method

onended

callback

function to call when playback ends. The `p5.MediaElement` is passed as the argument.

Function

` let beat; let isPlaying = false; let isDone = false; function setup() { createCanvas(100, 100); // Create a p5.MediaElement using createAudio(). beat = createAudio('assets/beat.mp3'); // Call handleEnd() when the beat finishes. beat.onended(handleEnd); describe('The text "Click to play" written in black on a gray square. A beat plays when the user clicks. The text "Done!" appears when the beat finishes playing.'); } function draw() { background(200); // Style the text. textAlign(CENTER); textSize(16); // Display different messages based on playback. if (isDone === true) { text('Done!', 50, 50); } else if (isPlaying === false) { text('Click to play', 50, 50); } else { text('Playing...', 50, 50); } } // Play the beat when the user presses the mouse. function mousePressed() { if (isPlaying === false) { isPlaying = true; beat.play(); } } // Set isDone when playback ends. function handleEnd() { isDone = false; } `

p5.MediaElement

DOM

DOM

p5.MediaElement

DOM

DOM

Sends the element's audio to an output.
The parameter, `audioNode`, can be an `AudioNode` or an object from the `p5.sound` library.
If no element is provided, as in `myElement.connect()`, the element connects to the main output. All connections are removed by the `.disconnect()` method.
Note: This method is meant to be used with the p5.sound.js addon library.

method

connect

audioNode

AudioNode from the Web Audio API, or an object from the p5.sound library

AudioNode|Object

p5.MediaElement

DOM

DOM

Disconnect all Web Audio routing, including to the main output.
This is useful if you want to re-route the output through audio effects, for example.

method

disconnect

p5.MediaElement

DOM

DOM

p5.MediaElement

DOM

DOM

Show the default HTMLMediaElement controls.
Note: The controls vary between web browsers.

method

showControls

` function setup() { createCanvas(100, 100); background('cornflowerblue'); // Style the text. textAlign(CENTER); textSize(50); // Display a dragon. text('🐉', 50, 50); // Create a p5.MediaElement using createAudio(). let dragon = createAudio('assets/lucky_dragons.mp3'); // Show the default media controls. dragon.showControls(); describe('A dragon emoji, 🐉, drawn in the center of a blue square. A song plays in the background. Audio controls are displayed beneath the canvas.'); } `

p5.MediaElement

DOM

DOM

Hide the default HTMLMediaElement controls.

method

hideControls

` let dragon; let isHidden = false; function setup() { createCanvas(100, 100); // Create a p5.MediaElement using createAudio(). dragon = createAudio('assets/lucky_dragons.mp3'); // Show the default media controls. dragon.showControls(); describe('The text "Double-click to hide controls" written in the middle of a gray square. A song plays in the background. Audio controls are displayed beneath the canvas. The controls appear/disappear when the user double-clicks the square.'); } function draw() { background(200); // Style the text. textAlign(CENTER); // Display a different message when controls are hidden or shown. if (isHidden === true) { text('Double-click to show controls', 10, 20, 80, 80); } else { text('Double-click to hide controls', 10, 20, 80, 80); } } // Show/hide controls based on a double-click. function doubleClicked() { if (isHidden === true) { dragon.showControls(); isHidden = false; } else { dragon.hideControls(); isHidden = true; } } `

p5.MediaElement

DOM

DOM

Schedules a function to call when the audio/video reaches a specific time during its playback.
The first parameter, `time`, is the time, in seconds, when the function should run. This value is passed to `callback` as its first argument.
The second parameter, `callback`, is the function to call at the specified cue time.
The third parameter, `value`, is optional and can be any type of value. `value` is passed to `callback`.
Calling `media.addCue()` returns an ID as a string. This is useful for removing the cue later.

method

addCue

time

cue time to run the callback function.

Number

callback

function to call at the cue time.

Function

value

object to pass as the argument to `callback`.

Object

### return
id ID of this cue, useful for `media.removeCue(id)`.

Number

` function setup() { createCanvas(100, 100); // Create a p5.MediaElement using createAudio(). let beat = createAudio('assets/beat.mp3'); // Play the beat in a loop. beat.loop(); // Schedule a few events. beat.addCue(0, changeBackground, 'red'); beat.addCue(2, changeBackground, 'deeppink'); beat.addCue(4, changeBackground, 'orchid'); beat.addCue(6, changeBackground, 'lavender'); describe('A red square with a beat playing in the background. Its color changes every 2 seconds while the audio plays.'); } // Change the background color. function changeBackground(c) { background(c); } `

p5.MediaElement

DOM

DOM

Removes a callback based on its ID.

method

removeCue

id

ID of the cue, created by `media.addCue()`.

Number

` let lavenderID; let isRemoved = false; function setup() { createCanvas(100, 100); // Create a p5.MediaElement using createAudio(). let beat = createAudio('assets/beat.mp3'); // Play the beat in a loop. beat.loop(); // Schedule a few events. beat.addCue(0, changeBackground, 'red'); beat.addCue(2, changeBackground, 'deeppink'); beat.addCue(4, changeBackground, 'orchid'); // Record the ID of the "lavender" callback. lavenderID = beat.addCue(6, changeBackground, 'lavender'); describe('The text "Double-click to remove lavender." written on a red square. The color changes every 2 seconds while the audio plays. The lavender option is removed when the user double-clicks the square.'); } function draw() { background(200); // Display different instructions based on the available callbacks. if (isRemoved === false) { text('Double-click to remove lavender.', 10, 10, 80, 80); } else { text('No more lavender.', 10, 10, 80, 80); } } // Change the background color. function changeBackground(c) { background(c); } // Remove the lavender color-change cue when the user double-clicks. function doubleClicked() { if (isRemoved === false) { beat.removeCue(lavenderID); isRemoved = true; } } `

p5.MediaElement

DOM

DOM

Removes all functions scheduled with `media.addCue()`.

method

clearCues

` let isChanging = true; function setup() { createCanvas(100, 100); background(200); // Create a p5.MediaElement using createAudio(). let beat = createAudio('assets/beat.mp3'); // Play the beat in a loop. beat.loop(); // Schedule a few events. beat.addCue(0, changeBackground, 'red'); beat.addCue(2, changeBackground, 'deeppink'); beat.addCue(4, changeBackground, 'orchid'); beat.addCue(6, changeBackground, 'lavender'); describe('The text "Double-click to stop changing." written on a square. The color changes every 2 seconds while the audio plays. The color stops changing when the user double-clicks the square.'); } function draw() { background(200); // Display different instructions based on the available callbacks. if (isChanging === true) { text('Double-click to stop changing.', 10, 10, 80, 80); } else { text('No more changes.', 10, 10, 80, 80); } } // Change the background color. function changeBackground(c) { background(c); } // Remove cued functions and stop changing colors when the user // double-clicks. function doubleClicked() { if (isChanging === true) { beat.clearCues(); isChanging = false; } } `

p5.MediaElement

DOM

DOM

Underlying File object. All `File` properties and methods are accessible.

property

file

` // Use the file input to load a // file and display its info. function setup() { createCanvas(100, 100); background(200); // Create a file input and place it beneath the canvas. // Call displayInfo() when the file loads. let input = createFileInput(displayInfo); input.position(0, 100); describe('A gray square with a file input beneath it. If the user loads a file, its info is written in black.'); } // Use the p5.File once it loads. function displayInfo(file) { background(200); // Display the p5.File's name. text(file.name, 10, 10, 80, 40); // Display the p5.File's type and subtype. text(`${file.type}/${file.subtype}`, 10, 70); // Display the p5.File's size in bytes. text(file.size, 10, 90); } `

p5.File

DOM

DOM

The file MIME type as a string.
For example, `'image'` and `'text'` are both MIME types.

property

type

` // Use the file input to load a file and display its info. function setup() { createCanvas(100, 100); background(200); // Create a file input and place it beneath the canvas. // Call displayType() when the file loads. let input = createFileInput(displayType); input.position(0, 100); describe('A gray square with a file input beneath it. If the user loads a file, its type is written in black.'); } // Display the p5.File's type once it loads. function displayType(file) { background(200); // Display the p5.File's type. text(`This is file's type is: ${file.type}`, 10, 10, 80, 80); } `

p5.File

DOM

DOM

The file subtype as a string.
For example, a file with an `'image'` MIME type may have a subtype such as `png` or `jpeg`.

property

subtype

` // Use the file input to load a // file and display its info. function setup() { createCanvas(100, 100); background(200); // Create a file input and place it beneath the canvas. // Call displaySubtype() when the file loads. let input = createFileInput(displaySubtype); input.position(0, 100); describe('A gray square with a file input beneath it. If the user loads a file, its subtype is written in black.'); } // Display the p5.File's type once it loads. function displaySubtype(file) { background(200); // Display the p5.File's subtype. text(`This is file's subtype is: ${file.subtype}`, 10, 10, 80, 80); } `

p5.File

DOM

DOM

The file name as a string.

property

name

` // Use the file input to load a // file and display its info. function setup() { createCanvas(100, 100); background(200); // Create a file input and place it beneath the canvas. // Call displayName() when the file loads. let input = createFileInput(displayName); input.position(0, 100); describe('A gray square with a file input beneath it. If the user loads a file, its name is written in black.'); } // Display the p5.File's name once it loads. function displayName(file) { background(200); // Display the p5.File's name. text(`This is file's name is: ${file.name}`, 10, 10, 80, 80); } `

p5.File

DOM

DOM

The number of bytes in the file.

property

size

` // Use the file input to load a file and display its info. function setup() { createCanvas(100, 100); background(200); // Create a file input and place it beneath the canvas. // Call displaySize() when the file loads. let input = createFileInput(displaySize); input.position(0, 100); describe('A gray square with a file input beneath it. If the user loads a file, its size in bytes is written in black.'); } // Display the p5.File's size in bytes once it loads. function displaySize(file) { background(200); // Display the p5.File's size. text(`This is file has ${file.size} bytes.`, 10, 10, 80, 80); } `

p5.File

DOM

DOM

A string containing the file's data.
Data can be either image data, text contents, or a parsed object in the case of JSON and p5.XML objects.

property

data

` // Use the file input to load a file and display its info. function setup() { createCanvas(100, 100); background(200); // Create a file input and place it beneath the canvas. // Call displayData() when the file loads. let input = createFileInput(displayData); input.position(0, 100); describe('A gray square with a file input beneath it. If the user loads a file, its data is written in black.'); } // Display the p5.File's data once it loads. function displayData(file) { background(200); // Display the p5.File's data, which looks like a random string of characters. text(file.data, 10, 10, 80, 80); } `

p5.File

DOM

DOM

The system variable deviceOrientation always contains the orientation of the device. The value of this variable will either be set 'landscape' or 'portrait'. If no data is available it will be set to 'undefined'. either LANDSCAPE or PORTRAIT.

property

deviceOrientation

Constant



p5

Events

Acceleration

The system variable accelerationX always contains the acceleration of the device along the x axis. Value is represented as meters per second squared.

property

accelerationX

Number



` // Move a touchscreen device to register // acceleration changes. function draw() { background(220, 50); fill('magenta'); ellipse(width / 2, height / 2, accelerationX); describe('Magnitude of device acceleration is displayed as ellipse size.'); } `

p5

Events

Acceleration

The system variable accelerationY always contains the acceleration of the device along the y axis. Value is represented as meters per second squared.

property

accelerationY

Number



` // Move a touchscreen device to register // acceleration changes. function draw() { background(220, 50); fill('magenta'); ellipse(width / 2, height / 2, accelerationY); describe('Magnitude of device acceleration is displayed as ellipse size'); } `

p5

Events

Acceleration

The system variable accelerationZ always contains the acceleration of the device along the z axis. Value is represented as meters per second squared.

property

accelerationZ

Number



` // Move a touchscreen device to register // acceleration changes. function draw() { background(220, 50); fill('magenta'); ellipse(width / 2, height / 2, accelerationZ); describe('Magnitude of device acceleration is displayed as ellipse size'); } `

p5

Events

Acceleration

The system variable pAccelerationX always contains the acceleration of the device along the x axis in the frame previous to the current frame. Value is represented as meters per second squared.

property

pAccelerationX

Number



p5

Events

Acceleration

The system variable pAccelerationY always contains the acceleration of the device along the y axis in the frame previous to the current frame. Value is represented as meters per second squared.

property

pAccelerationY

Number



p5

Events

Acceleration

The system variable pAccelerationZ always contains the acceleration of the device along the z axis in the frame previous to the current frame. Value is represented as meters per second squared.

property

pAccelerationZ

Number



p5

Events

Acceleration

The system variable rotationX always contains the rotation of the device along the x axis. If the sketch  angleMode() is set to DEGREES, the value will be -180 to 180. If it is set to RADIANS, the value will be -PI to PI.
Note: The order the rotations are called is important, ie. if used together, it must be called in the order Z-X-Y or there might be unexpected behaviour.

property

rotationX

Number



` function setup() { createCanvas(100, 100, WEBGL); } function draw() { background(200); //rotateZ(radians(rotationZ)); rotateX(radians(rotationX)); //rotateY(radians(rotationY)); box(200, 200, 200); describe(`red horizontal line right, green vertical line bottom. black background.`); } `

p5

Events

Acceleration

The system variable rotationY always contains the rotation of the device along the y axis. If the sketch  angleMode() is set to DEGREES, the value will be -90 to 90. If it is set to RADIANS, the value will be -PI/2 to PI/2.
Note: The order the rotations are called is important, ie. if used together, it must be called in the order Z-X-Y or there might be unexpected behaviour.

property

rotationY

Number



` function setup() { createCanvas(100, 100, WEBGL); } function draw() { background(200); //rotateZ(radians(rotationZ)); //rotateX(radians(rotationX)); rotateY(radians(rotationY)); box(200, 200, 200); describe(`red horizontal line right, green vertical line bottom. black background.`); } `

p5

Events

Acceleration

The system variable rotationZ always contains the rotation of the device along the z axis. If the sketch  angleMode() is set to DEGREES, the value will be 0 to 360. If it is set to RADIANS, the value will be 0 to 2*PI.
Unlike rotationX and rotationY, this variable is available for devices with a built-in compass only.
Note: The order the rotations are called is important, ie. if used together, it must be called in the order Z-X-Y or there might be unexpected behaviour.

` function setup() { createCanvas(100, 100, WEBGL); } function draw() { background(200); rotateZ(radians(rotationZ)); //rotateX(radians(rotationX)); //rotateY(radians(rotationY)); box(200, 200, 200); describe(`red horizontal line right, green vertical line bottom. black background.`); } `

property

rotationZ

Number



p5

Events

Acceleration

The system variable pRotationX always contains the rotation of the device along the x axis in the frame previous to the current frame. If the sketch  angleMode() is set to DEGREES, the value will be -180 to 180. If it is set to RADIANS, the value will be -PI to PI.
pRotationX can also be used with rotationX to determine the rotate direction of the device along the X-axis.

` // A simple if statement looking at whether // rotationX - pRotationX < 0 is true or not will be // sufficient for determining the rotate direction // in most cases. // Some extra logic is needed to account for cases where // the angles wrap around. let rotateDirection = 'clockwise'; // Simple range conversion to make things simpler. // This is not absolutely necessary but the logic // will be different in that case. let rX = rotationX + 180; let pRX = pRotationX + 180; if ((rX - pRX > 0 && rX - pRX < 270) || rX - pRX < -270) { rotateDirection = 'clockwise'; } else if (rX - pRX < 0 || rX - pRX > 270) { rotateDirection = 'counter-clockwise'; } print(rotateDirection); describe('no image to display.'); `

property

pRotationX

Number



p5

Events

Acceleration

The system variable pRotationY always contains the rotation of the device along the y axis in the frame previous to the current frame. If the sketch  angleMode() is set to DEGREES, the value will be -90 to 90. If it is set to RADIANS, the value will be -PI/2 to PI/2.
pRotationY can also be used with rotationY to determine the rotate direction of the device along the Y-axis.

` // A simple if statement looking at whether // rotationY - pRotationY < 0 is true or not will be // sufficient for determining the rotate direction // in most cases. // Some extra logic is needed to account for cases where // the angles wrap around. let rotateDirection = 'clockwise'; // Simple range conversion to make things simpler. // This is not absolutely necessary but the logic // will be different in that case. let rY = rotationY + 180; let pRY = pRotationY + 180; if ((rY - pRY > 0 && rY - pRY < 270) || rY - pRY < -270) { rotateDirection = 'clockwise'; } else if (rY - pRY < 0 || rY - pRY > 270) { rotateDirection = 'counter-clockwise'; } print(rotateDirection); describe('no image to display.'); `

property

pRotationY

Number



p5

Events

Acceleration

The system variable pRotationZ always contains the rotation of the device along the z axis in the frame previous to the current frame. If the sketch  angleMode() is set to DEGREES, the value will be 0 to 360. If it is set to RADIANS, the value will be 0 to 2*PI.
pRotationZ can also be used with rotationZ to determine the rotate direction of the device along the Z-axis.

` // A simple if statement looking at whether // rotationZ - pRotationZ < 0 is true or not will be // sufficient for determining the rotate direction // in most cases. // Some extra logic is needed to account for cases where // the angles wrap around. let rotateDirection = 'clockwise'; if ( (rotationZ - pRotationZ > 0 && rotationZ - pRotationZ < 270) || rotationZ - pRotationZ < -270 ) { rotateDirection = 'clockwise'; } else if (rotationZ - pRotationZ < 0 || rotationZ - pRotationZ > 270) { rotateDirection = 'counter-clockwise'; } print(rotateDirection); describe('no image to display.'); `

property

pRotationZ

Number



p5

Events

Acceleration

When a device is rotated, the axis that triggers the deviceTurned() method is stored in the turnAxis variable. The turnAxis variable is only defined within the scope of deviceTurned().

property

turnAxis

String



` // Run this example on a mobile device // Rotate the device by 90 degrees in the // X-axis to change the value. let value = 0; function draw() { fill(value); rect(25, 25, 50, 50); describe(`50-by-50 black rect in center of canvas. turns white on mobile when device turns`); describe(`50-by-50 black rect in center of canvas. turns white on mobile when x-axis turns`); } function deviceTurned() { if (turnAxis === 'X') { if (value === 0) { value = 255; } else if (value === 255) { value = 0; } } } `

p5

Events

Acceleration

The setMoveThreshold() function is used to set the movement threshold for the deviceMoved() function. The default threshold is set to 0.5.

method

setMoveThreshold

value

The threshold value

Number

` // Run this example on a mobile device // You will need to move the device incrementally further // the closer the square's color gets to white in order to change the value. let value = 0; let threshold = 0.5; function setup() { setMoveThreshold(threshold); } function draw() { fill(value); rect(25, 25, 50, 50); describe(`50-by-50 black rect in center of canvas. turns white on mobile when device moves`); } function deviceMoved() { value = value + 5; threshold = threshold + 0.1; if (value > 255) { value = 0; threshold = 30; } setMoveThreshold(threshold); } `

p5

Events

Acceleration

The setShakeThreshold() function is used to set the movement threshold for the deviceShaken() function. The default threshold is set to 30.

method

setShakeThreshold

value

The threshold value

Number

` // Run this example on a mobile device // You will need to shake the device more firmly // the closer the box's fill gets to white in order to change the value. let value = 0; let threshold = 30; function setup() { setShakeThreshold(threshold); } function draw() { fill(value); rect(25, 25, 50, 50); describe(`50-by-50 black rect in center of canvas. turns white on mobile when device is being shaked`); } function deviceMoved() { value = value + 5; threshold = threshold + 5; if (value > 255) { value = 0; threshold = 30; } setShakeThreshold(threshold); } `

p5

Events

Acceleration

The deviceMoved() function is called when the device is moved by more than the threshold value along X, Y or Z axis. The default threshold is set to 0.5. The threshold value can be changed using setMoveThreshold().

method

deviceMoved

` // Run this example on a mobile device // Move the device around // to change the value. let value = 0; function draw() { fill(value); rect(25, 25, 50, 50); describe(`50-by-50 black rect in center of canvas. turns white on mobile when device moves`); } function deviceMoved() { value = value + 5; if (value > 255) { value = 0; } } `

p5

Events

Acceleration

The deviceTurned() function is called when the device rotates by more than 90 degrees continuously.
The axis that triggers the deviceTurned() method is stored in the turnAxis variable. The deviceTurned() method can be locked to trigger on any axis: X, Y or Z by comparing the turnAxis variable to 'X', 'Y' or 'Z'.

method

deviceTurned

` // Run this example on a mobile device // Rotate the device by 90 degrees // to change the value. let value = 0; function draw() { fill(value); rect(25, 25, 50, 50); describe(`50-by-50 black rect in center of canvas. turns white on mobile when device turns`); } function deviceTurned() { if (value === 0) { value = 255; } else if (value === 255) { value = 0; } } `
` // Run this example on a mobile device // Rotate the device by 90 degrees in the // X-axis to change the value. let value = 0; function draw() { fill(value); rect(25, 25, 50, 50); describe(`50-by-50 black rect in center of canvas. turns white on mobile when x-axis turns`); } function deviceTurned() { if (turnAxis === 'X') { if (value === 0) { value = 255; } else if (value === 255) { value = 0; } } } `

p5

Events

Acceleration

The deviceShaken() function is called when the device total acceleration changes of accelerationX and accelerationY values is more than the threshold value. The default threshold is set to 30. The threshold value can be changed using setShakeThreshold().

method

deviceShaken

` // Run this example on a mobile device // Shake the device to change the value. let value = 0; function draw() { fill(value); rect(25, 25, 50, 50); describe(`50-by-50 black rect in center of canvas. turns white on mobile when device shakes`); } function deviceShaken() { value = value + 5; if (value > 255) { value = 0; } } `

p5

Events

Acceleration

A `Boolean` system variable that's `true` if any key is currently pressed and `false` if not.

property

keyIsPressed

Boolean



` // Click on the canvas to begin detecting key presses. function setup() { createCanvas(100, 100); describe( 'A gray square with a white square at its center. The white square turns black when the user presses a key.' ); } function draw() { background(200); // Style the square. if (keyIsPressed === true) { fill(0); } else { fill(255); } // Draw the square. square(25, 25, 50); } `
` // Click on the canvas to begin detecting key presses. function setup() { createCanvas(100, 100); describe( 'A gray square with a white square at its center. The white square turns black when the user presses a key.' ); } function draw() { background(200); // Style the square. if (keyIsPressed) { fill(0); } else { fill(255); } // Draw the square. square(25, 25, 50); } `
` // Click on the canvas to begin detecting key presses. function setup() { createCanvas(100, 100); describe( 'A gray square with the word "false" at its center. The word switches to "true" when the user presses a key.' ); } function draw() { background(200); // Style the text. textAlign(CENTER); textSize(16); // Display the value of keyIsPressed. text(keyIsPressed, 50, 50); } `

p5

Events

Keyboard

A `String` system variable that contains the value of the last key typed.
The key variable is helpful for checking whether an ASCII key has been typed. For example, the expression `key === "a"` evaluates to `true` if the `a` key was typed and `false` if not. `key` doesn’t update for special keys such as `LEFT_ARROW` and `ENTER`. Use keyCode instead for special keys. The keyIsDown() function should be used to check for multiple different key presses at the same time.

property

key

String



` // Click on the canvas to begin detecting key presses. function setup() { createCanvas(100, 100); describe( 'A gray square. The last key pressed is displayed at the center.' ); } function draw() { background(200); // Style the text. textAlign(CENTER); textSize(16); // Display the last key pressed. text(key, 50, 50); } `
` // Click on the canvas to begin detecting key presses. let x = 50; let y = 50; function setup() { createCanvas(100, 100); background(200); describe( 'A gray square with a black circle at its center. The circle moves when the user presses the keys "w", "a", "s", or "d". It leaves a trail as it moves.' ); } function draw() { // Update x and y if a key is pressed. if (keyIsPressed === true) { if (key === 'w') { y -= 1; } else if (key === 's') { y += 1; } else if (key === 'a') { x -= 1; } else if (key === 'd') { x += 1; } } // Style the circle. fill(0); // Draw the circle at (x, y). circle(x, y, 5); } `

p5

Events

Keyboard

A `Number` system variable that contains the code of the last key typed.
All keys have a `keyCode`. For example, the `a` key has the `keyCode` 65\. The `keyCode` variable is helpful for checking whether a special key has been typed. For example, the following conditional checks whether the enter key has been typed:
    if (keyCode === 13) {
      // Code to run if the enter key was pressed.
    }
    
The same code can be written more clearly using the system variable `ENTER` which has a value of 13:
    if (keyCode === ENTER) {
      // Code to run if the enter key was pressed.
    }
    
The system variables `BACKSPACE`, `DELETE`, `ENTER`, `RETURN`, `TAB`, `ESCAPE`, `SHIFT`, `CONTROL`, `OPTION`, `ALT`, `UP_ARROW`, `DOWN_ARROW`, `LEFT_ARROW`, and `RIGHT_ARROW` are all helpful shorthands the key codes of special keys. Key codes can be found on websites such as keycode.info.

property

keyCode

Integer



` // Click on the canvas to begin detecting key presses. function setup() { createCanvas(100, 100); describe( 'A gray square. The last key pressed and its code are displayed at the center.' ); } function draw() { background(200); // Style the text. textAlign(CENTER); textSize(16); // Display the last key pressed and its code. text(`${key} : ${keyCode}`, 50, 50); } `
` // Click on the canvas to begin detecting key presses. let x = 50; let y = 50; function setup() { createCanvas(100, 100); background(200); describe( 'A gray square with a black circle at its center. The circle moves when the user presses an arrow key. It leaves a trail as it moves.' ); } function draw() { // Update x and y if an arrow key is pressed. if (keyIsPressed === true) { if (keyCode === UP_ARROW) { y -= 1; } else if (keyCode === DOWN_ARROW) { y += 1; } else if (keyCode === LEFT_ARROW) { x -= 1; } else if (keyCode === RIGHT_ARROW) { x += 1; } } // Style the circle. fill(0); // Draw the circle at (x, y). circle(x, y, 5); } `

p5

Events

Keyboard

A function that's called once when any key is pressed.
Declaring the function `keyPressed()` sets a code block to run once automatically when the user presses any key:
    function keyPressed() {
      // Code to run.
    }
    
The key and keyCode variables will be updated with the most recently typed value when `keyPressed()` is called by p5.js:
    function keyPressed() {
      if (key === 'c') {
        // Code to run.
      }
    
      if (keyCode === ENTER) {
        // Code to run.
      }
    }
    
The parameter, `event`, is optional. `keyPressed()` is always passed a KeyboardEvent object with properties that describe the key press event:
    function keyPressed(event) {
      // Code to run that uses the event.
      console.log(event);
    }
    
Browsers may have default behaviors attached to various key events. For example, some browsers may jump to the bottom of a web page when the `SPACE` key is pressed. To prevent any default behavior for this event, add `return false;` to the end of the function.

method

keyPressed

event

optional `KeyboardEvent` callback argument.

KeyboardEvent

` // Click on the canvas to begin detecting key presses. let value = 0; function setup() { createCanvas(100, 100); describe( 'A gray square with a black square at its center. The inner square changes color when the user presses a key.' ); } function draw() { background(200); // Style the square. fill(value); // Draw the square. square(25, 25, 50); } // Toggle the background color when the user presses a key. function keyPressed() { if (value === 0) { value = 255; } else { value = 0; } // Uncomment to prevent any default behavior. // return false; } `
` // Click on the canvas to begin detecting key presses. let value = 0; function setup() { createCanvas(100, 100); describe( 'A gray square with a white square at its center. The inner square turns black when the user presses the "b" key. It turns white when the user presses the "a" key.' ); } function draw() { background(200); // Style the square. fill(value); // Draw the square. square(25, 25, 50); } // Reassign value when the user presses the 'a' or 'b' key. function keyPressed() { if (key === 'a') { value = 255; } else if (key === 'b') { value = 0; } // Uncomment to prevent any default behavior. // return false; } `
` // Click on the canvas to begin detecting key presses. let value = 0; function setup() { createCanvas(100, 100); describe( 'A gray square with a black square at its center. The inner square turns white when the user presses the left arrow key. It turns black when the user presses the right arrow key.' ); } function draw() { background(200); // Style the square. fill(value); // Draw the square. square(25, 25, 50); } // Toggle the background color when the user presses an arrow key. function keyPressed() { if (keyCode === LEFT_ARROW) { value = 255; } else if (keyCode === RIGHT_ARROW) { value = 0; } // Uncomment to prevent any default behavior. // return false; } `

p5

Events

Keyboard

A function that's called once when any key is released.
Declaring the function `keyReleased()` sets a code block to run once automatically when the user releases any key:
    function keyReleased() {
      // Code to run.
    }
    
The key and keyCode variables will be updated with the most recently released value when `keyReleased()` is called by p5.js:
    function keyReleased() {
      if (key === 'c') {
        // Code to run.
      }
    
      if (keyCode === ENTER) {
        // Code to run.
      }
    }
    
The parameter, `event`, is optional. `keyReleased()` is always passed a KeyboardEvent object with properties that describe the key press event:
    function keyReleased(event) {
      // Code to run that uses the event.
      console.log(event);
    }
    
Browsers may have default behaviors attached to various key events. To prevent any default behavior for this event, add `return false;` to the end of the function.

method

keyReleased

event

optional `KeyboardEvent` callback argument.

KeyboardEvent

` // Click on the canvas to begin detecting key presses. let value = 0; function setup() { createCanvas(100, 100); describe( 'A gray square with a black square at its center. The inner square changes color when the user releases a key.' ); } function draw() { background(200); // Style the square. fill(value); // Draw the square. square(25, 25, 50); } // Toggle value when the user releases a key. function keyReleased() { if (value === 0) { value = 255; } else { value = 0; } // Uncomment to prevent any default behavior. // return false; } `
` // Click on the canvas to begin detecting key presses. let value = 0; function setup() { createCanvas(100, 100); describe( 'A gray square with a black square at its center. The inner square becomes white when the user releases the "w" key.' ); } function draw() { background(200); // Style the square. fill(value); // Draw the square. square(25, 25, 50); } // Set value to 255 the user releases the 'w' key. function keyReleased() { if (key === 'w') { value = 255; } // Uncomment to prevent any default behavior. // return false; } `
` // Click on the canvas to begin detecting key presses. let value = 0; function setup() { createCanvas(100, 100); describe( 'A gray square with a black square at its center. The inner square turns white when the user presses and releases the left arrow key. It turns black when the user presses and releases the right arrow key.' ); } function draw() { background(200); // Style the square. fill(value); // Draw the square. square(25, 25, 50); } // Toggle the background color when the user releases an arrow key. function keyReleased() { if (keyCode === LEFT_ARROW) { value = 255; } else if (keyCode === RIGHT_ARROW) { value = 0; } // Uncomment to prevent any default behavior. // return false; } `

p5

Events

Keyboard

A function that's called once when keys with printable characters are pressed.
Declaring the function `keyTyped()` sets a code block to run once automatically when the user presses any key with a printable character such as `a` or 1. Modifier keys such as `SHIFT`, `CONTROL`, and the arrow keys will be ignored:
    function keyTyped() {
      // Code to run.
    }
    
The key and keyCode variables will be updated with the most recently released value when `keyTyped()` is called by p5.js:
    function keyTyped() {
      // Check for the "c" character using key.
      if (key === 'c') {
        // Code to run.
      }
    
      // Check for "c" using keyCode.
      if (keyCode === 67) {
        // Code to run.
      }
    }
    
The parameter, `event`, is optional. `keyTyped()` is always passed a KeyboardEvent object with properties that describe the key press event:
    function keyReleased(event) {
      // Code to run that uses the event.
      console.log(event);
    }
    
Note: Use the keyPressed() function and keyCode system variable to respond to modifier keys such as `ALT`.
Browsers may have default behaviors attached to various key events. To prevent any default behavior for this event, add `return false;` to the end of the function.

method

keyTyped

event

optional `KeyboardEvent` callback argument.

KeyboardEvent

` // Click on the canvas to begin detecting key presses. // Note: Pressing special keys such as SPACE have no effect. let value = 0; function setup() { createCanvas(100, 100); describe( 'A gray square with a white square at its center. The inner square changes color when the user presses a key.' ); } function draw() { background(200); // Style the square. fill(value); // Draw the square. square(25, 25, 50); } // Toggle the square's color when the user types a printable key. function keyTyped() { if (value === 0) { value = 255; } else { value = 0; } // Uncomment to prevent any default behavior. // return false; } `
` // Click on the canvas to begin detecting key presses. let value = 0; function setup() { createCanvas(100, 100); describe( 'A gray square with a white square at its center. The inner square turns black when the user types the "b" key. It turns white when the user types the "a" key.' ); } function draw() { background(200); // Style the square. fill(value); // Draw the square. square(25, 25, 50); } // Reassign value when the user types the 'a' or 'b' key. function keyTyped() { if (key === 'a') { value = 255; } else if (key === 'b') { value = 0; } // Uncomment to prevent any default behavior. // return false; } `

p5

Events

Keyboard

The onblur function is called when the user is no longer focused on the p5 element. Because the keyup events will not fire if the user is not focused on the element we must assume all keys currently down have been released.

p5

Events

Keyboard

Returns `true` if the key it’s checking is pressed and `false` if not.
`keyIsDown()` is helpful when checking for multiple different key presses. For example, `keyIsDown()` can be used to check if both `LEFT_ARROW` and `UP_ARROW` are pressed:
    if (keyIsDown(LEFT_ARROW) && keyIsDown(UP_ARROW)) {
      // Move diagonally.
    }
    
`keyIsDown()` can check for key presses using keyCode values, as in `keyIsDown(37)` or `keyIsDown(LEFT_ARROW)`. Key codes can be found on websites such as keycode.info.

method

keyIsDown

code

key to check.

Number

### return
whether the key is down or not.

Boolean

` // Click on the canvas to begin detecting key presses. let x = 50; let y = 50; function setup() { createCanvas(100, 100); background(200); describe( 'A gray square with a black circle at its center. The circle moves when the user presses an arrow key. It leaves a trail as it moves.' ); } function draw() { // Update x and y if an arrow key is pressed. if (keyIsDown(LEFT_ARROW) === true) { x -= 1; } if (keyIsDown(RIGHT_ARROW) === true) { x += 1; } if (keyIsDown(UP_ARROW) === true) { y -= 1; } if (keyIsDown(DOWN_ARROW) === true) { y += 1; } // Style the circle. fill(0); // Draw the circle. circle(x, y, 5); } `
` // Click on the canvas to begin detecting key presses. let x = 50; let y = 50; function setup() { createCanvas(100, 100); background(200); describe( 'A gray square with a black circle at its center. The circle moves when the user presses an arrow key. It leaves a trail as it moves.' ); } function draw() { // Update x and y if an arrow key is pressed. if (keyIsDown(37) === true) { x -= 1; } if (keyIsDown(39) === true) { x += 1; } if (keyIsDown(38) === true) { y -= 1; } if (keyIsDown(40) === true) { y += 1; } // Style the circle. fill(0); // Draw the circle. circle(x, y, 5); } `

p5

Events

Keyboard

A `Number` system variable that tracks the mouse's horizontal movement.
`movedX` tracks how many pixels the mouse moves left or right between frames. `movedX` will have a negative value if the mouse moves left between frames and a positive value if it moves right. `movedX` can be calculated as `mouseX - pmouseX`.
Note: `movedX` continues updating even when requestPointerLock() is active. But keep in mind that during an active pointer lock, mouseX and pmouseX are locked, so `movedX` is based on the MouseEvent's movementX value (which may behave differently in different browsers when the user is zoomed in or out).

property

movedX

Number



` function setup() { createCanvas(100, 100); describe( 'A gray square. The text ">>" appears when the user moves the mouse to the right. The text "<<" appears when the user moves the mouse to the left.' ); } function draw() { background(200); // Style the text. textAlign(CENTER); textSize(16); // Display >> when movedX is positive and // << when it's negative. if (movedX > 0) { text('>>', 50, 50); } else if (movedX < 0) { text('<<', 50, 50); } } `

p5

Events

Mouse

A `Number` system variable that tracks the mouse's vertical movement.
`movedY` tracks how many pixels the mouse moves up or down between frames. `movedY` will have a negative value if the mouse moves up between frames and a positive value if it moves down. `movedY` can be calculated as `mouseY - pmouseY`.
Note: `movedY` continues updating even when requestPointerLock() is active. But keep in mind that during an active pointer lock, mouseX and pmouseX are locked, so `movedX` is based on the MouseEvent's movementX value (which may behave differently in different browsers when the user is zoomed in or out).

property

movedY

Number



` function setup() { createCanvas(100, 100); describe( 'A gray square. The text "▲" appears when the user moves the mouse upward. The text "▼" appears when the user moves the mouse downward.' ); } function draw() { background(200); // Style the text. textAlign(CENTER); textSize(16); // Display ▼ when movedY is positive and // ▲ when it's negative. if (movedY > 0) { text('▼', 50, 50); } else if (movedY < 0) { text('▲', 50, 50); } } `

p5

Events

Mouse

A `Number` system variable that tracks the mouse's horizontal position.
`mouseX` keeps track of the mouse's position relative to the top-left corner of the canvas. For example, if the mouse is 50 pixels from the left edge of the canvas, then `mouseX` will be 50.
If touch is used instead of the mouse, then `mouseX` will hold the x-coordinate of the most recent touch point.

property

mouseX

Number



` function setup() { createCanvas(100, 100); describe("A vertical black line moves left and right following the mouse's x-position."); } function draw() { background(200); // Draw a vertical line that follows the mouse's x-coordinate. line(mouseX, 0, mouseX, 100); } `
` function setup() { createCanvas(100, 100); describe("A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse."); } function draw() { background(200); // Style the text. textAlign(CENTER); textSize(16); // Display the mouse's coordinates. text(`x: ${mouseX} y: ${mouseY}`, 50, 50); } `
` function setup() { createCanvas(100, 100, WEBGL); describe("A vertical black line moves left and right following the mouse's x-position."); } function draw() { background(200); // Adjust coordinates for WebGL mode. // The origin (0, 0) is at the center of the canvas. let mx = mouseX - 50; // Draw the line. line(mx, -50, mx, 50); } `
` let font; // Load a font for WebGL mode. function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100, WEBGL); describe( "A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse." ); } function draw() { background(200); // Style the text. textAlign(CENTER); textSize(16); textFont(font); fill(0); // Display the mouse's coordinates. text(`x: ${mouseX} y: ${mouseY}`, 0, 0); } `

p5

Events

Mouse

A `Number` system variable that tracks the mouse's vertical position.
`mouseY` keeps track of the mouse's position relative to the top-left corner of the canvas. For example, if the mouse is 50 pixels from the top edge of the canvas, then `mouseY` will be 50.
If touch is used instead of the mouse, then `mouseY` will hold the y-coordinate of the most recent touch point.

property

mouseY

Number



` function setup() { createCanvas(100, 100); describe("A horizontal black line moves up and down following the mouse's y-position."); } function draw() { background(200); // Draw a horizontal line that follows the mouse's y-coordinate. line(0, mouseY, 100, mouseY); } `
` function setup() { createCanvas(100, 100); describe("A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse."); } function draw() { background(200); // Style the text. textAlign(CENTER); textSize(16); // Display the mouse's coordinates. text(`x: ${mouseX} y: ${mouseY}`, 50, 50); } `
` function setup() { createCanvas(100, 100, WEBGL); describe("A horizontal black line moves up and down following the mouse's y-position."); } function draw() { background(200); // Adjust coordinates for WebGL mode. // The origin (0, 0) is at the center of the canvas. let my = mouseY - 50; // Draw the line. line(-50, my, 50, my); } `
` let font; // Load a font for WebGL mode. function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100, WEBGL); describe( "A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse." ); } function draw() { background(200); // Style the text. textAlign(CENTER); textSize(16); textFont(font); fill(0); // Display the mouse's coordinates. text(`x: ${mouseX} y: ${mouseY}`, 0, 0); } `

p5

Events

Mouse

A `Number` system variable that tracks the mouse's previous horizontal position.
`pmouseX` keeps track of the mouse's position relative to the top-left corner of the canvas. Its value is mouseX from the previous frame. For example, if the mouse was 50 pixels from the left edge of the canvas during the last frame, then `pmouseX` will be 50.
If touch is used instead of the mouse, then `pmouseX` will hold the x-coordinate of the last touch point.
Note: `pmouseX` is reset to the current mouseX value at the start of each touch event.

property

pmouseX

Number



` function setup() { createCanvas(100, 100); // Slow the frame rate. frameRate(10); describe('A line follows the mouse as it moves. The line grows longer with faster movements.'); } function draw() { background(200); line(pmouseX, pmouseY, mouseX, mouseY); } `
` function setup() { createCanvas(100, 100, WEBGL); describe('A line follows the mouse as it moves. The line grows longer with faster movements.'); } function draw() { background(200); // Adjust coordinates for WebGL mode. // The origin (0, 0) is at the center of the canvas. let pmx = pmouseX - 50; let pmy = pmouseY - 50; let mx = mouseX - 50; let my = mouseY - 50; // Draw the line. line(pmx, pmy, mx, my); } `

p5

Events

Mouse

A `Number` system variable that tracks the mouse's previous vertical position.
`pmouseY` keeps track of the mouse's position relative to the top-left corner of the canvas. Its value is mouseY from the previous frame. For example, if the mouse was 50 pixels from the top edge of the canvas during the last frame, then `pmouseY` will be 50.
If touch is used instead of the mouse, then `pmouseY` will hold the y-coordinate of the last touch point.
Note: `pmouseY` is reset to the current mouseY value at the start of each touch event.

property

pmouseY

Number



` function setup() { createCanvas(100, 100); // Slow the frame rate. frameRate(10); describe('A line follows the mouse as it moves. The line grows longer with faster movements.'); } function draw() { background(200); line(pmouseX, pmouseY, mouseX, mouseY); } `
` function setup() { createCanvas(100, 100, WEBGL); describe('A line follows the mouse as it moves. The line grows longer with faster movements.'); } function draw() { background(200); // Adjust coordinates for WebGL mode. // The origin (0, 0) is at the center of the canvas. let pmx = pmouseX - 50; let pmy = pmouseY - 50; let mx = mouseX - 50; let my = mouseY - 50; // Draw the line. line(pmx, pmy, mx, my); } `

p5

Events

Mouse

A `Number` variable that tracks the mouse's horizontal position within the browser.
`winMouseX` keeps track of the mouse's position relative to the top-left corner of the browser window. For example, if the mouse is 50 pixels from the left edge of the browser, then `winMouseX` will be 50.
On a touchscreen device, `winMouseX` will hold the x-coordinate of the most recent touch point.
Note: Use mouseX to track the mouse’s x-coordinate within the canvas.

property

winMouseX

Number



` function setup() { createCanvas(100, 100); describe("A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse."); } function draw() { background(200); // Style the text. textAlign(CENTER); textSize(16); // Display the mouse's coordinates within the browser window. text(`x: ${winMouseX} y: ${winMouseY}`, 50, 50); } `

p5

Events

Mouse

A `Number` variable that tracks the mouse's vertical position within the browser.
`winMouseY` keeps track of the mouse's position relative to the top-left corner of the browser window. For example, if the mouse is 50 pixels from the top edge of the browser, then `winMouseY` will be 50.
On a touchscreen device, `winMouseY` will hold the y-coordinate of the most recent touch point.
Note: Use mouseY to track the mouse’s y-coordinate within the canvas.

property

winMouseY

Number



` function setup() { createCanvas(100, 100); describe("A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse."); } function draw() { background(200); // Style the text. textAlign(CENTER); textSize(16); // Display the mouse's coordinates within the browser window. text(`x: ${winMouseX} y: ${winMouseY}`, 50, 50); } `

p5

Events

Mouse

A `Number` variable that tracks the mouse's previous horizontal position within the browser.
`pwinMouseX` keeps track of the mouse's position relative to the top-left corner of the browser window. Its value is winMouseX from the previous frame. For example, if the mouse was 50 pixels from the left edge of the browser during the last frame, then `pwinMouseX` will be 50.
On a touchscreen device, `pwinMouseX` will hold the x-coordinate of the most recent touch point. `pwinMouseX` is reset to the current winMouseX value at the start of each touch event.
Note: Use pmouseX to track the mouse’s previous x-coordinate within the canvas.

property

pwinMouseX

Number



` function setup() { createCanvas(100, 100); // Slow the frame rate. frameRate(10); describe('A gray square. A white circle at its center grows larger when the mouse moves horizontally.'); } function draw() { background(200); // Calculate the circle's diameter. let d = winMouseX - pwinMouseX; // Draw the circle. circle(50, 50, d); } `
` function setup() { // Create the canvas and set its position. let cnv = createCanvas(100, 100); cnv.position(20, 20); describe('A gray square with a number at its center. The number changes as the user moves the mouse vertically.'); } function draw() { background(200); // Style the text. textAlign(CENTER); textSize(16); // Display pwinMouseX. text(pwinMouseX, 50, 50); } `

p5

Events

Mouse

A `Number` variable that tracks the mouse's previous vertical position within the browser.
`pwinMouseY` keeps track of the mouse's position relative to the top-left corner of the browser window. Its value is winMouseY from the previous frame. For example, if the mouse was 50 pixels from the top edge of the browser during the last frame, then `pwinMouseY` will be 50.
On a touchscreen device, `pwinMouseY` will hold the y-coordinate of the most recent touch point. `pwinMouseY` is reset to the current winMouseY value at the start of each touch event.
Note: Use pmouseY to track the mouse’s previous y-coordinate within the canvas.

property

pwinMouseY

Number



` function setup() { createCanvas(100, 100); // Slow the frame rate. frameRate(10); describe('A gray square. A white circle at its center grows larger when the mouse moves vertically.'); } function draw() { background(200); // Calculate the circle's diameter. let d = winMouseY - pwinMouseY; // Draw the circle. circle(50, 50, d); } `
` function setup() { // Create the canvas and set its position. let cnv = createCanvas(100, 100); cnv.position(20, 20); describe('A gray square with a number at its center. The number changes as the user moves the mouse vertically.'); } function draw() { background(200); // Style the text. textAlign(CENTER); textSize(16); // Display pwinMouseY. text(pwinMouseY, 50, 50); } `

p5

Events

Mouse

A String system variable that contains the value of the last mouse button pressed.
The `mouseButton` variable is either `LEFT`, `RIGHT`, or `CENTER`, depending on which button was pressed last.
Note: Different browsers may track `mouseButton` differently. See MDN for more information.

property

mouseButton

Constant



` function setup() { createCanvas(100, 100); describe( 'A gray square with black text at its center. The text changes from 0 to either "left" or "right" when the user clicks a mouse button.' ); } function draw() { background(200); // Style the text. textAlign(CENTER); textSize(16); // Display the mouse button. text(mouseButton, 50, 50); } `
` function setup() { createCanvas(100, 100); describe( "A gray square. Different shapes appear at its center depending on the mouse button that's clicked." ); } function draw() { background(200); if (mouseIsPressed === true) { if (mouseButton === LEFT) { circle(50, 50, 50); } if (mouseButton === RIGHT) { square(25, 25, 50); } if (mouseButton === CENTER) { triangle(23, 75, 50, 20, 78, 75); } } } `

p5

Events

Mouse

A `Boolean` system variable that's `true` if the mouse is pressed and `false` if not.

property

mouseIsPressed

Boolean



` function setup() { createCanvas(100, 100); describe( 'A gray square with the word "false" at its center. The word changes to "true" when the user presses a mouse button.' ); } function draw() { background(200); // Style the text. textAlign(CENTER); textSize(16); // Display the mouseIsPressed variable. text(mouseIsPressed, 25, 50); } `
` function setup() { createCanvas(100, 100); describe( 'A gray square with a white square at its center. The inner square turns black when the user presses the mouse.' ); } function draw() { background(200); // Style the square. if (mouseIsPressed === true) { fill(0); } else { fill(255); } // Draw the square. square(25, 25, 50); } `

p5

Events

Mouse

A function that's called when the mouse moves.
Declaring the function `mouseMoved()` sets a code block to run automatically when the user moves the mouse without clicking any mouse buttons:
    function mouseMoved() {
      // Code to run.
    }
    
The mouse system variables, such as mouseX and mouseY, will be updated with their most recent value when `mouseMoved()` is called by p5.js:
    function mouseMoved() {
      if (mouseX < 50) {
        // Code to run if the mouse is on the left.
      }
    
      if (mouseY > 50) {
        // Code to run if the mouse is near the bottom.
      }
    }
    
The parameter, `event`, is optional. `mouseMoved()` is always passed a MouseEvent object with properties that describe the mouse move event:
    function mouseMoved(event) {
      // Code to run that uses the event.
      console.log(event);
    }
    
Browsers may have default behaviors attached to various mouse events. For example, some browsers highlight text when the user moves the mouse while pressing a mouse button. To prevent any default behavior for this event, add `return false;` to the end of the function.

method

mouseMoved

event

optional `MouseEvent` argument.

MouseEvent

` let value = 0; function setup() { createCanvas(100, 100); describe( 'A gray square with a black square at its center. The inner square becomes lighter as the mouse moves.' ); } function draw() { background(200); // Style the square. fill(value); // Draw the square. square(25, 25, 50); } function mouseMoved() { // Update the grayscale value. value += 5; // Reset the grayscale value. if (value > 255) { value = 0; } // Uncomment to prevent any default behavior. // return false; } `

p5

Events

Mouse

A function that's called when the mouse moves while a button is pressed.
Declaring the function `mouseDragged()` sets a code block to run automatically when the user clicks and drags the mouse:
    function mouseDragged() {
      // Code to run.
    }
    
The mouse system variables, such as mouseX and mouseY, will be updated with their most recent value when `mouseDragged()` is called by p5.js:
    function mouseDragged() {
      if (mouseX < 50) {
        // Code to run if the mouse is on the left.
      }
    
      if (mouseY > 50) {
        // Code to run if the mouse is near the bottom.
      }
    }
    
The parameter, `event`, is optional. `mouseDragged()` is always passed a MouseEvent object with properties that describe the mouse drag event:
    function mouseDragged(event) {
      // Code to run that uses the event.
      console.log(event);
    }
    
On touchscreen devices, `mouseDragged()` will run when a user moves a touch point if touchMoved() isn’t declared. If touchMoved() is declared, then touchMoved() will run when a user moves a touch point and `mouseDragged()` won’t.
Browsers may have default behaviors attached to various mouse events. For example, some browsers highlight text when the user moves the mouse while pressing a mouse button. To prevent any default behavior for this event, add `return false;` to the end of the function.

method

mouseDragged

event

optional `MouseEvent` argument.

MouseEvent

` let value = 0; function setup() { createCanvas(100, 100); describe( 'A gray square with a black square at its center. The inner square becomes lighter as the user drags the mouse.' ); } function draw() { background(200); // Style the square. fill(value); // Draw the square. square(25, 25, 50); } function mouseDragged() { // Update the grayscale value. value += 5; // Reset the grayscale value. if (value > 255) { value = 0; } // Uncomment to prevent any default behavior. // return false; } `

p5

Events

Mouse

A function that's called once when a mouse button is pressed.
Declaring the function `mousePressed()` sets a code block to run automatically when the user presses a mouse button:
    function mousePressed() {
      // Code to run.
    }
    
The mouse system variables, such as mouseX and mouseY, will be updated with their most recent value when `mousePressed()` is called by p5.js:
    function mousePressed() {
      if (mouseX < 50) {
        // Code to run if the mouse is on the left.
      }
    
      if (mouseY > 50) {
        // Code to run if the mouse is near the bottom.
      }
    }
    
The parameter, `event`, is optional. `mousePressed()` is always passed a MouseEvent object with properties that describe the mouse press event:
    function mousePressed(event) {
      // Code to run that uses the event.
      console.log(event);
    }
    
On touchscreen devices, `mousePressed()` will run when a user’s touch begins if touchStarted() isn’t declared. If touchStarted() is declared, then touchStarted() will run when a user’s touch begins and `mousePressed()` won’t.
Browsers may have default behaviors attached to various mouse events. For example, some browsers highlight text when the user moves the mouse while pressing a mouse button. To prevent any default behavior for this event, add `return false;` to the end of the function.
Note: `mousePressed()`, mouseReleased(), and mouseClicked() are all related. `mousePressed()` runs as soon as the user clicks the mouse. mouseReleased() runs as soon as the user releases the mouse click. mouseClicked() runs immediately after mouseReleased().

method

mousePressed

event

optional `MouseEvent` argument.

MouseEvent

` let value = 0; function setup() { createCanvas(100, 100); describe( 'A gray square with a black square at its center. The inner square becomes lighter when the user presses a mouse button.' ); } function draw() { background(200); // Style the square. fill(value); // Draw the square. square(25, 25, 50); } function mousePressed() { // Update the grayscale value. value += 5; // Reset the grayscale value. if (value > 255) { value = 0; } // Uncomment to prevent any default behavior. // return false; } `
` function setup() { createCanvas(100, 100); // Style the circle. fill('orange'); stroke('royalblue'); strokeWeight(10); describe( 'An orange circle with a thick, blue border drawn on a gray background. When the user presses and holds the mouse, the border becomes thin and pink. When the user releases the mouse, the border becomes thicker and changes color to blue.' ); } function draw() { background(220); // Draw the circle. circle(50, 50, 20); } // Set the stroke color and weight as soon as the user clicks. function mousePressed() { stroke('deeppink'); strokeWeight(3); } // Set the stroke and fill colors as soon as the user releases // the mouse. function mouseReleased() { stroke('royalblue'); // This is never visible because fill() is called // in mouseClicked() which runs immediately after // mouseReleased(); fill('limegreen'); } // Set the fill color and stroke weight after // mousePressed() and mouseReleased() are called. function mouseClicked() { fill('orange'); strokeWeight(10); } `

p5

Events

Mouse

A function that's called once when a mouse button is released.
Declaring the function `mouseReleased()` sets a code block to run automatically when the user releases a mouse button after having pressed it:
    function mouseReleased() {
      // Code to run.
    }
    
The mouse system variables, such as mouseX and mouseY, will be updated with their most recent value when `mouseReleased()` is called by p5.js:
    function mouseReleased() {
      if (mouseX < 50) {
        // Code to run if the mouse is on the left.
      }
    
      if (mouseY > 50) {
        // Code to run if the mouse is near the bottom.
      }
    }
    
The parameter, `event`, is optional. `mouseReleased()` is always passed a MouseEvent object with properties that describe the mouse release event:
    function mouseReleased(event) {
      // Code to run that uses the event.
      console.log(event);
    }
    
On touchscreen devices, `mouseReleased()` will run when a user’s touch ends if touchEnded() isn’t declared. If touchEnded() is declared, then touchEnded() will run when a user’s touch ends and `mouseReleased()` won’t.
Browsers may have default behaviors attached to various mouse events. For example, some browsers highlight text when the user moves the mouse while pressing a mouse button. To prevent any default behavior for this event, add `return false;` to the end of the function.
Note: mousePressed(), `mouseReleased()`, and mouseClicked() are all related. mousePressed() runs as soon as the user clicks the mouse. `mouseReleased()` runs as soon as the user releases the mouse click. mouseClicked() runs immediately after `mouseReleased()`.

method

mouseReleased

event

optional `MouseEvent` argument.

MouseEvent

` let value = 0; function setup() { createCanvas(100, 100); describe( 'A gray square with a black square at its center. The inner square becomes lighter when the user presses and releases a mouse button.' ); } function draw() { background(200); // Style the square. fill(value); // Draw the square. square(25, 25, 50); } function mouseReleased() { // Update the grayscale value. value += 5; // Reset the grayscale value. if (value > 255) { value = 0; } // Uncomment to prevent any default behavior. // return false; } `
` function setup() { createCanvas(100, 100); // Style the circle. fill('orange'); stroke('royalblue'); strokeWeight(10); describe( 'An orange circle with a thick, blue border drawn on a gray background. When the user presses and holds the mouse, the border becomes thin and pink. When the user releases the mouse, the border becomes thicker and changes color to blue.' ); } function draw() { background(220); // Draw the circle. circle(50, 50, 20); } // Set the stroke color and weight as soon as the user clicks. function mousePressed() { stroke('deeppink'); strokeWeight(3); } // Set the stroke and fill colors as soon as the user releases // the mouse. function mouseReleased() { stroke('royalblue'); // This is never visible because fill() is called // in mouseClicked() which runs immediately after // mouseReleased(); fill('limegreen'); } // Set the fill color and stroke weight after // mousePressed() and mouseReleased() are called. function mouseClicked() { fill('orange'); strokeWeight(10); } `

p5

Events

Mouse

A function that's called once after a mouse button is pressed and released.
Declaring the function `mouseClicked()` sets a code block to run automatically when the user releases a mouse button after having pressed it:
    function mouseClicked() {
      // Code to run.
    }
    
The mouse system variables, such as mouseX and mouseY, will be updated with their most recent value when `mouseClicked()` is called by p5.js:
    function mouseClicked() {
      if (mouseX < 50) {
        // Code to run if the mouse is on the left.
      }
    
      if (mouseY > 50) {
        // Code to run if the mouse is near the bottom.
      }
    }
    
The parameter, `event`, is optional. `mouseClicked()` is always passed a MouseEvent object with properties that describe the mouse click event:
    function mouseClicked(event) {
      // Code to run that uses the event.
      console.log(event);
    }
    
On touchscreen devices, `mouseClicked()` will run when a user’s touch ends if touchEnded() isn’t declared. If touchEnded() is declared, then touchEnded() will run when a user’s touch ends and `mouseClicked()` won’t.
Browsers may have default behaviors attached to various mouse events. For example, some browsers highlight text when the user moves the mouse while pressing a mouse button. To prevent any default behavior for this event, add `return false;` to the end of the function.
Note: mousePressed(), mouseReleased(), and `mouseClicked()` are all related. mousePressed() runs as soon as the user clicks the mouse. mouseReleased() runs as soon as the user releases the mouse click. `mouseClicked()` runs immediately after mouseReleased().

method

mouseClicked

event

optional `MouseEvent` argument.

MouseEvent

` let value = 0; function setup() { createCanvas(100, 100); describe( 'A gray square with a black square at its center. The inner square changes color when the user presses and releases a mouse button.' ); } function draw() { background(200); // Style the square. fill(value); // Draw the square. square(25, 25, 50); } // Toggle the square's color when the user clicks. function mouseClicked() { if (value === 0) { value = 255; } else { value = 0; } // Uncomment to prevent any default behavior. // return false; } `
` function setup() { createCanvas(100, 100); // Style the circle. fill('orange'); stroke('royalblue'); strokeWeight(10); describe( 'An orange circle with a thick, blue border drawn on a gray background. When the user presses and holds the mouse, the border becomes thin and pink. When the user releases the mouse, the border becomes thicker and changes color to blue.' ); } function draw() { background(220); // Draw the circle. circle(50, 50, 20); } // Set the stroke color and weight as soon as the user clicks. function mousePressed() { stroke('deeppink'); strokeWeight(3); } // Set the stroke and fill colors as soon as the user releases // the mouse. function mouseReleased() { stroke('royalblue'); // This is never visible because fill() is called // in mouseClicked() which runs immediately after // mouseReleased(); fill('limegreen'); } // Set the fill color and stroke weight after // mousePressed() and mouseReleased() are called. function mouseClicked() { fill('orange'); strokeWeight(10); } `

p5

Events

Mouse

A function that's called once when a mouse button is clicked twice quickly.
Declaring the function `doubleClicked()` sets a code block to run automatically when the user presses and releases the mouse button twice quickly:
    function doubleClicked() {
      // Code to run.
    }
    
The mouse system variables, such as mouseX and mouseY, will be updated with their most recent value when `doubleClicked()` is called by p5.js:
    function doubleClicked() {
      if (mouseX < 50) {
        // Code to run if the mouse is on the left.
      }
    
      if (mouseY > 50) {
        // Code to run if the mouse is near the bottom.
      }
    }
    
The parameter, `event`, is optional. `doubleClicked()` is always passed a MouseEvent object with properties that describe the double-click event:
    function doubleClicked(event) {
      // Code to run that uses the event.
      console.log(event);
    }
    
On touchscreen devices, code placed in `doubleClicked()` will run after two touches that occur within a short time.
Browsers may have default behaviors attached to various mouse events. For example, some browsers highlight text when the user moves the mouse while pressing a mouse button. To prevent any default behavior for this event, add `return false;` to the end of the function.

method

doubleClicked

event

optional `MouseEvent` argument.

MouseEvent

` let value = 0; function setup() { createCanvas(100, 100); describe( 'A gray square with a black square at its center. The inner square changes color when the user double-clicks.' ); } function draw() { background(200); // Style the square. fill(value); // Draw the square. square(25, 25, 50); } // Toggle the square's color when the user double-clicks. function doubleClicked() { if (value === 0) { value = 255; } else { value = 0; } // Uncomment to prevent any default behavior. // return false; } `
` let value = 0; function setup() { createCanvas(100, 100); describe( 'A gray square with a black circle at its center. When the user double-clicks on the circle, it changes color to white.' ); } function draw() { background(200); // Style the circle. fill(value); // Draw the circle. circle(50, 50, 80); } // Reassign value to 255 when the user double-clicks on the circle. function doubleClicked() { if (dist(50, 50, mouseX, mouseY) < 40) { value = 255; } // Uncomment to prevent any default behavior. // return false; } `

p5

Events

Mouse

A function that's called once when the mouse wheel moves.
Declaring the function `mouseWheel()` sets a code block to run automatically when the user scrolls with the mouse wheel:
    function mouseWheel() {
      // Code to run.
    }
    
The mouse system variables, such as mouseX and mouseY, will be updated with their most recent value when `mouseWheel()` is called by p5.js:
    function mouseWheel() {
      if (mouseX < 50) {
        // Code to run if the mouse is on the left.
      }
    
      if (mouseY > 50) {
        // Code to run if the mouse is near the bottom.
      }
    }
    
The parameter, `event`, is optional. `mouseWheel()` is always passed a MouseEvent object with properties that describe the mouse scroll event:
    function mouseWheel(event) {
      // Code to run that uses the event.
      console.log(event);
    }
    
The `event` object has many properties including `delta`, a `Number` containing the distance that the user scrolled. For example, `event.delta` might have the value 5 when the user scrolls up. `event.delta` is positive if the user scrolls up and negative if they scroll down. The signs are opposite on macOS with "natural" scrolling enabled.
Browsers may have default behaviors attached to various mouse events. For example, some browsers highlight text when the user moves the mouse while pressing a mouse button. To prevent any default behavior for this event, add `return false;` to the end of the function.
Note: On Safari, `mouseWheel()` may only work as expected if `return false;` is added at the end of the function.

method

mouseWheel

event

optional `WheelEvent` argument.

WheelEvent

` let circleSize = 0; function setup() { createCanvas(100, 100); describe( 'A gray square. A white circle at its center grows up when the user scrolls the mouse wheel.' ); } function draw() { background(200); // Draw the circle circle(50, 50, circleSize); } // Increment circleSize when the user scrolls the mouse wheel. function mouseWheel() { circleSize += 1; // Uncomment to prevent any default behavior. // return false; } `
` let direction = ''; function setup() { createCanvas(100, 100); describe( 'A gray square. An arrow at its center points up when the user scrolls up. The arrow points down when the user scrolls down.' ); } function draw() { background(200); // Style the text. textAlign(CENTER); textSize(16); // Draw an arrow that points where // the mouse last scrolled. text(direction, 50, 50); } // Change direction when the user scrolls the mouse wheel. function mouseWheel(event) { if (event.delta > 0) { direction = '▲'; } else { direction = '▼'; } // Uncomment to prevent any default behavior. // return false; } `

p5

Events

Mouse

Locks the mouse pointer to its current position and makes it invisible.
`requestPointerLock()` allows the mouse to move forever without leaving the screen. Calling `requestPointerLock()` locks the values of mouseX, mouseY, pmouseX, and pmouseY. movedX and movedY continue updating and can be used to get the distance the mouse moved since the last frame was drawn. Calling exitPointerLock() resumes updating the mouse system variables.
Note: Most browsers require an input, such as a click, before calling `requestPointerLock()`. It’s recommended to call `requestPointerLock()` in an event function such as doubleClicked().

method

requestPointerLock

` let score = 0; function setup() { createCanvas(100, 100); describe( 'A gray square with the text "Score: X" at its center. The score increases when the user moves the mouse upward. It decreases when the user moves the mouse downward.' ); } function draw() { background(200); // Update the score. score -= movedY; // Style the text. textAlign(CENTER); textSize(16); // Display the score. text(`Score: ${score}`, 50, 50); } // Lock the pointer when the user double-clicks. function doubleClicked() { requestPointerLock(); } `

p5

Events

Mouse

Exits a pointer lock started with requestPointerLock.
Calling `requestPointerLock()` locks the values of mouseX, mouseY, pmouseX, and pmouseY. Calling `exitPointerLock()` resumes updating the mouse system variables.
Note: Most browsers require an input, such as a click, before calling `requestPointerLock()`. It’s recommended to call `requestPointerLock()` in an event function such as doubleClicked().

method

exitPointerLock

` let isLocked = false; function setup() { createCanvas(100, 100); describe( 'A gray square with a word at its center. The word changes between "Unlocked" and "Locked" when the user double-clicks.' ); } function draw() { background(200); // Style the text. textAlign(CENTER); textSize(16); // Tell the user whether the pointer is locked. if (isLocked === true) { text('Locked', 50, 50); } else { text('Unlocked', 50, 50); } } // Toggle the pointer lock when the user double-clicks. function doubleClicked() { if (isLocked === true) { exitPointerLock(); isLocked = false; } else { requestPointerLock(); isLocked = true; } } `

p5

Events

Mouse

An `Array` of all the current touch points on a touchscreen device.
The `touches` array is empty by default. When the user touches their screen, a new touch point is tracked and added to the array. Touch points are `Objects` with the following properties:
    // Iterate over the touches array.
    for (let touch of touches) {
      // x-coordinate relative to the top-left
      // corner of the canvas.
      console.log(touch.x);
    
      // y-coordinate relative to the top-left
      // corner of the canvas.
      console.log(touch.y);
    
      // x-coordinate relative to the top-left
      // corner of the browser.
      console.log(touch.winX);
    
      // y-coordinate relative to the top-left
      // corner of the browser.
      console.log(touch.winY);
    
      // ID number
      console.log(touch.id);
    }
    

property

touches

Object[]



` // On a touchscreen device, touch the canvas using one or more fingers // at the same time. function setup() { createCanvas(100, 100); describe( 'A gray square. White circles appear where the user touches the square.' ); } function draw() { background(200); // Draw a circle at each touch point. for (let touch of touches) { circle(touch.x, touch.y, 40); } } `
` // On a touchscreen device, touch the canvas using one or more fingers // at the same time. function setup() { createCanvas(100, 100); describe( 'A gray square. Labels appear where the user touches the square, displaying the coordinates.' ); } function draw() { background(200); // Draw a label above each touch point. for (let touch of touches) { text(`${touch.x}, ${touch.y}`, touch.x, touch.y - 40); } } `

p5

Events

Touch

A function that's called once each time the user touches the screen.
Declaring a function called `touchStarted()` sets a code block to run automatically each time the user begins touching a touchscreen device:
    function touchStarted() {
      // Code to run.
    }
    
The touches array will be updated with the most recent touch points when `touchStarted()` is called by p5.js:
    function touchStarted() {
      // Paint over the background.
      background(200);
    
      // Mark each touch point once with a circle.
      for (let touch of touches) {
        circle(touch.x, touch.y, 40);
      }
    }
    
The parameter, event, is optional. `touchStarted()` will be passed a TouchEvent object with properties that describe the touch event:
    function touchStarted(event) {
      // Code to run that uses the event.
      console.log(event);
    }
    
On touchscreen devices, mousePressed() will run when a user’s touch starts if `touchStarted()` isn’t declared. If `touchStarted()` is declared, then `touchStarted()` will run when a user’s touch starts and mousePressed() won’t.
Note: `touchStarted()`, touchEnded(), and touchMoved() are all related. `touchStarted()` runs as soon as the user touches a touchscreen device. touchEnded() runs as soon as the user ends a touch. touchMoved() runs repeatedly as the user moves any touch points.

method

touchStarted

event

optional `TouchEvent` argument.

TouchEvent

` // On a touchscreen device, touch the canvas using one or more fingers // at the same time. let value = 0; function setup() { createCanvas(100, 100); describe( 'A gray square with a black square at its center. The inner square switches color between black and white each time the user touches the screen.' ); } function draw() { background(200); // Style the square. fill(value); // Draw the square. square(25, 25, 50); } // Toggle colors with each touch. function touchStarted() { if (value === 0) { value = 255; } else { value = 0; } } `
` // On a touchscreen device, touch the canvas using one or more fingers // at the same time. let bgColor = 50; let fillColor = 255; let borderWidth = 0.5; function setup() { createCanvas(100, 100); describe( 'A gray square with the number 0 at the top-center. The number tracks the number of places the user is touching the screen. Circles appear at each touch point and change style in response to events.' ); } function draw() { background(bgColor); // Style the text. textAlign(CENTER); textSize(16); fill(0); noStroke(); // Display the number of touch points. text(touches.length, 50, 20); // Style the touch points. fill(fillColor); stroke(0); strokeWeight(borderWidth); // Display the touch points as circles. for (let touch of touches) { circle(touch.x, touch.y, 40); } } // Set the background color to a random grayscale value. function touchStarted() { bgColor = random(80, 255); } // Set the fill color to a random grayscale value. function touchEnded() { fillColor = random(0, 255); } // Set the stroke weight. function touchMoved() { // Increment the border width. borderWidth += 0.1; // Reset the border width once it's too thick. if (borderWidth > 20) { borderWidth = 0.5; } } `

p5

Events

Touch

A function that's called when the user touches the screen and moves.
Declaring the function `touchMoved()` sets a code block to run automatically when the user touches a touchscreen device and moves:
    function touchMoved() {
      // Code to run.
    }
    
The touches array will be updated with the most recent touch points when `touchMoved()` is called by p5.js:
    function touchMoved() {
      // Paint over the background.
      background(200);
    
      // Mark each touch point while the user moves.
      for (let touch of touches) {
        circle(touch.x, touch.y, 40);
      }
    }
    
The parameter, event, is optional. `touchMoved()` will be passed a TouchEvent object with properties that describe the touch event:
    function touchMoved(event) {
      // Code to run that uses the event.
      console.log(event);
    }
    
On touchscreen devices, mouseDragged() will run when the user’s touch points move if `touchMoved()` isn’t declared. If `touchMoved()` is declared, then `touchMoved()` will run when a user’s touch points move and mouseDragged() won’t.
Note: touchStarted(), touchEnded(), and `touchMoved()` are all related. touchStarted() runs as soon as the user touches a touchscreen device. touchEnded() runs as soon as the user ends a touch. `touchMoved()` runs repeatedly as the user moves any touch points.

method

touchMoved

event

optional TouchEvent argument.

TouchEvent

` // On a touchscreen device, touch the canvas using one or more fingers // at the same time. let value = 0; function setup() { createCanvas(100, 100); describe( 'A gray square with a black square at its center. The inner square becomes lighter when the user touches the screen and moves.' ); } function draw() { background(200); // Style the square. fill(value); // Draw the square. square(25, 25, 50); } function touchMoved() { // Update the grayscale value. value += 5; // Reset the grayscale value. if (value > 255) { value = 0; } } `
` // On a touchscreen device, touch the canvas using one or more fingers // at the same time. let bgColor = 50; let fillColor = 255; let borderWidth = 0.5; function setup() { createCanvas(100, 100); describe( 'A gray square with the number 0 at the top-center. The number tracks the number of places the user is touching the screen. Circles appear at each touch point and change style in response to events.' ); } function draw() { background(bgColor); // Style the text. textAlign(CENTER); textSize(16); fill(0); noStroke(); // Display the number of touch points. text(touches.length, 50, 20); // Style the touch points. fill(fillColor); stroke(0); strokeWeight(borderWidth); // Display the touch points as circles. for (let touch of touches) { circle(touch.x, touch.y, 40); } } // Set the background color to a random grayscale value. function touchStarted() { bgColor = random(80, 255); } // Set the fill color to a random grayscale value. function touchEnded() { fillColor = random(0, 255); } // Set the stroke weight. function touchMoved() { // Increment the border width. borderWidth += 0.1; // Reset the border width once it's too thick. if (borderWidth > 20) { borderWidth = 0.5; } } `

p5

Events

Touch

A function that's called once each time a screen touch ends.
Declaring the function `touchEnded()` sets a code block to run automatically when the user stops touching a touchscreen device:
    function touchEnded() {
      // Code to run.
    }
    
The touches array will be updated with the most recent touch points when `touchEnded()` is called by p5.js:
    function touchEnded() {
      // Paint over the background.
      background(200);
    
      // Mark each remaining touch point when the user stops
      // a touch.
      for (let touch of touches) {
        circle(touch.x, touch.y, 40);
      }
    }
    
The parameter, event, is optional. `touchEnded()` will be passed a TouchEvent object with properties that describe the touch event:
    function touchEnded(event) {
      // Code to run that uses the event.
      console.log(event);
    }
    
On touchscreen devices, mouseReleased() will run when the user’s touch ends if `touchEnded()` isn’t declared. If `touchEnded()` is declared, then `touchEnded()` will run when a user’s touch ends and mouseReleased() won’t.
Note: touchStarted(), `touchEnded()`, and touchMoved() are all related. touchStarted() runs as soon as the user touches a touchscreen device. `touchEnded()` runs as soon as the user ends a touch. touchMoved() runs repeatedly as the user moves any touch points.

method

touchEnded

event

optional `TouchEvent` argument.

TouchEvent

` // On a touchscreen device, touch the canvas using one or more fingers // at the same time. let value = 0; function setup() { createCanvas(100, 100); describe( 'A gray square with a black square at its center. The inner square switches color between black and white each time the user stops touching the screen.' ); } function draw() { background(200); // Style the square. fill(value); // Draw the square. square(25, 25, 50); } // Toggle colors when a touch ends. function touchEnded() { if (value === 0) { value = 255; } else { value = 0; } } `
` // On a touchscreen device, touch the canvas using one or more fingers // at the same time. let bgColor = 50; let fillColor = 255; let borderWidth = 0.5; function setup() { createCanvas(100, 100); describe( 'A gray square with the number 0 at the top-center. The number tracks the number of places the user is touching the screen. Circles appear at each touch point and change style in response to events.' ); } function draw() { background(bgColor); // Style the text. textAlign(CENTER); textSize(16); fill(0); noStroke(); // Display the number of touch points. text(touches.length, 50, 20); // Style the touch points. fill(fillColor); stroke(0); strokeWeight(borderWidth); // Display the touch points as circles. for (let touch of touches) { circle(touch.x, touch.y, 40); } } // Set the background color to a random grayscale value. function touchStarted() { bgColor = random(80, 255); } // Set the fill color to a random grayscale value. function touchEnded() { fillColor = random(0, 255); } // Set the stroke weight. function touchMoved() { // Increment the border width. borderWidth += 0.1; // Reset the border width once it's too thick. if (borderWidth > 20) { borderWidth = 0.5; } } `

p5

Events

Touch

This module defines the filters for use with image buffers.
This module is basically a collection of functions stored in an object as opposed to modules. The functions are destructive, modifying the passed in canvas rather than creating a copy.
Generally speaking users of this module will use the Filters.apply method on a canvas to create an effect.
A number of functions are borrowed/adapted from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/ or the java processing implementation.

p5

Events

This module defines the p5 methods for the p5.Image class for drawing images to the main display canvas.

p5

Image

Image

Creates a new p5.Image object.
`createImage()` uses the `width` and `height` parameters to set the new p5.Image object's dimensions in pixels. The new p5.Image can be modified by updating its pixels array or by calling its get() and set() methods. The loadPixels() method must be called before reading or modifying pixel values. The updatePixels() method must be called for updates to take effect.
Note: The new p5.Image object is transparent by default.

method

createImage

width

width in pixels.

Integer

height

height in pixels.

Integer

### return
new p5.Image object.

p5.Image

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Image object. let img = createImage(66, 66); // Load the image's pixels into memory. img.loadPixels(); // Set all the image's pixels to black. for (let x = 0; x < img.width; x += 1) { for (let y = 0; y < img.height; y += 1) { img.set(x, y, 0); } } // Update the image's pixel values. img.updatePixels(); // Draw the image. image(img, 17, 17); describe('A black square drawn in the middle of a gray square.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create a p5.Image object. let img = createImage(66, 66); // Load the image's pixels into memory. img.loadPixels(); // Create a color gradient. for (let x = 0; x < img.width; x += 1) { for (let y = 0; y < img.height; y += 1) { // Calculate the transparency. let a = map(x, 0, img.width, 0, 255); // Create a p5.Color object. let c = color(0, a); // Set the pixel's color. img.set(x, y, c); } } // Update the image's pixels. img.updatePixels(); // Display the image. image(img, 17, 17); describe('A square with a horizontal color gradient that transitions from gray to black.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create a p5.Image object. let img = createImage(66, 66); // Load the pixels into memory. img.loadPixels(); // Get the current pixel density. let d = pixelDensity(); // Calculate the pixel that is halfway through the image's pixel array. let halfImage = 4 * (d * img.width) * (d * img.height / 2); // Set half of the image's pixels to black. for (let i = 0; i < halfImage; i += 4) { // Red. img.pixels[i] = 0; // Green. img.pixels[i + 1] = 0; // Blue. img.pixels[i + 2] = 0; // Alpha. img.pixels[i + 3] = 255; } // Update the image's pixels. img.updatePixels(); // Display the image. image(img, 17, 17); describe('A black square drawn in the middle of a gray square.'); } `

p5

Image

Image

Saves the current canvas as an image.
By default, `saveCanvas()` saves the canvas as a PNG image called `untitled.png`.
The first parameter, `filename`, is optional. It's a string that sets the file's name. If a file extension is included, as in `saveCanvas('drawing.png')`, then the image will be saved using that format.
The second parameter, `extension`, is also optional. It sets the files format. Either `'png'`, `'webp'`, or `'jpg'` can be used. For example, `saveCanvas('drawing', 'jpg')` saves the canvas to a file called `drawing.jpg`.
Note: The browser will either save the file immediately or prompt the user with a dialogue window.

method

saveCanvas

` function setup() { createCanvas(100, 100); background(255); // Save the canvas to 'untitled.png'. saveCanvas(); describe('A white square.'); } `
` function setup() { createCanvas(100, 100); background(255); // Save the canvas to 'myCanvas.jpg'. saveCanvas('myCanvas.jpg'); describe('A white square.'); } `
` function setup() { createCanvas(100, 100); background(255); // Save the canvas to 'myCanvas.jpg'. saveCanvas('myCanvas', 'jpg'); describe('A white square.'); } `
` function setup() { let cnv = createCanvas(100, 100); background(255); // Save the canvas to 'untitled.png'. saveCanvas(cnv); describe('A white square.'); } `
` function setup() { let cnv = createCanvas(100, 100); background(255); // Save the canvas to 'myCanvas.jpg'. saveCanvas(cnv, 'myCanvas.jpg'); describe('A white square.'); } `
` function setup() { let cnv = createCanvas(100, 100); background(255); // Save the canvas to 'myCanvas.jpg'. saveCanvas(cnv, 'myCanvas', 'jpg'); describe('A white square.'); } `

p5

Image

Image

selectedCanvas

reference to a specific HTML5 canvas element.

p5.Framebuffer|p5.Element|HTMLCanvasElement

filename

file name. Defaults to 'untitled'.

String

extension

file extension, either 'png', 'webp', or 'jpg'. Defaults to 'png'.

String

filename



String

extension



String

Captures a sequence of frames from the canvas that can be saved as images.
`saveFrames()` creates an array of frame objects. Each frame is stored as an object with its file type, file name, and image data as a string. For example, the first saved frame might have the following properties:
`{ ext: 'png', filename: 'frame0', imageData: 'data:image/octet-stream;base64, abc123' }`.
The first parameter, `filename`, sets the prefix for the file names. For example, setting the prefix to `'frame'` would generate the image files `frame0.png`, `frame1.png`, and so on.
The second parameter, `extension`, sets the file type to either `'png'` or `'jpg'`.
The third parameter, `duration`, sets the duration to record in seconds. The maximum duration is 15 seconds.
The fourth parameter, `framerate`, sets the number of frames to record per second. The maximum frame rate value is 22. Limits are placed on `duration` and `framerate` to avoid using too much memory. Recording large canvases can easily crash sketches or even web browsers.
The fifth parameter, `callback`, is optional. If a function is passed, image files won't be saved by default. The callback function can be used to process an array containing the data for each captured frame. The array of image data contains a sequence of objects with three properties for each frame: `imageData`, `filename`, and `extension`.
Note: Frames are downloaded as individual image files by default.

method

saveFrames

filename

prefix of file name.

String

extension

file extension, either 'jpg' or 'png'.

String

duration

duration in seconds to record. This parameter will be constrained to be less or equal to 15.

Number

framerate

number of frames to save per second. This parameter will be constrained to be less or equal to 22.

Number

callback

callback function that will be executed to handle the image data. This function should accept an array as argument. The array will contain the specified number of frames of objects. Each object has three properties: `imageData`, `filename`, and `extension`.

Function(Array)

` function setup() { createCanvas(100, 100); describe('A square repeatedly changes color from blue to pink.'); } function draw() { let r = frameCount % 255; let g = 50; let b = 100; background(r, g, b); } // Save the frames when the user presses the 's' key. function keyPressed() { if (key === 's') { saveFrames('frame', 'png', 1, 5); } } `
` function setup() { createCanvas(100, 100); describe('A square repeatedly changes color from blue to pink.'); } function draw() { let r = frameCount % 255; let g = 50; let b = 100; background(r, g, b); } // Print 5 frames when the user presses the mouse. function mousePressed() { saveFrames('frame', 'png', 1, 5, printFrames); } // Prints an array of objects containing raw image data, filenames, and extensions. function printFrames(frames) { for (let frame of frames) { print(frame); } } `

p5

Image

Image

Loads an image to create a p5.Image object.
`loadImage()` interprets the first parameter one of three ways. If the path to an image file is provided, `loadImage()` will load it. Paths to local files should be relative, such as `'assets/thundercat.jpg'`. URLs such as `'https://example.com/thundercat.jpg'` may be blocked due to browser security. Raw image data can also be passed as a base64 encoded image in the form `'data:image/png;base64,arandomsequenceofcharacters'`.
The second parameter is optional. If a function is passed, it will be called once the image has loaded. The callback function can optionally use the new p5.Image object.
The third parameter is also optional. If a function is passed, it will be called if the image fails to load. The callback function can optionally use the event error.
Images can take time to load. Calling `loadImage()` in preload() ensures images load before they're used in setup() or draw().

method

loadImage

path

path of the image to be loaded or base64 encoded image.

String

successCallback

function called with p5.Image once it loads.

function(p5.Image)

failureCallback

function called with event error if the image fails to load.

Function(Event)

### return
the p5.Image object.

p5.Image

` let img; // Load the image and create a p5.Image object. function preload() { img = loadImage('assets/laDefense.jpg'); } function setup() { createCanvas(100, 100); // Draw the image. image(img, 0, 0); describe('Image of the underside of a white umbrella and a gridded ceiling.'); } `
` function setup() { // Call handleImage() once the image loads. loadImage('assets/laDefense.jpg', handleImage); describe('Image of the underside of a white umbrella and a gridded ceiling.'); } // Display the image. function handleImage(img) { image(img, 0, 0); } `
` function setup() { // Call handleImage() once the image loads or // call handleError() if an error occurs. loadImage('assets/laDefense.jpg', handleImage, handleError); } // Display the image. function handleImage(img) { image(img, 0, 0); describe('Image of the underside of a white umbrella and a gridded ceiling.'); } // Log the error. function handleError(event) { console.error('Oops!', event); } `

p5

Image

Loading & Displaying

Generates a gif from a sketch and saves it to a file.
`saveGif()` may be called in setup() or at any point while a sketch is running.
The first parameter, `fileName`, sets the gif's file name.
The second parameter, `duration`, sets the gif's duration in seconds.
The third parameter, `options`, is optional. If an object is passed, `saveGif()` will use its properties to customize the gif. `saveGif()` recognizes the properties `delay`, `units`, `silent`, `notificationDuration`, and `notificationID`.

method

saveGif

filename

file name of gif.

String

duration

duration in seconds to capture from the sketch.

Number

options

an object that can contain five more properties: `delay`, a Number specifying how much time to wait before recording; `units`, a String that can be either 'seconds' or 'frames'. By default it's 'seconds’; `silent`, a Boolean that defines presence of progress notifications. By default it’s `false`; `notificationDuration`, a Number that defines how long in seconds the final notification will live. By default it's `0`, meaning the notification will never be removed; `notificationID`, a String that specifies the id of the notification's DOM element. By default it’s `'progressBar’`.

Object

` function setup() { createCanvas(100, 100); describe('A circle drawn in the middle of a gray square. The circle changes color from black to white, then repeats.'); } function draw() { background(200); // Style the circle. let c = frameCount % 255; fill(c); // Display the circle. circle(50, 50, 25); } // Save a 5-second gif when the user presses the 's' key. function keyPressed() { if (key === 's') { saveGif('mySketch', 5); } } `
` function setup() { createCanvas(100, 100); describe('A circle drawn in the middle of a gray square. The circle changes color from black to white, then repeats.'); } function draw() { background(200); // Style the circle. let c = frameCount % 255; fill(c); // Display the circle. circle(50, 50, 25); } // Save a 5-second gif when the user presses the 's' key. // Wait 1 second after the key press before recording. function keyPressed() { if (key === 's') { saveGif('mySketch', 5, { delay: 1 }); } } `

p5

Image

Loading & Displaying

Helper function for loading GIF-based images

p5

Image

Loading & Displaying

Draws an image to the canvas.
The first parameter, `img`, is the source image to be drawn. `img` can be any of the following objects:
    * p5.Image
    * p5.Element
    * p5.Texture
    * p5.Framebuffer
    * p5.FramebufferTexture
The second and third parameters, `dx` and `dy`, set the coordinates of the destination image's top left corner. See imageMode() for other ways to position images.
Here's a diagram that explains how optional parameters work in `image()`:
The fourth and fifth parameters, `dw` and `dh`, are optional. They set the the width and height to draw the destination image. By default, `image()` draws the full source image at its original size.
The sixth and seventh parameters, `sx` and `sy`, are also optional. These coordinates define the top left corner of a subsection to draw from the source image.
The eighth and ninth parameters, `sw` and `sh`, are also optional. They define the width and height of a subsection to draw from the source image. By default, `image()` draws the full subsection that begins at `(sx, sy)` and extends to the edges of the source image.
The ninth parameter, `fit`, is also optional. It enables a subsection of the source image to be drawn without affecting its aspect ratio. If `CONTAIN` is passed, the full subsection will appear within the destination rectangle. If `COVER` is passed, the subsection will completely cover the destination rectangle. This may have the effect of zooming into the subsection.
The tenth and eleventh parameters, `xAlign` and `yAlign`, are also optional. They determine how to align the fitted subsection. `xAlign` can be set to either `LEFT`, `RIGHT`, or `CENTER`. `yAlign` can be set to either `TOP`, `BOTTOM`, or `CENTER`. By default, both `xAlign` and `yAlign` are set to `CENTER`.

method

image

` let img; // Load the image. function preload() { img = loadImage('assets/laDefense.jpg'); } function setup() { createCanvas(100, 100); background(50); // Draw the image. image(img, 0, 0); describe('An image of the underside of a white umbrella with a gridded ceiling above.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/laDefense.jpg'); } function setup() { createCanvas(100, 100); background(50); // Draw the image. image(img, 10, 10); describe('An image of the underside of a white umbrella with a gridded ceiling above. The image has dark gray borders on its left and top.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/laDefense.jpg'); } function setup() { createCanvas(100, 100); background(50); // Draw the image 50x50. image(img, 0, 0, 50, 50); describe('An image of the underside of a white umbrella with a gridded ceiling above. The image is drawn in the top left corner of a dark gray square.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/laDefense.jpg'); } function setup() { createCanvas(100, 100); background(50); // Draw the center of the image. image(img, 25, 25, 50, 50, 25, 25, 50, 50); describe('An image of a gridded ceiling drawn in the center of a dark gray square.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/moonwalk.jpg'); } function setup() { createCanvas(100, 100); background(50); // Draw the image and scale it to fit within the canvas. image(img, 0, 0, width, height, 0, 0, img.width, img.height, CONTAIN); describe('An image of an astronaut on the moon. The top and bottom borders of the image are dark gray.'); } `
` let img; // Load the image. function preload() { // Image is 50 x 50 pixels. img = loadImage('assets/laDefense50.png'); } function setup() { createCanvas(100, 100); background(50); // Draw the image and scale it to cover the canvas. image(img, 0, 0, width, height, 0, 0, img.width, img.height, COVER); describe('A pixelated image of the underside of a white umbrella with a gridded ceiling above.'); } `

p5

Image

Loading & Displaying

img

image to display.

p5.Image|p5.Element|p5.Texture|p5.Framebuffer|p5.FramebufferTexture

x

x-coordinate of the top-left corner of the image.

Number

y

y-coordinate of the top-left corner of the image.

Number

width

width to draw the image.

Number

height

height to draw the image.

Number

img



p5.Image|p5.Element|p5.Texture|p5.Framebuffer|p5.FramebufferTexture

dx

the x-coordinate of the destination rectangle in which to draw the source image

Number

dy

the y-coordinate of the destination rectangle in which to draw the source image

Number

dWidth

the width of the destination rectangle

Number

dHeight

the height of the destination rectangle

Number

sx

the x-coordinate of the subsection of the source image to draw into the destination rectangle

Number

sy

the y-coordinate of the subsection of the source image to draw into the destination rectangle

Number

sWidth

the width of the subsection of the source image to draw into the destination rectangle

Number

sHeight

the height of the subsection of the source image to draw into the destination rectangle

Number

fit

either CONTAIN or COVER

Constant

xAlign

either LEFT, RIGHT or CENTER default is CENTER

Constant

yAlign

either TOP, BOTTOM or CENTER default is CENTER

Constant

Tints images using a color.
The version of `tint()` with one parameter interprets it one of four ways. If the parameter is a number, it's interpreted as a grayscale value. If the parameter is a string, it's interpreted as a CSS color string. An array of `[R, G, B, A]` values or a p5.Color object can also be used to set the tint color.
The version of `tint()` with two parameters uses the first one as a grayscale value and the second as an alpha value. For example, calling `tint(255, 128)` will make an image 50% transparent.
The version of `tint()` with three parameters interprets them as RGB or HSB values, depending on the current colorMode(). The optional fourth parameter sets the alpha value. For example, `tint(255, 0, 0, 100)` will give images a red tint and make them transparent.

method

tint

` let img; // Load the image. function preload() { img = loadImage('assets/laDefense.jpg'); } function setup() { createCanvas(100, 100); // Left image. image(img, 0, 0); // Right image. // Tint with a CSS color string. tint('red'); image(img, 50, 0); describe('Two images of an umbrella and a ceiling side-by-side. The image on the right has a red tint.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/laDefense.jpg'); } function setup() { createCanvas(100, 100); // Left image. image(img, 0, 0); // Right image. // Tint with RGB values. tint(255, 0, 0); image(img, 50, 0); describe('Two images of an umbrella and a ceiling side-by-side. The image on the right has a red tint.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/laDefense.jpg'); } function setup() { createCanvas(100, 100); // Left. image(img, 0, 0); // Right. // Tint with RGBA values. tint(255, 0, 0, 100); image(img, 50, 0); describe('Two images of an umbrella and a ceiling side-by-side. The image on the right has a transparent red tint.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/laDefense.jpg'); } function setup() { createCanvas(100, 100); // Left. image(img, 0, 0); // Right. // Tint with grayscale and alpha values. tint(255, 180); image(img, 50, 0); describe('Two images of an umbrella and a ceiling side-by-side. The image on the right is transparent.'); } `

p5

Image

Loading & Displaying

v1

red or hue value.

Number

v2

green or saturation value.

Number

v3

blue or brightness.

Number

alpha



Number

value

CSS color string.

String

gray

grayscale value.

Number

alpha



Number

values

array containing the red, green, blue & alpha components of the color.

Number[]

color

the tint color

p5.Color

Removes the current tint set by tint().
`noTint()` restores images to their original colors.

method

noTint

` let img; // Load the image. function preload() { img = loadImage('assets/laDefense.jpg'); } function setup() { createCanvas(100, 100); // Left. // Tint with a CSS color string. tint('red'); image(img, 0, 0); // Right. // Remove the tint. noTint(); image(img, 50, 0); describe('Two images of an umbrella and a ceiling side-by-side. The image on the left has a red tint.'); } `

p5

Image

Loading & Displaying

Changes the location from which images are drawn when image() is called.
By default, the first two parameters of image() are the x- and y-coordinates of the image's upper-left corner. The next parameters are its width and height. This is the same as calling `imageMode(CORNER)`.
`imageMode(CORNERS)` also uses the first two parameters of image() as the x- and y-coordinates of the image's top-left corner. The third and fourth parameters are the coordinates of its bottom-right corner.
`imageMode(CENTER)` uses the first two parameters of image() as the x- and y-coordinates of the image's center. The next parameters are its width and height.

method

imageMode

mode

either CORNER, CORNERS, or CENTER.

Constant

` let img; // Load the image. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); background(200); // Use CORNER mode. imageMode(CORNER); // Display the image. image(img, 10, 10, 50, 50); describe('A square image of a brick wall is drawn at the top left of a gray square.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); background(200); // Use CORNERS mode. imageMode(CORNERS); // Display the image. image(img, 10, 10, 90, 40); describe('An image of a brick wall is drawn on a gray square. The image is squeezed into a small rectangular area.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); background(200); // Use CENTER mode. imageMode(CENTER); // Display the image. image(img, 50, 50, 80, 80); describe('A square image of a brick wall is drawn on a gray square.'); } `

p5

Image

Loading & Displaying

This module defines the p5.Image class and P5 methods for drawing images to the main display canvas.

p5.Image

Image

Image

The image's width in pixels.

{Number}

property

width



` let img; // Load the image. function preload() { img = loadImage('assets/rockies.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0); // Calculate the center coordinates. let x = img.width / 2; let y = img.height / 2; // Draw a circle at the image's center. circle(x, y, 20); describe('An image of a mountain landscape with a white circle drawn in the middle.'); } `

p5.Image

Image

Image

The image's height in pixels.

{Number}

property

height



` let img; // Load the image. function preload() { img = loadImage('assets/rockies.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0); // Calculate the center coordinates. let x = img.width / 2; let y = img.height / 2; // Draw a circle at the image's center. circle(x, y, 20); describe('An image of a mountain landscape with a white circle drawn in the middle.'); } `

p5.Image

Image

Image

An array containing the color of each pixel in the image.
Colors are stored as numbers representing red, green, blue, and alpha (RGBA) values. `img.pixels` is a one-dimensional array for performance reasons.
Each pixel occupies four elements in the pixels array, one for each RGBA value. For example, the pixel at coordinates (0, 0) stores its RGBA values at `img.pixels[0]`, `img.pixels[1]`, `img.pixels[2]`, and `img.pixels[3]`, respectively. The next pixel at coordinates (1, 0) stores its RGBA values at `img.pixels[4]`, `img.pixels[5]`, `img.pixels[6]`, and `img.pixels[7]`. And so on. The `img.pixels` array for a 100×100 p5.Image object has 100 × 100 × 4 = 40,000 elements.
Accessing the RGBA values for a pixel in the image requires a little math as shown in the examples below. The img.loadPixels() method must be called before accessing the `img.pixels` array. The img.updatePixels() method must be called after any changes are made.

property

pixels

Number[]

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Image object. let img = createImage(66, 66); // Load the image's pixels. img.loadPixels(); for (let i = 0; i < img.pixels.length; i += 4) { // Red. img.pixels[i] = 0; // Green. img.pixels[i + 1] = 0; // Blue. img.pixels[i + 2] = 0; // Alpha. img.pixels[i + 3] = 255; } // Update the image. img.updatePixels(); // Display the image. image(img, 17, 17); describe('A black square drawn in the middle of a gray square.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create a p5.Image object. let img = createImage(66, 66); // Load the image's pixels. img.loadPixels(); // Set the pixels to red. for (let i = 0; i < img.pixels.length; i += 4) { // Red. img.pixels[i] = 255; // Green. img.pixels[i + 1] = 0; // Blue. img.pixels[i + 2] = 0; // Alpha. img.pixels[i + 3] = 255; } // Update the image. img.updatePixels(); // Display the image. image(img, 17, 17); describe('A red square drawn in the middle of a gray square.'); } `

p5.Image

Image

Image

Gets or sets the pixel density for high pixel density displays.
By default, the density will be set to 1.
Call this method with no arguments to get the default density, or pass in a number to set the density. If a non-positive number is provided, it defaults to 1.

method

pixelDensity

density

A scaling factor for the number of pixels per side

Number

### return
The current density if called without arguments, or the instance for chaining if setting density.

Number

p5.Image

Image

Image

Helper function for animating GIF-based images with time

p5.Image

Image

Image

Helper fxn for sharing pixel methods

p5.Image

Image

Image

Loads the current value of each pixel in the image into the `img.pixels` array.
`img.loadPixels()` must be called before reading or modifying pixel values.

method

loadPixels

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Image object. let img = createImage(66, 66); // Load the image's pixels. img.loadPixels(); // Set the pixels to black. for (let x = 0; x < img.width; x += 1) { for (let y = 0; y < img.height; y += 1) { img.set(x, y, 0); } } // Update the image. img.updatePixels(); // Display the image. image(img, 17, 17); describe('A black square drawn in the middle of a gray square.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create a p5.Image object. let img = createImage(66, 66); // Load the image's pixels. img.loadPixels(); for (let i = 0; i < img.pixels.length; i += 4) { // Red. img.pixels[i] = 0; // Green. img.pixels[i + 1] = 0; // Blue. img.pixels[i + 2] = 0; // Alpha. img.pixels[i + 3] = 255; } // Update the image. img.updatePixels(); // Display the image. image(img, 17, 17); describe('A black square drawn in the middle of a gray square.'); } `

p5.Image

Image

Image

Updates the canvas with the RGBA values in the img.pixels array.
`img.updatePixels()` only needs to be called after changing values in the img.pixels array. Such changes can be made directly after calling img.loadPixels() or by calling img.set().
The optional parameters `x`, `y`, `width`, and `height` define a subsection of the image to update. Doing so can improve performance in some cases.
If the image was loaded from a GIF, then calling `img.updatePixels()` will update the pixels in current frame.

method

updatePixels

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Image object. let img = createImage(66, 66); // Load the image's pixels. img.loadPixels(); // Set the pixels to black. for (let x = 0; x < img.width; x += 1) { for (let y = 0; y < img.height; y += 1) { img.set(x, y, 0); } } // Update the image. img.updatePixels(); // Display the image. image(img, 17, 17); describe('A black square drawn in the middle of a gray square.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create a p5.Image object. let img = createImage(66, 66); // Load the image's pixels. img.loadPixels(); // Set the pixels to black. for (let i = 0; i < img.pixels.length; i += 4) { // Red. img.pixels[i] = 0; // Green. img.pixels[i + 1] = 0; // Blue. img.pixels[i + 2] = 0; // Alpha. img.pixels[i + 3] = 255; } // Update the image. img.updatePixels(); // Display the image. image(img, 17, 17); describe('A black square drawn in the middle of a gray square.'); } `

p5.Image

Image

Image

x

x-coordinate of the upper-left corner of the subsection to update.

Integer

y

y-coordinate of the upper-left corner of the subsection to update.

Integer

w

width of the subsection to update.

Integer

h

height of the subsection to update.

Integer

Gets a pixel or a region of pixels from the image.
`img.get()` is easy to use but it's not as fast as img.pixels. Use img.pixels to read many pixel values.
The version of `img.get()` with no parameters returns the entire image.
The version of `img.get()` with two parameters, as in `img.get(10, 20)`, interprets them as coordinates. It returns an array with the `[R, G, B, A]` values of the pixel at the given point.
The version of `img.get()` with four parameters, as in `img,get(10, 20, 50, 90)`, interprets them as coordinates and dimensions. The first two parameters are the coordinates of the upper-left corner of the subsection. The last two parameters are the width and height of the subsection. It returns a subsection of the canvas in a new p5.Image object.
Use `img.get()` instead of get() to work directly with images.

method

get

### return
subsection as a p5.Image object.

p5.Image

` let img; // Load the image. function preload() { img = loadImage('assets/rockies.jpg'); } function setup() { createCanvas(100, 100); background(200); // Display the image. image(img, 0, 0); // Copy the image. let img2 = get(); // Display the copied image on the right. image(img2, 50, 0); describe('Two identical mountain landscapes shown side-by-side.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/rockies.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0); // Get a pixel's color. let c = img.get(50, 90); // Style the square using the pixel's color. fill(c); noStroke(); // Draw the square. square(25, 25, 50); describe('A mountain landscape with an olive green square in its center.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/rockies.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0); // Copy half of the image. let img2 = img.get(0, 0, img.width / 2, img.height / 2); // Display half of the image. image(img2, 50, 50); describe('A mountain landscape drawn on top of another mountain landscape.'); } `

p5.Image

Image

Image

x

x-coordinate of the pixel.

Number

y

y-coordinate of the pixel.

Number

w

width of the subsection to be returned.

Number

h

height of the subsection to be returned.

Number

##### return
subsection as a p5.Image object.

p5.Image

##### return
whole p5.Image

p5.Image

x



Number

y



Number

##### return
color of the pixel at (x, y) in array format `[R, G, B, A]`.

Number[]

Sets the color of one or more pixels within an image.
`img.set()` is easy to use but it's not as fast as img.pixels. Use img.pixels to set many pixel values.
`img.set()` interprets the first two parameters as x- and y-coordinates. It interprets the last parameter as a grayscale value, a `[R, G, B, A]` pixel array, a p5.Color object, or another p5.Image object.
img.updatePixels() must be called after using `img.set()` for changes to appear.

method

set

x

x-coordinate of the pixel.

Number

y

y-coordinate of the pixel.

Number

a

grayscale value | pixel array | p5.Color object | p5.Image to copy.

Number|Number[]|Object

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Image object. let img = createImage(100, 100); // Set four pixels to black. img.set(30, 20, 0); img.set(85, 20, 0); img.set(85, 75, 0); img.set(30, 75, 0); // Update the image. img.updatePixels(); // Display the image. image(img, 0, 0); describe('Four black dots arranged in a square drawn on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create a p5.Image object. let img = createImage(100, 100); // Create a p5.Color object. let black = color(0); // Set four pixels to black. img.set(30, 20, black); img.set(85, 20, black); img.set(85, 75, black); img.set(30, 75, black); // Update the image. img.updatePixels(); // Display the image. image(img, 0, 0); describe('Four black dots arranged in a square drawn on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create a p5.Image object. let img = createImage(66, 66); // Draw a color gradient. for (let x = 0; x < img.width; x += 1) { for (let y = 0; y < img.height; y += 1) { let c = map(x, 0, img.width, 0, 255); img.set(x, y, c); } } // Update the image. img.updatePixels(); // Display the image. image(img, 17, 17); describe('A square with a horizontal color gradient from black to white drawn on a gray background.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/rockies.jpg'); } function setup() { createCanvas(100, 100); // Create a p5.Image object. let img2 = createImage(100, 100); // Set the blank image's pixels using the landscape. img2.set(0, 0, img); // Display the second image. image(img2, 0, 0); describe('An image of a mountain landscape.'); } `

p5.Image

Image

Image

Resizes the image to a given width and height.
The image's original aspect ratio can be kept by passing 0 for either `width` or `height`. For example, calling `img.resize(50, 0)` on an image that was 500 × 300 pixels will resize it to 50 × 30 pixels.

method

resize

width

resized image width.

Number

height

resized image height.

Number

` let img; // Load the image. function preload() { img = loadImage('assets/rockies.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0); // Resize the image. img.resize(50, 100); // Display the resized image. image(img, 0, 0); describe('Two images of a mountain landscape. One copy of the image is squeezed horizontally.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/rockies.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0); // Resize the image, keeping the aspect ratio. img.resize(0, 30); // Display the resized image. image(img, 0, 0); describe('Two images of a mountain landscape. The small copy of the image covers the top-left corner of the larger image.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/rockies.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0); // Resize the image, keeping the aspect ratio. img.resize(60, 0); // Display the image. image(img, 0, 0); describe('Two images of a mountain landscape. The small copy of the image covers the top-left corner of the larger image.'); } `

p5.Image

Image

Image

Copies pixels from a source image to this image.
The first parameter, `srcImage`, is an optional p5.Image object to copy. If a source image isn't passed, then `img.copy()` can copy a region of this image to another region.
The next four parameters, `sx`, `sy`, `sw`, and `sh` determine the region to copy from the source image. `(sx, sy)` is the top-left corner of the region. `sw` and `sh` are the region's width and height.
The next four parameters, `dx`, `dy`, `dw`, and `dh` determine the region of this image to copy into. `(dx, dy)` is the top-left corner of the region. `dw` and `dh` are the region's width and height.
Calling `img.copy()` will scale pixels from the source region if it isn't the same size as the destination region.

method

copy

` let img; // Load the image. function preload() { img = loadImage('assets/rockies.jpg'); } function setup() { createCanvas(100, 100); // Copy one region of the image to another. img.copy(7, 22, 10, 10, 35, 25, 50, 50); // Display the image. image(img, 0, 0); // Outline the copied region. stroke(255); noFill(); square(7, 22, 10); describe('An image of a mountain landscape. A square region is outlined in white. A larger square contains a pixelated view of the outlined region.'); } `
` let mountains; let bricks; // Load the images. function preload() { mountains = loadImage('assets/rockies.jpg'); bricks = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); // Calculate the center of the bricks image. let x = bricks.width / 2; let y = bricks.height / 2; // Copy the bricks to the mountains image. mountains.copy(bricks, 0, 0, x, y, 0, 0, x, y); // Display the mountains image. image(mountains, 0, 0); describe('An image of a brick wall drawn at the top-left of an image of a mountain landscape.'); } `

p5.Image

Image

Image

srcImage

source image.

p5.Image|p5.Element

sx

x-coordinate of the source's upper-left corner.

Integer

sy

y-coordinate of the source's upper-left corner.

Integer

sw

source image width.

Integer

sh

source image height.

Integer

dx

x-coordinate of the destination's upper-left corner.

Integer

dy

y-coordinate of the destination's upper-left corner.

Integer

dw

destination image width.

Integer

dh

destination image height.

Integer

sx



Integer

sy



Integer

sw



Integer

sh



Integer

dx



Integer

dy



Integer

dw



Integer

dh



Integer

Masks part of the image with another.
`img.mask()` uses another p5.Image object's alpha channel as the alpha channel for this image. Masks are cumulative and can't be removed once applied. If the mask has a different pixel density from this image, the mask will be scaled.

method

mask

srcImage

source image.

p5.Image

` let photo; let maskImage; // Load the images. function preload() { photo = loadImage('assets/rockies.jpg'); maskImage = loadImage('assets/mask2.png'); } function setup() { createCanvas(100, 100); // Apply the mask. photo.mask(maskImage); // Display the image. image(photo, 0, 0); describe('An image of a mountain landscape. The right side of the image has a faded patch of white.'); } `

p5.Image

Image

Image

Applies an image filter to the image.
The preset options are:
`INVERT` Inverts the colors in the image. No parameter is used.
`GRAY` Converts the image to grayscale. No parameter is used.
`THRESHOLD` Converts the image to black and white. Pixels with a grayscale value above a given threshold are converted to white. The rest are converted to black. The threshold must be between 0.0 (black) and 1.0 (white). If no value is specified, 0.5 is used.
`OPAQUE` Sets the alpha channel to be entirely opaque. No parameter is used.
`POSTERIZE` Limits the number of colors in the image. Each color channel is limited to the number of colors specified. Values between 2 and 255 are valid, but results are most noticeable with lower values. The default value is 4.
`BLUR` Blurs the image. The level of blurring is specified by a blur radius. Larger values increase the blur. The default value is 4. A gaussian blur is used in `P2D` mode. A box blur is used in `WEBGL` mode.
`ERODE` Reduces the light areas. No parameter is used.
`DILATE` Increases the light areas. No parameter is used.

method

filter

filterType

either THRESHOLD, GRAY, OPAQUE, INVERT, POSTERIZE, ERODE, DILATE or BLUR.

Constant

filterParam

parameter unique to each filter.

Number

` let img; // Load the image. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); // Apply the INVERT filter. img.filter(INVERT); // Display the image. image(img, 0, 0); describe('A blue brick wall.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); // Apply the GRAY filter. img.filter(GRAY); // Display the image. image(img, 0, 0); describe('A brick wall drawn in grayscale.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); // Apply the THRESHOLD filter. img.filter(THRESHOLD); // Display the image. image(img, 0, 0); describe('A brick wall drawn in black and white.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); // Apply the OPAQUE filter. img.filter(OPAQUE); // Display the image. image(img, 0, 0); describe('A red brick wall.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); // Apply the POSTERIZE filter. img.filter(POSTERIZE, 3); // Display the image. image(img, 0, 0); describe('An image of a red brick wall drawn with a limited color palette.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); // Apply the BLUR filter. img.filter(BLUR, 3); // Display the image. image(img, 0, 0); describe('A blurry image of a red brick wall.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); // Apply the DILATE filter. img.filter(DILATE); // Display the image. image(img, 0, 0); describe('A red brick wall with bright lines between each brick.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); // Apply the ERODE filter. img.filter(ERODE); // Display the image. image(img, 0, 0); describe('A red brick wall with faint lines between each brick.'); } `

p5.Image

Image

Image

Copies a region of pixels from another image into this one.
The first parameter, `srcImage`, is the p5.Image object to blend.
The next four parameters, `sx`, `sy`, `sw`, and `sh` determine the region to blend from the source image. `(sx, sy)` is the top-left corner of the region. `sw` and `sh` are the regions width and height.
The next four parameters, `dx`, `dy`, `dw`, and `dh` determine the region of the canvas to blend into. `(dx, dy)` is the top-left corner of the region. `dw` and `dh` are the regions width and height.
The tenth parameter, `blendMode`, sets the effect used to blend the images' colors. The options are `BLEND`, `DARKEST`, `LIGHTEST`, `DIFFERENCE`, `MULTIPLY`, `EXCLUSION`, `SCREEN`, `REPLACE`, `OVERLAY`, `HARD_LIGHT`, `SOFT_LIGHT`, `DODGE`, `BURN`, `ADD`, or `NORMAL`.

method

blend

` let mountains; let bricks; // Load the images. function preload() { mountains = loadImage('assets/rockies.jpg'); bricks = loadImage('assets/bricks_third.jpg'); } function setup() { createCanvas(100, 100); // Blend the bricks image into the mountains. mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, ADD); // Display the mountains image. image(mountains, 0, 0); // Display the bricks image. image(bricks, 0, 0); describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears faded on the right of the image.'); } `
` let mountains; let bricks; // Load the images. function preload() { mountains = loadImage('assets/rockies.jpg'); bricks = loadImage('assets/bricks_third.jpg'); } function setup() { createCanvas(100, 100); // Blend the bricks image into the mountains. mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST); // Display the mountains image. image(mountains, 0, 0); // Display the bricks image. image(bricks, 0, 0); describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears transparent on the right of the image.'); } `
` let mountains; let bricks; // Load the images. function preload() { mountains = loadImage('assets/rockies.jpg'); bricks = loadImage('assets/bricks_third.jpg'); } function setup() { createCanvas(100, 100); // Blend the bricks image into the mountains. mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST); // Display the mountains image. image(mountains, 0, 0); // Display the bricks image. image(bricks, 0, 0); describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears washed out on the right of the image.'); } `

p5.Image

Image

Image

srcImage

source image

p5.Image

sx

x-coordinate of the source's upper-left corner.

Integer

sy

y-coordinate of the source's upper-left corner.

Integer

sw

source image width.

Integer

sh

source image height.

Integer

dx

x-coordinate of the destination's upper-left corner.

Integer

dy

y-coordinate of the destination's upper-left corner.

Integer

dw

destination image width.

Integer

dh

destination image height.

Integer

blendMode

the blend mode. either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.
Available blend modes are: normal | multiply | screen | overlay | darken | lighten | color-dodge | color-burn | hard-light | soft-light | difference | exclusion | hue | saturation | color | luminosity
http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/

Constant

sx



Integer

sy



Integer

sw



Integer

sh



Integer

dx



Integer

dy



Integer

dw



Integer

dh



Integer

blendMode



Constant

Saves the image to a file.
By default, `img.save()` saves the image as a PNG image called `untitled.png`.
The first parameter, `filename`, is optional. It's a string that sets the file's name. If a file extension is included, as in `img.save('drawing.png')`, then the image will be saved using that format.
The second parameter, `extension`, is also optional. It sets the files format. Either `'png'` or `'jpg'` can be used. For example, `img.save('drawing', 'jpg')` saves the canvas to a file called `drawing.jpg`.
Note: The browser will either save the file immediately or prompt the user with a dialogue window.
The image will only be downloaded as an animated GIF if it was loaded from a GIF file. See saveGif() to create new GIFs.

method

save

filename

filename. Defaults to 'untitled'.

String

extension

file extension, either 'png' or 'jpg'. Defaults to 'png'.

String

` let img; // Load the image. function preload() { img = loadImage('assets/rockies.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0); describe('An image of a mountain landscape. The image is downloaded when the user presses the "s", "j", or "p" key.'); } // Save the image with different options when the user presses a key. function keyPressed() { if (key === 's') { img.save(); } else if (key === 'j') { img.save('rockies.jpg'); } else if (key === 'p') { img.save('rockies', 'png'); } } `

p5.Image

Image

Image

Restarts an animated GIF at its first frame.

method

reset

` let gif; // Load the image. function preload() { gif = loadImage('assets/arnott-wallace-wink-loop-once.gif'); } function setup() { createCanvas(100, 100); describe('A cartoon face winks once and then freezes. Clicking resets the face and makes it wink again.'); } function draw() { background(255); // Display the image. image(gif, 0, 0); } // Reset the GIF when the user presses the mouse. function mousePressed() { gif.reset(); } `

p5.Image

Image

Image

Gets the index of the current frame in an animated GIF.

method

getCurrentFrame

### return
index of the GIF's current frame.

Number

` let gif; // Load the image. function preload() { gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif'); } function setup() { createCanvas(100, 100); describe('A cartoon eye repeatedly looks around, then outwards. A number displayed in the bottom-left corner increases from 0 to 124, then repeats.'); } function draw() { // Get the index of the current GIF frame. let index = gif.getCurrentFrame(); // Display the image. image(gif, 0, 0); // Display the current frame. text(index, 10, 90); } `

p5.Image

Image

Image

Sets the current frame in an animated GIF.

method

setFrame

index

index of the frame to display.

Number

` let gif; let frameSlider; // Load the image. function preload() { gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif'); } function setup() { createCanvas(100, 100); // Get the index of the last frame. let maxFrame = gif.numFrames() - 1; // Create a slider to control which frame is drawn. frameSlider = createSlider(0, maxFrame); frameSlider.position(10, 80); frameSlider.size(80); describe('A cartoon eye looks around when a slider is moved.'); } function draw() { // Get the slider's value. let index = frameSlider.value(); // Set the GIF's frame. gif.setFrame(index); // Display the image. image(gif, 0, 0); } `

p5.Image

Image

Image

Returns the number of frames in an animated GIF.

method

numFrames

### return
number of frames in the GIF.

Number

` let gif; // Load the image. function preload() { gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif'); } function setup() { createCanvas(100, 100); describe('A cartoon eye looks around. The text "n / 125" is shown at the bottom of the canvas.'); } function draw() { // Display the image. image(gif, 0, 0); // Display the current state of playback. let total = gif.numFrames(); let index = gif.getCurrentFrame(); text(`${index} / ${total}`, 30, 90); } `

p5.Image

Image

Image

Plays an animated GIF that was paused with img.pause().

method

play

` let gif; // Load the image. function preload() { gif = loadImage('assets/nancy-liang-wind-loop-forever.gif'); } function setup() { createCanvas(100, 100); describe('A drawing of a child with hair blowing in the wind. The animation freezes when clicked and resumes when released.'); } function draw() { background(255); image(gif, 0, 0); } // Pause the GIF when the user presses the mouse. function mousePressed() { gif.pause(); } // Play the GIF when the user releases the mouse. function mouseReleased() { gif.play(); } `

p5.Image

Image

Image

Pauses an animated GIF.
The GIF can be resumed by calling img.play().

method

pause

` let gif; // Load the image. function preload() { gif = loadImage('assets/nancy-liang-wind-loop-forever.gif'); } function setup() { createCanvas(100, 100); describe('A drawing of a child with hair blowing in the wind. The animation freezes when clicked and resumes when released.'); } function draw() { background(255); // Display the image. image(gif, 0, 0); } // Pause the GIF when the user presses the mouse. function mousePressed() { gif.pause(); } // Play the GIF when the user presses the mouse. function mouseReleased() { gif.play(); } `

p5.Image

Image

Image

Changes the delay between frames in an animated GIF.
The first parameter, `delay`, is the length of the delay in milliseconds.
The second parameter, `index`, is optional. If provided, only the frame at `index` will have its delay modified. All other frames will keep their default delay.

method

delay

d

delay in milliseconds between switching frames.

Number

index

index of the frame that will have its delay modified.

Number

` let gifFast; let gifSlow; // Load the images. function preload() { gifFast = loadImage('assets/arnott-wallace-eye-loop-forever.gif'); gifSlow = loadImage('assets/arnott-wallace-eye-loop-forever.gif'); } function setup() { createCanvas(100, 100); background(200); // Resize the images. gifFast.resize(50, 50); gifSlow.resize(50, 50); // Set the delay lengths. gifFast.delay(10); gifSlow.delay(100); describe('Two animated eyes looking around. The eye on the left moves faster than the eye on the right.'); } function draw() { // Display the images. image(gifFast, 0, 0); image(gifSlow, 50, 0); } `
` let gif; // Load the image. function preload() { gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif'); } function setup() { createCanvas(100, 100); // Set the delay of frame 67. gif.delay(3000, 67); describe('An animated eye looking around. It pauses for three seconds while it looks down.'); } function draw() { // Display the image. image(gif, 0, 0); } `

p5.Image

Image

Image

An array containing the color of each pixel on the canvas.
Colors are stored as numbers representing red, green, blue, and alpha (RGBA) values. `pixels` is a one-dimensional array for performance reasons.
Each pixel occupies four elements in the `pixels` array, one for each RGBA value. For example, the pixel at coordinates (0, 0) stores its RGBA values at `pixels[0]`, `pixels[1]`, `pixels[2]`, and `pixels[3]`, respectively. The next pixel at coordinates (1, 0) stores its RGBA values at `pixels[4]`, `pixels[5]`, `pixels[6]`, and `pixels[7]`. And so on. The `pixels` array for a 100×100 canvas has 100 × 100 × 4 = 40,000 elements.
Some displays use several smaller pixels to set the color at a single point. The pixelDensity() function returns the pixel density of the canvas. High density displays often have a pixelDensity() of 2. On such a display, the `pixels` array for a 100×100 canvas has 200 × 200 × 4 = 160,000 elements.
Accessing the RGBA values for a point on the canvas requires a little math as shown below. The loadPixels() function must be called before accessing the `pixels` array. The updatePixels() function must be called after any changes are made.

property

pixels

Number[]

` function setup() { createCanvas(100, 100); // Load the pixels array. loadPixels(); // Set the dot's coordinates. let x = 50; let y = 50; // Get the pixel density. let d = pixelDensity(); // Set the pixel(s) at the center of the canvas black. for (let i = 0; i < d; i += 1) { for (let j = 0; j < d; j += 1) { let index = 4 * ((y * d + j) * width * d + (x * d + i)); // Red. pixels[index] = 0; // Green. pixels[index + 1] = 0; // Blue. pixels[index + 2] = 0; // Alpha. pixels[index + 3] = 255; } } // Update the canvas. updatePixels(); describe('A black dot in the middle of a gray rectangle.'); } `
` function setup() { createCanvas(100, 100); // Load the pixels array. loadPixels(); // Get the pixel density. let d = pixelDensity(); // Calculate the halfway index in the pixels array. let halfImage = 4 * (d * width) * (d * height / 2); // Make the top half of the canvas red. for (let i = 0; i < halfImage; i += 4) { // Red. pixels[i] = 255; // Green. pixels[i + 1] = 0; // Blue. pixels[i + 2] = 0; // Alpha. pixels[i + 3] = 255; } // Update the canvas. updatePixels(); describe('A red rectangle drawn above a gray rectangle.'); } `
` function setup() { createCanvas(100, 100); // Create a p5.Color object. let pink = color(255, 102, 204); // Load the pixels array. loadPixels(); // Get the pixel density. let d = pixelDensity(); // Calculate the halfway index in the pixels array. let halfImage = 4 * (d * width) * (d * height / 2); // Make the top half of the canvas red. for (let i = 0; i < halfImage; i += 4) { pixels[i] = red(pink); pixels[i + 1] = green(pink); pixels[i + 2] = blue(pink); pixels[i + 3] = alpha(pink); } // Update the canvas. updatePixels(); describe('A pink rectangle drawn above a gray rectangle.'); } `

p5

Image

Pixels

Copies a region of pixels from one image to another.
The first parameter, `srcImage`, is the p5.Image object to blend.
The next four parameters, `sx`, `sy`, `sw`, and `sh` determine the region to blend from the source image. `(sx, sy)` is the top-left corner of the region. `sw` and `sh` are the regions width and height.
The next four parameters, `dx`, `dy`, `dw`, and `dh` determine the region of the canvas to blend into. `(dx, dy)` is the top-left corner of the region. `dw` and `dh` are the regions width and height.
The tenth parameter, `blendMode`, sets the effect used to blend the images' colors. The options are `BLEND`, `DARKEST`, `LIGHTEST`, `DIFFERENCE`, `MULTIPLY`, `EXCLUSION`, `SCREEN`, `REPLACE`, `OVERLAY`, `HARD_LIGHT`, `SOFT_LIGHT`, `DODGE`, `BURN`, `ADD`, or `NORMAL`

method

blend

` let img0; let img1; // Load the images. function preload() { img0 = loadImage('assets/rockies.jpg'); img1 = loadImage('assets/bricks_third.jpg'); } function setup() { createCanvas(100, 100); // Use the mountains as the background. background(img0); // Display the bricks. image(img1, 0, 0); // Display the bricks faded into the landscape. blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST); describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears faded on the right of the image.'); } `
` let img0; let img1; // Load the images. function preload() { img0 = loadImage('assets/rockies.jpg'); img1 = loadImage('assets/bricks_third.jpg'); } function setup() { createCanvas(100, 100); // Use the mountains as the background. background(img0); // Display the bricks. image(img1, 0, 0); // Display the bricks partially transparent. blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST); describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears transparent on the right of the image.'); } `
` let img0; let img1; // Load the images. function preload() { img0 = loadImage('assets/rockies.jpg'); img1 = loadImage('assets/bricks_third.jpg'); } function setup() { createCanvas(100, 100); // Use the mountains as the background. background(img0); // Display the bricks. image(img1, 0, 0); // Display the bricks washed out into the landscape. blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, ADD); describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears washed out on the right of the image.'); } `

p5

Image

Pixels

srcImage

source image.

p5.Image

sx

x-coordinate of the source's upper-left corner.

Integer

sy

y-coordinate of the source's upper-left corner.

Integer

sw

source image width.

Integer

sh

source image height.

Integer

dx

x-coordinate of the destination's upper-left corner.

Integer

dy

y-coordinate of the destination's upper-left corner.

Integer

dw

destination image width.

Integer

dh

destination image height.

Integer

blendMode

the blend mode. either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.

Constant

sx



Integer

sy



Integer

sw



Integer

sh



Integer

dx



Integer

dy



Integer

dw



Integer

dh



Integer

blendMode



Constant

Copies pixels from a source image to a region of the canvas.
The first parameter, `srcImage`, is the p5.Image object to blend. The source image can be the canvas itself or a p5.Image object. `copy()` will scale pixels from the source region if it isn't the same size as the destination region.
The next four parameters, `sx`, `sy`, `sw`, and `sh` determine the region to copy from the source image. `(sx, sy)` is the top-left corner of the region. `sw` and `sh` are the region's width and height.
The next four parameters, `dx`, `dy`, `dw`, and `dh` determine the region of the canvas to copy into. `(dx, dy)` is the top-left corner of the region. `dw` and `dh` are the region's width and height.

method

copy

` let img; // Load the image. function preload() { img = loadImage('assets/rockies.jpg'); } function setup() { createCanvas(100, 100); // Use the mountains as the background. background(img); // Copy a region of pixels to another spot. copy(img, 7, 22, 10, 10, 35, 25, 50, 50); // Outline the copied region. stroke(255); noFill(); square(7, 22, 10); describe('An image of a mountain landscape. A square region is outlined in white. A larger square contains a pixelated view of the outlined region.'); } `

p5

Image

Pixels

srcImage

source image.

p5.Image|p5.Element

sx

x-coordinate of the source's upper-left corner.

Integer

sy

y-coordinate of the source's upper-left corner.

Integer

sw

source image width.

Integer

sh

source image height.

Integer

dx

x-coordinate of the destination's upper-left corner.

Integer

dy

y-coordinate of the destination's upper-left corner.

Integer

dw

destination image width.

Integer

dh

destination image height.

Integer

sx



Integer

sy



Integer

sw



Integer

sh



Integer

dx



Integer

dy



Integer

dw



Integer

dh



Integer

Applies an image filter to the canvas.
The preset options are:
`INVERT` Inverts the colors in the image. No parameter is used.
`GRAY` Converts the image to grayscale. No parameter is used.
`THRESHOLD` Converts the image to black and white. Pixels with a grayscale value above a given threshold are converted to white. The rest are converted to black. The threshold must be between 0.0 (black) and 1.0 (white). If no value is specified, 0.5 is used.
`OPAQUE` Sets the alpha channel to entirely opaque. No parameter is used.
`POSTERIZE` Limits the number of colors in the image. Each color channel is limited to the number of colors specified. Values between 2 and 255 are valid, but results are most noticeable with lower values. The default value is 4.
`BLUR` Blurs the image. The level of blurring is specified by a blur radius. Larger values increase the blur. The default value is 4. A gaussian blur is used in `P2D` mode. A box blur is used in `WEBGL` mode.
`ERODE` Reduces the light areas. No parameter is used.
`DILATE` Increases the light areas. No parameter is used.
`filter()` uses WebGL in the background by default because it's faster. This can be disabled in `P2D` mode by adding a `false` argument, as in `filter(BLUR, false)`. This may be useful to keep computation off the GPU or to work around a lack of WebGL support.
In WebgL mode, `filter()` can also use custom shaders. See createFilterShader() for more information.

method

filter

` let img; // Load the image. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0); // Apply the INVERT filter. filter(INVERT); describe('A blue brick wall.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0); // Apply the GRAY filter. filter(GRAY); describe('A brick wall drawn in grayscale.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0); // Apply the THRESHOLD filter. filter(THRESHOLD); describe('A brick wall drawn in black and white.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0); // Apply the OPAQUE filter. filter(OPAQUE); describe('A red brick wall.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0); // Apply the POSTERIZE filter. filter(POSTERIZE, 3); describe('An image of a red brick wall drawn with limited color palette.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0); // Apply the BLUR filter. filter(BLUR, 3); describe('A blurry image of a red brick wall.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0); // Apply the DILATE filter. filter(DILATE); describe('A red brick wall with bright lines between each brick.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0); // Apply the ERODE filter. filter(ERODE); describe('A red brick wall with faint lines between each brick.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0); // Apply the BLUR filter. // Don't use WebGL. filter(BLUR, 3, false); describe('A blurry image of a red brick wall.'); } `

p5

Image

Pixels

filterType

either THRESHOLD, GRAY, OPAQUE, INVERT, POSTERIZE, BLUR, ERODE, DILATE or BLUR.

Constant

filterParam

parameter unique to each filter.

Number

useWebGL

flag to control whether to use fast WebGL filters (GPU) or original image filters (CPU); defaults to `true`.

Boolean

filterType



Constant

useWebGL



Boolean

shaderFilter

shader that's been loaded, with the frag shader using a `tex0` uniform.

p5.Shader

Gets a pixel or a region of pixels from the canvas.
`get()` is easy to use but it's not as fast as pixels. Use pixels to read many pixel values.
The version of `get()` with no parameters returns the entire canvas.
The version of `get()` with two parameters interprets them as coordinates. It returns an array with the `[R, G, B, A]` values of the pixel at the given point.
The version of `get()` with four parameters interprets them as coordinates and dimensions. It returns a subsection of the canvas as a p5.Image object. The first two parameters are the coordinates for the upper-left corner of the subsection. The last two parameters are the width and height of the subsection.
Use p5.Image.get() to work directly with p5.Image objects.

method

get

### return
subsection as a p5.Image object.

p5.Image

` let img; // Load the image. function preload() { img = loadImage('assets/rockies.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0); // Get the entire canvas. let c = get(); // Display half the canvas. image(c, 50, 0); describe('Two identical mountain landscapes shown side-by-side.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/rockies.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0); // Get the color of a pixel. let c = get(50, 90); // Style the square with the pixel's color. fill(c); noStroke(); // Display the square. square(25, 25, 50); describe('A mountain landscape with an olive green square in its center.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/rockies.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0); // Get a region of the image. let c = get(0, 0, 50, 50); // Display the region. image(c, 50, 50); describe('A mountain landscape drawn on top of another mountain landscape.'); } `

p5

Image

Pixels

x

x-coordinate of the pixel.

Number

y

y-coordinate of the pixel.

Number

w

width of the subsection to be returned.

Number

h

height of the subsection to be returned.

Number

##### return
subsection as a p5.Image object.

p5.Image

##### return
whole canvas as a p5.Image.

p5.Image

x



Number

y



Number

##### return
color of the pixel at (x, y) in array format `[R, G, B, A]`.

Number[]

Loads the current value of each pixel on the canvas into the pixels array.
`loadPixels()` must be called before reading from or writing to pixels.

method

loadPixels

` let img; // Load the image. function preload() { img = loadImage('assets/rockies.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0, 100, 100); // Get the pixel density. let d = pixelDensity(); // Calculate the halfway index in the pixels array. let halfImage = 4 * (d * width) * (d * height / 2); // Load the pixels array. loadPixels(); // Copy the top half of the canvas to the bottom. for (let i = 0; i < halfImage; i += 1) { pixels[i + halfImage] = pixels[i]; } // Update the canvas. updatePixels(); describe('Two identical images of mountain landscapes, one on top of the other.'); } `

p5

Image

Pixels

Sets the color of a pixel or draws an image to the canvas.
`set()` is easy to use but it's not as fast as pixels. Use pixels to set many pixel values.
`set()` interprets the first two parameters as x- and y-coordinates. It interprets the last parameter as a grayscale value, a `[R, G, B, A]` pixel array, a p5.Color object, or a p5.Image object. If an image is passed, the first two parameters set the coordinates for the image's upper-left corner, regardless of the current imageMode().
updatePixels() must be called after using `set()` for changes to appear.

method

set

x

x-coordinate of the pixel.

Number

y

y-coordinate of the pixel.

Number

c

grayscale value | pixel array | p5.Color object | p5.Image to copy.

Number|Number[]|Object

` function setup() { createCanvas(100, 100); background(200); // Set four pixels to black. set(30, 20, 0); set(85, 20, 0); set(85, 75, 0); set(30, 75, 0); // Update the canvas. updatePixels(); describe('Four black dots arranged in a square drawn on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create a p5.Color object. let black = color(0); // Set four pixels to black. set(30, 20, black); set(85, 20, black); set(85, 75, black); set(30, 75, black); // Update the canvas. updatePixels(); describe('Four black dots arranged in a square drawn on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(255); // Draw a horizontal color gradient. for (let x = 0; x < 100; x += 1) { for (let y = 0; y < 100; y += 1) { // Calculate the grayscale value. let c = map(x, 0, 100, 0, 255); // Set the pixel using the grayscale value. set(x, y, c); } } // Update the canvas. updatePixels(); describe('A horizontal color gradient from black to white.'); } `
` let img; // Load the image. function preload() { img = loadImage('assets/rockies.jpg'); } function setup() { createCanvas(100, 100); // Use the image to set all pixels. set(0, 0, img); // Update the canvas. updatePixels(); describe('An image of a mountain landscape.'); } `

p5

Image

Pixels

Updates the canvas with the RGBA values in the pixels array.
`updatePixels()` only needs to be called after changing values in the pixels array. Such changes can be made directly after calling loadPixels() or by calling set().

method

updatePixels

x

x-coordinate of the upper-left corner of region to update.

Number

y

y-coordinate of the upper-left corner of region to update.

Number

w

width of region to update.

Number

h

height of region to update.

Number

` let img; // Load the image. function preload() { img = loadImage('assets/rockies.jpg'); } function setup() { createCanvas(100, 100); // Display the image. image(img, 0, 0, 100, 100); // Get the pixel density. let d = pixelDensity(); // Calculate the halfway index in the pixels array. let halfImage = 4 * (d * width) * (d * height / 2); // Load the pixels array. loadPixels(); // Copy the top half of the canvas to the bottom. for (let i = 0; i < halfImage; i += 1) { pixels[i + halfImage] = pixels[i]; } // Update the canvas. updatePixels(); describe('Two identical images of mountain landscapes, one on top of the other.'); } `

p5

Image

Pixels

Loads a JSON file to create an `Object`.
JavaScript Object Notation (JSON) is a standard format for sending data between applications. The format is based on JavaScript objects which have keys and values. JSON files store data in an object with strings as keys. Values can be strings, numbers, Booleans, arrays, `null`, or other objects.
The first parameter, `path`, is always a string with the path to the file. Paths to local files should be relative, as in `loadJSON('assets/data.json')`. URLs such as `'https://example.com/data.json'` may be blocked due to browser security.
The second parameter, `successCallback`, is optional. If a function is passed, as in `loadJSON('assets/data.json', handleData)`, then the `handleData()` function will be called once the data loads. The object created from the JSON data will be passed to `handleData()` as its only argument.
The third parameter, `failureCallback`, is also optional. If a function is passed, as in `loadJSON('assets/data.json', handleData, handleFailure)`, then the `handleFailure()` function will be called if an error occurs while loading. The `Error` object will be passed to `handleFailure()` as its only argument.
Note: Data can take time to load. Calling `loadJSON()` within preload() ensures data loads before it's used in setup() or draw().

method

loadJSON

path

path of the JSON file to be loaded.

String

successCallback

function to call once the data is loaded. Will be passed the object.

Function

errorCallback

function to call if the data fails to load. Will be passed an `Error` event object.

Function

### return
object containing the loaded data.

Object

` let myData; // Load the JSON and create an object. function preload() { myData = loadJSON('assets/data.json'); } function setup() { createCanvas(100, 100); background(200); // Style the circle. fill(myData.color); noStroke(); // Draw the circle. circle(myData.x, myData.y, myData.d); describe('A pink circle on a gray background.'); } `
` let myData; // Load the JSON and create an object. function preload() { myData = loadJSON('assets/data.json'); } function setup() { createCanvas(100, 100); background(200); // Create a p5.Color object and make it transparent. let c = color(myData.color); c.setAlpha(80); // Style the circles. fill(c); noStroke(); // Iterate over the myData.bubbles array. for (let b of myData.bubbles) { // Draw a circle for each bubble. circle(b.x, b.y, b.d); } describe('Several pink bubbles floating in a blue sky.'); } `
` let myData; // Load the GeoJSON and create an object. function preload() { myData = loadJSON('https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson'); } function setup() { createCanvas(100, 100); background(200); // Get data about the most recent earthquake. let quake = myData.features[0].properties; // Draw a circle based on the earthquake's magnitude. circle(50, 50, quake.mag * 10); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(11); // Display the earthquake's location. text(quake.place, 5, 80, 100); describe(`A white circle on a gray background. The text "${quake.place}" is written beneath the circle.`); } `
` let bigQuake; // Load the GeoJSON and preprocess it. function preload() { loadJSON( 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson', handleData ); } function setup() { createCanvas(100, 100); background(200); // Draw a circle based on the earthquake's magnitude. circle(50, 50, bigQuake.mag * 10); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(11); // Display the earthquake's location. text(bigQuake.place, 5, 80, 100); describe(`A white circle on a gray background. The text "${bigQuake.place}" is written beneath the circle.`); } // Find the biggest recent earthquake. function handleData(data) { let maxMag = 0; // Iterate over the earthquakes array. for (let quake of data.features) { // Reassign bigQuake if a larger // magnitude quake is found. if (quake.properties.mag > maxMag) { bigQuake = quake.properties; } } } `
` let bigQuake; // Load the GeoJSON and preprocess it. function preload() { loadJSON( 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson', handleData, handleError ); } function setup() { createCanvas(100, 100); background(200); // Draw a circle based on the earthquake's magnitude. circle(50, 50, bigQuake.mag * 10); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(11); // Display the earthquake's location. text(bigQuake.place, 5, 80, 100); describe(`A white circle on a gray background. The text "${bigQuake.place}" is written beneath the circle.`); } // Find the biggest recent earthquake. function handleData(data) { let maxMag = 0; // Iterate over the earthquakes array. for (let quake of data.features) { // Reassign bigQuake if a larger // magnitude quake is found. if (quake.properties.mag > maxMag) { bigQuake = quake.properties; } } } // Log any errors to the console. function handleError(error) { console.log('Oops!', error); } `

p5

IO

Input

Loads a text file to create an `Array`.
The first parameter, `path`, is always a string with the path to the file. Paths to local files should be relative, as in `loadStrings('assets/data.txt')`. URLs such as `'https://example.com/data.txt'` may be blocked due to browser security.
The second parameter, `successCallback`, is optional. If a function is passed, as in `loadStrings('assets/data.txt', handleData)`, then the `handleData()` function will be called once the data loads. The array created from the text data will be passed to `handleData()` as its only argument.
The third parameter, `failureCallback`, is also optional. If a function is passed, as in `loadStrings('assets/data.txt', handleData, handleFailure)`, then the `handleFailure()` function will be called if an error occurs while loading. The `Error` object will be passed to `handleFailure()` as its only argument.
Note: Data can take time to load. Calling `loadStrings()` within preload() ensures data loads before it's used in setup() or draw().

method

loadStrings

path

path of the text file to be loaded.

String

successCallback

function to call once the data is loaded. Will be passed the array.

Function

errorCallback

function to call if the data fails to load. Will be passed an `Error` event object.

Function

### return
new array containing the loaded text.

String[]

` let myData; // Load the text and create an array. function preload() { myData = loadStrings('assets/test.txt'); } function setup() { createCanvas(100, 100); background(200); // Select a random line from the text. let phrase = random(myData); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(12); // Display the text. text(phrase, 10, 50, 90); describe(`The text "${phrase}" written in black on a gray background.`); } `
` let lastLine; // Load the text and preprocess it. function preload() { loadStrings('assets/test.txt', handleData); } function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(12); // Display the text. text(lastLine, 10, 50, 90); describe('The text "I talk like an orange" written in black on a gray background.'); } // Select the last line from the text. function handleData(data) { lastLine = data[data.length - 1]; } `
` let lastLine; // Load the text and preprocess it. function preload() { loadStrings('assets/test.txt', handleData, handleError); } function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(12); // Display the text. text(lastLine, 10, 50, 90); describe('The text "I talk like an orange" written in black on a gray background.'); } // Select the last line from the text. function handleData(data) { lastLine = data[data.length - 1]; } // Log any errors to the console. function handleError(error) { console.error('Oops!', error); } `

p5

IO

Input

Reads the contents of a file or URL and creates a p5.Table object with its values. If a file is specified, it must be located in the sketch's "data" folder. The filename parameter can also be a URL to a file found online. By default, the file is assumed to be comma-separated (in CSV format). Table only looks for a header row if the 'header' option is included.
This method is asynchronous, meaning it may not finish before the next line in your sketch is executed. Calling loadTable() inside preload() guarantees to complete the operation before setup() and draw() are called. Outside of preload(), you may supply a callback function to handle the object:
All files loaded and saved use UTF-8 encoding. This method is suitable for fetching files up to size of 64MB.

method

loadTable

filename

name of the file or URL to load

String

extension

parse the table by comma-separated values "csv", semicolon-separated values "ssv", or tab-separated values "tsv"

String

header

"header" to indicate table has header row

String

callback

function to be executed after loadTable() completes. On success, the Table object is passed in as the first argument.

Function

errorCallback

function to be executed if there is an error, response is passed in as first argument

Function

### return
Table object containing data

Object

` // Given the following CSV file called "mammals.csv" // located in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); //the file can be remote //table = loadTable("https://p5js.org/reference/assets/mammals.csv", // "csv", "header"); } function setup() { //count the columns print(table.getRowCount() + ' total rows in table'); print(table.getColumnCount() + ' total columns in table'); print(table.getColumn('name')); //["Goat", "Leopard", "Zebra"] //cycle through the table for (let r = 0; r < table.getRowCount(); r++) for (let c = 0; c < table.getColumnCount(); c++) { print(table.getString(r, c)); } describe(`randomly generated text from a file, for example "i smell like butter"`); } `

p5

IO

Input

Loads an XML file to create a p5.XML object.
Extensible Markup Language (XML) is a standard format for sending data between applications. Like HTML, the XML format is based on tags and attributes, as in `<time units="s">1234</time>`.
The first parameter, `path`, is always a string with the path to the file. Paths to local files should be relative, as in `loadXML('assets/data.xml')`. URLs such as `'https://example.com/data.xml'` may be blocked due to browser security.
The second parameter, `successCallback`, is optional. If a function is passed, as in `loadXML('assets/data.xml', handleData)`, then the `handleData()` function will be called once the data loads. The p5.XML object created from the data will be passed to `handleData()` as its only argument.
The third parameter, `failureCallback`, is also optional. If a function is passed, as in `loadXML('assets/data.xml', handleData, handleFailure)`, then the `handleFailure()` function will be called if an error occurs while loading. The `Error` object will be passed to `handleFailure()` as its only argument.
Note: Data can take time to load. Calling `loadXML()` within preload() ensures data loads before it's used in setup() or draw().

method

loadXML

path

path of the XML file to be loaded.

String

successCallback

function to call once the data is loaded. Will be passed the p5.XML object.

Function

errorCallback

function to call if the data fails to load. Will be passed an `Error` event object.

Function

### return
XML data loaded into a p5.XML object.

p5.XML

` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Get an array with all mammal tags. let mammals = myXML.getChildren('mammal'); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(14); // Iterate over the mammals array. for (let i = 0; i < mammals.length; i += 1) { // Calculate the y-coordinate. let y = (i + 1) * 25; // Get the mammal's common name. let name = mammals[i].getContent(); // Display the mammal's name. text(name, 20, y); } describe( 'The words "Goat", "Leopard", and "Zebra" written on three separate lines. The text is black on a gray background.' ); } `
` let lastMammal; // Load the XML and create a p5.XML object. function preload() { loadXML('assets/animals.xml', handleData); } function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(16); // Display the content of the last mammal element. text(lastMammal, 50, 50); describe('The word "Zebra" written in black on a gray background.'); } // Get the content of the last mammal element. function handleData(data) { // Get an array with all mammal elements. let mammals = data.getChildren('mammal'); // Get the content of the last mammal. lastMammal = mammals[mammals.length - 1].getContent(); } `
` let lastMammal; // Load the XML and preprocess it. function preload() { loadXML('assets/animals.xml', handleData, handleError); } function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(16); // Display the content of the last mammal element. text(lastMammal, 50, 50); describe('The word "Zebra" written in black on a gray background.'); } // Get the content of the last mammal element. function handleData(data) { // Get an array with all mammal elements. let mammals = data.getChildren('mammal'); // Get the content of the last mammal. lastMammal = mammals[mammals.length - 1].getContent(); } // Log any errors to the console. function handleError(error) { console.error('Oops!', error); } `

p5

IO

Input

This method is suitable for fetching files up to size of 64MB.

method

loadBytes

file

name of the file or URL to load

String

callback

function to be executed after loadBytes() completes

Function

errorCallback

function to be executed if there is an error

Function

### return
an object whose 'bytes' property will be the loaded buffer

Object

` 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)); } describe('no image displayed'); } `

p5

IO

Input

Method for executing an HTTP GET request. If data type is not specified, p5 will try to guess based on the URL, defaulting to text. This is equivalent to calling `httpDo(path, 'GET')`. The 'binary' datatype will return a Blob object, and the 'arrayBuffer' datatype will return an ArrayBuffer which can be used to initialize typed arrays (such as Uint8Array).

method

httpGet

### return
A promise that resolves with the data when the operation completes successfully or rejects with the error after one occurs.

Promise

` // Examples use USGS Earthquake API: // https://earthquake.usgs.gov/fdsnws/event/1/#methods let earthquakes; function preload() { // Get the most recent earthquake in the database let url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?' + 'format=geojson&limit;=1&orderby;=time'; httpGet(url, 'jsonp', false, function(response) { // when the HTTP request completes, populate the variable that holds the // earthquake data used in the visualization. earthquakes = response; }); } function draw() { if (!earthquakes) { // Wait until the earthquake data has loaded before drawing. return; } background(200); // Get the magnitude and name of the earthquake out of the loaded JSON let earthquakeMag = earthquakes.features[0].properties.mag; let earthquakeName = earthquakes.features[0].properties.place; ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10); textAlign(CENTER); text(earthquakeName, 0, height - 30, width, 30); noLoop(); } `

p5

IO

Input

path

name of the file or url to load

String

datatype

"json", "jsonp", "binary", "arrayBuffer", "xml", or "text"

String

data

param data passed sent with request

Object|Boolean

callback

function to be executed after httpGet() completes, data is passed in as first argument

Function

errorCallback

function to be executed if there is an error, response is passed in as first argument

Function

##### return
A promise that resolves with the data when the operation completes successfully or rejects with the error after one occurs.

Promise

path



String

data



Object|Boolean

callback



Function

errorCallback



Function

##### return


Promise

path



String

callback



Function

errorCallback



Function

##### return


Promise

Method for executing an HTTP POST request. If data type is not specified, p5 will try to guess based on the URL, defaulting to text. This is equivalent to calling `httpDo(path, 'POST')`.

method

httpPost

### return
A promise that resolves with the data when the operation completes successfully or rejects with the error after one occurs.

Promise

` // Examples use jsonplaceholder.typicode.com for a Mock Data API let url = 'https://jsonplaceholder.typicode.com/posts'; let postData = { userId: 1, title: 'p5 Clicked!', body: 'p5.js is very cool.' }; function setup() { createCanvas(100, 100); background(200); } function mousePressed() { httpPost(url, 'json', postData, function(result) { strokeWeight(2); text(result.body, mouseX, mouseY); }); } `
` let url = 'ttps://invalidURL'; // A bad URL that will cause errors let postData = { title: 'p5 Clicked!', body: 'p5.js is very cool.' }; function setup() { createCanvas(100, 100); background(200); } function mousePressed() { httpPost( url, 'json', postData, function(result) { // ... won't be called }, function(error) { strokeWeight(2); text(error.toString(), mouseX, mouseY); } ); } `

p5

IO

Input

path

name of the file or url to load

String

datatype

"json", "jsonp", "xml", or "text". If omitted, httpPost() will guess.

String

data

param data passed sent with request

Object|Boolean

callback

function to be executed after httpPost() completes, data is passed in as first argument

Function

errorCallback

function to be executed if there is an error, response is passed in as first argument

Function

##### return
A promise that resolves with the data when the operation completes successfully or rejects with the error after one occurs.

Promise

path



String

data



Object|Boolean

callback



Function

errorCallback



Function

##### return


Promise

path



String

callback



Function

errorCallback



Function

##### return


Promise

Method for executing an HTTP request. If data type is not specified, p5 will try to guess based on the URL, defaulting to text.  
  
For more advanced use, you may also pass in the path as the first argument and a object as the second argument, the signature follows the one specified in the Fetch API specification. This method is suitable for fetching files up to size of 64MB when "GET" is used.

method

httpDo

### return
A promise that resolves with the data when the operation completes successfully or rejects with the error after one occurs.

Promise

` // Examples use USGS Earthquake API: // https://earthquake.usgs.gov/fdsnws/event/1/#methods // displays an animation of all USGS earthquakes let earthquakes; let eqFeatureIndex = 0; function preload() { let url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson'; httpDo( url, { method: 'GET', // Other Request options, like special headers for apis headers: { authorization: 'Bearer secretKey' } }, function(res) { earthquakes = res; } ); } function draw() { // wait until the data is loaded if (!earthquakes || !earthquakes.features[eqFeatureIndex]) { return; } clear(); let feature = earthquakes.features[eqFeatureIndex]; let mag = feature.properties.mag; let rad = mag / 11 * ((width + height) / 2); fill(255, 0, 0, 100); ellipse(width / 2 + random(-2, 2), height / 2 + random(-2, 2), rad, rad); if (eqFeatureIndex >= earthquakes.features.length) { eqFeatureIndex = 0; } else { eqFeatureIndex += 1; } } `

p5

IO

Input

path

name of the file or url to load

String

method

either "GET", "POST", or "PUT", defaults to "GET"

String

datatype

"json", "jsonp", "xml", or "text"

String

data

param data passed sent with request

Object

callback

function to be executed after httpGet() completes, data is passed in as first argument

Function

errorCallback

function to be executed if there is an error, response is passed in as first argument

Function

##### return
A promise that resolves with the data when the operation completes successfully or rejects with the error after one occurs.

Promise

path



String

options

Request object options as documented in the "fetch" API reference

Object

callback



Function

errorCallback



Function

##### return


Promise

Creates a new p5.PrintWriter object.
p5.PrintWriter objects provide a way to save a sequence of text data, called the print stream, to the user's computer. They're low-level objects that enable precise control of text output. Functions such as saveStrings() and saveJSON() are easier to use for simple file saving.
The first parameter, `filename`, is the name of the file to be written. If a string is passed, as in `createWriter('words.txt')`, a new p5.PrintWriter object will be created that writes to a file named `words.txt`.
The second parameter, `extension`, is optional. If a string is passed, as in `createWriter('words', 'csv')`, the first parameter will be interpreted as the file name and the second parameter as the extension.

method

createWriter

name

name of the file to create.

String

extension

format to use for the file.

String

### return
stream for writing data.

p5.PrintWriter

` function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(12); // Display instructions. text('Double-click to save', 5, 50, 90); describe('The text "Double-click to save" written in black on a gray background.'); } // Save the file when the user double-clicks. function doubleClicked() { if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { // Create a p5.PrintWriter object. let myWriter = createWriter('xo.txt'); // Add some lines to the print stream. myWriter.print('XOO'); myWriter.print('OXO'); myWriter.print('OOX'); // Save the file and close the print stream. myWriter.close(); } } `
` function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(12); // Display instructions. text('Double-click to save', 5, 50, 90); describe('The text "Double-click to save" written in black on a gray background.'); } // Save the file when the user double-clicks. function doubleClicked() { if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { // Create a p5.PrintWriter object. // Use the file format .csv. let myWriter = createWriter('mauna_loa_co2', 'csv'); // Add some lines to the print stream. myWriter.print('date,ppm_co2'); myWriter.print('1960-01-01,316.43'); myWriter.print('1970-01-01,325.06'); myWriter.print('1980-01-01,337.9'); myWriter.print('1990-01-01,353.86'); myWriter.print('2000-01-01,369.45'); myWriter.print('2020-01-01,413.61'); // Save the file and close the print stream. myWriter.close(); } } `

p5

IO

Output

Writes data to the print stream without adding new lines.
The parameter, `data`, is the data to write. `data` can be a number or string, as in `myWriter.write('hi')`, or an array of numbers and strings, as in `myWriter.write([1, 2, 3])`. A comma will be inserted between array array elements when they're added to the print stream.

method

write

data

data to be written as a string, number, or array of strings and numbers.

String|Number|Array

` function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(12); // Display instructions. text('Double-click to save', 5, 50, 90); describe('The text "Double-click to save" written in black on a gray background.'); } // Save the file when the user double-clicks. function doubleClicked() { // Create a p5.PrintWriter object. let myWriter = createWriter('numbers.txt'); // Add some data to the print stream. myWriter.write('1,2,3,'); myWriter.write(['4', '5', '6']); // Save the file and close the print stream. myWriter.close(); } `

p5.PrintWriter

IO

Output

Writes data to the print stream with new lines added.
The parameter, `data`, is the data to write. `data` can be a number or string, as in `myWriter.print('hi')`, or an array of numbers and strings, as in `myWriter.print([1, 2, 3])`. A comma will be inserted between array array elements when they're added to the print stream.

method

print

data

data to be written as a string, number, or array of strings and numbers.

String|Number|Array

` function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(12); // Display instructions. text('Double-click to save', 5, 50, 90); describe('The text "Double-click to save" written in black on a gray background.'); } // Save the file when the user double-clicks. function doubleClicked() { // Create a p5.PrintWriter object. let myWriter = createWriter('numbers.txt'); // Add some data to the print stream. myWriter.print('1,2,3,'); myWriter.print(['4', '5', '6']); // Save the file and close the print stream. myWriter.close(); } `

p5.PrintWriter

IO

Output

Clears all data from the print stream.

method

clear

` function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(12); // Display instructions. text('Double-click to save', 5, 50, 90); describe('The text "Double-click to save" written in black on a gray background.'); } // Save the file when the user double-clicks. function doubleClicked() { // Create a p5.PrintWriter object. let myWriter = createWriter('numbers.txt'); // Add some data to the print stream. myWriter.print('Hello p5*js!'); // Clear the print stream. myWriter.clear(); // Save the file and close the print stream. myWriter.close(); } `

p5.PrintWriter

IO

Output

Saves the file and closes the print stream.

method

close

` function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(12); // Display instructions. text('Double-click to save', 5, 50, 90); describe('The text "Double-click to save" written in black on a gray background.'); } // Save the file when the user double-clicks. function doubleClicked() { // Create a p5.PrintWriter object. let myWriter = createWriter('cat.txt'); // Add some data to the print stream. // ASCII art courtesy Wikipedia: // https://en.wikipedia.org/wiki/ASCII_art myWriter.print(' (\\_/) '); myWriter.print("(='.'=)"); myWriter.print('(")_(")'); // Save the file and close the print stream. myWriter.close(); } `

p5.PrintWriter

IO

Output

Saves a given element(image, text, json, csv, wav, or html) to the client's computer. The first parameter can be a pointer to element we want to save. The element can be one of p5.Element,an Array of Strings, an Array of JSON, a JSON object, a p5.Table , a p5.Image, or a p5.SoundFile (requires p5.sound). The second parameter is a filename (including extension).The third parameter is for options specific to this type of object. This method will save a file that fits the given parameters. If it is called without specifying an element, by default it will save the whole canvas as an image file. You can optionally specify a filename as the first parameter in such a case. Note that it is not recommended to call this method within draw, as it will open a new save dialog on every render.

method

save

objectOrFilename

If filename is provided, will save canvas as an image with either png or jpg extension depending on the filename. If object is provided, will save depending on the object and filename (see examples above).

Object|String

filename

If an object is provided as the first parameter, then the second parameter indicates the filename, and should include an appropriate file extension (see examples above).

String

options

Additional options depend on filetype. For example, when saving JSON, `true` indicates that the output will be optimized for filesize, rather than readability.

Boolean|String

` // Saves the canvas as an image cnv = createCanvas(300, 300); save(cnv, 'myCanvas.jpg'); // Saves the canvas as an image by default save('myCanvas.jpg'); describe('An example for saving a canvas as an image.'); `
` // Saves p5.Image as an image img = createImage(10, 10); save(img, 'myImage.png'); describe('An example for saving a p5.Image element as an image.'); `
` // Saves p5.Renderer object as an image obj = createGraphics(100, 100); save(obj, 'myObject.png'); describe('An example for saving a p5.Renderer element.'); `
` let myTable = new p5.Table(); // Saves table as html file save(myTable, 'myTable.html'); // Comma Separated Values save(myTable, 'myTable.csv'); // Tab Separated Values save(myTable, 'myTable.tsv'); describe(`An example showing how to save a table in formats of HTML, CSV and TSV.`); `
` let myJSON = { a: 1, b: true }; // Saves pretty JSON save(myJSON, 'my.json'); // Optimizes JSON filesize save(myJSON, 'my.json', true); describe('An example for saving JSON to a txt file with some extra arguments.'); `
` // Saves array of strings to text file with line breaks after each item let arrayOfStrings = ['a', 'b']; save(arrayOfStrings, 'my.txt'); describe(`An example for saving an array of strings to text file with line breaks.`); `

p5

IO

Output

Saves an `Object` or `Array` to a JSON file.
JavaScript Object Notation (JSON) is a standard format for sending data between applications. The format is based on JavaScript objects which have keys and values. JSON files store data in an object with strings as keys. Values can be strings, numbers, Booleans, arrays, `null`, or other objects.
The first parameter, `json`, is the data to save. The data can be an array, as in `[1, 2, 3]`, or an object, as in `{ x: 50, y: 50, color: 'deeppink' }`.
The second parameter, `filename`, is a string that sets the file's name. For example, calling `saveJSON([1, 2, 3], 'data.json')` saves the array `[1, 2, 3]` to a file called `data.json` on the user's computer.
The third parameter, `optimize`, is optional. If `true` is passed, as in `saveJSON([1, 2, 3], 'data.json', true)`, then all unneeded whitespace will be removed to reduce the file size.
Note: The browser will either save the file immediately or prompt the user with a dialogue window.

method

saveJSON

json

data to save.

Array|Object

filename

name of the file to be saved.

String

optimize

whether to trim unneeded whitespace. Defaults to `true`.

Boolean

` function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(12); // Display instructions. text('Double-click to save', 5, 50, 90); describe('The text "Double-click to save" written in black on a gray background.'); } // Save the file when the user double-clicks. function doubleClicked() { if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { // Create an array. let data = [1, 2, 3]; // Save the JSON file. saveJSON(data, 'numbers.json'); } } `
` function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(12); // Display instructions. text('Double-click to save', 5, 50, 90); describe('The text "Double-click to save" written in black on a gray background.'); } // Save the file when the user double-clicks. function doubleClicked() { if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { // Create an object. let data = { x: mouseX, y: mouseY }; // Save the JSON file. saveJSON(data, 'state.json'); } } `
` function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(12); // Display instructions. text('Double-click to save', 5, 50, 90); describe('The text "Double-click to save" written in black on a gray background.'); } // Save the file when the user double-clicks. function doubleClicked() { if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { // Create an object. let data = { x: mouseX, y: mouseY }; // Save the JSON file and reduce its size. saveJSON(data, 'state.json', true); } } `

p5

IO

Output

Saves an `Array` of `String`s to a file, one per line.
The first parameter, `list`, is an array with the strings to save.
The second parameter, `filename`, is a string that sets the file's name. For example, calling `saveStrings(['0', '01', '011'], 'data.txt')` saves the array `['0', '01', '011']` to a file called `data.txt` on the user's computer.
The third parameter, `extension`, is optional. If a string is passed, as in `saveStrings(['0', '01', '0`1'], 'data', 'txt')`, the second parameter will be interpreted as the file name and the third parameter as the extension.
The fourth parameter, `isCRLF`, is also optional, If `true` is passed, as in `saveStrings(['0', '01', '011'], 'data', 'txt', true)`, then two characters, `\r ` , will be added to the end of each string to create new lines in the saved file. `\r` is a carriage return (CR) and ` ` is a line feed (LF). By default, only ` ` (line feed) is added to each string in order to create new lines.
Note: The browser will either save the file immediately or prompt the user with a dialogue window.

method

saveStrings

list

data to save.

String[]

filename

name of file to be saved.

String

extension

format to use for the file.

String

isCRLF

whether to add `\r ` to the end of each string. Defaults to `false`.

Boolean

` function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(12); // Display instructions. text('Double-click to save', 5, 50, 90); describe('The text "Double-click to save" written in black on a gray background.'); } // Save the file when the user double-clicks. function doubleClicked() { if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { // Create an array. let data = ['0', '01', '011']; // Save the text file. saveStrings(data, 'data.txt'); } } `
` function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(12); // Display instructions. text('Double-click to save', 5, 50, 90); describe('The text "Double-click to save" written in black on a gray background.'); } // Save the file when the user double-clicks. function doubleClicked() { if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { // Create an array. // ASCII art courtesy Wikipedia: // https://en.wikipedia.org/wiki/ASCII_art let data = [' (\\_/) ', "(='.'=)", '(")_(")']; // Save the text file. saveStrings(data, 'cat', 'txt'); } } `
` function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(12); // Display instructions. text('Double-click to save', 5, 50, 90); describe('The text "Double-click to save" written in black on a gray background.'); } // Save the file when the user double-clicks. function doubleClicked() { if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { // Create an array. // +--+ // / /| // +--+ + // | |/ // +--+ let data = [' +--+', ' / /|', '+--+ +', '| |/', '+--+']; // Save the text file. // Use CRLF for line endings. saveStrings(data, 'box', 'txt', true); } } `

p5

IO

Output

Writes the contents of a Table object to a file. Defaults to a text file with comma-separated-values ('csv') but can also use tab separation ('tsv'), or generate an HTML table ('html'). The file saving process and location of the saved file will vary between web browsers.

method

saveTable

Table

the Table object to save to a file

p5.Table

filename

the filename to which the Table should be saved

String

options

can be one of "tsv", "csv", or "html"

String

` let table; function setup() { table = new p5.Table(); table.addColumn('id'); table.addColumn('species'); table.addColumn('name'); let newRow = table.addRow(); newRow.setNum('id', table.getRowCount() - 1); newRow.setString('species', 'Panthera leo'); newRow.setString('name', 'Lion'); // To save, un-comment next line then click 'run' // saveTable(table, 'new.csv'); describe('no image displayed'); } // Saves the following to a file called 'new.csv': // id,species,name // 0,Panthera leo,Lion `

p5

IO

Output

Table Options Generic class for handling tabular data, typically from a CSV, TSV, or other sort of spreadsheet file. CSV files are  comma separated values, often with the data in quotes. TSV files use tabs as separators, and usually don't bother with the quotes. File names should end with .csv if they're comma separated. A rough "spec" for CSV can be found here. To load files, use the loadTable method. To save tables to your computer, use the save method or the saveTable method.
Possible options include:
    * csv - parse the table as comma-separated values 
    * tsv - parse the table as tab-separated values 
    * header - this table has a header (title) row 

p5.Table

IO

Table

An array containing the names of the columns in the table, if the "header" the table is loaded with the "header" parameter.

{String[]}

property

columns

` // Given the CSV file "mammals.csv" // in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { //print the column names for (let c = 0; c < table.getColumnCount(); c++) { print('column ' + c + ' is named ' + table.columns[c]); } } `

p5.Table

IO

Table

An array containing the p5.TableRow objects that make up the rows of the table. The same result as calling getRows()

{p5.TableRow[]}

property

rows

p5.Table

IO

Table

Use addRow() to add a new row of data to a p5.Table object. By default, an empty row is created. Typically, you would store a reference to the new row in a TableRow object (see newRow in the example above), and then set individual values using set().
If a p5.TableRow object is included as a parameter, then that row is duplicated and added to the table.

method

addRow

row

row to be added to the table

p5.TableRow

### return
the row that was added

p5.TableRow

` // Given the CSV file "mammals.csv" // in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { //add a row let newRow = table.addRow(); newRow.setString('id', table.getRowCount() - 1); newRow.setString('species', 'Canis Lupus'); newRow.setString('name', 'Wolf'); //print the results for (let r = 0; r < table.getRowCount(); r++) for (let c = 0; c < table.getColumnCount(); c++) print(table.getString(r, c)); describe('no image displayed'); } `

p5.Table

IO

Table

Removes a row from the table object.

method

removeRow

id

ID number of the row to remove

Integer

` // Given the CSV file "mammals.csv" // in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { //remove the first row table.removeRow(0); //print the results for (let r = 0; r < table.getRowCount(); r++) for (let c = 0; c < table.getColumnCount(); c++) print(table.getString(r, c)); describe('no image displayed'); } `

p5.Table

IO

Table

Returns a reference to the specified p5.TableRow. The reference can then be used to get and set values of the selected row.

method

getRow

rowID

ID number of the row to get

Integer

### return
p5.TableRow object

p5.TableRow

` // Given the CSV file "mammals.csv" // in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { let row = table.getRow(1); //print it column by column //note: a row is an object, not an array for (let c = 0; c < table.getColumnCount(); c++) { print(row.getString(c)); } describe('no image displayed'); } `

p5.Table

IO

Table

Gets all rows from the table. Returns an array of p5.TableRows.

method

getRows

### return
Array of p5.TableRows

p5.TableRow[]

` // Given the CSV file "mammals.csv" // in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { let rows = table.getRows(); //warning: rows is an array of objects for (let r = 0; r < rows.length; r++) { rows[r].set('name', 'Unicorn'); } //print the results for (let r = 0; r < table.getRowCount(); r++) for (let c = 0; c < table.getColumnCount(); c++) print(table.getString(r, c)); describe('no image displayed'); } `

p5.Table

IO

Table

Finds the first row in the Table that contains the value provided, and returns a reference to that row. Even if multiple rows are possible matches, only the first matching row is returned. The column to search may be specified by either its ID or title.

method

findRow

value

The value to match

String

column

ID number or title of the column to search

Integer|String

### return


p5.TableRow

` // Given the CSV file "mammals.csv" // in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { //find the animal named zebra let row = table.findRow('Zebra', 'name'); //find the corresponding species print(row.getString('species')); describe('no image displayed'); } `

p5.Table

IO

Table

Finds the rows in the Table that contain the value provided, and returns references to those rows. Returns an Array, so for must be used to iterate through all the rows, as shown in the example above. The column to search may be specified by either its ID or title.

method

findRows

value

The value to match

String

column

ID number or title of the column to search

Integer|String

### return
An Array of TableRow objects

p5.TableRow[]

` // Given the CSV file "mammals.csv" // in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { //add another goat let newRow = table.addRow(); newRow.setString('id', table.getRowCount() - 1); newRow.setString('species', 'Scape Goat'); newRow.setString('name', 'Goat'); //find the rows containing animals named Goat let rows = table.findRows('Goat', 'name'); print(rows.length + ' Goats found'); describe('no image displayed'); } `

p5.Table

IO

Table

Finds the first row in the Table that matches the regular expression provided, and returns a reference to that row. Even if multiple rows are possible matches, only the first matching row is returned. The column to search may be specified by either its ID or title.

method

matchRow

regexp

The regular expression to match

String|RegExp

column

The column ID (number) or title (string)

String|Integer

### return
TableRow object

p5.TableRow

` // Given the CSV file "mammals.csv" // in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { //Search using specified regex on a given column, return TableRow object let mammal = table.matchRow(new RegExp('ant'), 1); print(mammal.getString(1)); //Output "Panthera pardus" } `

p5.Table

IO

Table

Finds the rows in the Table that match the regular expression provided, and returns references to those rows. Returns an array, so for must be used to iterate through all the rows, as shown in the example. The column to search may be specified by either its ID or title.

method

matchRows

regexp

The regular expression to match

String

column

The column ID (number) or title (string)

String|Integer

### return
An Array of TableRow objects

p5.TableRow[]

` let table; function setup() { table = new p5.Table(); table.addColumn('name'); table.addColumn('type'); let newRow = table.addRow(); newRow.setString('name', 'Lion'); newRow.setString('type', 'Mammal'); newRow = table.addRow(); newRow.setString('name', 'Snake'); newRow.setString('type', 'Reptile'); newRow = table.addRow(); newRow.setString('name', 'Mosquito'); newRow.setString('type', 'Insect'); newRow = table.addRow(); newRow.setString('name', 'Lizard'); newRow.setString('type', 'Reptile'); let rows = table.matchRows('R.*', 'type'); for (let i = 0; i < rows.length; i++) { print(rows[i].getString('name') + ': ' + rows[i].getString('type')); } } // Sketch prints: // Snake: Reptile // Lizard: Reptile `

p5.Table

IO

Table

Retrieves all values in the specified column, and returns them as an array. The column may be specified by either its ID or title.

method

getColumn

column

String or Number of the column to return

String|Number

### return
Array of column values

Array

` // Given the CSV file "mammals.csv" // in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { //getColumn returns an array that can be printed directly print(table.getColumn('species')); //outputs ["Capra hircus", "Panthera pardus", "Equus zebra"] describe('no image displayed'); } `

p5.Table

IO

Table

Removes all rows from a Table. While all rows are removed, columns and column titles are maintained.

method

clearRows

` // Given the CSV file "mammals.csv" // in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { table.clearRows(); print(table.getRowCount() + ' total rows in table'); print(table.getColumnCount() + ' total columns in table'); describe('no image displayed'); } `

p5.Table

IO

Table

Use addColumn() to add a new column to a Table object. Typically, you will want to specify a title, so the column may be easily referenced later by name. (If no title is specified, the new column's title will be null.)

method

addColumn

title

title of the given column

String

` // Given the CSV file "mammals.csv" // in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { table.addColumn('carnivore'); table.set(0, 'carnivore', 'no'); table.set(1, 'carnivore', 'yes'); table.set(2, 'carnivore', 'no'); //print the results for (let r = 0; r < table.getRowCount(); r++) for (let c = 0; c < table.getColumnCount(); c++) print(table.getString(r, c)); describe('no image displayed'); } `

p5.Table

IO

Table

Returns the total number of columns in a Table.

method

getColumnCount

### return
Number of columns in this table

Integer

` // given the cvs file "blobs.csv" in /assets directory // ID, Name, Flavor, Shape, Color // Blob1, Blobby, Sweet, Blob, Pink // Blob2, Saddy, Savory, Blob, Blue let table; function preload() { table = loadTable('assets/blobs.csv'); } function setup() { createCanvas(200, 100); textAlign(CENTER); background(255); } function draw() { let numOfColumn = table.getColumnCount(); text('There are ' + numOfColumn + ' columns in the table.', 100, 50); } `

p5.Table

IO

Table

Returns the total number of rows in a Table.

method

getRowCount

### return
Number of rows in this table

Integer

` // given the cvs file "blobs.csv" in /assets directory // // ID, Name, Flavor, Shape, Color // Blob1, Blobby, Sweet, Blob, Pink // Blob2, Saddy, Savory, Blob, Blue let table; function preload() { table = loadTable('assets/blobs.csv'); } function setup() { createCanvas(200, 100); textAlign(CENTER); background(255); } function draw() { text('There are ' + table.getRowCount() + ' rows in the table.', 100, 50); } `

p5.Table

IO

Table

Removes any of the specified characters (or "tokens").
If no column is specified, then the values in all columns and rows are processed. A specific column may be referenced by either its ID or title.

method

removeTokens

chars

String listing characters to be removed

String

column

Column ID (number) or name (string)

String|Integer

` function setup() { let table = new p5.Table(); table.addColumn('name'); table.addColumn('type'); let newRow = table.addRow(); newRow.setString('name', ' $Lion ,'); newRow.setString('type', ',,,Mammal'); newRow = table.addRow(); newRow.setString('name', '$Snake '); newRow.setString('type', ',,,Reptile'); table.removeTokens(',$ '); print(table.getArray()); } // prints: // 0 "Lion" "Mamal" // 1 "Snake" "Reptile" `

p5.Table

IO

Table

Trims leading and trailing whitespace, such as spaces and tabs, from String table values. If no column is specified, then the values in all columns and rows are trimmed. A specific column may be referenced by either its ID or title.

method

trim

column

Column ID (number) or name (string)

String|Integer

` function setup() { let table = new p5.Table(); table.addColumn('name'); table.addColumn('type'); let newRow = table.addRow(); newRow.setString('name', ' Lion ,'); newRow.setString('type', ' Mammal '); newRow = table.addRow(); newRow.setString('name', ' Snake '); newRow.setString('type', ' Reptile '); table.trim(); print(table.getArray()); } // prints: // 0 "Lion" "Mamal" // 1 "Snake" "Reptile" `

p5.Table

IO

Table

Use removeColumn() to remove an existing column from a Table object. The column to be removed may be identified by either its title (a String) or its index value (an int). removeColumn(0) would remove the first column, removeColumn(1) would remove the second column, and so on.

method

removeColumn

column

columnName (string) or ID (number)

String|Integer

` // Given the CSV file "mammals.csv" // in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { table.removeColumn('id'); print(table.getColumnCount()); describe('no image displayed'); } `

p5.Table

IO

Table

Stores a value in the Table's specified row and column. The row is specified by its ID, while the column may be specified by either its ID or title.

method

set

row

row ID

Integer

column

column ID (Number) or title (String)

String|Integer

value

value to assign

String|Number

` // Given the CSV file "mammals.csv" // in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { table.set(0, 'species', 'Canis Lupus'); table.set(0, 'name', 'Wolf'); //print the results for (let r = 0; r < table.getRowCount(); r++) for (let c = 0; c < table.getColumnCount(); c++) print(table.getString(r, c)); describe('no image displayed'); } `

p5.Table

IO

Table

Stores a Float value in the Table's specified row and column. The row is specified by its ID, while the column may be specified by either its ID or title.

method

setNum

row

row ID

Integer

column

column ID (Number) or title (String)

String|Integer

value

value to assign

Number

` // Given the CSV file "mammals.csv" // in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { table.setNum(1, 'id', 1); print(table.getColumn(0)); //["0", 1, "2"] describe('no image displayed'); } `

p5.Table

IO

Table

Stores a String value in the Table's specified row and column. The row is specified by its ID, while the column may be specified by either its ID or title.

method

setString

row

row ID

Integer

column

column ID (Number) or title (String)

String|Integer

value

value to assign

String

` // Given the CSV file "mammals.csv" in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { //add a row let newRow = table.addRow(); newRow.setString('id', table.getRowCount() - 1); newRow.setString('species', 'Canis Lupus'); newRow.setString('name', 'Wolf'); print(table.getArray()); describe('no image displayed'); } `

p5.Table

IO

Table

Retrieves a value from the Table's specified row and column. The row is specified by its ID, while the column may be specified by either its ID or title.

method

get

row

row ID

Integer

column

columnName (string) or ID (number)

String|Integer

### return


String|Number

` // Given the CSV file "mammals.csv" // in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { print(table.get(0, 1)); //Capra hircus print(table.get(0, 'species')); //Capra hircus describe('no image displayed'); } `

p5.Table

IO

Table

Retrieves a Float value from the Table's specified row and column. The row is specified by its ID, while the column may be specified by either its ID or title.

method

getNum

row

row ID

Integer

column

columnName (string) or ID (number)

String|Integer

### return


Number

` // Given the CSV file "mammals.csv" // in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { print(table.getNum(1, 0) + 100); //id 1 + 100 = 101 describe('no image displayed'); } `

p5.Table

IO

Table

Retrieves a String value from the Table's specified row and column. The row is specified by its ID, while the column may be specified by either its ID or title.

method

getString

row

row ID

Integer

column

columnName (string) or ID (number)

String|Integer

### return


String

` // Given the CSV file "mammals.csv" // in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { // table is comma separated value "CSV" // and has specifying header for column labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { print(table.getString(0, 0)); // 0 print(table.getString(0, 1)); // Capra hircus print(table.getString(0, 2)); // Goat print(table.getString(1, 0)); // 1 print(table.getString(1, 1)); // Panthera pardus print(table.getString(1, 2)); // Leopard print(table.getString(2, 0)); // 2 print(table.getString(2, 1)); // Equus zebra print(table.getString(2, 2)); // Zebra describe('no image displayed'); } `

p5.Table

IO

Table

Retrieves all table data and returns as an object. If a column name is passed in, each row object will be stored with that attribute as its title.

method

getObject

headerColumn

Name of the column which should be used to title each row object (optional)

String

### return


Object

` // Given the CSV file "mammals.csv" // in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { let tableObject = table.getObject(); print(tableObject); //outputs an object describe('no image displayed'); } `

p5.Table

IO

Table

Retrieves all table data and returns it as a multidimensional array.

method

getArray

### return


Array

` // Given the CSV file "mammals.csv" // in the project's "assets" folder // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leoperd // 2,Equus zebra,Zebra let table; function preload() { // table is comma separated value "CSV" // and has specifying header for column labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { let tableArray = table.getArray(); for (let i = 0; i < tableArray.length; i++) { print(tableArray[i]); } describe('no image displayed'); } `

p5.Table

IO

Table

Stores a value in the TableRow's specified column. The column may be specified by either its ID or title.

method

set

column

Column ID (Number) or Title (String)

String|Integer

value

The value to be stored

String|Number

` // Given the CSV file "mammals.csv" in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { let rows = table.getRows(); for (let r = 0; r < rows.length; r++) { rows[r].set('name', 'Unicorn'); } //print the results print(table.getArray()); describe('no image displayed'); } `

p5.TableRow

IO

Table

Stores a Float value in the TableRow's specified column. The column may be specified by either its ID or title.

method

setNum

column

Column ID (Number) or Title (String)

String|Integer

value

The value to be stored as a Float

Number|String

` // Given the CSV file "mammals.csv" in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { let rows = table.getRows(); for (let r = 0; r < rows.length; r++) { rows[r].setNum('id', r + 10); } print(table.getArray()); describe('no image displayed'); } `

p5.TableRow

IO

Table

Stores a String value in the TableRow's specified column. The column may be specified by either its ID or title.

method

setString

column

Column ID (Number) or Title (String)

String|Integer

value

The value to be stored as a String

String|Number|Boolean|Object

` // Given the CSV file "mammals.csv" in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { let rows = table.getRows(); for (let r = 0; r < rows.length; r++) { let name = rows[r].getString('name'); rows[r].setString('name', 'A ' + name + ' named George'); } print(table.getArray()); describe('no image displayed'); } `

p5.TableRow

IO

Table

Retrieves a value from the TableRow's specified column. The column may be specified by either its ID or title.

method

get

column

columnName (string) or ID (number)

String|Integer

### return


String|Number

` // Given the CSV file "mammals.csv" in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { let names = []; let rows = table.getRows(); for (let r = 0; r < rows.length; r++) { names.push(rows[r].get('name')); } print(names); describe('no image displayed'); } `

p5.TableRow

IO

Table

Retrieves a Float value from the TableRow's specified column. The column may be specified by either its ID or title.

method

getNum

column

columnName (string) or ID (number)

String|Integer

### return
Float Floating point number

Number

` // Given the CSV file "mammals.csv" in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { let rows = table.getRows(); let minId = Infinity; let maxId = -Infinity; for (let r = 0; r < rows.length; r++) { let id = rows[r].getNum('id'); minId = min(minId, id); maxId = min(maxId, id); } print('minimum id = ' + minId + ', maximum id = ' + maxId); describe('no image displayed'); } `

p5.TableRow

IO

Table

Retrieves an String value from the TableRow's specified column. The column may be specified by either its ID or title.

method

getString

column

columnName (string) or ID (number)

String|Integer

### return
String

String

` // Given the CSV file "mammals.csv" in the project's "assets" folder: // // id,species,name // 0,Capra hircus,Goat // 1,Panthera pardus,Leopard // 2,Equus zebra,Zebra let table; function preload() { //my table is comma separated value "csv" //and has a header specifying the columns labels table = loadTable('assets/mammals.csv', 'csv', 'header'); } function setup() { let rows = table.getRows(); let longest = ''; for (let r = 0; r < rows.length; r++) { let species = rows[r].getString('species'); if (longest.length < species.length) { longest = species; } } print('longest: ' + longest); describe('no image displayed'); } `

p5.TableRow

IO

Table

Returns the element's parent element as a new p5.XML object.

method

getParent

### return
parent element.

p5.XML

` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Get an array with all mammal elements. let mammals = myXML.getChildren('mammal'); // Get the first mammal element. let firstMammal = mammals[0]; // Get the parent element. let parent = firstMammal.getParent(); // Get the parent element's name. let name = parent.getName(); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(14); // Display the parent element's name. text(name, 50, 50); describe('The word "animals" written in black on a gray background.'); } `

p5.XML

IO

Input

Returns the element's name as a `String`.
An XML element's name is given by its tag. For example, the element `<language>JavaScript</language>` has the name `language`.

method

getName

### return
name of the element.

String

` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Get an array with all mammal elements. let mammals = myXML.getChildren('mammal'); // Get the first mammal element. let firstMammal = mammals[0]; // Get the mammal element's name. let name = firstMammal.getName(); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(14); // Display the element's name. text(name, 50, 50); describe('The word "mammal" written in black on a gray background.'); } `

p5.XML

IO

Input

Sets the element's tag name.
An XML element's name is given by its tag. For example, the element `<language>JavaScript</language>` has the name `language`.
The parameter, `name`, is the element's new name as a string. For example, calling `myXML.setName('planet')` will make the element's new tag name `<planet></planet>`.

method

setName

name

new tag name of the element.

String

` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Get the element's original name. let oldName = myXML.getName(); // Set the element's name. myXML.setName('monsters'); // Get the element's new name. let newName = myXML.getName(); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(14); // Display the element's names. text(oldName, 50, 33); text(newName, 50, 67); describe( 'The words "animals" and "monsters" written on separate lines. The text is black on a gray background.' ); } `

p5.XML

IO

Input

Returns `true` if the element has child elements and `false` if not.

method

hasChildren

### return
whether the element has children.

Boolean

` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Check whether the element has child elements. let isParent = myXML.hasChildren(); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(14); // Style the text. if (isParent === true) { text('Parent', 50, 50); } else { text('Not Parent', 50, 50); } describe('The word "Parent" written in black on a gray background.'); } `

p5.XML

IO

Input

Returns an array with the names of the element's child elements as `String`s.

method

listChildren

### return
names of the child elements.

String[]

` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Get the names of the element's children as an array. let children = myXML.listChildren(); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(14); // Iterate over the array. for (let i = 0; i < children.length; i += 1) { // Calculate the y-coordinate. let y = (i + 1) * 25; // Display the child element's name. text(children[i], 10, y); } describe( 'The words "mammal", "mammal", "mammal", and "reptile" written on separate lines. The text is black on a gray background.' ); } `

p5.XML

IO

Input

Returns an array with the element's child elements as new p5.XML objects.
The parameter, `name`, is optional. If a string is passed, as in `myXML.getChildren('cat')`, then the method will only return child elements with the tag `<cat>`.

method

getChildren

name

name of the elements to return.

String

### return
child elements.

p5.XML[]

` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Get an array of the child elements. let children = myXML.getChildren(); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(14); // Iterate over the array. for (let i = 0; i < children.length; i += 1) { // Calculate the y-coordinate. let y = (i + 1) * 20; // Get the child element's content. let content = children[i].getContent(); // Display the child element's content. text(content, 10, y); } describe( 'The words "Goat", "Leopard", "Zebra", and "Turtle" written on separate lines. The text is black on a gray background.' ); } `
` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Get an array of the child elements // that are mammals. let children = myXML.getChildren('mammal'); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(14); // Iterate over the array. for (let i = 0; i < children.length; i += 1) { // Calculate the y-coordinate. let y = (i + 1) * 20; // Get the child element's content. let content = children[i].getContent(); // Display the child element's content. text(content, 10, y); } describe( 'The words "Goat", "Leopard", and "Zebra" written on separate lines. The text is black on a gray background.' ); } `

p5.XML

IO

Input

Returns the first matching child element as a new p5.XML object.
The parameter, `name`, is optional. If a string is passed, as in `myXML.getChild('cat')`, then the first child element with the tag `<cat>` will be returned. If a number is passed, as in `myXML.getChild(1)`, then the child element at that index will be returned.

method

getChild

name

element name or index.

String|Integer

### return
child element.

p5.XML

` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Get the first child element that is a mammal. let goat = myXML.getChild('mammal'); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(14); // Get the child element's content. let content = goat.getContent(); // Display the child element's content. text(content, 50, 50); describe('The word "Goat" written in black on a gray background.'); } `
` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Get the child element at index 1. let leopard = myXML.getChild(1); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(14); // Get the child element's content. let content = leopard.getContent(); // Display the child element's content. text(content, 50, 50); describe('The word "Leopard" written in black on a gray background.'); } `

p5.XML

IO

Input

Adds a new child element and returns a reference to it.
The parameter, `child`, is the p5.XML object to add as a child element. For example, calling `myXML.addChild(otherXML)` inserts `otherXML` as a child element of `myXML`.

method

addChild

child

child element to add.

p5.XML

### return
added child element.

p5.XML

` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Create a new p5.XML object. let newAnimal = new p5.XML(); // Set its properties. newAnimal.setName('hydrozoa'); newAnimal.setAttribute('id', 4); newAnimal.setAttribute('species', 'Physalia physalis'); newAnimal.setContent('Bluebottle'); // Add the child element. myXML.addChild(newAnimal); // Get the first child element that is a hydrozoa. let blueBottle = myXML.getChild('hydrozoa'); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(14); // Get the child element's content. let content = blueBottle.getContent(); // Display the child element's content. text(content, 50, 50); describe('The word "Bluebottle" written in black on a gray background.'); } `

p5.XML

IO

Input

Removes the first matching child element.
The parameter, `name`, is the child element to remove. If a string is passed, as in `myXML.removeChild('cat')`, then the first child element with the tag `<cat>` will be removed. If a number is passed, as in `myXML.removeChild(1)`, then the child element at that index will be removed.

method

removeChild

name

name or index of the child element to remove.

String|Integer

` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Remove the first mammal element. myXML.removeChild('mammal'); // Get an array of child elements. let children = myXML.getChildren(); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(14); // Iterate over the array. for (let i = 0; i < children.length; i += 1) { // Calculate the y-coordinate. let y = (i + 1) * 25; // Get the child element's content. let content = children[i].getContent(); // Display the child element's content. text(content, 10, y); } describe( 'The words "Leopard", "Zebra", and "Turtle" written on separate lines. The text is black on a gray background.' ); } `
` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Remove the element at index 2. myXML.removeChild(2); // Get an array of child elements. let children = myXML.getChildren(); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(14); // Iterate over the array. for (let i = 0; i < children.length; i += 1) { // Calculate the y-coordinate. let y = (i + 1) * 25; // Get the child element's content. let content = children[i].getContent(); // Display the child element's content. text(content, 10, y); } describe( 'The words "Goat", "Leopard", and "Turtle" written on separate lines. The text is black on a gray background.' ); } `

p5.XML

IO

Input

Returns the number of attributes the element has.

method

getAttributeCount

### return
number of attributes.

Integer

` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Get the first child element. let first = myXML.getChild(0); // Get the number of attributes. let numAttributes = first.getAttributeCount(); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(14); // Display the number of attributes. text(numAttributes, 50, 50); describe('The number "2" written in black on a gray background.'); } `

p5.XML

IO

Input

Returns an `Array` with the names of the element's attributes.
Note: Use myXML.getString() or myXML.getNum() to return an attribute's value.

method

listAttributes

### return
attribute names.

String[]

` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Get the first child element. let first = myXML.getChild(0); // Get the number of attributes. let attributes = first.listAttributes(); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(14); // Display the element's attributes. text(attributes, 50, 50); describe('The text "id,species" written in black on a gray background.'); } `

p5.XML

IO

Input

Returns `true` if the element has a given attribute and `false` if not.
The parameter, `name`, is a string with the name of the attribute being checked.
Note: Use myXML.getString() or myXML.getNum() to return an attribute's value.

method

hasAttribute

name

name of the attribute to be checked.

String

### return
whether the element has the attribute.

Boolean

` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Get the first mammal child element. let mammal = myXML.getChild('mammal'); // Check whether the element has an // species attribute. let hasSpecies = mammal.hasAttribute('species'); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(14); // Display whether the element has a species attribute. if (hasSpecies === true) { text('Species', 50, 50); } else { text('No species', 50, 50); } describe('The text "Species" written in black on a gray background.'); } `

p5.XML

IO

Input

Return an attribute's value as a `Number`.
The first parameter, `name`, is a string with the name of the attribute being checked. For example, calling `myXML.getNum('id')` returns the element's `id` attribute as a number.
The second parameter, `defaultValue`, is optional. If a number is passed, as in `myXML.getNum('id', -1)`, it will be returned if the attribute doesn't exist or can't be converted to a number.
Note: Use myXML.getString() or myXML.getNum() to return an attribute's value.

method

getNum

name

name of the attribute to be checked.

String

defaultValue

value to return if the attribute doesn't exist.

Number

### return
attribute value as a number.

Number

` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Get the first reptile child element. let reptile = myXML.getChild('reptile'); // Get the reptile's content. let content = reptile.getContent(); // Get the reptile's ID. let id = reptile.getNum('id'); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(14); // Display the ID attribute. text(`${content} is ${id + 1}th`, 5, 50, 90); describe(`The text "${content} is ${id + 1}th" written in black on a gray background.`); } `
` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Get the first reptile child element. let reptile = myXML.getChild('reptile'); // Get the reptile's content. let content = reptile.getContent(); // Get the reptile's size. let weight = reptile.getNum('weight', 135); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(14); // Display the ID attribute. text(`${content} is ${weight}kg`, 5, 50, 90); describe( `The text "${content} is ${weight}kg" written in black on a gray background.` ); } `

p5.XML

IO

Input

Return an attribute's value as a string.
The first parameter, `name`, is a string with the name of the attribute being checked. For example, calling `myXML.getString('color')` returns the element's `id` attribute as a string.
The second parameter, `defaultValue`, is optional. If a string is passed, as in `myXML.getString('color', 'deeppink')`, it will be returned if the attribute doesn't exist.
Note: Use myXML.getString() or myXML.getNum() to return an attribute's value.

method

getString

name

name of the attribute to be checked.

String

defaultValue

value to return if the attribute doesn't exist.

Number

### return
attribute value as a string.

String

` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Get the first reptile child element. let reptile = myXML.getChild('reptile'); // Get the reptile's content. let content = reptile.getContent(); // Get the reptile's species. let species = reptile.getString('species'); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(14); // Display the species attribute. text(`${content}: ${species}`, 5, 50, 90); describe(`The text "${content}: ${species}" written in black on a gray background.`); } `
` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Get the first reptile child element. let reptile = myXML.getChild('reptile'); // Get the reptile's content. let content = reptile.getContent(); // Get the reptile's color. let attribute = reptile.getString('color', 'green'); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(14); fill(attribute); // Display the element's content. text(content, 50, 50); describe(`The text "${content}" written in green on a gray background.`); } `

p5.XML

IO

Input

Sets an attribute to a given value.
The first parameter, `name`, is a string with the name of the attribute being set.
The second parameter, `value`, is the attribute's new value. For example, calling `myXML.setAttribute('id', 123)` sets the `id` attribute to the value 123.

method

setAttribute

name

name of the attribute to be set.

String

value

attribute's new value.

Number|String|Boolean

` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Get the first reptile child element. let reptile = myXML.getChild('reptile'); // Set the reptile's color. reptile.setAttribute('color', 'green'); // Get the reptile's content. let content = reptile.getContent(); // Get the reptile's color. let attribute = reptile.getString('color'); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(14); // Display the element's content. text(`${content} is ${attribute}`, 5, 50, 90); describe( `The text "${content} is ${attribute}" written in green on a gray background.` ); } `

p5.XML

IO

Input

Returns the element's content as a `String`.
The parameter, `defaultValue`, is optional. If a string is passed, as in `myXML.getContent('???')`, it will be returned if the element has no content.

method

getContent

defaultValue

value to return if the element has no content.

String

### return
element's content as a string.

String

` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Get the first reptile child element. let reptile = myXML.getChild('reptile'); // Get the reptile's content. let content = reptile.getContent(); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(14); // Display the element's content. text(content, 5, 50, 90); describe(`The text "${content}" written in green on a gray background.`); } `
` function setup() { createCanvas(100, 100); background(200); // Create a p5.XML object. let blankSpace = new p5.XML(); // Get the element's content and use a default value. let content = blankSpace.getContent('Your name'); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(14); // Display the element's content. text(content, 5, 50, 90); describe(`The text "${content}" written in green on a gray background.`); } `

p5.XML

IO

Input

Sets the element's content.
An element's content is the text between its tags. For example, the element `<language>JavaScript</language>` has the content `JavaScript`.
The parameter, `content`, is a string with the element's new content.

method

setContent

content

new content for the element.

String

` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Get the first reptile child element. let reptile = myXML.getChild('reptile'); // Get the reptile's original content. let oldContent = reptile.getContent(); // Set the reptile's content. reptile.setContent('Loggerhead'); // Get the reptile's new content. let newContent = reptile.getContent(); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(14); // Display the element's old and new content. text(`${oldContent}: ${newContent}`, 5, 50, 90); describe( `The text "${oldContent}: ${newContent}" written in green on a gray background.` ); } `

p5.XML

IO

Input

Returns the element as a `String`.
`myXML.serialize()` is useful for sending the element over the network or saving it to a file.

method

serialize

### return
element as a string.

String

` let myXML; // Load the XML and create a p5.XML object. function preload() { myXML = loadXML('assets/animals.xml'); } function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(12); // Display instructions. text('Double-click to save', 5, 50, 90); describe('The text "Double-click to save" written in black on a gray background.'); } // Save the file when the user double-clicks. function doubleClicked() { // Create a p5.PrintWriter object. // Use the file format .xml. let myWriter = createWriter('animals', 'xml'); // Serialize the XML data to a string. let data = myXML.serialize(); // Write the data to the print stream. myWriter.write(data); // Save the file and close the print stream. myWriter.close(); } `

p5.XML

IO

Input

Calculates the absolute value of a number.
A number's absolute value is its distance from zero on the number line. -5 and 5 are both five units away from zero, so calling `abs(-5)` and `abs(5)` both return 5. The absolute value of a number is always positive.

method

abs

n

number to compute.

Number

### return
absolute value of given number.

Number

` function setup() { createCanvas(100, 100); describe('A gray square with a vertical black line that divides it in half. A white rectangle gets taller when the user moves the mouse away from the line.'); } function draw() { background(200); // Divide the canvas. line(50, 0, 50, 100); // Calculate the mouse's distance from the middle. let h = abs(mouseX - 50); // Draw a rectangle based on the mouse's distance // from the middle. rect(0, 100 - h, 100, h); } `

p5

Math

Calculation

Calculates the closest integer value that is greater than or equal to a number.
For example, calling `ceil(9.03)` and `ceil(9.97)` both return the value 10.

method

ceil

n

number to round up.

Number

### return
rounded up number.

Integer

` function setup() { createCanvas(100, 100); background(200); // Use RGB color with values from 0 to 1. colorMode(RGB, 1); noStroke(); // Draw the left rectangle. let r = 0.3; fill(r, 0, 0); rect(0, 0, 50, 100); // Round r up to 1. r = ceil(r); // Draw the right rectangle. fill(r, 0, 0); rect(50, 0, 50, 100); describe('Two rectangles. The one on the left is dark red and the one on the right is bright red.'); } `

p5

Math

Calculation

Constrains a number between a minimum and maximum value.

method

constrain

n

number to constrain.

Number

low

minimum limit.

Number

high

maximum limit.

Number

### return
constrained number.

Number

` function setup() { createCanvas(100, 100); describe('A black dot drawn on a gray square follows the mouse from left to right. Its movement is constrained to the middle third of the square.'); } function draw() { background(200); let x = constrain(mouseX, 33, 67); let y = 50; strokeWeight(5); point(x, y); } `
` function setup() { createCanvas(100, 100); describe('Two vertical lines. Two circles move horizontally with the mouse. One circle stops at the vertical lines.'); } function draw() { background(200); // Set boundaries and draw them. let leftWall = 25; let rightWall = 75; line(leftWall, 0, leftWall, 100); line(rightWall, 0, rightWall, 100); // Draw a circle that follows the mouse freely. fill(255); circle(mouseX, 33, 9); // Draw a circle that's constrained. let xc = constrain(mouseX, leftWall, rightWall); fill(0); circle(xc, 67, 9); } `

p5

Math

Calculation

Calculates the distance between two points.
The version of `dist()` with four parameters calculates distance in two dimensions.
The version of `dist()` with six parameters calculates distance in three dimensions.
Use p5.Vector.dist() to calculate the distance between two p5.Vector objects.

method

dist

### return
distance between the two points.

Number

` function setup() { createCanvas(100, 100); background(200); // Set the coordinates. let x1 = 10; let y1 = 50; let x2 = 90; let y2 = 50; // Draw the points and a line connecting them. line(x1, y1, x2, y2); strokeWeight(5); point(x1, y1); point(x2, y2); // Calculate the distance. let d = dist(x1, y1, x2, y2); // Style the text. textAlign(CENTER); textSize(16); // Display the distance. text(d, 43, 40); describe('Two dots connected by a horizontal line. The number 80 is written above the center of the line.'); } `

p5

Math

Calculation

x1

x-coordinate of the first point.

Number

y1

y-coordinate of the first point.

Number

x2

x-coordinate of the second point.

Number

y2

y-coordinate of the second point.

Number

##### return
distance between the two points.

Number

x1



Number

y1



Number

z1

z-coordinate of the first point.

Number

x2



Number

y2



Number

z2

z-coordinate of the second point.

Number

##### return
distance between the two points.

Number

Calculates the value of Euler's number e (2.71828...) raised to the power of a number.

method

exp

n

exponent to raise.

Number

### return
e^n

Number

` function setup() { createCanvas(100, 100); background(200); // Top-left. let d = exp(1); circle(10, 10, d); // Left-center. d = exp(2); circle(20, 20, d); // Right-center. d = exp(3); circle(40, 40, d); // Bottom-right. d = exp(4); circle(80, 80, d); describe('A series of circles that grow exponentially from top left to bottom right.'); } `
` function setup() { createCanvas(100, 100); background(200); describe('A series of black dots that grow exponentially from left to right.'); } function draw() { // Invert the y-axis. scale(1, -1); translate(0, -100); // Calculate the coordinates. let x = frameCount; let y = 0.005 * exp(x * 0.1); // Draw a point. point(x, y); } `

p5

Math

Calculation

Calculates the closest integer value that is less than or equal to the value of a number.

method

floor

n

number to round down.

Number

### return
rounded down number.

Integer

` function setup() { createCanvas(100, 100); // Use RGB color with values from 0 to 1. colorMode(RGB, 1); noStroke(); // Draw the left rectangle. let r = 0.8; fill(r, 0, 0); rect(0, 0, 50, 100); // Round r down to 0. r = floor(r); // Draw the right rectangle. fill(r, 0, 0); rect(50, 0, 50, 100); describe('Two rectangles. The one on the left is bright red and the one on the right is black.'); } `

p5

Math

Calculation

Calculates a number between two numbers at a specific increment.
The `amt` parameter is the amount to interpolate between the two numbers. 0.0 is equal to the first number, 0.1 is very near the first number, 0.5 is half-way in between, and 1.0 is equal to the second number. The `lerp()` function is convenient for creating motion along a straight path and for drawing dotted lines.
If the value of `amt` is less than 0 or more than 1, `lerp()` will return a number outside of the original interval. For example, calling `lerp(0, 10, 1.5)` will return 15.

method

lerp

start

first value.

Number

stop

second value.

Number

amt

number.

Number

### return
lerped value.

Number

` function setup() { createCanvas(100, 100); background(200); // Declare variables for coordinates. 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); strokeWeight(5); // Draw the original points in black. stroke(0); point(a, 50); point(b, 50); // Draw the lerped points in gray. stroke(100); point(c, 50); point(d, 50); point(e, 50); describe('Five points in a horizontal line. The outer points are black and the inner points are gray.'); } `
` let x = 50; let y = 50; let targetX = 50; let targetY = 50; function setup() { createCanvas(100, 100); background(200); describe('A white circle at the center of a gray canvas. The circle moves to where the user clicks, then moves smoothly back to the center.'); } function draw() { background(220); // Move x and y toward the target. x = lerp(x, targetX, 0.05); y = lerp(y, targetY, 0.05); // Draw the circle. circle(x, y, 20); } // Set x and y when the user clicks the mouse. function mouseClicked() { x = mouseX; y = mouseY; } `

p5

Math

Calculation

Calculates the natural logarithm (the base-e logarithm) of a number.
`log()` expects the `n` parameter to be a value greater than 0 because the natural logarithm is defined that way.

method

log

n

number greater than 0.

Number

### return
natural logarithm of n.

Number

` function setup() { createCanvas(100, 100); background(200); // Top-left. let d = log(50); circle(33, 33, d); // Bottom-right. d = log(500000000); circle(67, 67, d); describe('Two white circles. The circle at the top-left is small. The circle at the bottom-right is about five times larger.'); } `
` function setup() { createCanvas(100, 100); background(200); describe('A series of black dots that get higher slowly from left to right.'); } function draw() { // Invert the y-axis. scale(1, -1); translate(0, -100); // Calculate coordinates. let x = frameCount; let y = 15 * log(x); // Draw a point. point(x, y); } `

p5

Math

Calculation

Calculates the magnitude, or length, of a vector.
A vector can be thought of in different ways. In one view, a vector is a point in space. The vector's components, `x` and `y`, are the point's coordinates `(x, y)`. A vector's magnitude is the distance from the origin `(0, 0)` to `(x, y)`. `mag(x, y)` is a shortcut for calling `dist(0, 0, x, y)`.
A vector can also be thought of as an arrow pointing in space. This view is helpful for programming motion. See p5.Vector for more details.
Use p5.Vector.mag() to calculate the magnitude of a p5.Vector object.

method

mag

x

first component.

Number

y

second component.

Number

### return
magnitude of vector.

Number

` function setup() { createCanvas(100, 100); background(200); // Set the vector's components. let x = 30; let y = 40; // Calculate the magnitude. let m = mag(x, y); // Style the text. textSize(16); // Display the vector and its magnitude. line(0, 0, x, y); text(m, x, y); describe('A diagonal line is drawn from the top left of the canvas. The number 50 is written at the end of the line.'); } `

p5

Math

Calculation

Re-maps a number from one range to another.
For example, calling `map(2, 0, 10, 0, 100)` returns 20. The first three arguments set the original value to 2 and the original range from 0 to 10. The last two arguments set the target range from 0 to 100. 20's position in the target range [0, 100] is proportional to 2's position in the original range [0, 10].
The sixth parameter, `withinBounds`, is optional. By default, `map()` can return values outside of the target range. For example, `map(11, 0, 10, 0, 100)` returns 110. Passing `true` as the sixth parameter constrains the remapped value to the target range. For example, `map(11, 0, 10, 0, 100, true)` returns 100.

method

map

value

the value to be remapped.

Number

start1

lower bound of the value's current range.

Number

stop1

upper bound of the value's current range.

Number

start2

lower bound of the value's target range.

Number

stop2

upper bound of the value's target range.

Number

withinBounds

constrain the value to the newly mapped range.

Boolean

### return
remapped number.

Number

` function setup() { createCanvas(100, 100); describe('Two horizontal lines. The top line grows horizontally as the mouse moves to the right. The bottom line also grows horizontally but is scaled to stay on the left half of the canvas.'); } function draw() { background(200); // Draw the top line. line(0, 25, mouseX, 25); // Remap mouseX from [0, 100] to [0, 50]. let x = map(mouseX, 0, 100, 0, 50); // Draw the bottom line. line(0, 75, x, 75); } `
` function setup() { createCanvas(100, 100); describe('A circle changes color from black to white as the mouse moves from left to right.'); } function draw() { background(200); // Remap mouseX from [0, 100] to [0, 255] let c = map(mouseX, 0, 100, 0, 255); // Style the circle. fill(c); // Draw the circle. circle(50, 50, 20); } `

p5

Math

Calculation

Returns the largest value in a sequence of numbers.
The version of `max()` with one parameter interprets it as an array of numbers and returns the largest number.
The version of `max()` with two or more parameters interprets them as individual numbers and returns the largest number.

method

max

### return
maximum number.

Number

` function setup() { createCanvas(100, 100); background(200); // Calculate the maximum of 10, 5, and 20. let m = max(10, 5, 20); // Style the text. textAlign(CENTER); textSize(16); // Display the max. text(m, 50, 50); describe('The number 20 written in the middle of a gray square.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create an array of numbers. let numbers = [10, 5, 20]; // Calculate the maximum of the array. let m = max(numbers); // Style the text. textAlign(CENTER); textSize(16); // Display the max. text(m, 50, 50); describe('The number 20 written in the middle of a gray square.'); } `

p5

Math

Calculation

n0

first number to compare.

Number

n1

second number to compare.

Number

##### return
maximum number.

Number

nums

numbers to compare.

Number[]

##### return


Number

Returns the smallest value in a sequence of numbers.
The version of `min()` with one parameter interprets it as an array of numbers and returns the smallest number.
The version of `min()` with two or more parameters interprets them as individual numbers and returns the smallest number.

method

min

### return
minimum number.

Number

` function setup() { createCanvas(100, 100); background(200); // Calculate the minimum of 10, 5, and 20. let m = min(10, 5, 20); // Style the text. textAlign(CENTER); textSize(16); // Display the min. text(m, 50, 50); describe('The number 5 written in the middle of a gray square.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create an array of numbers. let numbers = [10, 5, 20]; // Calculate the minimum of the array. let m = min(numbers); // Style the text. textAlign(CENTER); textSize(16); // Display the min. text(m, 50, 50); describe('The number 5 written in the middle of a gray square.'); } `

p5

Math

Calculation

n0

first number to compare.

Number

n1

second number to compare.

Number

##### return
minimum number.

Number

nums

numbers to compare.

Number[]

##### return


Number

Maps a number from one range to a value between 0 and 1.
For example, `norm(2, 0, 10)` returns 0.2. 2's position in the original range [0, 10] is proportional to 0.2's position in the range [0, 1]. This is the same as calling `map(2, 0, 10, 0, 1)`.
Numbers outside of the original range are not constrained between 0 and 1. Out-of-range values are often intentional and useful.

method

norm

value

incoming value to be normalized.

Number

start

lower bound of the value's current range.

Number

stop

upper bound of the value's current range.

Number

### return
normalized number.

Number

` function setup() { createCanvas(100, 100); // Use RGB color with values from 0 to 1. colorMode(RGB, 1); describe('A square changes color from black to red as the mouse moves from left to right.'); } function draw() { // Calculate the redValue. let redValue = norm(mouseX, 0, 100); // Paint the background. background(redValue, 0, 0); } `

p5

Math

Calculation

Calculates exponential expressions such as 23.
For example, `pow(2, 3)` evaluates the expression 2 × 2 × 2. `pow(2, -3)` evaluates 1 ÷ (2 × 2 × 2).

method

pow

n

base of the exponential expression.

Number

e

power by which to raise the base.

Number

### return
n^e.

Number

` function setup() { createCanvas(100, 100); background(200); // Set the base of the exponent. let base = 3; // Top-left. let d = pow(base, 1); circle(10, 10, d); // Left-center. d = pow(base, 2); circle(20, 20, d); // Right-center. d = pow(base, 3); circle(40, 40, d); // Bottom-right. d = pow(base, 4); circle(80, 80, d); describe('A series of circles that grow exponentially from top left to bottom right.'); } `

p5

Math

Calculation

Calculates the integer closest to a number.
For example, `round(133.8)` returns the value 134.
The second parameter, `decimals`, is optional. It sets the number of decimal places to use when rounding. For example, `round(12.34, 1)` returns 12.3. `decimals` is 0 by default.

method

round

n

number to round.

Number

decimals

number of decimal places to round to, default is 0.

Number

### return
rounded number.

Integer

` function setup() { createCanvas(100, 100); background(200); // Round a number. let x = round(4.2); // Style the text. textAlign(CENTER); textSize(16); // Display the rounded number. text(x, 50, 50); describe('The number 4 written in middle of the canvas.'); } `
` function setup() { createCanvas(100, 100); background(200); // Round a number to 2 decimal places. let x = round(12.782383, 2); // Style the text. textAlign(CENTER); textSize(16); // Display the rounded number. text(x, 50, 50); describe('The number 12.78 written in middle of canvas.'); } `

p5

Math

Calculation

Calculates the square of a number.
Squaring a number means multiplying the number by itself. For example, `sq(3)` evaluates 3 × 3 which is 9. `sq(-3)` evaluates -3 × -3 which is also 9. Multiplying two negative numbers produces a positive number. The value returned by `sq()` is always positive.

method

sq

n

number to square.

Number

### return
squared number.

Number

` function setup() { createCanvas(100, 100); background(200); // Top-left. let d = sq(3); circle(33, 33, d); // Bottom-right. d = sq(6); circle(67, 67, d); describe('Two white circles. The circle at the top-left is small. The circle at the bottom-right is four times larger.'); } `
` function setup() { createCanvas(100, 100); background(200); describe('A series of black dots that get higher quickly from left to right.'); } function draw() { // Invert the y-axis. scale(1, -1); translate(0, -100); // Calculate the coordinates. let x = frameCount; let y = 0.01 * sq(x); // Draw the point. point(x, y); } `

p5

Math

Calculation

Calculates the square root of a number.
A number's square root can be multiplied by itself to produce the original number. For example, `sqrt(9)` returns 3 because 3 × 3 = 9. `sqrt()` always returns a positive value. `sqrt()` doesn't work with negative arguments such as `sqrt(-9)`.

method

sqrt

n

non-negative number to square root.

Number

### return
square root of number.

Number

` function setup() { createCanvas(100, 100); background(200); // Top-left. let d = sqrt(16); circle(33, 33, d); // Bottom-right. d = sqrt(1600); circle(67, 67, d); describe('Two white circles. The circle at the top-left is small. The circle at the bottom-right is ten times larger.'); } `
` function setup() { createCanvas(100, 100); background(200); describe('A series of black dots that get higher slowly from left to right.'); } function draw() { // Invert the y-axis. scale(1, -1); translate(0, -100); // Calculate the coordinates. let x = frameCount; let y = 5 * sqrt(x); // Draw the point. point(x, y); } `

p5

Math

Calculation

Calculates the fractional part of a number.
A number's fractional part includes its decimal values. For example, `fract(12.34)` returns 0.34.

method

fract

n

number whose fractional part will be found.

Number

### return
fractional part of n.

Number

` function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(CENTER); textSize(16); // Original number. let n = 56.78; text(n, 50, 33); // Fractional part. let f = fract(n); text(f, 50, 67); describe('The number 56.78 written above the number 0.78.'); } `

p5

Math

Calculation

Creates a new p5.Vector object.
A vector can be thought of in different ways. In one view, a vector is like an arrow pointing in space. Vectors have both magnitude (length) and direction. This view is helpful for programming motion.
A vector's components determine its magnitude and direction. For example, calling `createVector(3, 4)` creates a new p5.Vector object with an x-component of 3 and a y-component of 4. From the origin, this vector's tip is 3 units to the right and 4 units down.
p5.Vector objects are often used to program motion because they simplify the math. For example, a moving ball has a position and a velocity. Position describes where the ball is in space. The ball's position vector extends from the origin to the ball's center. Velocity describes the ball's speed and the direction it's moving. If the ball is moving straight up, its velocity vector points straight up. Adding the ball's velocity vector to its position vector moves it, as in `pos.add(vel)`. Vector math relies on methods inside the p5.Vector class.

method

createVector

x

x component of the vector.

Number

y

y component of the vector.

Number

z

z component of the vector.

Number

### return
new p5.Vector object.

p5.Vector

` function setup() { createCanvas(100, 100); background(200); // Create p5.Vector objects. let p1 = createVector(25, 25); let p2 = createVector(50, 50); let p3 = createVector(75, 75); // Draw the dots. strokeWeight(5); point(p1); point(p2); point(p3); describe('Three black dots form a diagonal line from top left to bottom right.'); } `
` let pos; let vel; function setup() { createCanvas(100, 100); // Create p5.Vector objects. pos = createVector(50, 100); vel = createVector(0, -1); describe('A black dot moves from bottom to top on a gray square. The dot reappears at the bottom when it reaches the top.'); } function draw() { background(200); // Add velocity to position. pos.add(vel); // If the dot reaches the top of the canvas, // restart from the bottom. if (pos.y < 0) { pos.y = 100; } // Draw the dot. strokeWeight(5); point(pos); } `

p5

Math

Vector

Returns random numbers that can be tuned to feel organic.
Values returned by random() and randomGaussian() can change by large amounts between function calls. By contrast, values returned by `noise()` can be made "smooth". Calls to `noise()` with similar inputs will produce similar outputs. `noise()` is used to create textures, motion, shapes, terrains, and so on. Ken Perlin invented `noise()` while animating the original Tron film in the 1980s.
`noise()` always returns values between 0 and 1. It returns the same value for a given input while a sketch is running. `noise()` produces different results each time a sketch runs. The noiseSeed() function can be used to generate the same sequence of Perlin noise values each time a sketch runs.
The character of the noise can be adjusted in two ways. The first way is to scale the inputs. `noise()` interprets inputs as coordinates. The sequence of noise values will be smoother when the input coordinates are closer. The second way is to use the noiseDetail() function.
The version of `noise()` with one parameter computes noise values in one dimension. This dimension can be thought of as space, as in `noise(x)`, or time, as in `noise(t)`.
The version of `noise()` with two parameters computes noise values in two dimensions. These dimensions can be thought of as space, as in `noise(x, y)`, or space and time, as in `noise(x, t)`.
The version of `noise()` with three parameters computes noise values in three dimensions. These dimensions can be thought of as space, as in `noise(x, y, z)`, or space and time, as in `noise(x, y, t)`.

method

noise

x

x-coordinate in noise space.

Number

y

y-coordinate in noise space.

Number

z

z-coordinate in noise space.

Number

### return
Perlin noise value at specified coordinates.

Number

` function setup() { createCanvas(100, 100); describe('A black dot moves randomly on a gray square.'); } function draw() { background(200); // Calculate the coordinates. let x = 100 * noise(0.005 * frameCount); let y = 100 * noise(0.005 * frameCount + 10000); // Draw the point. strokeWeight(5); point(x, y); } `
` function setup() { createCanvas(100, 100); describe('A black dot moves randomly on a gray square.'); } function draw() { background(200); // Set the noise level and scale. let noiseLevel = 100; let noiseScale = 0.005; // Scale the input coordinate. let nt = noiseScale * frameCount; // Compute the noise values. let x = noiseLevel * noise(nt); let y = noiseLevel * noise(nt + 10000); // Draw the point. strokeWeight(5); point(x, y); } `
` function setup() { createCanvas(100, 100); describe('A hilly terrain drawn in gray against a black sky.'); } function draw() { // Set the noise level and scale. let noiseLevel = 100; let noiseScale = 0.02; // Scale the input coordinate. let x = frameCount; let nx = noiseScale * x; // Compute the noise value. let y = noiseLevel * noise(nx); // Draw the line. line(x, 0, x, y); } `
` function setup() { createCanvas(100, 100); describe('A calm sea drawn in gray against a black sky.'); } function draw() { background(200); // Set the noise level and scale. let noiseLevel = 100; let noiseScale = 0.002; // Iterate from left to right. for (let x = 0; x < width; x += 1) { // Scale the input coordinates. let nx = noiseScale * x; let nt = noiseScale * frameCount; // Compute the noise value. let y = noiseLevel * noise(nx, nt); // Draw the line. line(x, 0, x, y); } } `
` function setup() { createCanvas(100, 100); background(200); // Set the noise level and scale. let noiseLevel = 255; let noiseScale = 0.01; // Iterate from top to bottom. for (let y = 0; y < height; y += 1) { // Iterate from left to right. for (let x = 0; x < width; x += 1) { // Scale the input coordinates. let nx = noiseScale * x; let ny = noiseScale * y; // Compute the noise value. let c = noiseLevel * noise(nx, ny); // Draw the point. stroke(c); point(x, y); } } describe('A gray cloudy pattern.'); } `
` function setup() { createCanvas(100, 100); describe('A gray cloudy pattern that changes.'); } function draw() { // Set the noise level and scale. let noiseLevel = 255; let noiseScale = 0.009; // Iterate from top to bottom. for (let y = 0; y < height; y += 1) { // Iterate from left to right. for (let x = 0; x < width; x += 1) { // Scale the input coordinates. let nx = noiseScale * x; let ny = noiseScale * y; let nt = noiseScale * frameCount; // Compute the noise value. let c = noiseLevel * noise(nx, ny, nt); // Draw the point. stroke(c); point(x, y); } } } `

p5

Math

Noise

Adjusts the character of the noise produced by the noise() function.
Perlin noise values are created by adding layers of noise together. The noise layers, called octaves, are similar to harmonics in music. Lower octaves contribute more to the output signal. They define the overall intensity of the noise. Higher octaves create finer-grained details.
By default, noise values are created by combining four octaves. Each higher octave contributes half as much (50% less) compared to its predecessor. `noiseDetail()` changes the number of octaves and the falloff amount. For example, calling `noiseDetail(6, 0.25)` ensures that noise() will use six octaves. Each higher octave will contribute 25% as much (75% less) compared to its predecessor. Falloff values between 0 and 1 are valid. However, falloff values greater than 0.5 might result in noise values greater than 1.

method

noiseDetail

lod

number of octaves to be used by the noise.

Number

falloff

falloff factor for each octave.

Number

` function setup() { createCanvas(100, 100); // Set the noise level and scale. let noiseLevel = 255; let noiseScale = 0.02; // Iterate from top to bottom. for (let y = 0; y < height; y += 1) { // Iterate from left to right. for (let x = 0; x < width / 2; x += 1) { // Scale the input coordinates. let nx = noiseScale * x; let ny = noiseScale * y; // Compute the noise value with six octaves // and a low falloff factor. noiseDetail(6, 0.25); let c = noiseLevel * noise(nx, ny); // Draw the left side. stroke(c); point(x, y); // Compute the noise value with four octaves // and a high falloff factor. noiseDetail(4, 0.5); c = noiseLevel * noise(nx, ny); // Draw the right side. stroke(c); point(x + 50, y); } } describe('Two gray cloudy patterns. The pattern on the right is cloudier than the pattern on the left.'); } `

p5

Math

Noise

Sets the seed value for the noise() function.
By default, noise() produces different results each time a sketch is run. Calling `noiseSeed()` with a constant argument, such as `noiseSeed(99)`, makes noise() produce the same results each time a sketch is run.

method

noiseSeed

seed

seed value.

Number

` function setup() { createCanvas(100, 100); background(200); // Set the noise seed for consistent results. noiseSeed(99); describe('A black rectangle that grows randomly, first to the right and then to the left.'); } function draw() { // Set the noise level and scale. let noiseLevel = 100; let noiseScale = 0.005; // Scale the input coordinate. let nt = noiseScale * frameCount; // Compute the noise value. let x = noiseLevel * noise(nt); // Draw the line. line(x, 0, x, height); } `

p5

Math

Noise

The x component of the vector

{Number}

property

x

p5.Vector

Math

Vector

The y component of the vector

{Number}

property

y

p5.Vector

Math

Vector

The z component of the vector

{Number}

property

z

p5.Vector

Math

Vector

Returns a string representation of a vector.
Calling `toString()` is useful for printing vectors to the console while debugging.

method

toString

### return
string representation of the vector.

String

` function setup() { let v = createVector(20, 30); // Prints 'p5.Vector Object : [20, 30, 0]'. print(v.toString()); } `

p5.Vector

Math

Vector

Sets the vector's `x`, `y`, and `z` components.
`set()` can use separate numbers, as in `v.set(1, 2, 3)`, a p5.Vector object, as in `v.set(v2)`, or an array of numbers, as in `v.set([1, 2, 3])`.
If a value isn't provided for a component, it will be set to 0. For example, `v.set(4, 5)` sets `v.x` to 4, `v.y` to 5, and `v.z` to 0. Calling `set()` with no arguments, as in `v.set()`, sets all the vector's components to 0.

method

set

` function setup() { createCanvas(100, 100); background(200); // Style the points. strokeWeight(5); // Top left. let pos = createVector(25, 25); point(pos); // Top right. // set() with numbers. pos.set(75, 25); point(pos); // Bottom right. // set() with a p5.Vector. let p2 = createVector(75, 75); pos.set(p2); point(pos); // Bottom left. // set() with an array. let arr = [25, 75]; pos.set(arr); point(pos); describe('Four black dots arranged in a square on a gray background.'); } `

p5.Vector

Math

Vector

x

x component of the vector.

Number

y

y component of the vector.

Number

z

z component of the vector.

Number

value

vector to set.

p5.Vector|Number[]

Returns a copy of the p5.Vector object.

method

copy

### return
copy of the p5.Vector object.

p5.Vector

` function setup() { createCanvas(100 ,100); background(200); // Create a p5.Vector object. let pos = createVector(50, 50); // Make a copy. let pc = pos.copy(); // Draw the point. strokeWeight(5); point(pc); describe('A black point drawn in the middle of a gray square.'); } `

p5.Vector

Math

Vector

##### return
copy of the p5.Vector object.

p5.Vector

v

the p5.Vector to create a copy of

p5.Vector

##### return
the copy of the p5.Vector object

p5.Vector

Adds to a vector's `x`, `y`, and `z` components.
`add()` can use separate numbers, as in `v.add(1, 2, 3)`, another p5.Vector object, as in `v.add(v2)`, or an array of numbers, as in `v.add([1, 2, 3])`.
If a value isn't provided for a component, it won't change. For example, `v.add(4, 5)` adds 4 to `v.x`, 5 to `v.y`, and 0 to `v.z`. Calling `add()` with no arguments, as in `v.add()`, has no effect.
The static version of `add()`, as in `p5.Vector.add(v2, v1)`, returns a new p5.Vector object and doesn't change the originals.

method

add

` function setup() { createCanvas(100, 100); background(200); // Style the points. strokeWeight(5); // Top left. let pos = createVector(25, 25); point(pos); // Top right. // Add numbers. pos.add(50, 0); point(pos); // Bottom right. // Add a p5.Vector. let p2 = createVector(0, 50); pos.add(p2); point(pos); // Bottom left. // Add an array. let arr = [-50, 0]; pos.add(arr); point(pos); describe('Four black dots arranged in a square on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Top left. let p1 = createVector(25, 25); // Center. let p2 = createVector(50, 50); // Bottom right. // Add p1 and p2. let p3 = p5.Vector.add(p1, p2); // Draw the points. strokeWeight(5); point(p1); point(p2); point(p3); describe('Three black dots in a diagonal line from top left to bottom right.'); } `
` function setup() { createCanvas(100, 100); describe('Three arrows drawn on a gray square. A red arrow extends from the top left corner to the center. A blue arrow extends from the tip of the red arrow. A purple arrow extends from the origin to the tip of the blue arrow.'); } function draw() { background(200); let origin = createVector(0, 0); // Draw the red arrow. let v1 = createVector(50, 50); drawArrow(origin, v1, 'red'); // Draw the blue arrow. let v2 = createVector(-30, 20); drawArrow(v1, v2, 'blue'); // Purple arrow. let v3 = p5.Vector.add(v1, v2); drawArrow(origin, v3, 'purple'); } // Draws an arrow between two vectors. function drawArrow(base, vec, myColor) { push(); stroke(myColor); strokeWeight(3); fill(myColor); translate(base.x, base.y); line(0, 0, vec.x, vec.y); rotate(vec.heading()); let arrowSize = 7; translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); pop(); } `

p5.Vector

Math

Vector

x

x component of the vector to be added.

Number

y

y component of the vector to be added.

Number

z

z component of the vector to be added.

Number

value

The vector to add

p5.Vector|Number[]

v1

A p5.Vector to add

p5.Vector

v2

A p5.Vector to add

p5.Vector

target

vector to receive the result.

p5.Vector

##### return
resulting p5.Vector.

p5.Vector

Performs modulo (remainder) division with a vector's `x`, `y`, and `z` components.
`rem()` can use separate numbers, as in `v.rem(1, 2, 3)`, another p5.Vector object, as in `v.rem(v2)`, or an array of numbers, as in `v.rem([1, 2, 3])`.
If only one value is provided, as in `v.rem(2)`, then all the components will be set to their values modulo 2. If two values are provided, as in `v.rem(2, 3)`, then `v.z` won't change. Calling `rem()` with no arguments, as in `v.rem()`, has no effect.
The static version of `rem()`, as in `p5.Vector.rem(v2, v1)`, returns a new p5.Vector object and doesn't change the originals.

method

rem

` function setup() { // Create a p5.Vector object. let v = createVector(3, 4, 5); // Divide numbers. v.rem(2); // Prints 'p5.Vector Object : [1, 0, 1]'. print(v.toString()); } `
` function setup() { // Create a p5.Vector object. let v = createVector(3, 4, 5); // Divide numbers. v.rem(2, 3); // Prints 'p5.Vector Object : [1, 1, 5]'. print(v.toString()); } `
` function setup() { // Create a p5.Vector object. let v = createVector(3, 4, 5); // Divide numbers. v.rem(2, 3, 4); // Prints 'p5.Vector Object : [1, 1, 1]'. print(v.toString()); } `
` function setup() { // Create p5.Vector objects. let v1 = createVector(3, 4, 5); let v2 = createVector(2, 3, 4); // Divide a p5.Vector. v1.rem(v2); // Prints 'p5.Vector Object : [1, 1, 1]'. print(v1.toString()); } `
` function setup() { // Create a p5.Vector object. let v = createVector(3, 4, 5); // Divide an array. let arr = [2, 3, 4]; v.rem(arr); // Prints 'p5.Vector Object : [1, 1, 1]'. print(v.toString()); } `
` function setup() { // Create p5.Vector objects. let v1 = createVector(3, 4, 5); let v2 = createVector(2, 3, 4); // Divide without modifying the original vectors. let v3 = p5.Vector.rem(v1, v2); // Prints 'p5.Vector Object : [1, 1, 1]'. print(v3.toString()); } `

p5.Vector

Math

Vector

x

x component of divisor vector.

Number

y

y component of divisor vector.

Number

z

z component of divisor vector.

Number

value

divisor vector.

p5.Vector | Number[]

v1

The dividend p5.Vector

p5.Vector

v2

The divisor p5.Vector

p5.Vector

v1



p5.Vector

v2



p5.Vector

##### return
The resulting p5.Vector

p5.Vector

Subtracts from a vector's `x`, `y`, and `z` components.
`sub()` can use separate numbers, as in `v.sub(1, 2, 3)`, another p5.Vector object, as in `v.sub(v2)`, or an array of numbers, as in `v.sub([1, 2, 3])`.
If a value isn't provided for a component, it won't change. For example, `v.sub(4, 5)` subtracts 4 from `v.x`, 5 from `v.y`, and 0 from `v.z`. Calling `sub()` with no arguments, as in `v.sub()`, has no effect.
The static version of `sub()`, as in `p5.Vector.sub(v2, v1)`, returns a new p5.Vector object and doesn't change the originals.

method

sub

` function setup() { createCanvas(100, 100); background(200); // Style the points. strokeWeight(5); // Bottom right. let pos = createVector(75, 75); point(pos); // Top right. // Subtract numbers. pos.sub(0, 50); point(pos); // Top left. // Subtract a p5.Vector. let p2 = createVector(50, 0); pos.sub(p2); point(pos); // Bottom left. // Subtract an array. let arr = [0, -50]; pos.sub(arr); point(pos); describe('Four black dots arranged in a square on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create p5.Vector objects. let p1 = createVector(75, 75); let p2 = createVector(50, 50); // Subtract without modifying the original vectors. let p3 = p5.Vector.sub(p1, p2); // Draw the points. strokeWeight(5); point(p1); point(p2); point(p3); describe('Three black dots in a diagonal line from top left to bottom right.'); } `
` function setup() { createCanvas(100, 100); describe('Three arrows drawn on a gray square. A red and a blue arrow extend from the top left. A purple arrow extends from the tip of the red arrow to the tip of the blue arrow.'); } function draw() { background(200); let origin = createVector(0, 0); // Draw the red arrow. let v1 = createVector(50, 50); drawArrow(origin, v1, 'red'); // Draw the blue arrow. let v2 = createVector(20, 70); drawArrow(origin, v2, 'blue'); // Purple arrow. let v3 = p5.Vector.sub(v2, v1); drawArrow(v1, v3, 'purple'); } // Draws an arrow between two vectors. function drawArrow(base, vec, myColor) { push(); stroke(myColor); strokeWeight(3); fill(myColor); translate(base.x, base.y); line(0, 0, vec.x, vec.y); rotate(vec.heading()); let arrowSize = 7; translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); pop(); } `

p5.Vector

Math

Vector

x

x component of the vector to subtract.

Number

y

y component of the vector to subtract.

Number

z

z component of the vector to subtract.

Number

value

the vector to subtract

p5.Vector|Number[]

v1

A p5.Vector to subtract from

p5.Vector

v2

A p5.Vector to subtract

p5.Vector

target

vector to receive the result.

p5.Vector

##### return
The resulting p5.Vector

p5.Vector

Multiplies a vector's `x`, `y`, and `z` components.
`mult()` can use separate numbers, as in `v.mult(1, 2, 3)`, another p5.Vector object, as in `v.mult(v2)`, or an array of numbers, as in `v.mult([1, 2, 3])`.
If only one value is provided, as in `v.mult(2)`, then all the components will be multiplied by 2. If a value isn't provided for a component, it won't change. For example, `v.mult(4, 5)` multiplies `v.x` by 4, `v.y` by 5, and `v.z` by 1. Calling `mult()` with no arguments, as in `v.mult()`, has no effect.
The static version of `mult()`, as in `p5.Vector.mult(v, 2)`, returns a new p5.Vector object and doesn't change the originals.

method

mult

` function setup() { createCanvas(100, 100); background(200); // Style the points. strokeWeight(5); // Top-left. let p = createVector(25, 25); point(p); // Center. // Multiply all components by 2. p.mult(2); point(p); describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the center.'); } `
` function setup() { strokeWeight(5); // Top-left. let p = createVector(25, 25); point(p); // Bottom-right. // Multiply p.x * 2 and p.y * 3 p.mult(2, 3); point(p); describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); } `
` function setup() { createCanvas(100, 100); background(200); // Style the points. strokeWeight(5); // Top-left. let p = createVector(25, 25); point(p); // Bottom-right. // Multiply p.x * 2 and p.y * 3 let arr = [2, 3]; p.mult(arr); point(p); describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); } `
` function setup() { createCanvas(100, 100); background(200); // Style the points. strokeWeight(5); // Top-left. let p = createVector(25, 25); point(p); // Bottom-right. // Multiply p.x * p2.x and p.y * p2.y let p2 = createVector(2, 3); p.mult(p2); point(p); describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); } `
` function setup() { createCanvas(100, 100); background(200); // Style the points. strokeWeight(5); // Top-left. let p = createVector(25, 25); point(p); // Bottom-right. // Create a new p5.Vector with // p3.x = p.x * p2.x // p3.y = p.y * p2.y let p2 = createVector(2, 3); let p3 = p5.Vector.mult(p, p2); point(p3); describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); } `
` function setup() { createCanvas(100, 100); describe('Two arrows extending from the top left corner. The blue arrow is twice the length of the red arrow.'); } function draw() { background(200); let origin = createVector(0, 0); // Draw the red arrow. let v1 = createVector(25, 25); drawArrow(origin, v1, 'red'); // Draw the blue arrow. let v2 = p5.Vector.mult(v1, 2); drawArrow(origin, v2, 'blue'); } // Draws an arrow between two vectors. function drawArrow(base, vec, myColor) { push(); stroke(myColor); strokeWeight(3); fill(myColor); translate(base.x, base.y); line(0, 0, vec.x, vec.y); rotate(vec.heading()); let arrowSize = 7; translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); pop(); } `

p5.Vector

Math

Vector

n

The number to multiply with the vector

Number

x

number to multiply with the x component of the vector.

Number

y

number to multiply with the y component of the vector.

Number

z

number to multiply with the z component of the vector.

Number

arr

array to multiply with the components of the vector.

Number[]

v

vector to multiply with the components of the original vector.

p5.Vector

x



Number

y



Number

z



Number

##### return
resulting new p5.Vector.

p5.Vector

v



p5.Vector

n



Number

target

vector to receive the result.

p5.Vector

##### return
The resulting new p5.Vector

p5.Vector

v0



p5.Vector

v1



p5.Vector

target



p5.Vector

##### return
The resulting new p5.Vector

p5.Vector

v0



p5.Vector

arr



Number[]

target



p5.Vector

##### return
The resulting new p5.Vector

p5.Vector

Divides a vector's `x`, `y`, and `z` components.
`div()` can use separate numbers, as in `v.div(1, 2, 3)`, another p5.Vector object, as in `v.div(v2)`, or an array of numbers, as in `v.div([1, 2, 3])`.
If only one value is provided, as in `v.div(2)`, then all the components will be divided by 2. If a value isn't provided for a component, it won't change. For example, `v.div(4, 5)` divides `v.x` by, `v.y` by 5, and `v.z` by 1. Calling `div()` with no arguments, as in `v.div()`, has no effect.
The static version of `div()`, as in `p5.Vector.div(v, 2)`, returns a new p5.Vector object and doesn't change the originals.

method

div

` function setup() { createCanvas(100, 100); background(200); // Style the points. strokeWeight(5); // Center. let p = createVector(50, 50); point(p); // Top-left. // Divide p.x / 2 and p.y / 2 p.div(2); point(p); describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the center.'); } `
` function setup() { createCanvas(100, 100); background(200); // Style the points. strokeWeight(5); // Bottom-right. let p = createVector(50, 75); point(p); // Top-left. // Divide p.x / 2 and p.y / 3 p.div(2, 3); point(p); describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); } `
` function setup() { createCanvas(100, 100); background(200); // Style the points. strokeWeight(5); // Bottom-right. let p = createVector(50, 75); point(p); // Top-left. // Divide p.x / 2 and p.y / 3 let arr = [2, 3]; p.div(arr); point(p); describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); } `
` function setup() { createCanvas(100, 100); background(200); // Style the points. strokeWeight(5); // Bottom-right. let p = createVector(50, 75); point(p); // Top-left. // Divide p.x / 2 and p.y / 3 let p2 = createVector(2, 3); p.div(p2); point(p); describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); } `
` function setup() { createCanvas(100, 100); background(200); // Style the points. strokeWeight(5); // Bottom-right. let p = createVector(50, 75); point(p); // Top-left. // Create a new p5.Vector with // p3.x = p.x / p2.x // p3.y = p.y / p2.y let p2 = createVector(2, 3); let p3 = p5.Vector.div(p, p2); point(p3); describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); } `
` function draw() { background(200); let origin = createVector(0, 0); // Draw the red arrow. let v1 = createVector(50, 50); drawArrow(origin, v1, 'red'); // Draw the blue arrow. let v2 = p5.Vector.div(v1, 2); drawArrow(origin, v2, 'blue'); describe('Two arrows extending from the top left corner. The blue arrow is half the length of the red arrow.'); } // Draws an arrow between two vectors. function drawArrow(base, vec, myColor) { push(); stroke(myColor); strokeWeight(3); fill(myColor); translate(base.x, base.y); line(0, 0, vec.x, vec.y); rotate(vec.heading()); let arrowSize = 7; translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); pop(); } `

p5.Vector

Math

Vector

n

The number to divide the vector by

Number

x

number to divide with the x component of the vector.

Number

y

number to divide with the y component of the vector.

Number

z

number to divide with the z component of the vector.

Number

arr

array to divide the components of the vector by.

Number[]

v

vector to divide the components of the original vector by.

p5.Vector

x



Number

y



Number

z



Number

##### return
The resulting new p5.Vector

p5.Vector

v



p5.Vector

n



Number

target

The vector to receive the result

p5.Vector

##### return
The resulting new p5.Vector

p5.Vector

v0



p5.Vector

v1



p5.Vector

target



p5.Vector

##### return
The resulting new p5.Vector

p5.Vector

v0



p5.Vector

arr



Number[]

target



p5.Vector

##### return
The resulting new p5.Vector

p5.Vector

Calculates the magnitude (length) of the vector.
Use mag() to calculate the magnitude of a 2D vector using components as in `mag(x, y)`.

method

mag

### return
magnitude of the vector.

Number

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Vector object. let p = createVector(30, 40); // Draw a line from the origin. line(0, 0, p.x, p.y); // Style the text. textAlign(CENTER); textSize(16); // Display the vector's magnitude. let m = p.mag(); text(m, p.x, p.y); describe('A diagonal black line extends from the top left corner of a gray square. The number 50 is written at the end of the line.'); } `

p5.Vector

Math

Vector

##### return
magnitude of the vector.

Number

vecT

The vector to return the magnitude of

p5.Vector

##### return
The magnitude of vecT

Number

Calculates the magnitude (length) of the vector squared.

method

magSq

### return
squared magnitude of the vector.

Number

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Vector object. let p = createVector(30, 40); // Draw a line from the origin. line(0, 0, p.x, p.y); // Style the text. textAlign(CENTER); textSize(16); // Display the vector's magnitude squared. let m = p.magSq(); text(m, p.x, p.y); describe('A diagonal black line extends from the top left corner of a gray square. The number 2500 is written at the end of the line.'); } `

p5.Vector

Math

Vector

##### return
squared magnitude of the vector.

Number

vecT

the vector to return the squared magnitude of

p5.Vector

##### return
the squared magnitude of vecT

Number

Calculates the dot product of two vectors.
The dot product is a number that describes the overlap between two vectors. Visually, the dot product can be thought of as the "shadow" one vector casts on another. The dot product's magnitude is largest when two vectors point in the same or opposite directions. Its magnitude is 0 when two vectors form a right angle.
The version of `dot()` with one parameter interprets it as another p5.Vector object.
The version of `dot()` with multiple parameters interprets them as the `x`, `y`, and `z` components of another vector.
The static version of `dot()`, as in `p5.Vector.dot(v1, v2)`, is the same as calling `v1.dot(v2)`.

method

dot

### return
dot product.

Number

` function setup() { // Create p5.Vector objects. let v1 = createVector(3, 4); let v2 = createVector(3, 0); // Calculate the dot product. let dp = v1.dot(v2); // Prints "9" to the console. print(dp); } `
` function setup() { // Create p5.Vector objects. let v1 = createVector(1, 0); let v2 = createVector(0, 1); // Calculate the dot product. let dp = p5.Vector.dot(v1, v2); // Prints "0" to the console. print(dp); } `
` function setup() { createCanvas(100, 100); describe('Two arrows drawn on a gray square. A black arrow points to the right and a red arrow follows the mouse. The text "v1 • v2 = something" changes as the mouse moves.'); } function draw() { background(200); // Center. let v0 = createVector(50, 50); // Draw the black arrow. let v1 = createVector(30, 0); drawArrow(v0, v1, 'black'); // Draw the red arrow. let v2 = createVector(mouseX - 50, mouseY - 50); drawArrow(v0, v2, 'red'); // Display the dot product. let dp = v2.dot(v1); text(`v2 • v1 = ${dp}`, 10, 20); } // Draws an arrow between two vectors. function drawArrow(base, vec, myColor) { push(); stroke(myColor); strokeWeight(3); fill(myColor); translate(base.x, base.y); line(0, 0, vec.x, vec.y); rotate(vec.heading()); let arrowSize = 7; translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); pop(); } `

p5.Vector

Math

Vector

x

x component of the vector.

Number

y

y component of the vector.

Number

z

z component of the vector.

Number

##### return
dot product.

Number

v

p5.Vector to be dotted.

p5.Vector

##### return


Number

v1

first p5.Vector.

p5.Vector

v2

second p5.Vector.

p5.Vector

##### return
dot product.

Number

Calculates the cross product of two vectors.
The cross product is a vector that points straight out of the plane created by two vectors. The cross product's magnitude is the area of the parallelogram formed by the original two vectors.
The static version of `cross()`, as in `p5.Vector.cross(v1, v2)`, is the same as calling `v1.cross(v2)`.

method

cross

### return
cross product as a p5.Vector.

p5.Vector

` function setup() { // Create p5.Vector objects. let v1 = createVector(1, 0); let v2 = createVector(3, 4); // Calculate the cross product. let cp = v1.cross(v2); // Prints "p5.Vector Object : [0, 0, 4]" to the console. print(cp.toString()); } `
` function setup() { // Create p5.Vector objects. let v1 = createVector(1, 0); let v2 = createVector(3, 4); // Calculate the cross product. let cp = p5.Vector.cross(v1, v2); // Prints "p5.Vector Object : [0, 0, 4]" to the console. print(cp.toString()); } `

p5.Vector

Math

Vector

v

p5.Vector to be crossed.

p5.Vector

##### return
cross product as a p5.Vector.

p5.Vector

v1

first p5.Vector.

p5.Vector

v2

second p5.Vector.

p5.Vector

##### return
cross product.

Number

Calculates the distance between two points represented by vectors.
A point's coordinates can be represented by the components of a vector that extends from the origin to the point.
The static version of `dist()`, as in `p5.Vector.dist(v1, v2)`, is the same as calling `v1.dist(v2)`.
Use dist() to calculate the distance between points using coordinates as in `dist(x1, y1, x2, y2)`.

method

dist

### return
distance.

Number

` function setup() { createCanvas(100, 100); background(200); // Create p5.Vector objects. let v1 = createVector(1, 0); let v2 = createVector(0, 1); // Calculate the distance between them. let d = v1.dist(v2); // Prints "1.414..." to the console. print(d); } `
` function setup() { createCanvas(100, 100); background(200); // Create p5.Vector objects. let v1 = createVector(1, 0); let v2 = createVector(0, 1); // Calculate the distance between them. let d = p5.Vector.dist(v1, v2); // Prints "1.414..." to the console. print(d); } `
` function setup() { createCanvas(100, 100); describe('Three arrows drawn on a gray square. A red and a blue arrow extend from the top left. A purple arrow extends from the tip of the red arrow to the tip of the blue arrow. The number 36 is written in black near the purple arrow.'); } function draw() { background(200); let origin = createVector(0, 0); // Draw the red arrow. let v1 = createVector(50, 50); drawArrow(origin, v1, 'red'); // Draw the blue arrow. let v2 = createVector(20, 70); drawArrow(origin, v2, 'blue'); // Purple arrow. let v3 = p5.Vector.sub(v2, v1); drawArrow(v1, v3, 'purple'); // Style the text. textAlign(CENTER); // Display the magnitude. The same as floor(v3.mag()); let m = floor(p5.Vector.dist(v1, v2)); text(m, 50, 75); } // Draws an arrow between two vectors. function drawArrow(base, vec, myColor) { push(); stroke(myColor); strokeWeight(3); fill(myColor); translate(base.x, base.y); line(0, 0, vec.x, vec.y); rotate(vec.heading()); let arrowSize = 7; translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); pop(); } `

p5.Vector

Math

Vector

v

x, y, and z coordinates of a p5.Vector.

p5.Vector

##### return
distance.

Number

v1

The first p5.Vector

p5.Vector

v2

The second p5.Vector

p5.Vector

##### return
The distance

Number

Scales the components of a p5.Vector object so that its magnitude is 1.
The static version of `normalize()`, as in `p5.Vector.normalize(v)`, returns a new p5.Vector object and doesn't change the original.

method

normalize

### return
normalized p5.Vector.

p5.Vector

` function setup() { createCanvas(100, 100); background(200); // Create a p5.Vector. let v = createVector(10, 20, 2); // Normalize. v.normalize(); // Prints "p5.Vector Object : [0.445..., 0.890..., 0.089...]" to the console. print(v.toString()); } `
` function setup() { createCanvas(100, 100); background(200); // Create a p5.Vector. let v0 = createVector(10, 20, 2); // Create a normalized copy. let v1 = p5.Vector.normalize(v0); // Prints "p5.Vector Object : [10, 20, 2]" to the console. print(v0.toString()); // Prints "p5.Vector Object : [0.445..., 0.890..., 0.089...]" to the console. print(v1.toString()); } `
` function setup() { createCanvas(100, 100); describe("A red and blue arrow extend from the center of a circle. Both arrows follow the mouse, but the blue arrow's length is fixed to the circle's radius."); } function draw() { background(240); // Vector to the center. let v0 = createVector(50, 50); // Vector from the center to the mouse. let v1 = createVector(mouseX - 50, mouseY - 50); // Circle's radius. let r = 25; // Draw the red arrow. drawArrow(v0, v1, 'red'); // Draw the blue arrow. v1.normalize(); drawArrow(v0, v1.mult(r), 'blue'); // Draw the circle. noFill(); circle(50, 50, r * 2); } // Draws an arrow between two vectors. function drawArrow(base, vec, myColor) { push(); stroke(myColor); strokeWeight(3); fill(myColor); translate(base.x, base.y); line(0, 0, vec.x, vec.y); rotate(vec.heading()); let arrowSize = 7; translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); pop(); } `

p5.Vector

Math

Vector

##### return
normalized p5.Vector.

p5.Vector

v

The vector to normalize

p5.Vector

target

The vector to receive the result

p5.Vector

##### return
The vector v, normalized to a length of 1

p5.Vector

Limits a vector's magnitude to a maximum value.
The static version of `limit()`, as in `p5.Vector.limit(v, 5)`, returns a new p5.Vector object and doesn't change the original.

method

limit

` function setup() { // Create a p5.Vector object. let v = createVector(10, 20, 2); // Limit its magnitude. v.limit(5); // Prints "p5.Vector Object : [2.227..., 4.454..., 0.445...]" to the console. print(v.toString()); } `
` function setup() { // Create a p5.Vector object. let v0 = createVector(10, 20, 2); // Create a copy an limit its magintude. let v1 = p5.Vector.limit(v0, 5); // Prints "p5.Vector Object : [2.227..., 4.454..., 0.445...]" to the console. print(v1.toString()); } `
` function setup() { createCanvas(100, 100); describe("A red and blue arrow extend from the center of a circle. Both arrows follow the mouse, but the blue arrow never crosses the circle's edge."); } function draw() { background(240); // Vector to the center. let v0 = createVector(50, 50); // Vector from the center to the mouse. let v1 = createVector(mouseX - 50, mouseY - 50); // Circle's radius. let r = 25; // Draw the red arrow. drawArrow(v0, v1, 'red'); // Draw the blue arrow. drawArrow(v0, v1.limit(r), 'blue'); // Draw the circle. noFill(); circle(50, 50, r * 2); } // Draws an arrow between two vectors. function drawArrow(base, vec, myColor) { push(); stroke(myColor); strokeWeight(3); fill(myColor); translate(base.x, base.y); line(0, 0, vec.x, vec.y); rotate(vec.heading()); let arrowSize = 7; translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); pop(); } `

p5.Vector

Math

Vector

max

maximum magnitude for the vector.

Number

v

the vector to limit

p5.Vector

max



Number

target

the vector to receive the result (Optional)

p5.Vector

##### return
v with a magnitude limited to max

p5.Vector

Sets a vector's magnitude to a given value.
The static version of `setMag()`, as in `p5.Vector.setMag(v, 10)`, returns a new p5.Vector object and doesn't change the original.

method

setMag

` function setup() { // Create a p5.Vector object. let v = createVector(3, 4, 0); // Prints "5" to the console. print(v.mag()); // Set its magnitude to 10. v.setMag(10); // Prints "p5.Vector Object : [6, 8, 0]" to the console. print(v.toString()); } `
` function setup() { // Create a p5.Vector object. let v0 = createVector(3, 4, 0); // Create a copy with a magnitude of 10. let v1 = p5.Vector.setMag(v0, 10); // Prints "5" to the console. print(v0.mag()); // Prints "p5.Vector Object : [6, 8, 0]" to the console. print(v1.toString()); } `
` function setup() { createCanvas(100, 100); describe('Two arrows extend from the top left corner of a square toward its center. The red arrow reaches the center and the blue arrow only extends part of the way.'); } function draw() { background(240); let origin = createVector(0, 0); let v = createVector(50, 50); // Draw the red arrow. drawArrow(origin, v, 'red'); // Set v's magnitude to 30. v.setMag(30); // Draw the blue arrow. drawArrow(origin, v, 'blue'); } // Draws an arrow between two vectors. function drawArrow(base, vec, myColor) { push(); stroke(myColor); strokeWeight(3); fill(myColor); translate(base.x, base.y); line(0, 0, vec.x, vec.y); rotate(vec.heading()); let arrowSize = 7; translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); pop(); } `

p5.Vector

Math

Vector

len

new length for this vector.

Number

v

the vector to set the magnitude of

p5.Vector

len



Number

target

the vector to receive the result (Optional)

p5.Vector

##### return
v with a magnitude set to len

p5.Vector

Calculates the angle a 2D vector makes with the positive x-axis.
By convention, the positive x-axis has an angle of 0. Angles increase in the clockwise direction.
If the vector was created with createVector(), `heading()` returns angles in the units of the current angleMode().
The static version of `heading()`, as in `p5.Vector.heading(v)`, works the same way.

method

heading

### return
angle of rotation.

Number

` function setup() { // Create a p5.Vector object. let v = createVector(1, 1); // Prints "0.785..." to the console. print(v.heading()); // Use degrees. angleMode(DEGREES); // Prints "45" to the console. print(v.heading()); } `
` function setup() { // Create a p5.Vector object. let v = createVector(1, 1); // Prints "0.785..." to the console. print(p5.Vector.heading(v)); // Use degrees. angleMode(DEGREES); // Prints "45" to the console. print(p5.Vector.heading(v)); } `
` function setup() { createCanvas(100, 100); describe('A black arrow extends from the top left of a square to its center. The text "Radians: 0.79" and "Degrees: 45" is written near the tip of the arrow.'); } function draw() { background(200); let origin = createVector(0, 0); let v = createVector(50, 50); // Draw the black arrow. drawArrow(origin, v, 'black'); // Use radians. angleMode(RADIANS); // Display the heading in radians. let h = round(v.heading(), 2); text(`Radians: ${h}`, 20, 70); // Use degrees. angleMode(DEGREES); // Display the heading in degrees. h = v.heading(); text(`Degrees: ${h}`, 20, 85); } // Draws an arrow between two vectors. function drawArrow(base, vec, myColor) { push(); stroke(myColor); strokeWeight(3); fill(myColor); translate(base.x, base.y); line(0, 0, vec.x, vec.y); rotate(vec.heading()); let arrowSize = 7; translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); pop(); } `

p5.Vector

Math

Vector

##### return
angle of rotation.

Number

v

the vector to find the angle of

p5.Vector

##### return
the angle of rotation

Number

Rotates a 2D vector to a specific angle without changing its magnitude.
By convention, the positive x-axis has an angle of 0. Angles increase in the clockwise direction.
If the vector was created with createVector(), `setHeading()` uses the units of the current angleMode().

method

setHeading

angle

angle of rotation.

Number

` function setup() { // Create a p5.Vector object. let v = createVector(0, 1); // Prints "1.570..." to the console. print(v.heading()); // Point to the left. v.setHeading(PI); // Prints "3.141..." to the console. print(v.heading()); } `
` function setup() { // Use degrees. angleMode(DEGREES); // Create a p5.Vector object. let v = createVector(0, 1); // Prints "90" to the console. print(v.heading()); // Point to the left. v.setHeading(180); // Prints "180" to the console. print(v.heading()); } `
` function setup() { createCanvas(100, 100); describe('Two arrows extend from the center of a gray square. The red arrow points to the right and the blue arrow points down.'); } function draw() { background(200); // Create p5.Vector objects. let v0 = createVector(50, 50); let v1 = createVector(30, 0); // Draw the red arrow. drawArrow(v0, v1, 'red'); // Point down. v1.setHeading(HALF_PI); // Draw the blue arrow. drawArrow(v0, v1, 'blue'); } // Draws an arrow between two vectors. function drawArrow(base, vec, myColor) { push(); stroke(myColor); strokeWeight(3); fill(myColor); translate(base.x, base.y); line(0, 0, vec.x, vec.y); rotate(vec.heading()); let arrowSize = 7; translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); pop(); } `

p5.Vector

Math

Vector

Rotates a 2D vector by an angle without changing its magnitude.
By convention, the positive x-axis has an angle of 0. Angles increase in the clockwise direction.
If the vector was created with createVector(), `rotate()` uses the units of the current angleMode().
The static version of `rotate()`, as in `p5.Vector.rotate(v, PI)`, returns a new p5.Vector object and doesn't change the original.

method

rotate

` function setup() { // Create a p5.Vector object. let v = createVector(1, 0); // Prints "p5.Vector Object : [1, 0, 0]" to the console. print(v.toString()); // Rotate a quarter turn. v.rotate(HALF_PI); // Prints "p5.Vector Object : [0, 1, 0]" to the console. print(v.toString()); } `
` function setup() { // Use degrees. angleMode(DEGREES); // Create a p5.Vector object. let v = createVector(1, 0); // Prints "p5.Vector Object : [1, 0, 0]" to the console. print(v.toString()); // Rotate a quarter turn. v.rotate(90); // Prints "p5.Vector Object : [0, 1, 0]" to the console. print(v.toString()); } `
` function setup() { // Create a p5.Vector object. let v0 = createVector(1, 0); // Create a rotated copy. let v1 = p5.Vector.rotate(v0, HALF_PI); // Prints "p5.Vector Object : [1, 0, 0]" to the console. print(v0.toString()); // Prints "p5.Vector Object : [0, 1, 0]" to the console. print(v1.toString()); } `
` function setup() { // Use degrees. angleMode(DEGREES); // Create a p5.Vector object. let v0 = createVector(1, 0); // Create a rotated copy. let v1 = p5.Vector.rotate(v0, 90); // Prints "p5.Vector Object : [1, 0, 0]" to the console. print(v0.toString()); // Prints "p5.Vector Object : [0, 1, 0]" to the console. print(v1.toString()); } `
` let v0; let v1; function setup() { createCanvas(100, 100); // Create p5.Vector objects. v0 = createVector(50, 50); v1 = createVector(30, 0); describe('A black arrow extends from the center of a gray square. The arrow rotates clockwise.'); } function draw() { background(240); // Rotate v1. v1.rotate(0.01); // Draw the black arrow. drawArrow(v0, v1, 'black'); } // Draws an arrow between two vectors. function drawArrow(base, vec, myColor) { push(); stroke(myColor); strokeWeight(3); fill(myColor); translate(base.x, base.y); line(0, 0, vec.x, vec.y); rotate(vec.heading()); let arrowSize = 7; translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); pop(); } `

p5.Vector

Math

Vector

angle

angle of rotation.

Number

v



p5.Vector

angle



Number

target

The vector to receive the result

p5.Vector

##### return
The resulting new p5.Vector

p5.Vector

Calculates the angle between two vectors.
The angles returned are signed, which means that `v1.angleBetween(v2) === -v2.angleBetween(v1)`.
If the vector was created with createVector(), `angleBetween()` returns angles in the units of the current angleMode().

method

angleBetween

### return
angle between the vectors.

Number

` function setup() { // Create p5.Vector objects. let v0 = createVector(1, 0); let v1 = createVector(0, 1); // Prints "1.570..." to the console. print(v0.angleBetween(v1)); // Prints "-1.570..." to the console. print(v1.angleBetween(v0)); } `
` function setup() { // Use degrees. angleMode(DEGREES); // Create p5.Vector objects. let v0 = createVector(1, 0); let v1 = createVector(0, 1); // Prints "90" to the console. print(v0.angleBetween(v1)); // Prints "-90" to the console. print(v1.angleBetween(v0)); } `
` function setup() { // Create p5.Vector objects. let v0 = createVector(1, 0); let v1 = createVector(0, 1); // Prints "1.570..." to the console. print(p5.Vector.angleBetween(v0, v1)); // Prints "-1.570..." to the console. print(p5.Vector.angleBetween(v1, v0)); } `
` function setup() { // Use degrees. angleMode(DEGREES); // Create p5.Vector objects. let v0 = createVector(1, 0); let v1 = createVector(0, 1); // Prints "90" to the console. print(p5.Vector.angleBetween(v0, v1)); // Prints "-90" to the console. print(p5.Vector.angleBetween(v1, v0)); } `
` function setup() { createCanvas(100, 100); describe('Two arrows extend from the center of a gray square. A red arrow points to the right and a blue arrow points down. The text "Radians: 1.57" and "Degrees: 90" is written above the arrows.'); } function draw() { background(200); // Create p5.Vector objects. let v0 = createVector(50, 50); let v1 = createVector(30, 0); let v2 = createVector(0, 30); // Draw the red arrow. drawArrow(v0, v1, 'red'); // Draw the blue arrow. drawArrow(v0, v2, 'blue'); // Use radians. angleMode(RADIANS); // Display the angle in radians. let angle = round(v1.angleBetween(v2), 2); text(`Radians: ${angle}`, 20, 20); // Use degrees. angleMode(DEGREES); // Display the angle in degrees. angle = round(v1.angleBetween(v2), 2); text(`Degrees: ${angle}`, 20, 35); } // Draws an arrow between two vectors. function drawArrow(base, vec, myColor) { push(); stroke(myColor); strokeWeight(3); fill(myColor); translate(base.x, base.y); line(0, 0, vec.x, vec.y); rotate(vec.heading()); let arrowSize = 7; translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); pop(); } `

p5.Vector

Math

Vector

value

x, y, and z components of a p5.Vector.

p5.Vector

##### return
angle between the vectors.

Number

v1

the first vector.

p5.Vector

v2

the second vector.

p5.Vector

##### return
angle between the two vectors.

Number

Calculates new `x`, `y`, and `z` components that are proportionally the same distance between two vectors.
The `amt` parameter is the amount to interpolate between the old vector and the new vector. 0.0 keeps all components equal to the old vector's, 0.5 is halfway between, and 1.0 sets all components equal to the new vector's.
The static version of `lerp()`, as in `p5.Vector.lerp(v0, v1, 0.5)`, returns a new p5.Vector object and doesn't change the original.

method

lerp

` function setup() { // Create a p5.Vector object. let v0 = createVector(1, 1, 1); let v1 = createVector(3, 3, 3); // Interpolate. v0.lerp(v1, 0.5); // Prints "p5.Vector Object : [2, 2, 2]" to the console. print(v0.toString()); } `
` function setup() { // Create a p5.Vector object. let v = createVector(1, 1, 1); // Interpolate. v.lerp(3, 3, 3, 0.5); // Prints "p5.Vector Object : [2, 2, 2]" to the console. print(v.toString()); } `
` function setup() { // Create p5.Vector objects. let v0 = createVector(1, 1, 1); let v1 = createVector(3, 3, 3); // Interpolate. let v2 = p5.Vector.lerp(v0, v1, 0.5); // Prints "p5.Vector Object : [2, 2, 2]" to the console. print(v2.toString()); } `
` function setup() { createCanvas(100, 100); describe('Three arrows extend from the center of a gray square. A red arrow points to the right, a blue arrow points down, and a purple arrow points to the bottom right.'); } function draw() { background(200); // Create p5.Vector objects. let v0 = createVector(50, 50); let v1 = createVector(30, 0); let v2 = createVector(0, 30); // Interpolate. let v3 = p5.Vector.lerp(v1, v2, 0.5); // Draw the red arrow. drawArrow(v0, v1, 'red'); // Draw the blue arrow. drawArrow(v0, v2, 'blue'); // Draw the purple arrow. drawArrow(v0, v3, 'purple'); } // Draws an arrow between two vectors. function drawArrow(base, vec, myColor) { push(); stroke(myColor); strokeWeight(3); fill(myColor); translate(base.x, base.y); line(0, 0, vec.x, vec.y); rotate(vec.heading()); let arrowSize = 7; translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); pop(); } `

p5.Vector

Math

Vector

x

x component.

Number

y

y component.

Number

z

z component.

Number

amt

amount of interpolation between 0.0 (old vector) and 1.0 (new vector). 0.5 is halfway between.

Number

v

p5.Vector to lerp toward.

p5.Vector

amt



Number

v1



p5.Vector

v2



p5.Vector

amt



Number

target

The vector to receive the result

p5.Vector

##### return
The lerped value

p5.Vector

Calculates a new heading and magnitude that are between two vectors.
The `amt` parameter is the amount to interpolate between the old vector and the new vector. 0.0 keeps the heading and magnitude equal to the old vector's, 0.5 sets them halfway between, and 1.0 sets the heading and magnitude equal to the new vector's.
`slerp()` differs from lerp() because it interpolates magnitude. Calling `v0.slerp(v1, 0.5)` sets `v0`'s magnitude to a value halfway between its original magnitude and `v1`'s. Calling `v0.lerp(v1, 0.5)` makes no such guarantee.
The static version of `slerp()`, as in `p5.Vector.slerp(v0, v1, 0.5)`, returns a new p5.Vector object and doesn't change the original.

method

slerp

### return


p5.Vector

` function setup() { // Create a p5.Vector object. let v0 = createVector(3, 0); // Prints "3" to the console. print(v0.mag()); // Prints "0" to the console. print(v0.heading()); // Create a p5.Vector object. let v1 = createVector(0, 1); // Prints "1" to the console. print(v1.mag()); // Prints "1.570..." to the console. print(v1.heading()); // Interpolate halfway between v0 and v1. v0.slerp(v1, 0.5); // Prints "2" to the console. print(v0.mag()); // Prints "0.785..." to the console. print(v0.heading()); } `
` function setup() { // Create a p5.Vector object. let v0 = createVector(3, 0); // Prints "3" to the console. print(v0.mag()); // Prints "0" to the console. print(v0.heading()); // Create a p5.Vector object. let v1 = createVector(0, 1); // Prints "1" to the console. print(v1.mag()); // Prints "1.570..." to the console. print(v1.heading()); // Create a p5.Vector that's halfway between v0 and v1. let v3 = p5.Vector.slerp(v0, v1, 0.5); // Prints "2" to the console. print(v3.mag()); // Prints "0.785..." to the console. print(v3.heading()); } `
` function setup() { createCanvas(100, 100); describe('Three arrows extend from the center of a gray square. A red arrow points to the right, a blue arrow points to the left, and a purple arrow points down.'); } function draw() { background(200); // Create p5.Vector objects. let v0 = createVector(50, 50); let v1 = createVector(20, 0); let v2 = createVector(-40, 0); // Create a p5.Vector that's halfway between v1 and v2. let v3 = p5.Vector.slerp(v1, v2, 0.5); // Draw the red arrow. drawArrow(v0, v1, 'red'); // Draw the blue arrow. drawArrow(v0, v2, 'blue'); // Draw the purple arrow. drawArrow(v0, v3, 'purple'); } // Draws an arrow between two vectors. function drawArrow(base, vec, myColor) { push(); stroke(myColor); strokeWeight(3); fill(myColor); translate(base.x, base.y); line(0, 0, vec.x, vec.y); rotate(vec.heading()); let arrowSize = 7; translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); pop(); } `

p5.Vector

Math

Vector

v

p5.Vector to slerp toward.

p5.Vector

amt

amount of interpolation between 0.0 (old vector) and 1.0 (new vector). 0.5 is halfway between.

Number

##### return


p5.Vector

v1

old vector.

p5.Vector

v2

new vector.

p5.Vector

amt



Number

target

vector to receive the result.

p5.Vector

##### return
slerped vector between v1 and v2

p5.Vector

Reflects a vector about a line in 2D or a plane in 3D.
The orientation of the line or plane is described by a normal vector that points away from the shape.
The static version of `reflect()`, as in `p5.Vector.reflect(v, n)`, returns a new p5.Vector object and doesn't change the original.

method

reflect

` function setup() { // Create a normal vector. let n = createVector(0, 1); // Create a vector to reflect. let v = createVector(4, 6); // Reflect v about n. v.reflect(n); // Prints "p5.Vector Object : [4, -6, 0]" to the console. print(v.toString()); } `
` function setup() { // Create a normal vector. let n = createVector(0, 1); // Create a vector to reflect. let v0 = createVector(4, 6); // Create a reflected vector. let v1 = p5.Vector.reflect(v0, n); // Prints "p5.Vector Object : [4, -6, 0]" to the console. print(v1.toString()); } `
` function setup() { createCanvas(100, 100); describe('Three arrows extend from the center of a gray square with a vertical line down its middle. A black arrow points to the right, a blue arrow points to the bottom left, and a red arrow points to the bottom right.'); } function draw() { background(200); // Draw a vertical line. line(50, 0, 50, 100); // Create a normal vector. let n = createVector(1, 0); // Center. let v0 = createVector(50, 50); // Create a vector to reflect. let v1 = createVector(30, 40); // Create a reflected vector. let v2 = p5.Vector.reflect(v1, n); // Scale the normal vector for drawing. n.setMag(30); // Draw the black arrow. drawArrow(v0, n, 'black'); // Draw the red arrow. drawArrow(v0, v1, 'red'); // Draw the blue arrow. drawArrow(v0, v2, 'blue'); } // Draws an arrow between two vectors. function drawArrow(base, vec, myColor) { push(); stroke(myColor); strokeWeight(3); fill(myColor); translate(base.x, base.y); line(0, 0, vec.x, vec.y); rotate(vec.heading()); let arrowSize = 7; translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); pop(); } `

p5.Vector

Math

Vector

surfaceNormal

p5.Vector to reflect about.

p5.Vector

incidentVector

vector to be reflected.

p5.Vector

surfaceNormal



p5.Vector

target

vector to receive the result.

p5.Vector

##### return
the reflected vector

p5.Vector

Returns the vector's components as an array of numbers.

method

array

### return
array with the vector's components.

Number[]

` function setup() { // Create a p5.Vector object. let v = createVector(20, 30); // Prints "[20, 30, 0]" to the console. print(v.array()); } `

p5.Vector

Math

Vector

##### return
array with the vector's components.

Number[]

v

the vector to convert to an array

p5.Vector

##### return
an Array with the 3 values

Number[]

Checks whether all the vector's components are equal to another vector's.
`equals()` returns `true` if the vector's components are all the same as another vector's and `false` if not.
The version of `equals()` with one parameter interprets it as another p5.Vector object.
The version of `equals()` with multiple parameters interprets them as the components of another vector. Any missing parameters are assigned the value 0.
The static version of `equals()`, as in `p5.Vector.equals(v0, v1)`, interprets both parameters as p5.Vector objects.

method

equals

### return
whether the vectors are equal.

Boolean

` function setup() { // Create p5.Vector objects. let v0 = createVector(10, 20, 30); let v1 = createVector(10, 20, 30); let v2 = createVector(0, 0, 0); // Prints "true" to the console. print(v0.equals(v1)); // Prints "false" to the console. print(v0.equals(v2)); } `
` function setup() { // Create p5.Vector objects. let v0 = createVector(5, 10, 20); let v1 = createVector(5, 10, 20); let v2 = createVector(13, 10, 19); // Prints "true" to the console. print(v0.equals(v1.x, v1.y, v1.z)); // Prints "false" to the console. print(v0.equals(v2.x, v2.y, v2.z)); } `
` function setup() { // Create p5.Vector objects. let v0 = createVector(10, 20, 30); let v1 = createVector(10, 20, 30); let v2 = createVector(0, 0, 0); // Prints "true" to the console. print(p5.Vector.equals(v0, v1)); // Prints "false" to the console. print(p5.Vector.equals(v0, v2)); } `

p5.Vector

Math

Vector

x

x component of the vector.

Number

y

y component of the vector.

Number

z

z component of the vector.

Number

##### return
whether the vectors are equal.

Boolean

value

vector to compare.

p5.Vector|Array

##### return


Boolean

v1

the first vector to compare

p5.Vector|Array

v2

the second vector to compare

p5.Vector|Array

##### return


Boolean

Creates a new 2D vector from an angle.

method

fromAngle

angle

desired angle, in radians. Unaffected by angleMode().

Number

length

length of the new vector (defaults to 1).

Number

### return
new p5.Vector object.

p5.Vector

` function setup() { // Create a p5.Vector object. let v = p5.Vector.fromAngle(0); // Prints "p5.Vector Object : [1, 0, 0]" to the console. print(v.toString()); } `
` function setup() { // Create a p5.Vector object. let v = p5.Vector.fromAngle(0, 30); // Prints "p5.Vector Object : [30, 0, 0]" to the console. print(v.toString()); } `
` function setup() { createCanvas(100, 100); describe('A black arrow extends from the center of a gray square. It points to the right.'); } function draw() { background(200); // Create a p5.Vector to the center. let v0 = createVector(50, 50); // Create a p5.Vector with an angle 0 and magnitude 30. let v1 = p5.Vector.fromAngle(0, 30); // Draw the black arrow. drawArrow(v0, v1, 'black'); } // Draws an arrow between two vectors. function drawArrow(base, vec, myColor) { push(); stroke(myColor); strokeWeight(3); fill(myColor); translate(base.x, base.y); line(0, 0, vec.x, vec.y); rotate(vec.heading()); let arrowSize = 7; translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); pop(); } `

p5.Vector

Math

Vector

Creates a new 3D vector from a pair of ISO spherical angles.

method

fromAngles

theta

polar angle in radians (zero is up).

Number

phi

azimuthal angle in radians (zero is out of the screen).

Number

length

length of the new vector (defaults to 1).

Number

### return
new p5.Vector object.

p5.Vector

` function setup() { // Create a p5.Vector object. let v = p5.Vector.fromAngles(0, 0); // Prints "p5.Vector Object : [0, -1, 0]" to the console. print(v.toString()); } `
` function setup() { createCanvas(100, 100, WEBGL); describe('A light shines on a pink sphere as it orbits.'); } function draw() { background(0); // Calculate the ISO angles. let theta = frameCount * 0.05; let phi = 0; // Create a p5.Vector object. let v = p5.Vector.fromAngles(theta, phi, 100); // Create a point light using the p5.Vector. let c = color('deeppink'); pointLight(c, v); // Style the sphere. fill(255); noStroke(); // Draw the sphere. sphere(35); } `

p5.Vector

Math

Vector

Creates a new 2D unit vector with a random heading.

method

random2D

### return
new p5.Vector object.

p5.Vector

` function setup() { // Create a p5.Vector object. let v = p5.Vector.random2D(); // Prints "p5.Vector Object : [x, y, 0]" to the console // where x and y are small random numbers. print(v.toString()); } `
` function setup() { createCanvas(100, 100); // Slow the frame rate. frameRate(1); describe('A black arrow in extends from the center of a gray square. It changes direction once per second.'); } function draw() { background(200); // Create a p5.Vector to the center. let v0 = createVector(50, 50); // Create a random p5.Vector. let v1 = p5.Vector.random2D(); // Scale v1 for drawing. v1.mult(30); // Draw the black arrow. drawArrow(v0, v1, 'black'); } // Draws an arrow between two vectors. function drawArrow(base, vec, myColor) { push(); stroke(myColor); strokeWeight(3); fill(myColor); translate(base.x, base.y); line(0, 0, vec.x, vec.y); rotate(vec.heading()); let arrowSize = 7; translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); pop(); } `

p5.Vector

Math

Vector

Creates a new 3D unit vector with a random heading.

method

random3D

### return
new p5.Vector object.

p5.Vector

` function setup() { // Create a p5.Vector object. let v = p5.Vector.random3D(); // Prints "p5.Vector Object : [x, y, z]" to the console // where x, y, and z are small random numbers. print(v.toString()); } `

p5.Vector

Math

Vector

Multiplies a vector by a scalar and returns a new vector.

p5.Vector

Math

Vector

Rotates the vector (only 2D vectors) by the given angle; magnitude remains the same. Returns a new vector.

p5.Vector

Math

Vector

Divides a vector by a scalar and returns a new vector.

p5.Vector

Math

Vector

Calculates the dot product of two vectors.

p5.Vector

Math

Vector

Calculates the cross product of two vectors.

p5.Vector

Math

Vector

Calculates the Euclidean distance between two points (considering a point as a vector object).

p5.Vector

Math

Vector

Linear interpolate a vector to another vector and return the result as a new vector.

p5.Vector

Math

Vector

Performs spherical linear interpolation with the other vector and returns the resulting vector. This works in both 3D and 2D. As for 2D, the result of slerping between 2D vectors is always a 2D vector.

p5.Vector

Math

Vector

Calculates the magnitude (length) of the vector and returns the result as a float (this is simply the equation `sqrt(x*x + y*y + z*z)`.)

p5.Vector

Math

Vector

Calculates the squared magnitude of the vector and returns the result as a float (this is simply the equation (x*x + y*y + z*z).) Faster if the real length is not required in the case of comparing vectors, etc.

p5.Vector

Math

Vector

Normalize the vector to length 1 (make it a unit vector).

p5.Vector

Math

Vector

Limit the magnitude of the vector to the value used for the max parameter.

p5.Vector

Math

Vector

Set the magnitude of the vector to the value used for the len parameter.

p5.Vector

Math

Vector

Calculate the angle of rotation for this vector (only 2D vectors). p5.Vectors created using createVector() will take the current angleMode into consideration, and give the angle in radians or degrees accordingly.

p5.Vector

Math

Vector

Calculates and returns the angle between two vectors. This function will take the angleMode on v1 into consideration, and give the angle in radians or degrees accordingly.

p5.Vector

Math

Vector

Reflect a vector about a normal to a line in 2D, or about a normal to a plane in 3D.

p5.Vector

Math

Vector

Return a representation of this vector as a float array. This is only for temporary use. If used in any other fashion, the contents should be copied by using the p5.Vector.copy() method to copy into your own vector.

p5.Vector

Math

Vector

Equality check against a p5.Vector

p5.Vector

Math

Vector

Replaces the components of a p5.Vector that are very close to zero with zero.
In computers, handling numbers with decimals can give slightly imprecise answers due to the way those numbers are represented. This can make it hard to check if a number is zero, as it may be close but not exactly zero. This method rounds very close numbers to zero to make those checks easier
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON

method

clampToZero

### return
with components very close to zero replaced with zero.

p5.Vector

p5.Vector

Math

Vector

Sets the seed value for the random() and randomGaussian() functions.
By default, random() and randomGaussian() produce different results each time a sketch is run. Calling `randomSeed()` with a constant argument, such as `randomSeed(99)`, makes these functions produce the same results each time a sketch is run.

method

randomSeed

seed

seed value.

Number

` function setup() { createCanvas(100, 100); background(200); // Get random coordinates. let x = random(0, 100); let y = random(0, 100); // Draw the white circle. circle(x, y, 10); // Set a random seed for consistency. randomSeed(99); // Get random coordinates. x = random(0, 100); y = random(0, 100); // Draw the black circle. fill(0); circle(x, y, 10); describe('A white circle appears at a random position. A black circle appears at (27.4, 25.8).'); } `

p5

Math

Random

Returns a random number or a random element from an array.
`random()` follows uniform distribution, which means that all outcomes are equally likely. When `random()` is used to generate numbers, all numbers in the output range are equally likely to be returned. When `random()` is used to select elements from an array, all elements are equally likely to be chosen.
By default, `random()` produces different results each time a sketch runs. The randomSeed() function can be used to generate the same sequence of numbers or choices each time a sketch runs.
The version of `random()` with no parameters returns a random number from 0 up to but not including 1.
The version of `random()` with one parameter works one of two ways. If the argument passed is a number, `random()` returns a random number from 0 up to but not including the number. For example, calling `random(5)` returns values between 0 and 5. If the argument passed is an array, `random()` returns a random element from that array. For example, calling `random(['🦁', '🐯', '🐻'])` returns either a lion, tiger, or bear emoji.
The version of `random()` with two parameters returns a random number from a given range. The arguments passed set the range's lower and upper bounds. For example, calling `random(-5, 10.2)` returns values from -5 up to but not including 10.2.

method

random

### return
random number.

Number

` function setup() { createCanvas(100, 100); background(200); // Get random coordinates between 0 and 100. let x = random(0, 100); let y = random(0, 100); // Draw a point. strokeWeight(5); point(x, y); describe('A black dot appears in a random position on a gray square.'); } `
` function setup() { createCanvas(100, 100); background(200); // Get random coordinates between 0 and 100. let x = random(100); let y = random(100); // Draw the point. strokeWeight(5); point(x, y); describe('A black dot appears in a random position on a gray square.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create an array of emoji strings. let animals = ['🦁', '🐯', '🐻']; // Choose a random element from the array. let choice = random(animals); // Style the text. textAlign(CENTER); textSize(20); // Display the emoji. text(choice, 50, 50); describe('An animal face is displayed at random. Either a lion, tiger, or bear.'); } `
` function setup() { createCanvas(100, 100); // Slow the frame rate. frameRate(5); describe('A black dot moves around randomly on a gray square.'); } function draw() { background(200); // Get random coordinates between 0 and 100. let x = random(100); let y = random(100); // Draw the point. strokeWeight(5); point(x, y); } `
` function setup() { createCanvas(100, 100); // Slow the frame rate. frameRate(5); describe('A black dot moves around randomly in the middle of a gray square.'); } function draw() { background(200); // Get random coordinates between 45 and 55. let x = random(45, 55); let y = random(45, 55); // Draw the point. strokeWeight(5); point(x, y); } `
` let x = 50; let y = 50; function setup() { createCanvas(100, 100); background(200); describe('A black dot moves around randomly leaving a trail.'); } function draw() { // Update x and y randomly. x += random(-1, 1); y += random(-1, 1); // Draw the point. point(x, y); } `

p5

Math

Random

min

lower bound (inclusive).

Number

max

upper bound (exclusive).

Number

##### return
random number.

Number

choices

array to choose from.

Array

##### return
random element from the array.

*

Returns a random number fitting a Gaussian, or normal, distribution.
Normal distributions look like bell curves when plotted. Values from a normal distribution cluster around a central value called the mean. The cluster's standard deviation describes its spread.
By default, `randomGaussian()` produces different results each time a sketch runs. The randomSeed() function can be used to generate the same sequence of numbers each time a sketch runs.
There's no minimum or maximum value that `randomGaussian()` might return. Values far from the mean are very unlikely and values near the mean are very likely.
The version of `randomGaussian()` with no parameters returns values with a mean of 0 and standard deviation of 1.
The version of `randomGaussian()` with one parameter interprets the argument passed as the mean. The standard deviation is 1.
The version of `randomGaussian()` with two parameters interprets the first argument passed as the mean and the second as the standard deviation.

method

randomGaussian

mean

mean.

Number

sd

standard deviation.

Number

### return
random number.

Number

` function setup() { createCanvas(100, 100); background(200); describe('Three horizontal black lines are filled in randomly. The top line spans entire canvas. The middle line is very short. The bottom line spans two-thirds of the canvas.'); } function draw() { // Style the circles. noStroke(); fill(0, 10); // Uniform distribution between 0 and 100. let x = random(100); let y = 25; circle(x, y, 5); // Gaussian distribution with a mean of 50 and sd of 1. x = randomGaussian(50); y = 50; circle(x, y, 5); // Gaussian distribution with a mean of 50 and sd of 10. x = randomGaussian(50, 10); y = 75; circle(x, y, 5); } `

p5

Math

Random

Calculates the arc cosine of a number.
`acos()` is the inverse of cos(). It expects arguments in the range -1 to 1. By default, `acos()` returns values in the range 0 to π (about 3.14). If the angleMode() is `DEGREES`, then values are returned in the range 0 to 180.

method

acos

value

value whose arc cosine is to be returned.

Number

### return
arc cosine of the given value.

Number

` function setup() { createCanvas(100, 100); background(200); // Calculate cos() and acos() values. let a = PI; let c = cos(a); let ac = acos(c); // Display the values. text(`${round(a, 3)}`, 35, 25); text(`${round(c, 3)}`, 35, 50); text(`${round(ac, 3)}`, 35, 75); describe('The numbers 3.142, -1, and 3.142 written on separate rows.'); } `
` function setup() { createCanvas(100, 100); background(200); // Calculate cos() and acos() values. let a = PI + QUARTER_PI; let c = cos(a); let ac = acos(c); // Display the values. text(`${round(a, 3)}`, 35, 25); text(`${round(c, 3)}`, 35, 50); text(`${round(ac, 3)}`, 35, 75); describe('The numbers 3.927, -0.707, and 2.356 written on separate rows.'); } `

p5

Math

Trigonometry

Calculates the arc sine of a number.
`asin()` is the inverse of sin(). It expects input values in the range of -1 to 1. By default, `asin()` returns values in the range -π ÷ 2 (about -1.57) to π ÷ 2 (about 1.57). If the angleMode() is `DEGREES` then values are returned in the range -90 to 90.

method

asin

value

value whose arc sine is to be returned.

Number

### return
arc sine of the given value.

Number

` function setup() { createCanvas(100, 100); background(200); // Calculate sin() and asin() values. let a = PI / 3; let s = sin(a); let as = asin(s); // Display the values. text(`${round(a, 3)}`, 35, 25); text(`${round(s, 3)}`, 35, 50); text(`${round(as, 3)}`, 35, 75); describe('The numbers 1.047, 0.866, and 1.047 written on separate rows.'); } `
` function setup() { createCanvas(100, 100); background(200); // Calculate sin() and asin() values. let a = PI + PI / 3; let s = sin(a); let as = asin(s); // Display the values. text(`${round(a, 3)}`, 35, 25); text(`${round(s, 3)}`, 35, 50); text(`${round(as, 3)}`, 35, 75); describe('The numbers 4.189, -0.866, and -1.047 written on separate rows.'); } `

p5

Math

Trigonometry

Calculates the arc tangent of a number.
`atan()` is the inverse of tan(). It expects input values in the range of -Infinity to Infinity. By default, `atan()` returns values in the range -π ÷ 2 (about -1.57) to π ÷ 2 (about 1.57). If the angleMode() is `DEGREES` then values are returned in the range -90 to 90.

method

atan

value

value whose arc tangent is to be returned.

Number

### return
arc tangent of the given value.

Number

` function setup() { createCanvas(100, 100); background(200); // Calculate tan() and atan() values. let a = PI / 3; let t = tan(a); let at = atan(t); // Display the values. text(`${round(a, 3)}`, 35, 25); text(`${round(t, 3)}`, 35, 50); text(`${round(at, 3)}`, 35, 75); describe('The numbers 1.047, 1.732, and 1.047 written on separate rows.'); } `
` function setup() { createCanvas(100, 100); background(200); // Calculate tan() and atan() values. let a = PI + PI / 3; let t = tan(a); let at = atan(t); // Display the values. text(`${round(a, 3)}`, 35, 25); text(`${round(t, 3)}`, 35, 50); text(`${round(at, 3)}`, 35, 75); describe('The numbers 4.189, 1.732, and 1.047 written on separate rows.'); } `

p5

Math

Trigonometry

Calculates the angle formed by a point, the origin, and the positive x-axis.
`atan2()` is most often used for orienting geometry to the mouse's position, as in `atan2(mouseY, mouseX)`. The first parameter is the point's y-coordinate and the second parameter is its x-coordinate.
By default, `atan2()` returns values in the range -π (about -3.14) to π (3.14). If the angleMode() is `DEGREES`, then values are returned in the range -180 to 180.

method

atan2

y

y-coordinate of the point.

Number

x

x-coordinate of the point.

Number

### return
arc tangent of the given point.

Number

` function setup() { createCanvas(100, 100); describe('A rectangle at the top-left of the canvas rotates with mouse movements.'); } function draw() { background(200); // Calculate the angle between the mouse // and the origin. let a = atan2(mouseY, mouseX); // Rotate. rotate(a); // Draw the shape. rect(0, 0, 60, 10); } `
` function setup() { createCanvas(100, 100); describe('A rectangle at the center of the canvas rotates with mouse movements.'); } function draw() { background(200); // Translate the origin to the center. translate(50, 50); // Get the mouse's coordinates relative to the origin. let x = mouseX - 50; let y = mouseY - 50; // Calculate the angle between the mouse and the origin. let a = atan2(y, x); // Rotate. rotate(a); // Draw the shape. rect(-30, -5, 60, 10); } `

p5

Math

Trigonometry

Calculates the cosine of an angle.
`cos()` is useful for many geometric tasks in creative coding. The values returned oscillate between -1 and 1 as the input angle increases. `cos()` calculates the cosine of an angle, using radians by default, or according to if angleMode() setting (RADIANS or DEGREES).

method

cos

angle

the angle, in radians by default, or according to if angleMode() setting (RADIANS or DEGREES).

Number

### return
cosine of the angle.

Number

` function setup() { createCanvas(100, 100); describe('A white ball on a string oscillates left and right.'); } function draw() { background(200); // Calculate the coordinates. let x = 30 * cos(frameCount * 0.05) + 50; let y = 50; // Draw the oscillator. line(50, y, x, y); circle(x, y, 20); } `
` function setup() { createCanvas(100, 100); background(200); describe('A series of black dots form a wave pattern.'); } function draw() { // Calculate the coordinates. let x = frameCount; let y = 30 * cos(x * 0.1) + 50; // Draw the point. point(x, y); } `
` function setup() { createCanvas(100, 100); background(200); describe('A series of black dots form an infinity symbol.'); } function draw() { // Calculate the coordinates. let x = 30 * cos(frameCount * 0.1) + 50; let y = 10 * sin(frameCount * 0.2) + 50; // Draw the point. point(x, y); } `

p5

Math

Trigonometry

Calculates the sine of an angle.
`sin()` is useful for many geometric tasks in creative coding. The values returned oscillate between -1 and 1 as the input angle increases. `sin()` calculates the sine of an angle, using radians by default, or according to if angleMode() setting (RADIANS or DEGREES).

method

sin

angle

the angle, in radians by default, or according to if angleMode() setting (RADIANS or DEGREES).

Number

### return
sine of the angle.

Number

` function setup() { createCanvas(100, 100); describe('A white ball on a string oscillates up and down.'); } function draw() { background(200); // Calculate the coordinates. let x = 50; let y = 30 * sin(frameCount * 0.05) + 50; // Draw the oscillator. line(50, y, x, y); circle(x, y, 20); } `
` function setup() { createCanvas(100, 100); background(200); describe('A series of black dots form a wave pattern.'); } function draw() { // Calculate the coordinates. let x = frameCount; let y = 30 * sin(x * 0.1) + 50; // Draw the point. point(x, y); } `
` function setup() { createCanvas(100, 100); background(200); describe('A series of black dots form an infinity symbol.'); } function draw() { // Calculate the coordinates. let x = 30 * cos(frameCount * 0.1) + 50; let y = 10 * sin(frameCount * 0.2) + 50; // Draw the point. point(x, y); } `

p5

Math

Trigonometry

Calculates the tangent of an angle.
`tan()` is useful for many geometric tasks in creative coding. The values returned range from -Infinity to Infinity and repeat periodically as the input angle increases. `tan()` calculates the tan of an angle, using radians by default, or according to if angleMode() setting (RADIANS or DEGREES).

method

tan

angle

the angle, in radians by default, or according to if angleMode() setting (RADIANS or DEGREES).

Number

### return
tangent of the angle.

Number

` function setup() { createCanvas(100, 100); background(200); describe('A series of identical curves drawn with black dots. Each curve starts from the top of the canvas, continues down at a slight angle, flattens out at the middle of the canvas, then continues to the bottom.'); } function draw() { // Calculate the coordinates. let x = frameCount; let y = 5 * tan(x * 0.1) + 50; // Draw the point. point(x, y); } `

p5

Math

Trigonometry

Converts an angle measured in radians to its value in degrees.
Degrees and radians are both units for measuring angles. There are 360˚ in one full rotation. A full rotation is 2 × π (about 6.28) radians.
The same angle can be expressed in with either unit. For example, 90° is a quarter of a full rotation. The same angle is 2 × π ÷ 4 (about 1.57) radians.

method

degrees

radians

radians value to convert to degrees.

Number

### return
converted angle.

Number

` function setup() { createCanvas(100, 100); background(200); // Calculate the angle conversion. let rad = QUARTER_PI; let deg = degrees(rad); // Display the conversion. text(`${round(rad, 2)} rad = ${deg}˚`, 10, 50); describe('The text "0.79 rad = 45˚".'); } `

p5

Math

Trigonometry

Converts an angle measured in degrees to its value in radians.
Degrees and radians are both units for measuring angles. There are 360˚ in one full rotation. A full rotation is 2 × π (about 6.28) radians.
The same angle can be expressed in with either unit. For example, 90° is a quarter of a full rotation. The same angle is 2 × π ÷ 4 (about 1.57) radians.

method

radians

degrees

degree value to convert to radians.

Number

### return
converted angle.

Number

` function setup() { createCanvas(100, 100); background(200); // Calculate the angle conversion. let deg = 45; let rad = radians(deg); // Display the angle conversion. text(`${deg}˚ = ${round(rad, 3)} rad`, 10, 50); describe('The text "45˚ = 0.785 rad".'); } `

p5

Math

Trigonometry

Changes the unit system used to measure angles.
Degrees and radians are both units for measuring angles. There are 360˚ in one full rotation. A full rotation is 2 × π (about 6.28) radians.
Functions such as rotate() and sin() expect angles measured radians by default. Calling `angleMode(DEGREES)` switches to degrees. Calling `angleMode(RADIANS)` switches back to radians.
Calling `angleMode()` with no arguments returns current angle mode, which is either `RADIANS` or `DEGREES`.

method

angleMode

` function setup() { createCanvas(100, 100); background(200); // Rotate 1/8 turn. rotate(QUARTER_PI); // Draw a line. line(0, 0, 80, 0); describe('A diagonal line radiating from the top-left corner of a square.'); } `
` function setup() { createCanvas(100, 100); background(200); // Use degrees. angleMode(DEGREES); // Rotate 1/8 turn. rotate(45); // Draw a line. line(0, 0, 80, 0); describe('A diagonal line radiating from the top-left corner of a square.'); } `
` function setup() { createCanvas(100, 100); background(50); // Calculate the angle to rotate. let angle = TWO_PI / 7; // Move the origin to the center. translate(50, 50); // Style the flower. noStroke(); fill(255, 50); // Draw the flower. for (let i = 0; i < 7; i += 1) { ellipse(0, 0, 80, 20); rotate(angle); } describe('A translucent white flower on a dark background.'); } `
` function setup() { createCanvas(100, 100); background(50); // Use degrees. angleMode(DEGREES); // Calculate the angle to rotate. let angle = 360 / 7; // Move the origin to the center. translate(50, 50); // Style the flower. noStroke(); fill(255, 50); // Draw the flower. for (let i = 0; i < 7; i += 1) { ellipse(0, 0, 80, 20); rotate(angle); } describe('A translucent white flower on a dark background.'); } `
` function setup() { createCanvas(100, 100); describe('A white ball on a string oscillates left and right.'); } function draw() { background(200); // Calculate the coordinates. let x = 30 * cos(frameCount * 0.05) + 50; let y = 50; // Draw the oscillator. line(50, y, x, y); circle(x, y, 20); } `
` function setup() { createCanvas(100, 100); // Use degrees. angleMode(DEGREES); describe('A white ball on a string oscillates left and right.'); } function draw() { background(200); // Calculate the coordinates. let x = 30 * cos(frameCount * 2.86) + 50; let y = 50; // Draw the oscillator. line(50, y, x, y); circle(x, y, 20); } `
` function setup() { createCanvas(100, 100); background(200); // Draw the upper line. rotate(PI / 6); line(0, 0, 80, 0); // Use degrees. angleMode(DEGREES); // Draw the lower line. rotate(30); line(0, 0, 80, 0); describe('Two diagonal lines radiating from the top-left corner of a square. The lines are oriented 30 degrees from the edges of the square and 30 degrees apart from each other.'); } `

p5

Math

Trigonometry

mode

either RADIANS or DEGREES.

Constant

##### return
mode either RADIANS or DEGREES

Constant

Sets the way text is aligned when text() is called.
By default, calling `text('hi', 10, 20)` places the bottom-left corner of the text's bounding box at (10, 20).
The first parameter, `horizAlign`, changes the way text() interprets x-coordinates. By default, the x-coordinate sets the left edge of the bounding box. `textAlign()` accepts the following values for `horizAlign`: `LEFT`, `CENTER`, or `RIGHT`.
The second parameter, `vertAlign`, is optional. It changes the way text() interprets y-coordinates. By default, the y-coordinate sets the bottom edge of the bounding box. `textAlign()` accepts the following values for `vertAlign`: `TOP`, `BOTTOM`, `CENTER`, or `BASELINE`.

method

textAlign

` function setup() { createCanvas(100, 100); background(200); // Draw a vertical line. strokeWeight(0.5); line(50, 0, 50, 100); // Top line. textSize(16); textAlign(RIGHT); text('ABCD', 50, 30); // Middle line. textAlign(CENTER); text('EFGH', 50, 50); // Bottom line. textAlign(LEFT); text('IJKL', 50, 70); describe('The letters ABCD displayed at top-left, EFGH at center, and IJKL at bottom-right. A vertical line divides the canvas in half.'); } `
` function setup() { createCanvas(100, 100); background(200); strokeWeight(0.5); // First line. line(0, 12, width, 12); textAlign(CENTER, TOP); text('TOP', 50, 12); // Second line. line(0, 37, width, 37); textAlign(CENTER, CENTER); text('CENTER', 50, 37); // Third line. line(0, 62, width, 62); textAlign(CENTER, BASELINE); text('BASELINE', 50, 62); // Fourth line. line(0, 97, width, 97); textAlign(CENTER, BOTTOM); text('BOTTOM', 50, 97); describe('The words "TOP", "CENTER", "BASELINE", and "BOTTOM" each drawn relative to a horizontal line. Their positions demonstrate different vertical alignments.'); } `

p5

Typography

Attributes

horizAlign

horizontal alignment, either LEFT, CENTER, or RIGHT.

Constant

vertAlign

vertical alignment, either TOP, BOTTOM, CENTER, or BASELINE.

Constant

##### return


Object

Sets the spacing between lines of text when text() is called.
Note: Spacing is measured in pixels.
Calling `textLeading()` without an argument returns the current spacing.

method

textLeading

` function setup() { createCanvas(100, 100); background(200); // " " starts a new line of text. let lines = 'one two'; // Left. text(lines, 10, 25); // Right. textLeading(30); text(lines, 70, 25); describe('The words "one" and "two" written on separate lines twice. The words on the left have less vertical spacing than the words on the right.'); } `

p5

Typography

Attributes

leading

spacing between lines of text in units of pixels.

Number

##### return


Number

Sets the font size when text() is called.
Note: Font size is measured in pixels.
Calling `textSize()` without an argument returns the current size.

method

textSize

` function setup() { createCanvas(100, 100); background(200); // Top. textSize(12); text('Font Size 12', 10, 30); // Middle. textSize(14); text('Font Size 14', 10, 60); // Bottom. textSize(16); text('Font Size 16', 10, 90); describe('The text "Font Size 12" drawn small, "Font Size 14" drawn medium, and "Font Size 16" drawn large.'); } `

p5

Typography

Attributes

size

size of the letters in units of pixels.

Number

##### return


Number

Sets the style for system fonts when text() is called.
The parameter, `style`, can be either `NORMAL`, `ITALIC`, `BOLD`, or `BOLDITALIC`.
`textStyle()` may be overridden by CSS styling. This function doesn't affect fonts loaded with loadFont().

method

textStyle

` function setup() { createCanvas(100, 100); background(200); // Style the text. textSize(12); textAlign(CENTER); // First row. textStyle(NORMAL); text('Normal', 50, 15); // Second row. textStyle(ITALIC); text('Italic', 50, 40); // Third row. textStyle(BOLD); text('Bold', 50, 65); // Fourth row. textStyle(BOLDITALIC); text('Bold Italic', 50, 90); describe('The words "Normal" displayed normally, "Italic" in italic, "Bold" in bold, and "Bold Italic" in bold italics.'); } `

p5

Typography

Attributes

style

styling for text, either NORMAL, ITALIC, BOLD or BOLDITALIC.

Constant

##### return


String

Calculates the maximum width of a string of text drawn when text() is called.

method

textWidth

str

string of text to measure.

String

### return
width measured in units of pixels.

Number

` function setup() { createCanvas(100, 100); background(200); // Style the text. textSize(28); strokeWeight(0.5); // Calculate the text width. let s = 'yoyo'; let w = textWidth(s); // Display the text. text(s, 22, 55); // Underline the text. line(22, 55, 22 + w, 55); describe('The word "yoyo" underlined.'); } `
` function setup() { createCanvas(100, 100); background(200); // Style the text. textSize(28); strokeWeight(0.5); // Calculate the text width. // " " starts a new line. let s = 'yo yo'; let w = textWidth(s); // Display the text. text(s, 22, 55); // Underline the text. line(22, 55, 22 + w, 55); describe('The word "yo" written twice, one copy beneath the other. The words are divided by a horizontal line.'); } `

p5

Typography

Attributes

Calculates the ascent of the current font at its current size.
The ascent represents the distance, in pixels, of the tallest character above the baseline.

method

textAscent

### return
ascent measured in units of pixels.

Number

` let font; function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100); background(200); // Style the text. textFont(font); // Different for each font. let fontScale = 0.8; let baseY = 75; strokeWeight(0.5); // Draw small text. textSize(24); text('dp', 0, baseY); // Draw baseline and ascent. let a = textAscent() * fontScale; line(0, baseY, 23, baseY); line(23, baseY - a, 23, baseY); // Draw large text. textSize(48); text('dp', 45, baseY); // Draw baseline and ascent. a = textAscent() * fontScale; line(45, baseY, 91, baseY); line(91, baseY - a, 91, baseY); describe('The letters "dp" written twice in different sizes. Each version has a horizontal baseline. A vertical line extends upward from each baseline to the top of the "d".'); } `

p5

Typography

Attributes

Calculates the descent of the current font at its current size.
The descent represents the distance, in pixels, of the character with the longest descender below the baseline.

method

textDescent

### return
descent measured in units of pixels.

Number

` let font; function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100); background(200); // Style the font. textFont(font); // Different for each font. let fontScale = 0.9; let baseY = 75; strokeWeight(0.5); // Draw small text. textSize(24); text('dp', 0, baseY); // Draw baseline and descent. let d = textDescent() * fontScale; line(0, baseY, 23, baseY); line(23, baseY, 23, baseY + d); // Draw large text. textSize(48); text('dp', 45, baseY); // Draw baseline and descent. d = textDescent() * fontScale; line(45, baseY, 91, baseY); line(91, baseY, 91, baseY + d); describe('The letters "dp" written twice in different sizes. Each version has a horizontal baseline. A vertical line extends downward from each baseline to the bottom of the "p".'); } `

p5

Typography

Attributes

Helper function to measure ascent and descent.

p5

Typography

Attributes

Sets the style for wrapping text when text() is called.
The parameter, `style`, can be one of the following values:
`WORD` starts new lines of text at spaces. If a string of text doesn't have spaces, it may overflow the text box and the canvas. This is the default style.
`CHAR` starts new lines as needed to stay within the text box.
`textWrap()` only works when the maximum width is set for a text box. For example, calling `text('Have a wonderful day', 0, 10, 100)` sets the maximum width to 100 pixels.
Calling `textWrap()` without an argument returns the current style.

method

textWrap

style

text wrapping style, either WORD or CHAR.

Constant

### return
style

String

` function setup() { createCanvas(100, 100); background(200); // Style the text. textSize(20); textWrap(WORD); // Display the text. text('Have a wonderful day', 0, 10, 100); describe('The text "Have a wonderful day" written across three lines.'); } `
` function setup() { createCanvas(100, 100); background(200); // Style the text. textSize(20); textWrap(CHAR); // Display the text. text('Have a wonderful day', 0, 10, 100); describe('The text "Have a wonderful day" written across two lines.'); } `
` function setup() { createCanvas(100, 100); background(200); // Style the text. textSize(20); textWrap(CHAR); // Display the text. text('祝你有美好的一天', 0, 10, 100); describe('The text "祝你有美好的一天" written across two lines.'); } `

p5

Typography

Attributes

Loads a font and creates a p5.Font object. `loadFont()` can load fonts in either .otf or .ttf format. Loaded fonts can be used to style text on the canvas and in HTML elements.
The first parameter, `path`, is the path to a font file. Paths to local files should be relative. For example, `'assets/inconsolata.otf'`. The Inconsolata font used in the following examples can be downloaded for free here. Paths to remote files should be URLs. For example, `'https://example.com/inconsolata.otf'`. URLs may be blocked due to browser security.
The second parameter, `successCallback`, is optional. If a function is passed, it will be called once the font has loaded. The callback function may use the new p5.Font object if needed.
The third parameter, `failureCallback`, is also optional. If a function is passed, it will be called if the font fails to load. The callback function may use the error Event object if needed.
Fonts can take time to load. Calling `loadFont()` in preload() ensures fonts load before they're used in setup() or draw().

method

loadFont

path

path of the font to be loaded.

String

successCallback

function called with the p5.Font object after it loads.

Function

failureCallback

function called with the error Event object if the font fails to load.

Function

### return
p5.Font object.

p5.Font

` let font; function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { fill('deeppink'); textFont(font); textSize(36); text('p5*js', 10, 50); describe('The text "p5*js" written in pink on a white background.'); } `
` function setup() { loadFont('assets/inconsolata.otf', font => { fill('deeppink'); textFont(font); textSize(36); text('p5*js', 10, 50); describe('The text "p5*js" written in pink on a white background.'); }); } `
` function setup() { loadFont('assets/inconsolata.otf', success, failure); } function success(font) { fill('deeppink'); textFont(font); textSize(36); text('p5*js', 10, 50); describe('The text "p5*js" written in pink on a white background.'); } function failure(event) { console.error('Oops!', event); } `
` function preload() { loadFont('assets/inconsolata.otf'); } function setup() { let p = createP('p5*js'); p.style('color', 'deeppink'); p.style('font-family', 'Inconsolata'); p.style('font-size', '36px'); p.position(10, 50); describe('The text "p5*js" written in pink on a white background.'); } `

p5

Typography

Loading & Displaying

Draws text to the canvas.
The first parameter, `str`, is the text to be drawn. The second and third parameters, `x` and `y`, set the coordinates of the text's bottom-left corner. See textAlign() for other ways to align text.
The fourth and fifth parameters, `maxWidth` and `maxHeight`, are optional. They set the dimensions of the invisible rectangle containing the text. By default, they set its maximum width and height. See rectMode() for other ways to define the rectangular text box. Text will wrap to fit within the text box. Text outside of the box won't be drawn.
Text can be styled a few ways. Call the fill() function to set the text's fill color. Call stroke() and strokeWeight() to set the text's outline. Call textSize() and textFont() to set the text's size and font, respectively.
Note: `WEBGL` mode only supports fonts loaded with loadFont(). Calling stroke() has no effect in `WEBGL` mode.

method

text

str

text to be displayed.

String|Object|Array|Number|Boolean

x

x-coordinate of the text box.

Number

y

y-coordinate of the text box.

Number

maxWidth

maximum width of the text box. See rectMode() for other options.

Number

maxHeight

maximum height of the text box. See rectMode() for other options.

Number

` function setup() { background(200); text('hi', 50, 50); describe('The text "hi" written in black in the middle of a gray square.'); } `
` function setup() { background('skyblue'); textSize(100); text('🌈', 0, 100); describe('A rainbow in a blue sky.'); } `
` function setup() { textSize(32); fill(255); stroke(0); strokeWeight(4); text('hi', 50, 50); describe('The text "hi" written in white with a black outline.'); } `
` function setup() { background('black'); textSize(22); fill('yellow'); text('rainbows', 6, 20); fill('cornflowerblue'); text('rainbows', 6, 45); fill('tomato'); text('rainbows', 6, 70); fill('limegreen'); text('rainbows', 6, 95); describe('The text "rainbows" written on several lines, each in a different color.'); } `
` function setup() { background(200); let s = 'The quick brown fox jumps over the lazy dog.'; text(s, 10, 10, 70, 80); describe('The sample text "The quick brown fox..." written in black across several lines.'); } `
` function setup() { background(200); rectMode(CENTER); let s = 'The quick brown fox jumps over the lazy dog.'; text(s, 50, 50, 70, 80); describe('The sample text "The quick brown fox..." written in black across several lines.'); } `
` let font; function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100, WEBGL); textFont(font); textSize(32); textAlign(CENTER, CENTER); } function draw() { background(0); rotateY(frameCount / 30); text('p5*js', 0, 0); describe('The text "p5*js" written in white and spinning in 3D.'); } `

p5

Typography

Loading & Displaying

Sets the font used by the text() function.
The first parameter, `font`, sets the font. `textFont()` recognizes either a p5.Font object or a string with the name of a system font. For example, `'Courier New'`.
The second parameter, `size`, is optional. It sets the font size in pixels. This has the same effect as calling textSize().
Note: `WEBGL` mode only supports fonts loaded with loadFont().

method

textFont

### return
current font or p5 Object.

Object

` function setup() { background(200); textFont('Courier New'); textSize(24); text('hi', 35, 55); describe('The text "hi" written in a black, monospace font on a gray background.'); } `
` function setup() { background('black'); fill('palegreen'); textFont('Courier New', 10); text('You turn to the left and see a door. Do you enter?', 5, 5, 90, 90); text('>', 5, 70); describe('A text prompt from a game is written in a green, monospace font on a black background.'); } `
` function setup() { background(200); textFont('Verdana'); let currentFont = textFont(); text(currentFont, 25, 50); describe('The text "Verdana" written in a black, sans-serif font on a gray background.'); } `
` let fontRegular; let fontItalic; let fontBold; function preload() { fontRegular = loadFont('assets/Regular.otf'); fontItalic = loadFont('assets/Italic.ttf'); fontBold = loadFont('assets/Bold.ttf'); } function setup() { background(200); textFont(fontRegular); text('I am Normal', 10, 30); textFont(fontItalic); text('I am Italic', 10, 50); textFont(fontBold); text('I am Bold', 10, 70); describe('The statements "I am Normal", "I am Italic", and "I am Bold" written in black on separate lines. The statements have normal, italic, and bold fonts, respectively.'); } `

p5

Typography

Loading & Displaying

##### return
current font or p5 Object.

Object

font

font as a p5.Font object or a string.

Object|String

size

font size in pixels.

Number

The font's underlying opentype.js font object.

property

font

p5.Font

Typography

Loading & Displaying

Returns the bounding box for a string of text written using the font.
The bounding box is the smallest rectangle that can contain a string of text. `font.textBounds()` returns an object with the bounding box's location and size. For example, calling `font.textBounds('p5*js', 5, 20)` returns an object in the format `{ x: 5.7, y: 12.1 , w: 9.9, h: 28.6 }`. The `x` and `y` properties are always the coordinates of the bounding box's top-left corner.
The first parameter, `str`, is a string of text. The second and third parameters, `x` and `y`, are the text's position. By default, they set the coordinates of the bounding box's bottom-left corner. See textAlign() for more ways to align text.
The fourth parameter, `fontSize`, is optional. It sets the font size used to determine the bounding box. By default, `font.textBounds()` will use the current textSize().

method

textBounds

str

string of text.

String

x

x-coordinate of the text.

Number

y

y-coordinate of the text.

Number

fontSize

font size. Defaults to the current textSize().

Number

### return
object describing the bounding box with properties x, y, w, and h.

Object

` let font; function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100); background(200); // Display the bounding box. let bbox = font.textBounds('p5*js', 35, 53); rect(bbox.x, bbox.y, bbox.w, bbox.h); // Style the text. textFont(font); // Display the text. text('p5*js', 35, 53); describe('The text "p5*js" written in black inside a white rectangle.'); } `
` let font; function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100); background(200); // Style the text. textFont(font); textSize(15); textAlign(CENTER, CENTER); // Display the bounding box. let bbox = font.textBounds('p5*js', 50, 50); rect(bbox.x, bbox.y, bbox.w, bbox.h); // Display the text. text('p5*js', 50, 50); describe('The text "p5*js" written in black inside a white rectangle.'); } `
` let font; function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100); background(200); // Display the bounding box. let bbox = font.textBounds('p5*js', 31, 53, 15); rect(bbox.x, bbox.y, bbox.w, bbox.h); // Style the text. textFont(font); textSize(15); // Display the text. text('p5*js', 31, 53); describe('The text "p5*js" written in black inside a white rectangle.'); } `

p5.Font

Typography

Loading & Displaying

Returns an array of points outlining a string of text written using the font.
Each point object in the array has three properties that describe the point's location and orientation, called its path angle. For example, `{ x: 10, y: 20, alpha: 450 }`.
The first parameter, `str`, is a string of text. The second and third parameters, `x` and `y`, are the text's position. By default, they set the coordinates of the bounding box's bottom-left corner. See textAlign() for more ways to align text.
The fourth parameter, `fontSize`, is optional. It sets the text's font size. By default, `font.textToPoints()` will use the current textSize().
The fifth parameter, `options`, is also optional. `font.textToPoints()` expects an object with the following properties:
`sampleFactor` is the ratio of the text's path length to the number of samples. It defaults to 0.1. Higher values produce more points along the path and are more precise.
`simplifyThreshold` removes collinear points if it's set to a number other than 0. The value represents the threshold angle to use when determining whether two edges are collinear.

method

textToPoints

str

string of text.

String

x

x-coordinate of the text.

Number

y

y-coordinate of the text.

Number

fontSize

font size. Defaults to the current textSize().

Number

options

object with sampleFactor and simplifyThreshold properties.

Object

### return
array of point objects, each with x, y, and alpha (path angle) properties.

Array

` let font; function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100); background(200); // Get the point array. let points = font.textToPoints('p5*js', 6, 60, 35, { sampleFactor: 0.5 }); // Draw a dot at each point. for (let p of points) { point(p.x, p.y); } describe('A set of black dots outlining the text "p5*js" on a gray background.'); } `

p5.Font

Typography

Loading & Displaying

Adds a value to the end of an array. Extends the length of the array by one. Maps to Array.push().

method

append

Use array.push(value) instead.

array

Array to append

Array

value

to be added to the Array

Any

### return
the array that was appended to

Array

` function setup() { let myArray = ['Mango', 'Apple', 'Papaya']; print(myArray); // ['Mango', 'Apple', 'Papaya'] append(myArray, 'Peach'); print(myArray); // ['Mango', 'Apple', 'Papaya', 'Peach'] } `

p5

Data

Array Functions

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.

method

arrayCopy

Use arr1.copyWithin(arr2) instead.

` let src = ['A', 'B', 'C']; let dst = [1, 2, 3]; let srcPosition = 1; let dstPosition = 0; let length = 2; print(src); // ['A', 'B', 'C'] print(dst); // [ 1 , 2 , 3 ] arrayCopy(src, srcPosition, dst, dstPosition, length); print(dst); // ['B', 'C', 3] `

p5

Data

Array Functions

src

the source Array

Array

srcPosition

starting position in the source Array

Integer

dst

the destination Array

Array

dstPosition

starting position in the destination Array

Integer

length

number of Array elements to be copied

Integer

src



Array

dst



Array

length



Integer

Concatenates two arrays, maps to Array.concat(). Does not modify the input arrays.

method

concat

Use arr1.concat(arr2) instead.

a

first Array to concatenate

Array

b

second Array to concatenate

Array

### return
concatenated array

Array

` function setup() { let arr1 = ['A', 'B', 'C']; let arr2 = [1, 2, 3]; print(arr1); // ['A','B','C'] print(arr2); // [1,2,3] let arr3 = concat(arr1, arr2); print(arr1); // ['A','B','C'] print(arr2); // [1, 2, 3] print(arr3); // ['A','B','C', 1, 2, 3] } `

p5

Data

Array Functions

Reverses the order of an array, maps to Array.reverse()

method

reverse

Use array.reverse() instead.

list

Array to reverse

Array

### return
the reversed list

Array

` function setup() { let myArray = ['A', 'B', 'C']; print(myArray); // ['A','B','C'] reverse(myArray); print(myArray); // ['C','B','A'] } `

p5

Data

Array Functions

Decreases an array by one element and returns the shortened array, maps to Array.pop().

method

shorten

Use array.pop() instead.

list

Array to shorten

Array

### return
shortened Array

Array

` function setup() { let myArray = ['A', 'B', 'C']; print(myArray); // ['A', 'B', 'C'] let newArray = shorten(myArray); print(myArray); // ['A','B','C'] print(newArray); // ['A','B'] } `

p5

Data

Array Functions

Shuffles the elements of an array.
The first parameter, `array`, is the array to be shuffled. For example, calling `shuffle(myArray)` will shuffle the elements of `myArray`. By default, the original array won’t be modified. Instead, a copy will be created, shuffled, and returned.
The second parameter, `modify`, is optional. If `true` is passed, as in `shuffle(myArray, true)`, then the array will be shuffled in place without making a copy.

method

shuffle

array

array to shuffle.

Array

bool

if `true`, shuffle the original array in place. Defaults to `false`.

Boolean

### return
shuffled array.

Array

` function setup() { createCanvas(100, 100); background(200); // Create an array of colors. let colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']; // Create a shuffled copy of the array. let shuffledColors = shuffle(colors); // Draw a row of circles using the original array. for (let i = 0; i < colors.length; i += 1) { // Calculate the x-coordinate. let x = (i + 1) * 12.5; // Style the circle. let c = colors[i]; fill(c); // Draw the circle. circle(x, 33, 10); } // Draw a row of circles using the original array. for (let i = 0; i < shuffledColors.length; i += 1) { // Calculate the x-coordinate. let x = (i + 1) * 12.5; // Style the circle. let c = shuffledColors[i]; fill(c); // Draw the circle. circle(x, 67, 10); } describe( 'Two rows of circles on a gray background. The top row follows the color sequence ROYGBIV. The bottom row has all the same colors but they are shuffled.' ); } `
` function setup() { createCanvas(100, 100); background(200); // Create an array of colors. let colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']; // Shuffle the array. shuffle(colors, true); // Draw a row of circles using the original array. for (let i = 0; i < colors.length; i += 1) { // Calculate the x-coordinate. let x = (i + 1) * 12.5; // Style the circle. let c = colors[i]; fill(c); // Draw the circle. circle(x, 50, 10); } describe( 'A row of colorful circles on a gray background. Their sequence changes each time the sketch runs.' ); } `

p5

Data

Array Functions

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.

method

sort

Use array.sort() instead.

list

Array to sort

Array

count

number of elements to sort, starting from 0

Integer

### return
the sorted list

Array

` function setup() { let words = ['banana', 'apple', 'pear', 'lime']; print(words); // ['banana', 'apple', 'pear', 'lime'] let count = 4; // length of array words = sort(words, count); print(words); // ['apple', 'banana', 'lime', 'pear'] } `
` function setup() { let numbers = [2, 6, 1, 5, 14, 9, 8, 12]; print(numbers); // [2, 6, 1, 5, 14, 9, 8, 12] let count = 5; // Less than the length of the array numbers = sort(numbers, count); print(numbers); // [1,2,5,6,14,9,8,12] } `

p5

Data

Array Functions

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

method

splice

Use array.splice() instead.

list

Array to splice into

Array

value

value to be spliced in

Any

position

in the array from which to insert data

Integer

### return
the list

Array

` function setup() { let myArray = [0, 1, 2, 3, 4]; let 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] } `

p5

Data

Array Functions

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.

method

subset

Use array.slice() instead.

list

Array to extract from

Array

start

position to begin

Integer

count

number of values to extract

Integer

### return
Array of extracted elements

Array

` function setup() { let myArray = [1, 2, 3, 4, 5]; print(myArray); // [1, 2, 3, 4, 5] let sub1 = subset(myArray, 0, 3); let sub2 = subset(myArray, 2, 2); print(sub1); // [1,2,3] print(sub2); // [3,4] } `

p5

Data

Array Functions

Converts a `String` to a floating point (decimal) `Number`.
`float()` converts strings that resemble numbers, such as `'12.34'`, into numbers.
The parameter, `str`, is the string value to convert. For example, calling `float('12.34')` returns the number `12.34`. If an array of strings is passed, as in `float(['12.34', '56.78'])`, then an array of numbers will be returned.
Note: If a string can't be converted to a number, as in `float('giraffe')`, then the value `NaN` (not a number) will be returned.

method

float

### return
converted number.

Number

` function setup() { createCanvas(100, 100); background(200); // Create a string variable. let original = '12.3'; // Convert the string to a number. let converted = float(original); // Double the converted value. let twice = converted * 2; // Style the text. textAlign(CENTER, CENTER); textSize(12); // Display the original and converted values. text(`${original} × 2 = ${twice}`, 50, 50); describe('The text "12.3 × 2 = 24.6" written in black on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create an array of strings. let original = ['60', '30', '15']; // Convert the strings to numbers. let diameters = float(original); for (let d of diameters) { // Draw a circle. circle(50, 50, d); } describe('Three white, concentric circles on a gray background.'); } `

p5

Data

Conversion

str

string to convert.

String

##### return
converted number.

Number

ns

array of strings to convert.

String[]

##### return
converted numbers.

Number[]

Converts a `Boolean`, `String`, or decimal `Number` to an integer.
`int()` converts values to integers. Integers are positive or negative numbers without decimals. If the original value has decimals, as in -34.56, they're removed to produce an integer such as -34.
The parameter, `n`, is the value to convert. If `n` is a Boolean, as in `int(false)` or `int(true)`, then the number 0 (`false`) or 1 (`true`) will be returned. If `n` is a string or number, as in `int('45')` or `int(67.89)`, then an integer will be returned. If an array is passed, as in `int([12.34, 56.78])`, then an array of integers will be returned.
Note: If a value can't be converted to a number, as in `int('giraffe')`, then the value `NaN` (not a number) will be returned.

method

int

### return
converted number.

Number

` function setup() { createCanvas(100, 100); background(200); // Create a Boolean variable. let original = false; // Convert the Boolean to an integer. let converted = int(original); // Style the text. textAlign(CENTER, CENTER); textSize(16); // Display the original and converted values. text(`${original} : ${converted}`, 50, 50); describe('The text "false : 0" written in black on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create a string variable. let original = '12.34'; // Convert the string to an integer. let converted = int(original); // Style the text. textAlign(CENTER, CENTER); textSize(14); // Display the original and converted values. text(`${original} ≈ ${converted}`, 50, 50); describe('The text "12.34 ≈ 12" written in black on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create a decimal number variable. let original = 12.34; // Convert the decimal number to an integer. let converted = int(original); // Style the text. textAlign(CENTER, CENTER); textSize(14); // Display the original and converted values. text(`${original} ≈ ${converted}`, 50, 50); describe('The text "12.34 ≈ 12" written in black on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create an array of strings. let original = ['60', '30', '15']; // Convert the strings to integers. let diameters = int(original); for (let d of diameters) { // Draw a circle. circle(50, 50, d); } describe('Three white, concentric circles on a gray background.'); } `

p5

Data

Conversion

n

value to convert.

String|Boolean|Number

##### return
converted number.

Number

ns

values to convert.

Array

##### return
converted numbers.

Number[]

Converts a `Boolean` or `Number` to `String`.
`str()` converts values to strings. See the String reference page for guidance on using template literals instead.
The parameter, `n`, is the value to convert. If `n` is a Boolean, as in `str(false)` or `str(true)`, then the value will be returned as a string, as in `'false'` or `'true'`. If `n` is a number, as in `str(123)`, then its value will be returned as a string, as in `'123'`. If an array is passed, as in `str([12.34, 56.78])`, then an array of strings will be returned.

method

str

n

value to convert.

String|Boolean|Number

### return
converted string.

String

` function setup() { createCanvas(100, 100); background(200); // Create a Boolean variable. let original = false; // Convert the Boolean to a string. let converted = str(original); // Style the text. textAlign(CENTER, CENTER); textSize(16); // Display the original and converted values. text(`${original} : ${converted}`, 50, 50); describe('The text "false : false" written in black on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create a number variable. let original = 123; // Convert the number to a string. let converted = str(original); // Style the text. textAlign(CENTER, CENTER); textSize(16); // Display the original and converted values. text(`${original} = ${converted}`, 50, 50); describe('The text "123 = 123" written in black on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create an array of numbers. let original = [12, 34, 56]; // Convert the numbers to strings. let strings = str(original); // Create an empty string variable. let final = ''; // Concatenate all the strings. for (let s of strings) { final += s; } // Style the text. textAlign(CENTER, CENTER); textSize(16); // Display the concatenated string. text(final, 50, 50); describe('The text "123456" written in black on a gray background.'); } `

p5

Data

Conversion

Converts a `String` or `Number` to a `Boolean`.
`boolean()` converts values to `true` or `false`.
The parameter, `n`, is the value to convert. If `n` is a string, then `boolean('true')` will return `true` and every other string value will return `false`. If `n` is a number, then `boolean(0)` will return `false` and every other numeric value will return `true`. If an array is passed, as `in boolean([0, 1, 'true', 'blue'])`, then an array of Boolean values will be returned.

method

boolean

### return
converted Boolean value.

Boolean

` function setup() { createCanvas(100, 100); background(200); // Create a number variable. let original = 0; // Convert the number to a Boolean value. let converted = boolean(original); // Style the circle based on the converted value. if (converted === true) { fill('blue'); } else { fill('red'); } // Draw the circle. circle(50, 50, 40); describe('A red circle on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create a string variable. let original = 'true'; // Convert the string to a Boolean value. let converted = boolean(original); // Style the circle based on the converted value. if (converted === true) { fill('blue'); } else { fill('red'); } // Draw the circle. circle(50, 50, 40); describe('A blue circle on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create an array of values. let original = [0, 'hi', 123, 'true']; // Convert the array to a Boolean values. let converted = boolean(original); // Iterate over the array of converted Boolean values. for (let i = 0; i < converted.length; i += 1) { // Style the circle based on the converted value. if (converted[i] === true) { fill('blue'); } else { fill('red'); } // Calculate the x-coordinate. let x = (i + 1) * 20; // Draw the circle. circle(x, 50, 15); } describe( 'A row of circles on a gray background. The two circles on the left are red and the two on the right are blue.' ); } `

p5

Data

Conversion

n

value to convert.

String|Boolean|Number

##### return
converted Boolean value.

Boolean

ns

values to convert.

Array

##### return
converted Boolean values.

Boolean[]

Converts a `Boolean`, `String`, or `Number` to its byte value.
`byte()` converts a value to an integer (whole number) between -128 and 127\. Values greater than 127 wrap around while negative values are unchanged. For example, 128 becomes -128 and -129 remains the same.
The parameter, `n`, is the value to convert. If `n` is a Boolean, as in `byte(false)` or `byte(true)`, the number 0 (`false`) or 1 (`true`) will be returned. If `n` is a string or number, as in `byte('256')` or `byte(256)`, then the byte value will be returned. Decimal values are ignored. If an array is passed, as in `byte([true, 123, '456'])`, then an array of byte values will be returned.
Note: If a value can't be converted to a number, as in `byte('giraffe')`, then the value `NaN` (not a number) will be returned.

method

byte

### return
converted byte value.

Number

` function setup() { createCanvas(100, 100); background(200); // Create a Boolean variable. let original = true; // Convert the Boolean to its byte value. let converted = byte(original); // Style the text. textAlign(CENTER, CENTER); textSize(16); // Display the original and converted values. text(`${original} : ${converted}`, 50, 50); describe('The text "true : 1" written in black on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create a string variable. let original = '256'; // Convert the string to its byte value. let converted = byte(original); // Style the text. textAlign(CENTER, CENTER); textSize(16); // Display the original and converted values. text(`${original} : ${converted}`, 50, 50); describe('The text "256 : 0" written in black on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create a number variable. let original = 256; // Convert the number to its byte value. let converted = byte(original); // Style the text. textAlign(CENTER, CENTER); textSize(16); // Display the original and converted values. text(`${original} : ${converted}`, 50, 50); describe('The text "256 : 0" written in black on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create an array of values. let original = [false, '64', 383]; // Convert the array elements to their byte values. let converted = byte(original); // Iterate over the converted array elements. for (let i = 0; i < converted.length; i += 1) { // Style the circle. fill(converted[i]); // Calculate the x-coordinate. let x = (i + 1) * 25; // Draw the circle. circle(x, 50, 20); } describe( 'Three gray circles on a gray background. The circles get lighter from left to right.' ); } `

p5

Data

Conversion

n

value to convert.

String|Boolean|Number

##### return
converted byte value.

Number

ns

values to convert.

Array

##### return
converted byte values.

Number[]

Converts a `Number` or `String` to a single-character `String`.
`char()` converts numbers to their single-character string representations.
The parameter, `n`, is the value to convert. If a number is passed, as in `char(65)`, the corresponding single-character string is returned. If a string is passed, as in `char('65')`, the string is converted to an integer (whole number) and the corresponding single-character string is returned. If an array is passed, as in `char([65, 66, 67])`, an array of single-character strings is returned.
See MDN for more information about conversions.

method

char

### return
converted single-character string.

String

` function setup() { createCanvas(100, 100); background(200); // Create a number variable. let original = 65; // Convert the number to a char. let converted = char(original); // Style the text. textAlign(CENTER, CENTER); textSize(16); // Display the original and converted values. text(`${original} : ${converted}`, 50, 50); describe('The text "65 : A" written in black on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create a string variable. let original = '65'; // Convert the string to a char. let converted = char(original); // Style the text. textAlign(CENTER, CENTER); textSize(16); // Display the original and converted values. text(`${original} : ${converted}`, 50, 50); describe('The text "65 : A" written in black on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create an array of numbers. let original = ['65', 66, '67']; // Convert the string to a char. let converted = char(original); // Style the text. textAlign(CENTER, CENTER); textSize(16); // Iterate over elements of the converted array. for (let i = 0; i < converted.length; i += 1) { // Calculate the y-coordinate. let y = (i + 1) * 25; // Display the original and converted values. text(`${original[i]} : ${converted[i]}`, 50, y); } describe( 'The text "65 : A", "66 : B", and "67 : C" written on three separate lines. The text is in black on a gray background.' ); } `

p5

Data

Conversion

n

value to convert.

String|Number

##### return
converted single-character string.

String

ns

values to convert.

Array

##### return
converted single-character strings.

String[]

Converts a single-character `String` to a `Number`.
`unchar()` converts single-character strings to their corresponding integer (whole number).
The parameter, `n`, is the character to convert. For example, `unchar('A')`, returns the number 65. If an array is passed, as in `unchar(['A', 'B', 'C'])`, an array of integers is returned.

method

unchar

### return
converted number.

Number

` function setup() { createCanvas(100, 100); background(200); // Create a string variable. let original = 'A'; // Convert the string to a number. let converted = unchar(original); // Style the text. textAlign(CENTER, CENTER); textSize(16); // Display the original and converted values. text(`${original} : ${converted}`, 50, 50); describe('The text "A : 65" written in black on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create an array of characters. let original = ['A', 'B', 'C']; // Convert the string to a number. let converted = unchar(original); // Style the text. textAlign(CENTER, CENTER); textSize(16); // Iterate over elements of the converted array. for (let i = 0; i < converted.length; i += 1) { // Calculate the y-coordinate. let y = (i + 1) * 25; // Display the original and converted values. text(`${original[i]} : ${converted[i]}`, 50, y); } describe( 'The text "A : 65", "B : 66", and "C :67" written on three separate lines. The text is in black on a gray background.' ); } `

p5

Data

Conversion

n

value to convert.

String

##### return
converted number.

Number

ns

values to convert.

String[]

##### return
converted numbers.

Number[]

Converts a `Number` to a `String` with its hexadecimal value.
`hex()` converts a number to a string with its hexadecimal number value. Hexadecimal (hex) numbers are base-16, which means there are 16 unique digits. Hex extends the numbers 0–9 with the letters A–F. For example, the number `11` (eleven) in base-10 is written as the letter `B` in hex.
The first parameter, `n`, is the number to convert. For example, `hex(20)`, returns the string `'00000014'`. If an array is passed, as in `hex([1, 10, 100])`, an array of hexadecimal strings is returned.
The second parameter, `digits`, is optional. If a number is passed, as in `hex(20, 2)`, it sets the number of hexadecimal digits to display. For example, calling `hex(20, 2)` returns the string `'14'`.

method

hex

### return
converted hexadecimal value.

String

` function setup() { createCanvas(100, 100); background(200); // Create a number variable. let original = 20; // Convert the number to a hex string. let converted = hex(original); // Style the text. textAlign(CENTER, CENTER); textSize(14); // Display the original and converted values. text(`${original} = ${converted}`, 50, 50); describe('The text "20 = 00000014" written in black on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create a number variable. let original = 20; // Convert the number to a hex string. // Only display two hex digits. let converted = hex(original, 2); // Style the text. textAlign(CENTER, CENTER); textSize(16); // Display the original and converted values. text(`${original} = ${converted}`, 50, 50); describe('The text "20 = 14" written in black on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create an array of numbers. let original = [1, 10, 100]; // Convert the numbers to hex strings. // Only use two hex digits. let converted = hex(original, 2); // Style the text. textAlign(RIGHT, CENTER); textSize(16); // Iterate over the converted values. for (let i = 0; i < converted.length; i += 1) { // Calculate the y-coordinate. let y = (i + 1) * 25; // Display the original and converted values. text(`${ original[i]} = ${converted[i]}`, 75, y); } describe( 'The text "1 = 01", "10 = 0A", and "100 = 64" written on three separate lines. The text is in black on a gray background.' ); } `

p5

Data

Conversion

n

value to convert.

Number

digits

number of digits to include.

Number

##### return
converted hexadecimal value.

String

ns

values to convert.

Number[]

digits



Number

##### return
converted hexadecimal values.

String[]

Converts a `String` with a hexadecimal value to a `Number`.
`unhex()` converts a string with its hexadecimal number value to a number. Hexadecimal (hex) numbers are base-16, which means there are 16 unique digits. Hex extends the numbers 0–9 with the letters A–F. For example, the number `11` (eleven) in base-10 is written as the letter `B` in hex.
The first parameter, `n`, is the hex string to convert. For example, `unhex('FF')`, returns the number 255. If an array is passed, as in `unhex(['00', '80', 'FF'])`, an array of numbers is returned.

method

unhex

### return
converted number.

Number

` function setup() { createCanvas(100, 100); background(200); // Create a a hex string variable let original = 'FF'; // Convert the hex string to a number. let converted = unhex(original); // Style the text. textAlign(CENTER, CENTER); textSize(16); // Display the original and converted values. text(`${original} = ${converted}`, 50, 50); describe('The text "FF = 255" written in black on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create an array of numbers. let original = ['00', '80', 'FF']; // Convert the numbers to hex strings. // Only use two hex digits. let converted = unhex(original, 2); // Style the text. textAlign(RIGHT, CENTER); textSize(16); // Iterate over the converted values. for (let i = 0; i < converted.length; i += 1) { // Calculate the y-coordinate. let y = (i + 1) * 25; // Display the original and converted values. text(`${ original[i]} = ${converted[i]}`, 80, y); } describe( 'The text "00 = 0", "80 = 128", and "FF = 255" written on three separate lines. The text is in black on a gray background.' ); } `

p5

Data

Conversion

n

value to convert.

String

##### return
converted number.

Number

ns

values to convert.

String[]

##### return
converted numbers.

Number[]

Combines an array of strings into one string.
The first parameter, `list`, is the array of strings to join.
The second parameter, `separator`, is the character(s) that should be used to separate the combined strings. For example, calling `join(myWords, ' : ')` would return a string of words each separated by a colon and spaces.

method

join

list

array of strings to combine.

Array

separator

character(s) to place between strings when they're combined.

String

### return
combined string.

String

` function setup() { createCanvas(100, 100); background(200); // Create an array of strings. let myWords = ['one', 'two', 'three']; // Create a combined string let combined = join(myWords, ' : '); // Style the text. textAlign(CENTER, CENTER); // Display the combined string. text(combined, 50, 50); describe('The text "one : two : three" written in black on a gray canvas.'); } `

p5

Data

String Functions

Applies a regular expression to a string and returns an array with the first match.
`match()` uses regular expressions (regex) to match patterns in text. For example, the regex `abc` can be used to search a string for the exact sequence of characters `abc`. See MDN. for more information about regexes.
The first parameter, `str`, is the string to search.
The second parameter, `regex`, is a string with the regular expression to apply. For example, calling `match('Hello, p5*js!', '[a-z][0-9]')` would return the array `['p5']`.
Note: If no matches are found, `null` is returned.

method

match

str

string to search.

String

regexp

regular expression to match.

String

### return
match if found.

String[]

` function setup() { createCanvas(100, 100); background(200); // Create a string variable. let string = 'Hello, p5*js!'; // Match the characters that are lowercase // letters followed by digits. let matches = match(string, '[a-z][0-9]'); // Print the matches array to the console: // ['p5'] print(matches); // Style the text. textAlign(CENTER, CENTER); textSize(16); // Display the matches. text(matches, 50, 50); describe('The text "p5" written in black on a gray canvas.'); } `

p5

Data

String Functions

Applies a regular expression to a string and returns an array of matches.
`match()` uses regular expressions (regex) to match patterns in text. For example, the regex `abc` can be used to search a string for the exact sequence of characters `abc`. See MDN. for more information about regexes. `matchAll()` is different from match() because it returns every match, not just the first.
The first parameter, `str`, is the string to search.
The second parameter, `regex`, is a string with the regular expression to apply. For example, calling `matchAll('p5*js is easier than abc123', '[a-z][0-9]')` would return the 2D array `[['p5'], ['c1']]`.
Note: If no matches are found, an empty array `[]` is returned.

method

matchAll

str

string to search.

String

regexp

regular expression to match.

String

### return
matches found.

String[]

` function setup() { createCanvas(100, 100); background(200); // Create a string variable. let string = 'p5*js is easier than abc123'; // Match the character sequences that are // lowercase letters followed by digits. let matches = matchAll(string, '[a-z][0-9]'); // Print the matches array to the console: // [['p5'], ['c1']] print(matches); // Style the text. textAlign(CENTER, CENTER); textSize(16); // Iterate over the matches array. for (let i = 0; i < matches.length; i += 1) { // Calculate the y-coordainate. let y = (i + 1) * 33; // Display the match. text(matches[i], 50, y); } describe( 'The text "p5" and "c1" written on separate lines. The text is black on a gray background.' ); } `

p5

Data

String Functions

Converts a `Number` into a `String` with a given number of digits.
`nf()` converts numbers such as `123.45` into strings formatted with a set number of digits, as in `'123.4500'`.
The first parameter, `num`, is the number to convert to a string. For example, calling `nf(123.45)` returns the string `'123.45'`. If an array of numbers is passed, as in `nf([123.45, 67.89])`, an array of formatted strings will be returned.
The second parameter, `left`, is optional. If a number is passed, as in `nf(123.45, 4)`, it sets the minimum number of digits to include to the left of the decimal place. If `left` is larger than the number of digits in `num`, then unused digits will be set to 0. For example, calling `nf(123.45, 4)` returns the string `'0123.45'`.
The third parameter, `right`, is also optional. If a number is passed, as in `nf(123.45, 4, 1)`, it sets the minimum number of digits to include to the right of the decimal place. If `right` is smaller than the number of decimal places in `num`, then `num` will be rounded to the given number of decimal places. For example, calling `nf(123.45, 4, 1)` returns the string `'0123.5'`. If right is larger than the number of decimal places in `num`, then unused decimal places will be set to 0. For example, calling `nf(123.45, 4, 3)` returns the string `'0123.450'`.
When the number is negative, for example, calling `nf(-123.45, 5, 2)` returns the string `'-00123.45'`.

method

nf

### return
formatted string.

String

` function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(LEFT, CENTER); textSize(16); // Create a number variable. let number = 123.45; // Display the number as a string. let formatted = nf(number); text(formatted, 20, 20); let negative = nf(-number, 4, 2); text(negative, 20, 40); // Display the number with four digits // to the left of the decimal. let left = nf(number, 4); text(left, 20, 60); // Display the number with four digits // to the left of the decimal and one // to the right. let right = nf(number, 4, 1); text(right, 20, 80); describe( 'The numbers "123.45", "-0123.45", "0123.45", and "0123.5" written on four separate lines. The text is in black on a gray background.' ); } `

p5

Data

String Functions

num

number to format.

Number|String

left

number of digits to include to the left of the decimal point.

Integer|String

right

number of digits to include to the right of the decimal point.

Integer|String

##### return
formatted string.

String

nums

numbers to format.

Number[]

left



Integer|String

right



Integer|String

##### return
formatted strings.

String[]

Converts a `Number` into a `String` with commas to mark units of 1,000.
`nfc()` converts numbers such as 12345 into strings formatted with commas to mark the thousands place, as in `'12,345'`.
The first parameter, `num`, is the number to convert to a string. For example, calling `nfc(12345)` returns the string `'12,345'`.
The second parameter, `right`, is optional. If a number is passed, as in `nfc(12345, 1)`, it sets the minimum number of digits to include to the right of the decimal place. If `right` is smaller than the number of decimal places in `num`, then `num` will be rounded to the given number of decimal places. For example, calling `nfc(12345.67, 1)` returns the string `'12,345.7'`. If `right` is larger than the number of decimal places in `num`, then unused decimal places will be set to 0. For example, calling `nfc(12345.67, 3)` returns the string `'12,345.670'`.

method

nfc

### return
formatted string.

String

` function setup() { createCanvas(100, 100); background(200); // Style the text. textAlign(LEFT, CENTER); textSize(16); // Create a number variable. let number = 12345; // Display the number as a string. let commas = nfc(number); text(commas, 15, 33); // Display the number with four digits // to the left of the decimal. let decimals = nfc(number, 2); text(decimals, 15, 67); describe( 'The numbers "12,345" and "12,345.00" written on separate lines. The text is in black on a gray background.' ); } `
` function setup() { createCanvas(100, 100); background(200); // Create an array of numbers. let numbers = [12345, 6789]; // Convert the numbers to formatted strings. let formatted = nfc(numbers); // Style the text. textAlign(CENTER, CENTER); textSize(14); // Iterate over the array. for (let i = 0; i < formatted.length; i += 1) { // Calculate the y-coordinate. let y = (i + 1) * 33; // Display the original and formatted numbers. text(`${numbers[i]} : ${formatted[i]}`, 50, y); } describe( 'The text "12345 : 12,345" and "6789 : 6,789" written on two separate lines. The text is in black on a gray background.' ); } `

p5

Data

String Functions

num

number to format.

Number|String

right

number of digits to include to the right of the decimal point.

Integer|String

##### return
formatted string.

String

nums

numbers to format.

Number[]

right



Integer|String

##### return
formatted strings.

String[]

Converts a `Number` into a `String` with a plus or minus sign.
`nfp()` converts numbers such as 123 into strings formatted with a `+` or `-` symbol to mark whether they're positive or negative, as in `'+123'`.
The first parameter, `num`, is the number to convert to a string. For example, calling `nfp(123.45)` returns the string `'+123.45'`. If an array of numbers is passed, as in `nfp([123.45, -6.78])`, an array of formatted strings will be returned.
The second parameter, `left`, is optional. If a number is passed, as in `nfp(123.45, 4)`, it sets the minimum number of digits to include to the left of the decimal place. If `left` is larger than the number of digits in `num`, then unused digits will be set to 0. For example, calling `nfp(123.45, 4)` returns the string `'+0123.45'`.
The third parameter, `right`, is also optional. If a number is passed, as in `nfp(123.45, 4, 1)`, it sets the minimum number of digits to include to the right of the decimal place. If `right` is smaller than the number of decimal places in `num`, then `num` will be rounded to the given number of decimal places. For example, calling `nfp(123.45, 4, 1)` returns the string `'+0123.5'`. If `right` is larger than the number of decimal places in `num`, then unused decimal places will be set to 0. For example, calling `nfp(123.45, 4, 3)` returns the string `'+0123.450'`.

method

nfp

### return
formatted string.

String

` function setup() { createCanvas(100, 100); background(200); // Create number variables. let positive = 123; let negative = -123; // Convert the positive number to a formatted string. let p = nfp(positive); // Convert the negative number to a formatted string // with four digits to the left of the decimal // and two digits to the right of the decimal. let n = nfp(negative, 4, 2); // Style the text. textAlign(CENTER, CENTER); textSize(14); // Display the original and formatted numbers. text(`${positive} : ${p}`, 50, 33); text(`${negative} : ${n}`, 50, 67); describe( 'The text "123 : +123" and "-123 : -123.00" written on separate lines. The text is in black on a gray background.' ); } `
` function setup() { createCanvas(100, 100); background(200); // Create number variables. let numbers = [123, -4.56]; // Convert the numbers to formatted strings // with four digits to the left of the decimal // and one digit to the right of the decimal. let formatted = nfp(numbers, 4, 1); // Style the text. textAlign(CENTER, CENTER); textSize(14); // Iterate over the array. for (let i = 0; i < formatted.length; i += 1) { // Calculate the y-coordinate. let y = (i + 1) * 33; // Display the original and formatted numbers. text(`${numbers[i]} : ${formatted[i]}`, 50, y); } describe( 'The text "123 : +0123.0" and "-4.56 : 00-4.6" written on separate lines. The text is in black on a gray background.' ); } `

p5

Data

String Functions

num

number to format.

Number

left

number of digits to include to the left of the decimal point.

Integer

right

number of digits to include to the right of the decimal point.

Integer

##### return
formatted string.

String

nums

numbers to format.

Number[]

left



Integer

right



Integer

##### return
formatted strings.

String[]

Converts a positive `Number` into a `String` with an extra space in front.
`nfs()` converts positive numbers such as 123.45 into strings formatted with an extra space in front, as in ' 123.45'. Doing so can be helpful for aligning positive and negative numbers.
The first parameter, `num`, is the number to convert to a string. For example, calling `nfs(123.45)` returns the string `' 123.45'`.
The second parameter, `left`, is optional. If a number is passed, as in `nfs(123.45, 4)`, it sets the minimum number of digits to include to the left of the decimal place. If `left` is larger than the number of digits in `num`, then unused digits will be set to 0. For example, calling `nfs(123.45, 4)` returns the string `' 0123.45'`.
The third parameter, `right`, is also optional. If a number is passed, as in `nfs(123.45, 4, 1)`, it sets the minimum number of digits to include to the right of the decimal place. If `right` is smaller than the number of decimal places in `num`, then `num` will be rounded to the given number of decimal places. For example, calling `nfs(123.45, 4, 1)` returns the string `' 0123.5'`. If `right` is larger than the number of decimal places in `num`, then unused decimal places will be set to 0. For example, calling `nfs(123.45, 4, 3)` returns the string `' 0123.450'`.

method

nfs

### return
formatted string.

String

` function setup() { createCanvas(100, 100); background(200); // Create number variables. let positive = 123; let negative = -123; // Convert the positive number to a formatted string. let formatted = nfs(positive); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(16); // Display the negative number and the formatted positive number. text(negative, 50, 33); text(formatted, 50, 67); describe( 'The numbers -123 and 123 written on separate lines. The numbers align vertically. The text is in black on a gray background.' ); } `
` function setup() { createCanvas(100, 100); background(200); // Create a number variable. let number = 123.45; // Convert the positive number to a formatted string. // Use four digits to the left of the decimal and // one digit to the right. let formatted = nfs(number, 4, 1); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(16); // Display a negative version of the number and // the formatted positive version. text('-0123.5', 50, 33); text(formatted, 50, 67); describe( 'The numbers "-0123.5" and "0123.5" written on separate lines. The numbers align vertically. The text is in black on a gray background.' ); } `

p5

Data

String Functions

num

number to format.

Number

left

number of digits to include to the left of the decimal point.

Integer

right

number of digits to include to the right of the decimal point.

Integer

##### return
formatted string.

String

nums

numbers to format.

Array

left



Integer

right



Integer

##### return
formatted strings.

String[]

Splits a `String` into pieces and returns an array containing the pieces.
The first parameter, `value`, is the string to split.
The second parameter, `delim`, is the character(s) that should be used to split the string. For example, calling `split('rock...paper...scissors', '...')` would return the array `['rock', 'paper', 'scissors']` because there are three periods `...` between each word.

method

split

value

the String to be split

String

delim

the String used to separate the data

String

### return
Array of Strings

String[]

` function setup() { createCanvas(100, 100); background(200); // Create a string variable. let string = 'rock...paper...scissors'; // Split the string at each ... let words = split(string, '...'); // Print the array to the console: // ["rock", "paper", "scissors"] print(words); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(16); // Iterate over the words array. for (let i = 0; i < words.length; i += 1) { // Calculate the y-coordinate. let y = (i + 1) * 25; // Display the word. text(words[i], 50, y); } describe( 'The words "rock", "paper", and "scissors" written on separate lines. The text is black on a gray background.' ); } `

p5

Data

String Functions

Splits a `String` into pieces and returns an array containing the pieces.
`splitTokens()` is an enhanced version of split(). It can split a string when any characters from a list are detected.
The first parameter, `value`, is the string to split.
The second parameter, `delim`, is optional. It sets the character(s) that should be used to split the string. `delim` can be a single string, as in `splitTokens('rock...paper...scissors...shoot', '...')`, or an array of strings, as in `splitTokens('rock;paper,scissors...shoot, [';', ',', '...'])`. By default, if no `delim` characters are specified, then any whitespace character is used to split. Whitespace characters include tab (`\t`), line feed (` `), carriage return (`\r`), form feed (`\f`), and space.

method

splitTokens

value

string to split.

String

delim

character(s) to use for splitting the string.

String

### return
separated strings.

String[]

` function setup() { createCanvas(100, 100); background(200); // Create a string variable. let string = 'rock paper scissors shoot'; // Split the string at each space. let words = splitTokens(string); // Print the array to the console. print(words); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(12); // Iterate over the words array. for (let i = 0; i < words.length; i += 1) { // Calculate the y-coordinate. let y = (i + 1) * 20; // Display the word. text(words[i], 50, y); } describe( 'The words "rock", "paper", "scissors", and "shoot" written on separate lines. The text is black on a gray background.' ); } `
` function setup() { createCanvas(100, 100); background(200); // Create a string variable. let string = 'rock...paper...scissors...shoot'; // Split the string at each ... let words = splitTokens(string, '...'); // Print the array to the console. print(words); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(12); // Iterate over the words array. for (let i = 0; i < words.length; i += 1) { // Calculate the y-coordinate. let y = (i + 1) * 20; // Display the word. text(words[i], 50, y); } describe( 'The words "rock", "paper", "scissors", and "shoot" written on separate lines. The text is black on a gray background.' ); } `
` function setup() { createCanvas(100, 100); background(200); // Create a string variable. let string = 'rock;paper,scissors...shoot'; // Split the string at each semicolon, comma, or ... let words = splitTokens(string, [';', ',', '...']); // Print the array to the console. print(words); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(12); // Iterate over the words array. for (let i = 0; i < words.length; i += 1) { // Calculate the y-coordinate. let y = (i + 1) * 20; // Display the word. text(words[i], 50, y); } describe( 'The words "rock", "paper", "scissors", and "shoot" written on separate lines. The text is black on a gray background.' ); } `

p5

Data

String Functions

Removes whitespace from the start and end of a `String` without changing the middle.
`trim()` trims whitespace characters such as spaces, carriage returns, tabs, Unicode "nbsp" character.
The parameter, `str`, is the string to trim. If a single string is passed, as in `trim(' pad ')`, a single string is returned. If an array of strings is passed, as in `trim([' pad ', ' space '])`, an array of strings is returned.

method

trim

### return
trimmed string.

String

` function setup() { createCanvas(100, 100); background(200); // Create a string variable. let string = ' p5*js '; // Trim the whitespace. let trimmed = trim(string); // Style the text. textAlign(CENTER, CENTER); textSize(16); // Display the text. text(`Hello, ${trimmed}!`, 50, 50); describe('The text "Hello, p5*js!" written in black on a gray background.'); } `
` function setup() { createCanvas(100, 100); background(200); // Create an array of strings. let strings = [' wide ', ' open ', ' spaces ']; // Trim the whitespace. let trimmed = trim(strings); // Style the text. textAlign(CENTER, CENTER); textFont('Courier New'); textSize(10); // Display the text. text(`${trimmed[0]} ${trimmed[1]} ${trimmed[2]}`, 50, 50); describe('The text "wide open spaces" written in black on a gray background.'); } `

p5

Data

String Functions

str

string to trim.

String

##### return
trimmed string.

String

strs

strings to trim.

String[]

##### return
trimmed strings.

String[]

Returns the current day as a number from 1–31.

method

day

### return
current day between 1 and 31.

Integer

` function setup() { createCanvas(100, 100); background(200); // Get the current day. let d = day(); // Style the text. textAlign(LEFT, CENTER); textSize(12); textFont('Courier New'); // Display the day. text(`Current day: ${d}`, 20, 50, 60); describe(`The text 'Current day: ${d}' written in black on a gray background.`); } `

p5

IO

Time & Date

Returns the current hour as a number from 0–23.

method

hour

### return
current hour between 0 and 23.

Integer

` function setup() { createCanvas(100, 100); background(200); // Get the current hour. let h = hour(); // Style the text. textAlign(LEFT, CENTER); textSize(12); textFont('Courier New'); // Display the hour. text(`Current hour: ${h}`, 20, 50, 60); describe(`The text 'Current hour: ${h}' written in black on a gray background.`); } `

p5

IO

Time & Date

Returns the current minute as a number from 0–59.

method

minute

### return
current minute between 0 and 59.

Integer

` function setup() { createCanvas(100, 100); background(200); // Get the current minute. let m = minute(); // Style the text. textAlign(LEFT, CENTER); textSize(12); textFont('Courier New'); // Display the minute. text(`Current minute: ${m}`, 10, 50, 80); describe(`The text 'Current minute: ${m}' written in black on a gray background.`); } `

p5

IO

Time & Date

Returns the number of milliseconds since a sketch started running.
`millis()` keeps track of how long a sketch has been running in milliseconds (thousandths of a second). This information is often helpful for timing events and animations.
If a sketch has a setup() function, then `millis()` begins tracking time before the code in setup() runs. If a sketch includes a preload() function, then `millis()` begins tracking time as soon as the code in preload() starts running.

method

millis

### return
number of milliseconds since starting the sketch.

Number

` function setup() { createCanvas(100, 100); background(200); // Get the number of milliseconds the sketch has run. let ms = millis(); // Style the text. textAlign(LEFT, CENTER); textSize(10); textFont('Courier New'); // Display how long it took setup() to be called. text(`Startup time: ${round(ms, 2)} ms`, 5, 50, 90); describe( `The text 'Startup time: ${round(ms, 2)} ms' written in black on a gray background.` ); } `
` function setup() { createCanvas(100, 100); describe('The text "Running time: S sec" written in black on a gray background. The number S increases as the sketch runs.'); } function draw() { background(200); // Get the number of seconds the sketch has run. let s = millis() / 1000; // Style the text. textAlign(LEFT, CENTER); textSize(10); textFont('Courier New'); // Display how long the sketch has run. text(`Running time: ${nf(s, 1, 1)} sec`, 5, 50, 90); } `
` function setup() { createCanvas(100, 100); describe('A white circle oscillates left and right on a gray background.'); } function draw() { background(200); // Get the number of seconds the sketch has run. let s = millis() / 1000; // Calculate an x-coordinate. let x = 30 * sin(s) + 50; // Draw the circle. circle(x, 50, 30); } `
` // Load the GeoJSON. function preload() { loadJSON('https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson'); } function setup() { createCanvas(100, 100); background(200); // Get the number of milliseconds the sketch has run. let ms = millis(); // Style the text. textAlign(LEFT, CENTER); textFont('Courier New'); textSize(11); // Display how long it took to load the data. text(`It took ${round(ms, 2)} ms to load the data`, 5, 50, 100); describe( `The text "It took ${round(ms, 2)} ms to load the data" written in black on a gray background.` ); } `

p5

IO

Time & Date

Returns the current month as a number from 1–12.

method

month

### return
current month between 1 and 12.

Integer

` function setup() { createCanvas(100, 100); background(200); // Get the current month. let m = month(); // Style the text. textAlign(LEFT, CENTER); textSize(12); textFont('Courier New'); // Display the month. text(`Current month: ${m}`, 10, 50, 80); describe(`The text 'Current month: ${m}' written in black on a gray background.`); } `

p5

IO

Time & Date

Returns the current second as a number from 0–59.

method

second

### return
current second between 0 and 59.

Integer

` function setup() { createCanvas(100, 100); background(200); // Get the current second. let s = second(); // Style the text. textAlign(LEFT, CENTER); textSize(12); textFont('Courier New'); // Display the second. text(`Current second: ${s}`, 10, 50, 80); describe(`The text 'Current second: ${s}' written in black on a gray background.`); } `

p5

IO

Time & Date

Returns the current year as a number such as 1999.

method

year

### return
current year.

Integer

` function setup() { createCanvas(100, 100); background(200); // Get the current year. let y = year(); // Style the text. textAlign(LEFT, CENTER); textSize(12); textFont('Courier New'); // Display the year. text(`Current year: ${y}`, 10, 50, 80); describe(`The text 'Current year: ${y}' written in black on a gray background.`); } `

p5

IO

Time & Date

Begins adding shapes to a new p5.Geometry object.
The `beginGeometry()` and endGeometry() functions help with creating complex 3D shapes from simpler ones such as sphere(). `beginGeometry()` begins adding shapes to a custom p5.Geometry object and endGeometry() stops adding them.
`beginGeometry()` and endGeometry() can help to make sketches more performant. For example, if a complex 3D shape doesn’t change while a sketch runs, then it can be created with `beginGeometry()` and endGeometry(). Creating a p5.Geometry object once and then drawing it will run faster than repeatedly drawing the individual pieces.
See buildGeometry() for another way to build 3D shapes.
Note: `beginGeometry()` can only be used in WebGL mode.

method

beginGeometry

` // Click and drag the mouse to view the scene from different angles. let shape; function setup() { createCanvas(100, 100, WEBGL); // Start building the p5.Geometry object. beginGeometry(); // Add a cone. cone(); // Stop building the p5.Geometry object. shape = endGeometry(); describe('A white cone drawn on a gray background.'); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Style the p5.Geometry object. noStroke(); // Draw the p5.Geometry object. model(shape); } `
` // Click and drag the mouse to view the scene from different angles. let shape; function setup() { createCanvas(100, 100, WEBGL); // Create the p5.Geometry object. createArrow(); describe('A white arrow drawn on a gray background.'); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Style the p5.Geometry object. noStroke(); // Draw the p5.Geometry object. model(shape); } function createArrow() { // Start building the p5.Geometry object. beginGeometry(); // Add shapes. push(); rotateX(PI); cone(10); translate(0, -10, 0); cylinder(3, 20); pop(); // Stop building the p5.Geometry object. shape = endGeometry(); } `
` // Click and drag the mouse to view the scene from different angles. let blueArrow; let redArrow; function setup() { createCanvas(100, 100, WEBGL); // Create the arrows. redArrow = createArrow('red'); blueArrow = createArrow('blue'); describe('A red arrow and a blue arrow drawn on a gray background. The blue arrow rotates slowly.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Style the arrows. noStroke(); // Draw the red arrow. model(redArrow); // Translate and rotate the coordinate system. translate(30, 0, 0); rotateZ(frameCount * 0.01); // Draw the blue arrow. model(blueArrow); } function createArrow(fillColor) { // Start building the p5.Geometry object. beginGeometry(); fill(fillColor); // Add shapes to the p5.Geometry object. push(); rotateX(PI); cone(10); translate(0, -10, 0); cylinder(3, 20); pop(); // Stop building the p5.Geometry object. let shape = endGeometry(); return shape; } `
` // Click and drag the mouse to view the scene from different angles. let button; let particles; function setup() { createCanvas(100, 100, WEBGL); // Create a button to reset the particle system. button = createButton('Reset'); // Call resetModel() when the user presses the button. button.mousePressed(resetModel); // Add the original set of particles. resetModel(); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Style the particles. noStroke(); // Draw the particles. model(particles); } function resetModel() { // If the p5.Geometry object has already been created, // free those resources. if (particles) { freeGeometry(particles); } // Create a new p5.Geometry object with random spheres. particles = createParticles(); } function createParticles() { // Start building the p5.Geometry object. beginGeometry(); // Add shapes. for (let i = 0; i < 60; i += 1) { // Calculate random coordinates. let x = randomGaussian(0, 20); let y = randomGaussian(0, 20); let z = randomGaussian(0, 20); push(); // Translate to the particle's coordinates. translate(x, y, z); // Draw the particle. sphere(5); pop(); } // Stop building the p5.Geometry object. let shape = endGeometry(); return shape; } `

p5

Shape

3D Primitives

Stops adding shapes to a new p5.Geometry object and returns the object.
The `beginGeometry()` and endGeometry() functions help with creating complex 3D shapes from simpler ones such as sphere(). `beginGeometry()` begins adding shapes to a custom p5.Geometry object and endGeometry() stops adding them.
`beginGeometry()` and endGeometry() can help to make sketches more performant. For example, if a complex 3D shape doesn’t change while a sketch runs, then it can be created with `beginGeometry()` and endGeometry(). Creating a p5.Geometry object once and then drawing it will run faster than repeatedly drawing the individual pieces.
See buildGeometry() for another way to build 3D shapes.
Note: `endGeometry()` can only be used in WebGL mode.

method

endGeometry

### return
new 3D shape.

p5.Geometry

` // Click and drag the mouse to view the scene from different angles. let shape; function setup() { createCanvas(100, 100, WEBGL); // Start building the p5.Geometry object. beginGeometry(); // Add a cone. cone(); // Stop building the p5.Geometry object. shape = endGeometry(); describe('A white cone drawn on a gray background.'); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Style the p5.Geometry object. noStroke(); // Draw the p5.Geometry object. model(shape); } `
` // Click and drag the mouse to view the scene from different angles. let shape; function setup() { createCanvas(100, 100, WEBGL); // Create the p5.Geometry object. createArrow(); describe('A white arrow drawn on a gray background.'); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Style the p5.Geometry object. noStroke(); // Draw the p5.Geometry object. model(shape); } function createArrow() { // Start building the p5.Geometry object. beginGeometry(); // Add shapes. push(); rotateX(PI); cone(10); translate(0, -10, 0); cylinder(3, 20); pop(); // Stop building the p5.Geometry object. shape = endGeometry(); } `
` // Click and drag the mouse to view the scene from different angles. let blueArrow; let redArrow; function setup() { createCanvas(100, 100, WEBGL); // Create the arrows. redArrow = createArrow('red'); blueArrow = createArrow('blue'); describe('A red arrow and a blue arrow drawn on a gray background. The blue arrow rotates slowly.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Style the arrows. noStroke(); // Draw the red arrow. model(redArrow); // Translate and rotate the coordinate system. translate(30, 0, 0); rotateZ(frameCount * 0.01); // Draw the blue arrow. model(blueArrow); } function createArrow(fillColor) { // Start building the p5.Geometry object. beginGeometry(); fill(fillColor); // Add shapes to the p5.Geometry object. push(); rotateX(PI); cone(10); translate(0, -10, 0); cylinder(3, 20); pop(); // Stop building the p5.Geometry object. let shape = endGeometry(); return shape; } `
` // Click and drag the mouse to view the scene from different angles. let button; let particles; function setup() { createCanvas(100, 100, WEBGL); // Create a button to reset the particle system. button = createButton('Reset'); // Call resetModel() when the user presses the button. button.mousePressed(resetModel); // Add the original set of particles. resetModel(); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Style the particles. noStroke(); // Draw the particles. model(particles); } function resetModel() { // If the p5.Geometry object has already been created, // free those resources. if (particles) { freeGeometry(particles); } // Create a new p5.Geometry object with random spheres. particles = createParticles(); } function createParticles() { // Start building the p5.Geometry object. beginGeometry(); // Add shapes. for (let i = 0; i < 60; i += 1) { // Calculate random coordinates. let x = randomGaussian(0, 20); let y = randomGaussian(0, 20); let z = randomGaussian(0, 20); push(); // Translate to the particle's coordinates. translate(x, y, z); // Draw the particle. sphere(5); pop(); } // Stop building the p5.Geometry object. let shape = endGeometry(); return shape; } `

p5

Shape

3D Primitives

Creates a custom p5.Geometry object from simpler 3D shapes.
`buildGeometry()` helps with creating complex 3D shapes from simpler ones such as sphere(). It can help to make sketches more performant. For example, if a complex 3D shape doesn’t change while a sketch runs, then it can be created with `buildGeometry()`. Creating a p5.Geometry object once and then drawing it will run faster than repeatedly drawing the individual pieces.
The parameter, `callback`, is a function with the drawing instructions for the new p5.Geometry object. It will be called once to create the new 3D shape.
See beginGeometry() and endGeometry() for another way to build 3D shapes.
Note: `buildGeometry()` can only be used in WebGL mode.

method

buildGeometry

callback

function that draws the shape.

Function

### return
new 3D shape.

p5.Geometry

` // Click and drag the mouse to view the scene from different angles. let shape; function setup() { createCanvas(100, 100, WEBGL); // Create the p5.Geometry object. shape = buildGeometry(createShape); describe('A white cone drawn on a gray background.'); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Style the p5.Geometry object. noStroke(); // Draw the p5.Geometry object. model(shape); } // Create p5.Geometry object from a single cone. function createShape() { cone(); } `
` // Click and drag the mouse to view the scene from different angles. let shape; function setup() { createCanvas(100, 100, WEBGL); // Create the arrow. shape = buildGeometry(createArrow); describe('A white arrow drawn on a gray background.'); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Style the arrow. noStroke(); // Draw the arrow. model(shape); } function createArrow() { // Add shapes to the p5.Geometry object. push(); rotateX(PI); cone(10); translate(0, -10, 0); cylinder(3, 20); pop(); } `
` // Click and drag the mouse to view the scene from different angles. let shape; function setup() { createCanvas(100, 100, WEBGL); // Create the p5.Geometry object. shape = buildGeometry(createArrow); describe('Two white arrows drawn on a gray background. The arrow on the right rotates slowly.'); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Style the arrows. noStroke(); // Draw the p5.Geometry object. model(shape); // Translate and rotate the coordinate system. translate(30, 0, 0); rotateZ(frameCount * 0.01); // Draw the p5.Geometry object again. model(shape); } function createArrow() { // Add shapes to the p5.Geometry object. push(); rotateX(PI); cone(10); translate(0, -10, 0); cylinder(3, 20); pop(); } `
` // Click and drag the mouse to view the scene from different angles. let button; let particles; function setup() { createCanvas(100, 100, WEBGL); // Create a button to reset the particle system. button = createButton('Reset'); // Call resetModel() when the user presses the button. button.mousePressed(resetModel); // Add the original set of particles. resetModel(); describe('A set of white spheres on a gray background. The spheres are positioned randomly. Their positions reset when the user presses the Reset button.'); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Style the particles. noStroke(); // Draw the particles. model(particles); } function resetModel() { // If the p5.Geometry object has already been created, // free those resources. if (particles) { freeGeometry(particles); } // Create a new p5.Geometry object with random spheres. particles = buildGeometry(createParticles); } function createParticles() { for (let i = 0; i < 60; i += 1) { // Calculate random coordinates. let x = randomGaussian(0, 20); let y = randomGaussian(0, 20); let z = randomGaussian(0, 20); push(); // Translate to the particle's coordinates. translate(x, y, z); // Draw the particle. sphere(5); pop(); } } `

p5

Shape

3D Primitives

Clears a p5.Geometry object from the graphics processing unit (GPU) memory.
p5.Geometry objects can contain lots of data about their vertices, surface normals, colors, and so on. Complex 3D shapes can use lots of memory which is a limited resource in many GPUs. Calling `freeGeometry()` can improve performance by freeing a p5.Geometry object’s resources from GPU memory. `freeGeometry()` works with p5.Geometry objects created with beginGeometry() and endGeometry(), buildGeometry(), and loadModel().
The parameter, `geometry`, is the p5.Geometry object to be freed.
Note: A p5.Geometry object can still be drawn after its resources are cleared from GPU memory. It may take longer to draw the first time it’s redrawn.
Note: `freeGeometry()` can only be used in WebGL mode.

method

freeGeometry

geometry

3D shape whose resources should be freed.

p5.Geometry

` function setup() { createCanvas(100, 100, WEBGL); background(200); // Create a p5.Geometry object. beginGeometry(); cone(); let shape = endGeometry(); // Draw the shape. model(shape); // Free the shape's resources. freeGeometry(shape); } `
` // Click and drag the mouse to view the scene from different angles. let button; let particles; function setup() { createCanvas(100, 100, WEBGL); // Create a button to reset the particle system. button = createButton('Reset'); // Call resetModel() when the user presses the button. button.mousePressed(resetModel); // Add the original set of particles. resetModel(); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Style the particles. noStroke(); // Draw the particles. model(particles); } function resetModel() { // If the p5.Geometry object has already been created, // free those resources. if (particles) { freeGeometry(particles); } // Create a new p5.Geometry object with random spheres. particles = buildGeometry(createParticles); } function createParticles() { for (let i = 0; i < 60; i += 1) { // Calculate random coordinates. let x = randomGaussian(0, 20); let y = randomGaussian(0, 20); let z = randomGaussian(0, 20); push(); // Translate to the particle's coordinates. translate(x, y, z); // Draw the particle. sphere(5); pop(); } } `

p5

Shape

3D Primitives

Draws a plane.
A plane is a four-sided, flat shape with every angle measuring 90˚. It’s similar to a rectangle and offers advanced drawing features in WebGL mode.
The first parameter, `width`, is optional. If a `Number` is passed, as in `plane(20)`, it sets the plane’s width and height. By default, `width` is 50.
The second parameter, `height`, is also optional. If a `Number` is passed, as in `plane(20, 30)`, it sets the plane’s height. By default, `height` is set to the plane’s `width`.
The third parameter, `detailX`, is also optional. If a `Number` is passed, as in `plane(20, 30, 5)` it sets the number of triangle subdivisions to use along the x-axis. All 3D shapes are made by connecting triangles to form their surfaces. By default, `detailX` is 1.
The fourth parameter, `detailY`, is also optional. If a `Number` is passed, as in `plane(20, 30, 5, 7)` it sets the number of triangle subdivisions to use along the y-axis. All 3D shapes are made by connecting triangles to form their surfaces. By default, `detailY` is 1.
Note: `plane()` can only be used in WebGL mode.

method

plane

width

width of the plane.

Number

height

height of the plane.

Number

detailX

number of triangle subdivisions along the x-axis.

Integer

detailY

number of triangle subdivisions along the y-axis.

Integer

` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white plane on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the plane. plane(); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white plane on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the plane. // Set its width and height to 30. plane(30); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white plane on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the plane. // Set its width to 30 and height to 50. plane(30, 50); } `

p5

Shape

3D Primitives

Draws a box (rectangular prism).
A box is a 3D shape with six faces. Each face makes a 90˚ with four neighboring faces.
The first parameter, `width`, is optional. If a `Number` is passed, as in `box(20)`, it sets the box’s width and height. By default, `width` is 50.
The second parameter, `height`, is also optional. If a `Number` is passed, as in `box(20, 30)`, it sets the box’s height. By default, `height` is set to the box’s `width`.
The third parameter, `depth`, is also optional. If a `Number` is passed, as in `box(20, 30, 40)`, it sets the box’s depth. By default, `depth` is set to the box’s `height`.
The fourth parameter, `detailX`, is also optional. If a `Number` is passed, as in `box(20, 30, 40, 5)`, it sets the number of triangle subdivisions to use along the x-axis. All 3D shapes are made by connecting triangles to form their surfaces. By default, `detailX` is 1.
The fifth parameter, `detailY`, is also optional. If a number is passed, as in `box(20, 30, 40, 5, 7)`, it sets the number of triangle subdivisions to use along the y-axis. All 3D shapes are made by connecting triangles to form their surfaces. By default, `detailY` is 1.
Note: `box()` can only be used in WebGL mode.

method

box

width

width of the box.

Number

height

height of the box.

Number

depth

depth of the box.

Number

detailX

number of triangle subdivisions along the x-axis.

Integer

detailY

number of triangle subdivisions along the y-axis.

Integer

` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white box on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the box. box(); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white box on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the box. // Set its width and height to 30. box(30); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white box on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the box. // Set its width to 30 and height to 50. box(30, 50); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white box on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the box. // Set its width to 30, height to 50, and depth to 10. box(30, 50, 10); } `

p5

Shape

3D Primitives

Draws a sphere.
A sphere is a 3D shape with triangular faces that connect to form a round surface. Spheres with few faces look like crystals. Spheres with many faces have smooth surfaces and look like balls.
The first parameter, `radius`, is optional. If a `Number` is passed, as in `sphere(20)`, it sets the radius of the sphere. By default, `radius` is 50.
The second parameter, `detailX`, is also optional. If a `Number` is passed, as in `sphere(20, 5)`, it sets the number of triangle subdivisions to use along the x-axis. All 3D shapes are made by connecting triangles to form their surfaces. By default, `detailX` is 24.
The third parameter, `detailY`, is also optional. If a `Number` is passed, as in `sphere(20, 5, 2)`, it sets the number of triangle subdivisions to use along the y-axis. All 3D shapes are made by connecting triangles to form their surfaces. By default, `detailY` is 16.
Note: `sphere()` can only be used in WebGL mode.

method

sphere

radius

radius of the sphere. Defaults to 50.

Number

detailX

number of triangle subdivisions along the x-axis. Defaults to 24.

Integer

detailY

number of triangle subdivisions along the y-axis. Defaults to 16.

Integer

` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white sphere on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the sphere. sphere(); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white sphere on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the sphere. // Set its radius to 30. sphere(30); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white sphere on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the sphere. // Set its radius to 30. // Set its detailX to 6. sphere(30, 6); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white sphere on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the sphere. // Set its radius to 30. // Set its detailX to 24. // Set its detailY to 4. sphere(30, 24, 4); } `

p5

Shape

3D Primitives

Draws a cylinder.
A cylinder is a 3D shape with triangular faces that connect a flat bottom to a flat top. Cylinders with few faces look like boxes. Cylinders with many faces have smooth surfaces.
The first parameter, `radius`, is optional. If a `Number` is passed, as in `cylinder(20)`, it sets the radius of the cylinder’s base. By default, `radius` is 50.
The second parameter, `height`, is also optional. If a `Number` is passed, as in `cylinder(20, 30)`, it sets the cylinder’s height. By default, `height` is set to the cylinder’s `radius`.
The third parameter, `detailX`, is also optional. If a `Number` is passed, as in `cylinder(20, 30, 5)`, it sets the number of edges used to form the cylinder's top and bottom. Using more edges makes the top and bottom look more like circles. By default, `detailX` is 24.
The fourth parameter, `detailY`, is also optional. If a `Number` is passed, as in `cylinder(20, 30, 5, 2)`, it sets the number of triangle subdivisions to use along the y-axis, between cylinder's the top and bottom. All 3D shapes are made by connecting triangles to form their surfaces. By default, `detailY` is 1.
The fifth parameter, `bottomCap`, is also optional. If a `false` is passed, as in `cylinder(20, 30, 5, 2, false)` the cylinder’s bottom won’t be drawn. By default, `bottomCap` is `true`.
The sixth parameter, `topCap`, is also optional. If a `false` is passed, as in `cylinder(20, 30, 5, 2, false, false)` the cylinder’s top won’t be drawn. By default, `topCap` is `true`.
Note: `cylinder()` can only be used in WebGL mode.

method

cylinder

radius

radius of the cylinder. Defaults to 50.

Number

height

height of the cylinder. Defaults to the value of `radius`.

Number

detailX

number of edges along the top and bottom. Defaults to 24.

Integer

detailY

number of triangle subdivisions along the y-axis. Defaults to 1.

Integer

bottomCap

whether to draw the cylinder's bottom. Defaults to `true`.

Boolean

topCap

whether to draw the cylinder's top. Defaults to `true`.

Boolean

` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white cylinder on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the cylinder. cylinder(); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white cylinder on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the cylinder. // Set its radius and height to 30. cylinder(30); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white cylinder on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the cylinder. // Set its radius to 30 and height to 50. cylinder(30, 50); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white box on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the cylinder. // Set its radius to 30 and height to 50. // Set its detailX to 5. cylinder(30, 50, 5); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white cylinder on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the cylinder. // Set its radius to 30 and height to 50. // Set its detailX to 24 and detailY to 2. cylinder(30, 50, 24, 2); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white cylinder on a gray background. Its top is missing.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the cylinder. // Set its radius to 30 and height to 50. // Set its detailX to 24 and detailY to 1. // Don't draw its bottom. cylinder(30, 50, 24, 1, false); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white cylinder on a gray background. Its top and bottom are missing.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the cylinder. // Set its radius to 30 and height to 50. // Set its detailX to 24 and detailY to 1. // Don't draw its bottom or top. cylinder(30, 50, 24, 1, false, false); } `

p5

Shape

3D Primitives

Draws a cone.
A cone is a 3D shape with triangular faces that connect a flat bottom to a single point. Cones with few faces look like pyramids. Cones with many faces have smooth surfaces.
The first parameter, `radius`, is optional. If a `Number` is passed, as in `cone(20)`, it sets the radius of the cone’s base. By default, `radius` is 50.
The second parameter, `height`, is also optional. If a `Number` is passed, as in `cone(20, 30)`, it sets the cone’s height. By default, `height` is set to the cone’s `radius`.
The third parameter, `detailX`, is also optional. If a `Number` is passed, as in `cone(20, 30, 5)`, it sets the number of edges used to form the cone's base. Using more edges makes the base look more like a circle. By default, `detailX` is 24.
The fourth parameter, `detailY`, is also optional. If a `Number` is passed, as in `cone(20, 30, 5, 7)`, it sets the number of triangle subdivisions to use along the y-axis connecting the base to the tip. All 3D shapes are made by connecting triangles to form their surfaces. By default, `detailY` is 1.
The fifth parameter, `cap`, is also optional. If a `false` is passed, as in `cone(20, 30, 5, 7, false)` the cone’s base won’t be drawn. By default, `cap` is `true`.
Note: `cone()` can only be used in WebGL mode.

method

cone

radius

radius of the cone's base. Defaults to 50.

Number

height

height of the cone. Defaults to the value of `radius`.

Number

detailX

number of edges used to draw the base. Defaults to 24.

Integer

detailY

number of triangle subdivisions along the y-axis. Defaults to 1.

Integer

cap

whether to draw the cone's base. Defaults to `true`.

Boolean

` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white cone on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the cone. cone(); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white cone on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the cone. // Set its radius and height to 30. cone(30); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white cone on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the cone. // Set its radius to 30 and height to 50. cone(30, 50); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white cone on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the cone. // Set its radius to 30 and height to 50. // Set its detailX to 5. cone(30, 50, 5); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white pyramid on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the cone. // Set its radius to 30 and height to 50. // Set its detailX to 5. cone(30, 50, 5); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white cone on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the cone. // Set its radius to 30 and height to 50. // Set its detailX to 24 and detailY to 2. cone(30, 50, 24, 2); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white cone on a gray background. Its base is missing.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the cone. // Set its radius to 30 and height to 50. // Set its detailX to 24 and detailY to 1. // Don't draw its base. cone(30, 50, 24, 1, false); } `

p5

Shape

3D Primitives

Draws an ellipsoid.
An ellipsoid is a 3D shape with triangular faces that connect to form a round surface. Ellipsoids with few faces look like crystals. Ellipsoids with many faces have smooth surfaces and look like eggs. `ellipsoid()` defines a shape by its radii. This is different from ellipse() which uses diameters (width and height).
The first parameter, `radiusX`, is optional. If a `Number` is passed, as in `ellipsoid(20)`, it sets the radius of the ellipsoid along the x-axis. By default, `radiusX` is 50.
The second parameter, `radiusY`, is also optional. If a `Number` is passed, as in `ellipsoid(20, 30)`, it sets the ellipsoid’s radius along the y-axis. By default, `radiusY` is set to the ellipsoid’s `radiusX`.
The third parameter, `radiusZ`, is also optional. If a `Number` is passed, as in `ellipsoid(20, 30, 40)`, it sets the ellipsoid’s radius along the z-axis. By default, `radiusZ` is set to the ellipsoid’s `radiusY`.
The fourth parameter, `detailX`, is also optional. If a `Number` is passed, as in `ellipsoid(20, 30, 40, 5)`, it sets the number of triangle subdivisions to use along the x-axis. All 3D shapes are made by connecting triangles to form their surfaces. By default, `detailX` is 24.
The fifth parameter, `detailY`, is also optional. If a `Number` is passed, as in `ellipsoid(20, 30, 40, 5, 7)`, it sets the number of triangle subdivisions to use along the y-axis. All 3D shapes are made by connecting triangles to form their surfaces. By default, `detailY` is 16.
Note: `ellipsoid()` can only be used in WebGL mode.

method

ellipsoid

radiusX

radius of the ellipsoid along the x-axis. Defaults to 50.

Number

radiusY

radius of the ellipsoid along the y-axis. Defaults to `radiusX`.

Number

radiusZ

radius of the ellipsoid along the z-axis. Defaults to `radiusY`.

Number

detailX

number of triangle subdivisions along the x-axis. Defaults to 24.

Integer

detailY

number of triangle subdivisions along the y-axis. Defaults to 16.

Integer

` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white sphere on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the ellipsoid. // Set its radiusX to 30. ellipsoid(30); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white ellipsoid on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the ellipsoid. // Set its radiusX to 30. // Set its radiusY to 40. ellipsoid(30, 40); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white ellipsoid on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the ellipsoid. // Set its radiusX to 30. // Set its radiusY to 40. // Set its radiusZ to 50. ellipsoid(30, 40, 50); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white ellipsoid on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the ellipsoid. // Set its radiusX to 30. // Set its radiusY to 40. // Set its radiusZ to 50. // Set its detailX to 4. ellipsoid(30, 40, 50, 4); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white ellipsoid on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the ellipsoid. // Set its radiusX to 30. // Set its radiusY to 40. // Set its radiusZ to 50. // Set its detailX to 4. // Set its detailY to 3. ellipsoid(30, 40, 50, 4, 3); } `

p5

Shape

3D Primitives

Draws a torus.
A torus is a 3D shape with triangular faces that connect to form a ring. Toruses with few faces look flattened. Toruses with many faces have smooth surfaces.
The first parameter, `radius`, is optional. If a `Number` is passed, as in `torus(30)`, it sets the radius of the ring. By default, `radius` is 50.
The second parameter, `tubeRadius`, is also optional. If a `Number` is passed, as in `torus(30, 15)`, it sets the radius of the tube. By default, `tubeRadius` is 10.
The third parameter, `detailX`, is also optional. If a `Number` is passed, as in `torus(30, 15, 5)`, it sets the number of edges used to draw the hole of the torus. Using more edges makes the hole look more like a circle. By default, `detailX` is 24.
The fourth parameter, `detailY`, is also optional. If a `Number` is passed, as in `torus(30, 15, 5, 7)`, it sets the number of triangle subdivisions to use while filling in the torus’ height. By default, `detailY` is 16.
Note: `torus()` can only be used in WebGL mode.

method

torus

radius

radius of the torus. Defaults to 50.

Number

tubeRadius

radius of the tube. Defaults to 10.

Number

detailX

number of edges that form the hole. Defaults to 24.

Integer

detailY

number of triangle subdivisions along the y-axis. Defaults to 16.

Integer

` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white torus on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the torus. torus(); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white torus on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the torus. // Set its radius to 30. torus(30); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white torus on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the torus. // Set its radius to 30 and tubeRadius to 15. torus(30, 15); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white torus on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the torus. // Set its radius to 30 and tubeRadius to 15. // Set its detailX to 5. torus(30, 15, 5); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white torus on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the torus. // Set its radius to 30 and tubeRadius to 15. // Set its detailX to 5. // Set its detailY to 3. torus(30, 15, 5, 3); } `

p5

Shape

3D Primitives

Adds geometry from the renderer's immediate mode into the builder's combined geometry.

p5

Shape

Adds geometry from the renderer's retained mode into the builder's combined geometry.

p5

Shape

Cleans up the state of the renderer and returns the combined geometry that was built.

### return
p5.Geometry The flattened, combined geometry

p5

Shape

Keeps track of how many custom geometry objects have been made so that each can be assigned a unique ID.

p5

Shape

Allows the user to orbit around a 3D sketch using a mouse, trackpad, or touchscreen.
3D sketches are viewed through an imaginary camera. Calling `orbitControl()` within the draw() function allows the user to change the camera’s position:
          function draw() {
            background(200);
          
            // Enable orbiting with the mouse.
            orbitControl();
          
            // Rest of sketch.
          }
          
Left-clicking and dragging or swipe motion will rotate the camera position about the center of the sketch. Right-clicking and dragging or multi-swipe will pan the camera position without rotation. Using the mouse wheel (scrolling) or pinch in/out will move the camera further or closer from the center of the sketch.
The first three parameters, `sensitivityX`, `sensitivityY`, and `sensitivityZ`, are optional. They’re numbers that set the sketch’s sensitivity to movement along each axis. For example, calling `orbitControl(1, 2, -1)` keeps movement along the x-axis at its default value, makes the sketch twice as sensitive to movement along the y-axis, and reverses motion along the z-axis. By default, all sensitivity values are 1.
The fourth parameter, `options`, is also optional. It’s an object that changes the behavior of orbiting. For example, calling `orbitControl(1, 1, 1, options)` keeps the default sensitivity values while changing the behaviors set with `options`. The object can have the following properties:
          let options = {
            // Setting this to false makes mobile interactions smoother by
            // preventing accidental interactions with the page while orbiting.
            // By default, it's true.
            disableTouchActions: true,
          
            // Setting this to true makes the camera always rotate in the
            // direction the mouse/touch is moving.
            // By default, it's false.
            freeRotation: false
          };
          
          orbitControl(1, 1, 1, options);
          

method

orbitControl

sensitivityX

sensitivity to movement along the x-axis. Defaults to 1.

Number

sensitivityY

sensitivity to movement along the y-axis. Defaults to 1.

Number

sensitivityZ

sensitivity to movement along the z-axis. Defaults to 1.

Number

options

object with two optional properties, `disableTouchActions` and `freeRotation`. Both are `Boolean`s. `disableTouchActions` defaults to `true` and `freeRotation` defaults to `false`.

Object

` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A multicolor box on a gray background. The camera angle changes when the user interacts using a mouse, trackpad, or touchscreen.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Style the box. normalMaterial(); // Draw the box. box(30, 50); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A multicolor box on a gray background. The camera angle changes when the user interacts using a mouse, trackpad, or touchscreen.'); } function draw() { background(200); // Enable orbiting with the mouse. // Make the interactions 3X sensitive. orbitControl(3, 3, 3); // Style the box. normalMaterial(); // Draw the box. box(30, 50); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A multicolor box on a gray background. The camera angle changes when the user interacts using a mouse, trackpad, or touchscreen.'); } function draw() { background(200); // Create an options object. let options = { disableTouchActions: false, freeRotation: true }; // Enable orbiting with the mouse. // Prevent accidental touch actions on touchscreen devices // and enable free rotation. orbitControl(1, 1, 1, options); // Style the box. normalMaterial(); // Draw the box. box(30, 50); } `

p5

3D

Interaction

Adds a grid and an axes icon to clarify orientation in 3D sketches.
`debugMode()` adds a grid that shows where the “ground” is in a sketch. By default, the grid will run through the origin `(0, 0, 0)` of the sketch along the XZ plane. `debugMode()` also adds an axes icon that points along the positive x-, y-, and z-axes. Calling `debugMode()` displays the grid and axes icon with their default size and position.
There are four ways to call `debugMode()` with optional parameters to customize the debugging environment.
The first way to call `debugMode()` has one parameter, `mode`. If the system constant `GRID` is passed, as in `debugMode(GRID)`, then the grid will be displayed and the axes icon will be hidden. If the constant `AXES` is passed, as in `debugMode(AXES)`, then the axes icon will be displayed and the grid will be hidden.
The second way to call `debugMode()` has six parameters. The first parameter, `mode`, selects either `GRID` or `AXES` to be displayed. The next five parameters, `gridSize`, `gridDivisions`, `xOff`, `yOff`, and `zOff` are optional. They’re numbers that set the appearance of the grid (`gridSize` and `gridDivisions`) and the placement of the axes icon (`xOff`, `yOff`, and `zOff`). For example, calling `debugMode(20, 5, 10, 10, 10)` sets the `gridSize` to 20 pixels, the number of `gridDivisions` to 5, and offsets the axes icon by 10 pixels along the x-, y-, and z-axes.
The third way to call `debugMode()` has five parameters. The first parameter, `mode`, selects either `GRID` or `AXES` to be displayed. The next four parameters, `axesSize`, `xOff`, `yOff`, and `zOff` are optional. They’re numbers that set the appearance of the size of the axes icon (`axesSize`) and its placement (`xOff`, `yOff`, and `zOff`).
The fourth way to call `debugMode()` has nine optional parameters. The first five parameters, `gridSize`, `gridDivisions`, `gridXOff`, `gridYOff`, and `gridZOff` are numbers that set the appearance of the grid. For example, calling `debugMode(100, 5, 0, 0, 0)` sets the `gridSize` to 100, the number of `gridDivisions` to 5, and sets all the offsets to 0 so that the grid is centered at the origin. The next four parameters, `axesSize`, `xOff`, `yOff`, and `zOff` are numbers that set the appearance of the size of the axes icon (`axesSize`) and its placement (`axesXOff`, `axesYOff`, and `axesZOff`). For example, calling `debugMode(100, 5, 0, 0, 0, 50, 10, 10, 10)` sets the `gridSize` to 100, the number of `gridDivisions` to 5, and sets all the offsets to 0 so that the grid is centered at the origin. It then sets the `axesSize` to 50 and offsets the icon 10 pixels along each axis.

method

debugMode

` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); // Enable debug mode. debugMode(); describe('A multicolor box on a gray background. A grid and axes icon are displayed near the box.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Style the box. normalMaterial(); // Draw the box. box(20, 40); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); // Enable debug mode. // Only display the axes icon. debugMode(AXES); describe('A multicolor box on a gray background. A grid and axes icon are displayed near the box.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Style the box. normalMaterial(); // Draw the box. box(20, 40); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); // Enable debug mode. // Only display the grid and customize it: // - size: 50 // - divisions: 10 // - offsets: 0, 20, 0 debugMode(GRID, 50, 10, 0, 20, 0); describe('A multicolor box on a gray background. A grid is displayed below the box.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Style the box. normalMaterial(); // Draw the box. box(20, 40); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); // Enable debug mode. // Display the grid and axes icon and customize them: // Grid // ---- // - size: 50 // - divisions: 10 // - offsets: 0, 20, 0 // Axes // ---- // - size: 50 // - offsets: 0, 0, 0 debugMode(50, 10, 0, 20, 0, 50, 0, 0, 0); describe('A multicolor box on a gray background. A grid is displayed below the box. An axes icon is displayed at the center of the box.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Style the box. normalMaterial(); // Draw the box. box(20, 40); } `

p5

3D

Interaction

mode

either GRID or AXES

Constant

mode



Constant

gridSize

side length of the grid.

Number

gridDivisions

number of divisions in the grid.

Number

xOff

offset from origin along the x-axis.

Number

yOff

offset from origin along the y-axis.

Number

zOff

offset from origin along the z-axis.

Number

mode



Constant

axesSize

length of axes icon markers.

Number

xOff



Number

yOff



Number

zOff



Number

gridSize



Number

gridDivisions



Number

gridXOff

grid offset from the origin along the x-axis.

Number

gridYOff

grid offset from the origin along the y-axis.

Number

gridZOff

grid offset from the origin along the z-axis.

Number

axesSize



Number

axesXOff

axes icon offset from the origin along the x-axis.

Number

axesYOff

axes icon offset from the origin along the y-axis.

Number

axesZOff

axes icon offset from the origin along the z-axis.

Number

Turns off debugMode() in a 3D sketch.

method

noDebugMode

` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); // Enable debug mode. debugMode(); describe('A multicolor box on a gray background. A grid and axes icon are displayed near the box. They disappear when the user double-clicks.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Style the box. normalMaterial(); // Draw the box. box(20, 40); } // Disable debug mode when the user double-clicks. function doubleClicked() { noDebugMode(); } `

p5

3D

Interaction

Creates a light that shines from all directions.
Ambient light does not come from one direction. Instead, 3D shapes are lit evenly from all sides. Ambient lights are almost always used in combination with other types of lights.
There are three ways to call `ambientLight()` with optional parameters to set the light’s color.
The first way to call `ambientLight()` has two parameters, `gray` and `alpha`. `alpha` is optional. Grayscale and alpha values between 0 and 255 can be passed to set the ambient light’s color, as in `ambientLight(50)` or `ambientLight(50, 30)`.
The second way to call `ambientLight()` has one parameter, color. A p5.Color object, an array of color values, or a CSS color string, as in `ambientLight('magenta')`, can be passed to set the ambient light’s color.
The third way to call `ambientLight()` has four parameters, `v1`, `v2`, `v3`, and `alpha`. `alpha` is optional. RGBA, HSBA, or HSLA values can be passed to set the ambient light’s colors, as in `ambientLight(255, 0, 0)` or `ambientLight(255, 0, 0, 30)`. Color values will be interpreted using the current colorMode().

method

ambientLight

` // Click and drag the mouse to view the scene from different angles. // Double-click the canvas to turn on the light. let isLit = false; function setup() { createCanvas(100, 100, WEBGL); describe('A sphere drawn against a gray background. The sphere appears to change color when the user double-clicks.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Control the light. if (isLit === true) { // Use a grayscale value of 80. ambientLight(80); } // Draw the sphere. sphere(30); } // Turn on the ambient light when the user double-clicks. function doubleClicked() { isLit = true; } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A faded magenta sphere drawn against a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. // Use a p5.Color object. let c = color('orchid'); ambientLight(c); // Draw the sphere. sphere(); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A faded magenta sphere drawn against a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. // Use a CSS color string. ambientLight('#DA70D6'); // Draw the sphere. sphere(30); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A faded magenta sphere drawn against a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. // Use RGB values ambientLight(218, 112, 214); // Draw the sphere. sphere(30); } `

p5

3D

Lights

v1

red or hue value in the current colorMode().

Number

v2

green or saturation value in the current colorMode().

Number

v3

blue, brightness, or lightness value in the current colorMode().

Number

alpha

alpha (transparency) value in the current colorMode().

Number

gray

grayscale value between 0 and 255.

Number

alpha



Number

value

color as a CSS string.

String

values

color as an array of RGBA, HSBA, or HSLA values.

Number[]

color

color as a p5.Color object.

p5.Color

Sets the specular color for lights.
`specularColor()` affects lights that bounce off a surface in a preferred direction. These lights include directionalLight(), pointLight(), and spotLight(). The function helps to create highlights on p5.Geometry objects that are styled with specularMaterial(). If a geometry does not use specularMaterial(), then `specularColor()` will have no effect.
Note: `specularColor()` doesn’t affect lights that bounce in all directions, including ambientLight() and imageLight().
There are three ways to call `specularColor()` with optional parameters to set the specular highlight color.
The first way to call `specularColor()` has two optional parameters, `gray` and `alpha`. Grayscale and alpha values between 0 and 255, as in `specularColor(50)` or `specularColor(50, 80)`, can be passed to set the specular highlight color.
The second way to call `specularColor()` has one optional parameter, `color`. A p5.Color object, an array of color values, or a CSS color string can be passed to set the specular highlight color.
The third way to call `specularColor()` has four optional parameters, `v1`, `v2`, `v3`, and `alpha`. RGBA, HSBA, or HSLA values, as in `specularColor(255, 0, 0, 80)`, can be passed to set the specular highlight color. Color values will be interpreted using the current colorMode().

method

specularColor

` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white sphere drawn on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // No specular color. // Draw the sphere. sphere(30); } `
` // Click and drag the mouse to view the scene from different angles. // Double-click the canvas to add a point light. let isLit = false; function setup() { createCanvas(100, 100, WEBGL); describe('A sphere drawn on a gray background. A spotlight starts shining when the user double-clicks.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Style the sphere. noStroke(); specularColor(100); specularMaterial(255, 255, 255); // Control the light. if (isLit === true) { // Add a white point light from the top-right. pointLight(255, 255, 255, 30, -20, 40); } // Draw the sphere. sphere(30); } // Turn on the point light when the user double-clicks. function doubleClicked() { isLit = true; } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A black sphere drawn on a gray background. An area on the surface of the sphere is highlighted in blue.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Add a specular highlight. // Use a p5.Color object. let c = color('dodgerblue'); specularColor(c); // Add a white point light from the top-right. pointLight(255, 255, 255, 30, -20, 40); // Style the sphere. noStroke(); // Add a white specular material. specularMaterial(255, 255, 255); // Draw the sphere. sphere(30); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A black sphere drawn on a gray background. An area on the surface of the sphere is highlighted in blue.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Add a specular highlight. // Use a CSS color string. specularColor('#1E90FF'); // Add a white point light from the top-right. pointLight(255, 255, 255, 30, -20, 40); // Style the sphere. noStroke(); // Add a white specular material. specularMaterial(255, 255, 255); // Draw the sphere. sphere(30); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A black sphere drawn on a gray background. An area on the surface of the sphere is highlighted in blue.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Add a specular highlight. // Use RGB values. specularColor(30, 144, 255); // Add a white point light from the top-right. pointLight(255, 255, 255, 30, -20, 40); // Style the sphere. noStroke(); // Add a white specular material. specularMaterial(255, 255, 255); // Draw the sphere. sphere(30); } `

p5

3D

Lights

v1

red or hue value in the current colorMode().

Number

v2

green or saturation value in the current colorMode().

Number

v3

blue, brightness, or lightness value in the current colorMode().

Number

gray

grayscale value between 0 and 255.

Number

value

color as a CSS string.

String

values

color as an array of RGBA, HSBA, or HSLA values.

Number[]

color

color as a p5.Color object.

p5.Color

Creates a light that shines in one direction.
Directional lights don’t shine from a specific point. They’re like a sun that shines from somewhere offscreen. The light’s direction is set using three `(x, y, z)` values between -1 and 1. For example, setting a light’s direction as `(1, 0, 0)` will light p5.Geometry objects from the left since the light faces directly to the right. A maximum of 5 directional lights can be active at once.
There are four ways to call `directionalLight()` with parameters to set the light’s color and direction.
The first way to call `directionalLight()` has six parameters. The first three parameters, `v1`, `v2`, and `v3`, set the light’s color using the current colorMode(). The last three parameters, `x`, `y`, and `z`, set the light’s direction. For example, `directionalLight(255, 0, 0, 1, 0, 0)` creates a red `(255, 0, 0)` light that shines to the right `(1, 0, 0)`.
The second way to call `directionalLight()` has four parameters. The first three parameters, `v1`, `v2`, and `v3`, set the light’s color using the current colorMode(). The last parameter, `direction` sets the light’s direction using a p5.Vector object. For example, `directionalLight(255, 0, 0, lightDir)` creates a red `(255, 0, 0)` light that shines in the direction the `lightDir` vector points.
The third way to call `directionalLight()` has four parameters. The first parameter, `color`, sets the light’s color using a p5.Color object or an array of color values. The last three parameters, `x`, `y`, and `z`, set the light’s direction. For example, `directionalLight(myColor, 1, 0, 0)` creates a light that shines to the right `(1, 0, 0)` with the color value of `myColor`.
The fourth way to call `directionalLight()` has two parameters. The first parameter, `color`, sets the light’s color using a p5.Color object or an array of color values. The second parameter, `direction`, sets the light’s direction using a p5.Color object. For example, `directionalLight(myColor, lightDir)` creates a light that shines in the direction the `lightDir` vector points with the color value of `myColor`.

method

directionalLight

` // Click and drag the mouse to view the scene from different angles. // Double-click to turn on the directional light. let isLit = false; function setup() { createCanvas(100, 100, WEBGL); describe('A sphere drawn on a gray background. A red light starts shining from above when the user double-clicks.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Control the light. if (isLit === true) { // Add a red directional light from above. // Use RGB values and XYZ directions. directionalLight(255, 0, 0, 0, 1, 0); } // Style the sphere. noStroke(); // Draw the sphere. sphere(30); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A sphere drawn on a gray background. The top of the sphere appears bright red. The color gets darker toward the bottom.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Add a red directional light from above. // Use a p5.Color object and XYZ directions. let c = color(255, 0, 0); directionalLight(c, 0, 1, 0); // Style the sphere. noStroke(); // Draw the sphere. sphere(30); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A sphere drawn on a gray background. The top of the sphere appears bright red. The color gets darker toward the bottom.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Add a red directional light from above. // Use a p5.Color object and a p5.Vector object. let c = color(255, 0, 0); let lightDir = createVector(0, 1, 0); directionalLight(c, lightDir); // Style the sphere. noStroke(); // Draw the sphere. sphere(30); } `

p5

3D

Lights

v1

red or hue value in the current colorMode().

Number

v2

green or saturation value in the current colorMode().

Number

v3

blue, brightness, or lightness value in the current colorMode().

Number

x

x-component of the light's direction between -1 and 1.

Number

y

y-component of the light's direction between -1 and 1.

Number

z

z-component of the light's direction between -1 and 1.

Number

v1



Number

v2



Number

v3



Number

direction

direction of the light as a p5.Vector object.

p5.Vector

color

color as a p5.Color object, an array of color values, or as a CSS string.

p5.Color|Number[]|String

x



Number

y



Number

z



Number

color



p5.Color|Number[]|String

direction



p5.Vector

Creates a light that shines from a point in all directions.
Point lights are like light bulbs that shine in all directions. They can be placed at different positions to achieve different lighting effects. A maximum of 5 point lights can be active at once.
There are four ways to call `pointLight()` with parameters to set the light’s color and position.
The first way to call `pointLight()` has six parameters. The first three parameters, `v1`, `v2`, and `v3`, set the light’s color using the current colorMode(). The last three parameters, `x`, `y`, and `z`, set the light’s position. For example, `pointLight(255, 0, 0, 50, 0, 0)` creates a red `(255, 0, 0)` light that shines from the coordinates `(50, 0, 0)`.
The second way to call `pointLight()` has four parameters. The first three parameters, `v1`, `v2`, and `v3`, set the light’s color using the current colorMode(). The last parameter, position sets the light’s position using a p5.Vector object. For example, `pointLight(255, 0, 0, lightPos)` creates a red `(255, 0, 0)` light that shines from the position set by the `lightPos` vector.
The third way to call `pointLight()` has four parameters. The first parameter, `color`, sets the light’s color using a p5.Color object or an array of color values. The last three parameters, `x`, `y`, and `z`, set the light’s position. For example, `directionalLight(myColor, 50, 0, 0)` creates a light that shines from the coordinates `(50, 0, 0)` with the color value of `myColor`.
The fourth way to call `pointLight()` has two parameters. The first parameter, `color`, sets the light’s color using a p5.Color object or an array of color values. The second parameter, `position`, sets the light’s position using a p5.Vector object. For example, `directionalLight(myColor, lightPos)` creates a light that shines from the position set by the `lightPos` vector with the color value of `myColor`.

method

pointLight

` // Click and drag the mouse to view the scene from different angles. // Double-click to turn on the point light. let isLit = false; function setup() { createCanvas(100, 100, WEBGL); describe('A sphere drawn on a gray background. A red light starts shining from above when the user double-clicks.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Control the light. if (isLit === true) { // Add a red point light from above. // Use RGB values and XYZ coordinates. pointLight(255, 0, 0, 0, -150, 0); } // Style the sphere. noStroke(); // Draw the sphere. sphere(30); } // Turn on the point light when the user double-clicks. function doubleClicked() { isLit = true; } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A sphere drawn on a gray background. The top of the sphere appears bright red. The color gets darker toward the bottom.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Add a red point light from above. // Use a p5.Color object and XYZ directions. let c = color(255, 0, 0); pointLight(c, 0, -150, 0); // Style the sphere. noStroke(); // Draw the sphere. sphere(30); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A sphere drawn on a gray background. The top of the sphere appears bright red. The color gets darker toward the bottom.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Add a red point light from above. // Use a p5.Color object and a p5.Vector object. let c = color(255, 0, 0); let lightPos = createVector(0, -150, 0); pointLight(c, lightPos); // Style the sphere. noStroke(); // Draw the sphere. sphere(30); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('Four spheres arranged in a square and drawn on a gray background. The spheres appear bright red toward the center of the square. The color gets darker toward the corners of the square.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Add a red point light that points to the center of the scene. // Use a p5.Color object and a p5.Vector object. let c = color(255, 0, 0); let lightPos = createVector(0, 0, 65); pointLight(c, lightPos); // Style the spheres. noStroke(); // Draw a sphere up and to the left. push(); translate(-25, -25, 25); sphere(10); pop(); // Draw a box up and to the right. push(); translate(25, -25, 25); sphere(10); pop(); // Draw a sphere down and to the left. push(); translate(-25, 25, 25); sphere(10); pop(); // Draw a box down and to the right. push(); translate(25, 25, 25); sphere(10); pop(); } `

p5

3D

Lights

v1

red or hue value in the current colorMode().

Number

v2

green or saturation value in the current colorMode().

Number

v3

blue, brightness, or lightness value in the current colorMode().

Number

x

x-coordinate of the light.

Number

y

y-coordinate of the light.

Number

z

z-coordinate of the light.

Number

v1



Number

v2



Number

v3



Number

position

position of the light as a p5.Vector object.

p5.Vector

color

color as a p5.Color object, an array of color values, or a CSS string.

p5.Color|Number[]|String

x



Number

y



Number

z



Number

color



p5.Color|Number[]|String

position



p5.Vector

Creates an ambient light from an image.
`imageLight()` simulates a light shining from all directions. The effect is like placing the sketch at the center of a giant sphere that uses the image as its texture. The image's diffuse light will be affected by fill() and the specular reflections will be affected by specularMaterial() and shininess().
The parameter, `img`, is the p5.Image object to use as the light source.

method

imageLight

img

image to use as the light source.

p5.image

` // Click and drag the mouse to view the scene from different angles. let img; // Load an image and create a p5.Image object. function preload() { img = loadImage('assets/outdoor_spheremap.jpg'); } function setup() { createCanvas(100, 100, WEBGL); describe('A sphere floating above a landscape. The surface of the sphere reflects the landscape.'); } function draw() { // Enable orbiting with the mouse. orbitControl(); // Draw the image as a panorama (360˚ background). panorama(img); // Add a soft ambient light. ambientLight(50); // Add light from the image. imageLight(img); // Style the sphere. specularMaterial(20); shininess(100); noStroke(); // Draw the sphere. sphere(30); } `

p5

3D

Lights

Creates an immersive 3D background.
`panorama()` transforms images containing 360˚ content, such as maps or HDRIs, into immersive 3D backgrounds that surround a sketch. Exploring the space requires changing the camera's perspective with functions such as orbitControl() or camera().

method

panorama

img

360˚ image to use as the background.

p5.Image

` // Click and drag the mouse to view the scene from different angles. let img; // Load an image and create a p5.Image object. function preload() { img = loadImage('assets/outdoor_spheremap.jpg'); } function setup() { createCanvas(100 ,100 ,WEBGL); describe('A sphere floating above a landscape. The surface of the sphere reflects the landscape. The full landscape is viewable in 3D as the user drags the mouse.'); } function draw() { // Add the panorama. panorama(img); // Enable orbiting with the mouse. orbitControl(); // Use the image as a light source. imageLight(img); // Style the sphere. noStroke(); specularMaterial(50); shininess(200); metalness(100); // Draw the sphere. sphere(30); } `

p5

3D

Lights

Places an ambient and directional light in the scene. The lights are set to ambientLight(128, 128, 128) and directionalLight(128, 128, 128, 0, 0, -1).
Note: lights need to be called (whether directly or indirectly) within draw() to remain persistent in a looping program. Placing them in setup() will cause them to only have an effect the first time through the loop.

method

lights

` // Click and drag the mouse to view the scene from different angles. // Double-click to turn on the lights. let isLit = false; function setup() { createCanvas(100, 100, WEBGL); describe('A white box drawn against a gray background. The quality of the light changes when the user double-clicks.'); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Control the lights. if (isLit === true) { lights(); } // Draw the box. box(); } // Turn on the lights when the user double-clicks. function doubleClicked() { isLit = true; } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A white box drawn against a gray background.'); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. ambientLight(128, 128, 128); directionalLight(128, 128, 128, 0, 0, -1); // Draw the box. box(); } `

p5

3D

Lights

Sets the falloff rate for pointLight() and spotLight().
A light’s falloff describes the intensity of its beam at a distance. For example, a lantern has a slow falloff, a flashlight has a medium falloff, and a laser pointer has a sharp falloff.
`lightFalloff()` has three parameters, `constant`, `linear`, and `quadratic`. They’re numbers used to calculate falloff at a distance, `d`, as follows:
`falloff = 1 / (constant + d * linear + (d * d) * quadratic)`
Note: `constant`, `linear`, and `quadratic` should always be set to values greater than 0.

method

lightFalloff

constant

constant value for calculating falloff.

Number

linear

linear value for calculating falloff.

Number

quadratic

quadratic value for calculating falloff.

Number

` // Click and drag the mouse to view the scene from different angles. // Double-click to change the falloff rate. let useFalloff = false; function setup() { createCanvas(100, 100, WEBGL); describe('A sphere drawn against a gray background. The intensity of the light changes when the user double-clicks.'); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Set the light falloff. if (useFalloff === true) { lightFalloff(2, 0, 0); } // Add a white point light from the front. pointLight(255, 255, 255, 0, 0, 100); // Style the sphere. noStroke(); // Draw the sphere. sphere(30); } // Change the falloff value when the user double-clicks. function doubleClicked() { useFalloff = true; } `

p5

3D

Lights

Creates a light that shines from a point in one direction.
Spot lights are like flashlights that shine in one direction creating a cone of light. The shape of the cone can be controlled using the angle and concentration parameters. A maximum of 5 spot lights can be active at once.
There are eight ways to call `spotLight()` with parameters to set the light’s color, position, direction. For example, `spotLight(255, 0, 0, 0, 0, 0, 1, 0, 0)` creates a red `(255, 0, 0)` light at the origin `(0, 0, 0)` that points to the right `(1, 0, 0)`.
The `angle` parameter is optional. It sets the radius of the light cone. For example, `spotLight(255, 0, 0, 0, 0, 0, 1, 0, 0, PI / 16)` creates a red `(255, 0, 0)` light at the origin `(0, 0, 0)` that points to the right `(1, 0, 0)` with an angle of `PI / 16` radians. By default, `angle` is `PI / 3` radians.
The `concentration` parameter is also optional. It focuses the light towards the center of the light cone. For example, `spotLight(255, 0, 0, 0, 0, 0, 1, 0, 0, PI / 16, 50)` creates a red `(255, 0, 0)` light at the origin `(0, 0, 0)` that points to the right `(1, 0, 0)` with an angle of `PI / 16` radians at concentration of 50. By default, `concentration` is 100.

method

spotLight

` // Click and drag the mouse to view the scene from different angles. // Double-click to adjust the spotlight. let isLit = false; function setup() { createCanvas(100, 100, WEBGL); describe('A white sphere drawn on a gray background. A red spotlight starts shining when the user double-clicks.'); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Control the spotlight. if (isLit === true) { // Add a red spot light that shines into the screen. // Set its angle to PI / 32 radians. spotLight(255, 0, 0, 0, 0, 100, 0, 0, -1, PI / 32); } // Draw the sphere. sphere(30); } // Turn on the spotlight when the user double-clicks. function doubleClicked() { isLit = true; } `
` // Click and drag the mouse to view the scene from different angles. // Double-click to adjust the spotlight. let isLit = false; function setup() { createCanvas(100, 100, WEBGL); describe('A white sphere drawn on a gray background. A red spotlight starts shining when the user double-clicks.'); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Control the spotlight. if (isLit === true) { // Add a red spot light that shines into the screen. // Set its angle to PI / 3 radians (default). // Set its concentration to 1000. let c = color(255, 0, 0); let position = createVector(0, 0, 100); let direction = createVector(0, 0, -1); spotLight(c, position, direction, PI / 3, 1000); } // Draw the sphere. sphere(30); } // Turn on the spotlight when the user double-clicks. function doubleClicked() { isLit = true; } `

p5

3D

Lights

v1

red or hue value in the current colorMode().

Number

v2

green or saturation value in the current colorMode().

Number

v3

blue, brightness, or lightness value in the current colorMode().

Number

x

x-coordinate of the light.

Number

y

y-coordinate of the light.

Number

z

z-coordinate of the light.

Number

rx

x-component of light direction between -1 and 1.

Number

ry

y-component of light direction between -1 and 1.

Number

rz

z-component of light direction between -1 and 1.

Number

angle

angle of the light cone. Defaults to `PI / 3`.

Number

concentration

concentration of the light. Defaults to 100.

Number

color

color as a p5.Color object, an array of color values, or a CSS string.

p5.Color|Number[]|String

position

position of the light as a p5.Vector object.

p5.Vector

direction

direction of light as a p5.Vector object.

p5.Vector

angle



Number

concentration



Number

v1



Number

v2



Number

v3



Number

position



p5.Vector

direction



p5.Vector

angle



Number

concentration



Number

color



p5.Color|Number[]|String

x



Number

y



Number

z



Number

direction



p5.Vector

angle



Number

concentration



Number

color



p5.Color|Number[]|String

position



p5.Vector

rx



Number

ry



Number

rz



Number

angle



Number

concentration



Number

v1



Number

v2



Number

v3



Number

x



Number

y



Number

z



Number

direction



p5.Vector

angle



Number

concentration



Number

v1



Number

v2



Number

v3



Number

position



p5.Vector

rx



Number

ry



Number

rz



Number

angle



Number

concentration



Number

color



p5.Color|Number[]|String

x



Number

y



Number

z



Number

rx



Number

ry



Number

rz



Number

angle



Number

concentration



Number

Removes all lights from the sketch.
Calling `noLights()` removes any lights created with lights(), ambientLight(), directionalLight(), pointLight(), or spotLight(). These functions may be called after `noLights()` to create a new lighting scheme.

method

noLights

` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('Two spheres drawn against a gray background. The top sphere is white and the bottom sphere is red.'); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Style the spheres. noStroke(); // Draw the top sphere. push(); translate(0, -25, 0); sphere(20); pop(); // Turn off the lights. noLights(); // Add a red directional light that points into the screen. directionalLight(255, 0, 0, 0, 0, -1); // Draw the bottom sphere. push(); translate(0, 25, 0); sphere(20); pop(); } `

p5

3D

Lights

Loads a 3D model to create a p5.Geometry object.
`loadModel()` can load 3D models from OBJ and STL files. Once the model is loaded, it can be displayed with the model() function, as in `model(shape)`.
There are three ways to call `loadModel()` with optional parameters to help process the model.
The first parameter, `path`, is always a `String` with the path to the file. Paths to local files should be relative, as in `loadModel('assets/model.obj')`. URLs such as `'https://example.com/model.obj'` may be blocked due to browser security.
Note: When loading a `.obj` file that references materials stored in `.mtl` files, p5.js will attempt to load and apply those materials. To ensure that the `.obj` file reads the `.mtl` file correctly include the `.mtl` file alongside it.
The first way to call `loadModel()` has three optional parameters after the file path. The first optional parameter, `successCallback`, is a function to call once the model loads. For example, `loadModel('assets/model.obj', handleModel)` will call the `handleModel()` function once the model loads. The second optional parameter, `failureCallback`, is a function to call if the model fails to load. For example, `loadModel('assets/model.obj', handleModel, handleFailure)` will call the `handleFailure()` function if an error occurs while loading. The third optional parameter, `fileType`, is the model’s file extension as a string. For example, `loadModel('assets/model', handleModel, handleFailure, '.obj')` will try to load the file model as a `.obj` file.
The second way to call `loadModel()` has four optional parameters after the file path. The first optional parameter is a `Boolean` value. If `true` is passed, as in `loadModel('assets/model.obj', true)`, then the model will be resized to ensure it fits the canvas. The next three parameters are `successCallback`, `failureCallback`, and `fileType` as described above.
The third way to call `loadModel()` has one optional parameter after the file path. The optional parameter, `options`, is an `Object` with options, as in `loadModel('assets/model.obj', options)`. The `options` object can have the following properties:
          let options = {
            // Enables standardized size scaling during loading if set to true.
            normalize: true,
          
            // Function to call once the model loads.
            successCallback: handleModel,
          
            // Function to call if an error occurs while loading.
            failureCallback: handleError,
          
            // Model's file extension.
            fileType: '.stl',
          
            // Flips the U texture coordinates of the model.
            flipU: false,
          
            // Flips the V texture coordinates of the model.
            flipV: false
          };
          
          // Pass the options object to loadModel().
          loadModel('assets/model.obj', options);
          
Models can take time to load. Calling `loadModel()` in preload() ensures models load before they're used in setup() or draw().
Note: There’s no support for colored STL files. STL files with color will be rendered without color.

method

loadModel

### return
the p5.Geometry object

p5.Geometry

` // Click and drag the mouse to view the scene from different angles. let shape; // Load the file and create a p5.Geometry object. function preload() { shape = loadModel('assets/teapot.obj'); } function setup() { createCanvas(100, 100, WEBGL); describe('A white teapot drawn against a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the shape. model(shape); } `
` // Click and drag the mouse to view the scene from different angles. let shape; // Load the file and create a p5.Geometry object. // Normalize the geometry's size to fit the canvas. function preload() { shape = loadModel('assets/teapot.obj', true); } function setup() { createCanvas(100, 100, WEBGL); describe('A white teapot drawn against a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the shape. model(shape); } `
` // Click and drag the mouse to view the scene from different angles. let shape; // Load the file and create a p5.Geometry object. function preload() { loadModel('assets/teapot.obj', true, handleModel); } function setup() { createCanvas(100, 100, WEBGL); describe('A white teapot drawn against a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the shape. model(shape); } // Set the shape variable and log the geometry's // ID to the console. function handleModel(data) { shape = data; console.log(shape.gid); } `
` // Click and drag the mouse to view the scene from different angles. let shape; // Load the file and create a p5.Geometry object. function preload() { loadModel('assets/wrong.obj', true, handleModel, handleError); } function setup() { createCanvas(100, 100, WEBGL); describe('A white teapot drawn against a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the shape. model(shape); } // Set the shape variable and print the geometry's // ID to the console. function handleModel(data) { shape = data; console.log(shape.gid); } // Print an error message if the file doesn't load. function handleError(error) { console.error('Oops!', error); } `
` // Click and drag the mouse to view the scene from different angles. let shape; // Load the file and create a p5.Geometry object. function preload() { loadModel('assets/teapot.obj', true, handleModel, handleError, '.obj'); } function setup() { createCanvas(100, 100, WEBGL); describe('A white teapot drawn against a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the shape. model(shape); } // Set the shape variable and print the geometry's // ID to the console. function handleModel(data) { shape = data; console.log(shape.gid); } // Print an error message if the file doesn't load. function handleError(error) { console.error('Oops!', error); } `
` // Click and drag the mouse to view the scene from different angles. let shape; let options = { normalize: true, successCallback: handleModel, failureCallback: handleError, fileType: '.obj' }; // Load the file and create a p5.Geometry object. function preload() { loadModel('assets/teapot.obj', options); } function setup() { createCanvas(100, 100, WEBGL); describe('A white teapot drawn against a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the shape. model(shape); } // Set the shape variable and print the geometry's // ID to the console. function handleModel(data) { shape = data; console.log(shape.gid); } // Print an error message if the file doesn't load. function handleError(error) { console.error('Oops!', error); } `

p5

Shape

3D Models

path

path of the model to be loaded.

String

normalize

if `true`, scale the model to fit the canvas.

Boolean

successCallback

function to call once the model is loaded. Will be passed the p5.Geometry object.

function(p5.Geometry)

failureCallback

function to call if the model fails to load. Will be passed an `Error` event object.

Function(Event)

fileType

model’s file extension. Either `'.obj'` or `'.stl'`.

String

##### return
the p5.Geometry object

p5.Geometry

path



String

successCallback



function(p5.Geometry)

failureCallback



Function(Event)

fileType



String

##### return
new p5.Geometry object.

p5.Geometry

path



String

options

loading options.

Object

successCallback



function(p5.Geometry)

failureCallback



Function(Event)

fileType



String

normalize



Boolean

flipU



Boolean

flipV



Boolean

##### return
new p5.Geometry object.

p5.Geometry

Parse OBJ lines into model. For reference, this is what a simple model of a square might look like:
v -0.5 -0.5 0.5 v -0.5 -0.5 -0.5 v -0.5 0.5 -0.5 v -0.5 0.5 0.5
f 4 3 2 1

p5

Shape

3D Models

STL files can be of two types, ASCII and Binary,
We need to convert the arrayBuffer to an array of strings, to parse it as an ASCII file.

p5

Shape

3D Models

This function checks if the file is in ASCII format or in Binary format
It is done by searching keyword `solid` at the start of the file.
An ASCII STL data must begin with `solid` as the first six bytes. However, ASCII STLs lacking the SPACE after the `d` are known to be plentiful. So, check the first 5 bytes for `solid`.
Several encodings, such as UTF-8, precede the text with up to 5 bytes: https://en.wikipedia.org/wiki/Byte_order_mark#Byte_order_marks_by_encoding Search for `solid` to start anywhere after those prefixes.

p5

Shape

3D Models

This function matches the `query` at the provided `offset`

p5

Shape

3D Models

This function parses the Binary STL files. https://en.wikipedia.org/wiki/STL_%28file_format%29#Binary_STL
Currently there is no support for the colors provided in STL files.

p5

Shape

3D Models

ASCII STL file starts with `solid 'nameOfFile'` Then contain the normal of the face, starting with `facet normal` Next contain a keyword indicating the start of face vertex, `outer loop` Next comes the three vertex, starting with `vertex x y z` Vertices ends with `endloop` Face ends with `endfacet` Next face starts with `facet normal` The end of the file is indicated by `endsolid`

p5

Shape

3D Models

Draws a p5.Geometry object to the canvas.
The parameter, `model`, is the p5.Geometry object to draw. p5.Geometry objects can be built with buildGeometry(), or beginGeometry() and endGeometry(). They can also be loaded from a file with loadGeometry().
Note: `model()` can only be used in WebGL mode.

method

model

model

3D shape to be drawn.

p5.Geometry

` // Click and drag the mouse to view the scene from different angles. let shape; function setup() { createCanvas(100, 100, WEBGL); // Create the p5.Geometry object. shape = buildGeometry(createShape); describe('A white cone drawn on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the p5.Geometry object. model(shape); } // Create p5.Geometry object from a single cone. function createShape() { cone(); } `
` // Click and drag the mouse to view the scene from different angles. let shape; function setup() { createCanvas(100, 100, WEBGL); // Create the p5.Geometry object. shape = buildGeometry(createArrow); describe('Two white arrows drawn on a gray background. The arrow on the right rotates slowly.'); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Style the arrows. noStroke(); // Draw the p5.Geometry object. model(shape); // Translate and rotate the coordinate system. translate(30, 0, 0); rotateZ(frameCount * 0.01); // Draw the p5.Geometry object again. model(shape); } function createArrow() { // Add shapes to the p5.Geometry object. push(); rotateX(PI); cone(10); translate(0, -10, 0); cylinder(3, 20); pop(); } `
` // Click and drag the mouse to view the scene from different angles. let shape; // Load the file and create a p5.Geometry object. function preload() { shape = loadModel('assets/octahedron.obj'); } function setup() { createCanvas(100, 100, WEBGL); describe('A white octahedron drawn against a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the shape. model(shape); } `

p5

Shape

3D Models

Load a 3d model from an OBJ or STL string.
OBJ and STL files lack a built-in sense of scale, causing models exported from different programs to vary in size. If your model doesn't display correctly, consider using `loadModel()` with `normalize` set to `true` to standardize its size. Further adjustments can be made using the `scale()` function.
Also, the support for colored STL files is not present. STL files with color will be rendered without color properties.
    * Options can include:
    * `modelString`: Specifies the plain text string of either an stl or obj file to be loaded.
    * `fileType`: Defines the file extension of the model.
    * `normalize`: Enables standardized size scaling during loading if set to true.
    * `successCallback`: Callback for post-loading actions with the 3D model object.
    * `failureCallback`: Handles errors if model loading fails, receiving an event error.
    * `flipU`: Flips the U texture coordinates of the model.
    * `flipV`: Flips the V texture coordinates of the model.

method

createModel

### return
the p5.Geometry object

p5.Geometry

` const octahedron_model = ` v 0.000000E+00 0.000000E+00 40.0000 v 22.5000 22.5000 0.000000E+00 v 22.5000 -22.5000 0.000000E+00 v -22.5000 -22.5000 0.000000E+00 v -22.5000 22.5000 0.000000E+00 v 0.000000E+00 0.000000E+00 -40.0000 f 1 2 3 f 1 3 4 f 1 4 5 f 1 5 2 f 6 5 4 f 6 4 3 f 6 3 2 f 6 2 5 `; //draw a spinning octahedron let octahedron; function setup() { createCanvas(100, 100, WEBGL); octahedron = createModel(octahedron_model, '.obj'); describe('Vertically rotating 3D octahedron.'); } function draw() { background(200); rotateX(frameCount * 0.01); rotateY(frameCount * 0.01); model(octahedron); } `

p5

Shape

3D Models

modelString

String of the object to be loaded

String

fileType

The file extension of the model (`.stl`, `.obj`).

String

normalize

If true, scale the model to a standardized size when loading

Boolean

successCallback

Function to be called once the model is loaded. Will be passed the 3D model object.

function(p5.Geometry)

failureCallback

called with event error if the model fails to load.

Function(Event)

##### return
the p5.Geometry object

p5.Geometry

modelString



String

fileType



String

successCallback



function(p5.Geometry)

failureCallback



Function(Event)

##### return
the p5.Geometry object

p5.Geometry

modelString



String

fileType



String

options



Object

successCallback



function(p5.Geometry)

failureCallback



Function(Event)

normalize



Boolean

flipU



Boolean

flipV



Boolean

##### return
the p5.Geometry object

p5.Geometry

Loads vertex and fragment shaders to create a p5.Shader object.
Shaders are programs that run on the graphics processing unit (GPU). They can process many pixels at the same time, making them fast for many graphics tasks. They’re written in a language called GLSL and run along with the rest of the code in a sketch.
Once the p5.Shader object is created, it can be used with the shader() function, as in `shader(myShader)`. A shader program consists of two files, a vertex shader and a fragment shader. The vertex shader affects where 3D geometry is drawn on the screen and the fragment shader affects color.
`loadShader()` loads the vertex and fragment shaders from their `.vert` and `.frag` files. For example, calling `loadShader('assets/shader.vert', 'assets/shader.frag')` loads both required shaders and returns a p5.Shader object.
The third parameter, `successCallback`, is optional. If a function is passed, it will be called once the shader has loaded. The callback function can use the new p5.Shader object as its parameter.
The fourth parameter, `failureCallback`, is also optional. If a function is passed, it will be called if the shader fails to load. The callback function can use the event error as its parameter.
Shaders can take time to load. Calling `loadShader()` in preload() ensures shaders load before they're used in setup() or draw().
Note: Shaders can only be used in WebGL mode.

method

loadShader

vertFilename

path of the vertex shader to be loaded.

String

fragFilename

path of the fragment shader to be loaded.

String

successCallback

function to call once the shader is loaded. Can be passed the p5.Shader object.

Function

failureCallback

function to call if the shader fails to load. Can be passed an `Error` event object.

Function

### return
new shader created from the vertex and fragment shader files.

p5.Shader

` // Note: A "uniform" is a global variable within a shader program. let mandelbrot; // Load the shader and create a p5.Shader object. function preload() { mandelbrot = loadShader('assets/shader.vert', 'assets/shader.frag'); } function setup() { createCanvas(100, 100, WEBGL); // Compile and apply the p5.Shader object. shader(mandelbrot); // Set the shader uniform p to an array. mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]); // Set the shader uniform r to the value 1.5. mandelbrot.setUniform('r', 1.5); // Add a quad as a display surface for the shader. quad(-1, -1, 1, -1, 1, 1, -1, 1); describe('A black fractal image on a magenta background.'); } `
` // Note: A "uniform" is a global variable within a shader program. let mandelbrot; // Load the shader and create a p5.Shader object. function preload() { mandelbrot = loadShader('assets/shader.vert', 'assets/shader.frag'); } function setup() { createCanvas(100, 100, WEBGL); // Use the p5.Shader object. shader(mandelbrot); // Set the shader uniform p to an array. mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]); describe('A fractal image zooms in and out of focus.'); } function draw() { // Set the shader uniform r to a value that oscillates between 0 and 2. mandelbrot.setUniform('r', sin(frameCount * 0.01) + 1); // Add a quad as a display surface for the shader. quad(-1, -1, 1, -1, 1, 1, -1, 1); } `

p5

3D

Material

Creates a new p5.Shader object.
Shaders are programs that run on the graphics processing unit (GPU). They can process many pixels at the same time, making them fast for many graphics tasks. They’re written in a language called GLSL and run along with the rest of the code in a sketch.
Once the p5.Shader object is created, it can be used with the shader() function, as in `shader(myShader)`. A shader program consists of two parts, a vertex shader and a fragment shader. The vertex shader affects where 3D geometry is drawn on the screen and the fragment shader affects color.
The first parameter, `vertSrc`, sets the vertex shader. It’s a string that contains the vertex shader program written in GLSL.
The second parameter, `fragSrc`, sets the fragment shader. It’s a string that contains the fragment shader program written in GLSL.
A shader can optionally describe hooks, which are functions in GLSL that users may choose to provide to customize the behavior of the shader using the `modify()` method of `p5.Shader`. These are added by describing the hooks in a third parameter, `options`, and referencing the hooks in your `vertSrc` or `fragSrc`. Hooks for the vertex or fragment shader are described under the `vertex` and `fragment` keys of `options`. Each one is an object. where each key is the type and name of a hook function, and each value is a string with the parameter list and default implementation of the hook. For example, to let users optionally run code at the start of the vertex shader, the options object could include:
    {
      vertex: {
        'void beforeVertex': '() {}'
      }
    }
    
Then, in your vertex shader source, you can run a hook by calling a function with the same name prefixed by `HOOK_`. If you want to check if the default hook has been replaced, maybe to avoid extra overhead, you can check if the same name prefixed by `AUGMENTED_HOOK_` has been defined:
    void main() {
      // In most cases, just calling the hook is fine:
      HOOK_beforeVertex();
    
      // Alternatively, for more efficiency:
      #ifdef AUGMENTED_HOOK_beforeVertex
      HOOK_beforeVertex();
      #endif
    
      // Add the rest of your shader code here!
    }
    
Note: Only filter shaders can be used in 2D mode. All shaders can be used in WebGL mode.

method

createShader

vertSrc

source code for the vertex shader.

String

fragSrc

source code for the fragment shader.

String

options

An optional object describing how this shader can be augmented with hooks. It can include:
    * `vertex`: An object describing the available vertex shader hooks.
    * `fragment`: An object describing the available frament shader hooks.

Object

### return
new shader object created from the vertex and fragment shaders.

p5.Shader

` // Note: A "uniform" is a global variable within a shader program. // Create a string with the vertex shader program. // The vertex shader is called for each vertex. let vertSrc = ` precision highp float; uniform mat4 uModelViewMatrix; uniform mat4 uProjectionMatrix; attribute vec3 aPosition; attribute vec2 aTexCoord; varying vec2 vTexCoord; void main() { vTexCoord = aTexCoord; vec4 positionVec4 = vec4(aPosition, 1.0); gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4; } `; // Create a string with the fragment shader program. // The fragment shader is called for each pixel. let fragSrc = ` precision highp float; void main() { // Set each pixel's RGBA value to yellow. gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0); } `; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Shader object. let shaderProgram = createShader(vertSrc, fragSrc); // Compile and apply the p5.Shader object. shader(shaderProgram); // Style the drawing surface. noStroke(); // Add a plane as a drawing surface. plane(100, 100); describe('A yellow square.'); } `
` // Note: A "uniform" is a global variable within a shader program. // Create a string with the vertex shader program. // The vertex shader is called for each vertex. let vertSrc = ` precision highp float; uniform mat4 uModelViewMatrix; uniform mat4 uProjectionMatrix; attribute vec3 aPosition; attribute vec2 aTexCoord; varying vec2 vTexCoord; void main() { vTexCoord = aTexCoord; vec4 positionVec4 = vec4(aPosition, 1.0); gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4; } `; // Create a string with the fragment shader program. // The fragment shader is called for each pixel. let fragSrc = ` precision highp float; uniform vec2 p; uniform float r; const int numIterations = 500; varying vec2 vTexCoord; void main() { vec2 c = p + gl_FragCoord.xy * r; vec2 z = c; float n = 0.0; for (int i = numIterations; i > 0; i--) { if (z.x * z.x + z.y * z.y > 4.0) { n = float(i) / float(numIterations); break; } z = vec2(z.x * z.x - z.y * z.y, 2.0 * z.x * z.y) + c; } gl_FragColor = vec4( 0.5 - cos(n * 17.0) / 2.0, 0.5 - cos(n * 13.0) / 2.0, 0.5 - cos(n * 23.0) / 2.0, 1.0 ); } `; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Shader object. let mandelbrot = createShader(vertSrc, fragSrc); // Compile and apply the p5.Shader object. shader(mandelbrot); // Set the shader uniform p to an array. // p is the center point of the Mandelbrot image. mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]); // Set the shader uniform r to 0.005. // r is the size of the image in Mandelbrot-space. mandelbrot.setUniform('r', 0.005); // Style the drawing surface. noStroke(); // Add a plane as a drawing surface. plane(100, 100); describe('A black fractal image on a magenta background.'); } `
` // Note: A "uniform" is a global variable within a shader program. // Create a string with the vertex shader program. // The vertex shader is called for each vertex. let vertSrc = ` precision highp float; uniform mat4 uModelViewMatrix; uniform mat4 uProjectionMatrix; attribute vec3 aPosition; attribute vec2 aTexCoord; varying vec2 vTexCoord; void main() { vTexCoord = aTexCoord; vec4 positionVec4 = vec4(aPosition, 1.0); gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4; } `; // Create a string with the fragment shader program. // The fragment shader is called for each pixel. let fragSrc = ` precision highp float; uniform vec2 p; uniform float r; const int numIterations = 500; varying vec2 vTexCoord; void main() { vec2 c = p + gl_FragCoord.xy * r; vec2 z = c; float n = 0.0; for (int i = numIterations; i > 0; i--) { if (z.x * z.x + z.y * z.y > 4.0) { n = float(i) / float(numIterations); break; } z = vec2(z.x * z.x - z.y * z.y, 2.0 * z.x * z.y) + c; } gl_FragColor = vec4( 0.5 - cos(n * 17.0) / 2.0, 0.5 - cos(n * 13.0) / 2.0, 0.5 - cos(n * 23.0) / 2.0, 1.0 ); } `; let mandelbrot; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Shader object. mandelbrot = createShader(vertSrc, fragSrc); // Apply the p5.Shader object. shader(mandelbrot); // Set the shader uniform p to an array. // p is the center point of the Mandelbrot image. mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]); describe('A fractal image zooms in and out of focus.'); } function draw() { // Set the shader uniform r to a value that oscillates // between 0 and 0.005. // r is the size of the image in Mandelbrot-space. let radius = 0.005 * (sin(frameCount * 0.01) + 1); mandelbrot.setUniform('r', radius); // Style the drawing surface. noStroke(); // Add a plane as a drawing surface. plane(100, 100); } `
` // A shader with hooks. let myShader; // A shader with modified hooks. let modifiedShader; // Create a string with the vertex shader program. // The vertex shader is called for each vertex. let vertSrc = ` precision highp float; uniform mat4 uModelViewMatrix; uniform mat4 uProjectionMatrix; attribute vec3 aPosition; attribute vec2 aTexCoord; void main() { vec4 positionVec4 = vec4(aPosition, 1.0); gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4; } `; // Create a fragment shader that uses a hook. let fragSrc = ` precision highp float; void main() { // Let users override the color gl_FragColor = HOOK_getColor(vec4(1., 0., 0., 1.)); } `; function setup() { createCanvas(50, 50, WEBGL); // Create a shader with hooks myShader = createShader(vertSrc, fragSrc, { fragment: { 'vec4 getColor': '(vec4 color) { return color; }' } }); // Make a version of the shader with a hook overridden modifiedShader = myShader.modify({ 'vec4 getColor': `(vec4 color) { return vec4(0., 0., 1., 1.); }` }); } function draw() { noStroke(); push(); shader(myShader); translate(-width/3, 0); sphere(10); pop(); push(); shader(modifiedShader); translate(width/3, 0); sphere(10); pop(); } `

p5

3D

Material

Creates a p5.Shader object to be used with the filter() function.
`createFilterShader()` works like createShader() but has a default vertex shader included. `createFilterShader()` is intended to be used along with filter() for filtering the contents of a canvas. A filter shader will be applied to the whole canvas instead of just p5.Geometry objects.
The parameter, `fragSrc`, sets the fragment shader. It’s a string that contains the fragment shader program written in GLSL.
The p5.Shader object that's created has some uniforms that can be set:
    * `sampler2D tex0`, which contains the canvas contents as a texture.
    * `vec2 canvasSize`, which is the width and height of the canvas, not including pixel density.
    * `vec2 texelSize`, which is the size of a physical pixel including pixel density. This is calculated as `1.0 / (width * density)` for the pixel width and `1.0 / (height * density)` for the pixel height.
The p5.Shader that's created also provides `varying vec2 vTexCoord`, a coordinate with values between 0 and 1. `vTexCoord` describes where on the canvas the pixel will be drawn.
For more info about filters and shaders, see Adam Ferriss' repo of shader examples or the Introduction to Shaders tutorial.

method

createFilterShader

fragSrc

source code for the fragment shader.

String

### return
new shader object created from the fragment shader.

p5.Shader

` function setup() { let fragSrc = `precision highp float; void main() { gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0); }`; createCanvas(100, 100, WEBGL); let s = createFilterShader(fragSrc); filter(s); describe('a yellow canvas'); } `
` let img, s; function preload() { img = loadImage('assets/bricks.jpg'); } function setup() { let fragSrc = `precision highp float; // x,y coordinates, given from the vertex shader varying vec2 vTexCoord; // the canvas contents, given from filter() uniform sampler2D tex0; // other useful information from the canvas uniform vec2 texelSize; uniform vec2 canvasSize; // a custom variable from this sketch uniform float darkness; void main() { // get the color at current pixel vec4 color = texture2D(tex0, vTexCoord); // set the output color color.b = 1.0; color *= darkness; gl_FragColor = vec4(color.rgb, 1.0); }`; createCanvas(100, 100, WEBGL); s = createFilterShader(fragSrc); } function draw() { image(img, -50, -50); s.setUniform('darkness', 0.5); filter(s); describe('a image of bricks tinted dark blue'); } `

p5

3D

Material

Sets the p5.Shader object to apply while drawing.
Shaders are programs that run on the graphics processing unit (GPU). They can process many pixels or vertices at the same time, making them fast for many graphics tasks. They’re written in a language called GLSL and run along with the rest of the code in a sketch. p5.Shader objects can be created using the createShader() and loadShader() functions.
The parameter, `s`, is the p5.Shader object to apply. For example, calling `shader(myShader)` applies `myShader` to process each pixel on the canvas. The shader will be used for:
    * Fills when a texture is enabled if it includes a uniform `sampler2D`.
    * Fills when lights are enabled if it includes the attribute `aNormal`, or if it has any of the following uniforms: `uUseLighting`, `uAmbientLightCount`, `uDirectionalLightCount`, `uPointLightCount`, `uAmbientColor`, `uDirectionalDiffuseColors`, `uDirectionalSpecularColors`, `uPointLightLocation`, `uPointLightDiffuseColors`, `uPointLightSpecularColors`, `uLightingDirection`, or `uSpecular`.
    * Fills whenever there are no lights or textures.
    * Strokes if it includes the uniform `uStrokeWeight`.
The source code from a p5.Shader object's fragment and vertex shaders will be compiled the first time it's passed to `shader()`. See MDN for more information about compiling shaders.
Calling resetShader() restores a sketch’s default shaders.
Note: Shaders can only be used in WebGL mode.

method

shader

s

p5.Shader object to apply.

p5.Shader

` // Note: A "uniform" is a global variable within a shader program. // Create a string with the vertex shader program. // The vertex shader is called for each vertex. let vertSrc = ` precision highp float; uniform mat4 uModelViewMatrix; uniform mat4 uProjectionMatrix; attribute vec3 aPosition; attribute vec2 aTexCoord; varying vec2 vTexCoord; void main() { vTexCoord = aTexCoord; vec4 positionVec4 = vec4(aPosition, 1.0); gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4; } `; // Create a string with the fragment shader program. // The fragment shader is called for each pixel. let fragSrc = ` precision highp float; void main() { // Set each pixel's RGBA value to yellow. gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0); } `; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Shader object. let shaderProgram = createShader(vertSrc, fragSrc); // Apply the p5.Shader object. shader(shaderProgram); // Style the drawing surface. noStroke(); // Add a plane as a drawing surface. plane(100, 100); describe('A yellow square.'); } `
` // Note: A "uniform" is a global variable within a shader program. let mandelbrot; // Load the shader and create a p5.Shader object. function preload() { mandelbrot = loadShader('assets/shader.vert', 'assets/shader.frag'); } function setup() { createCanvas(100, 100, WEBGL); // Use the p5.Shader object. shader(mandelbrot); // Set the shader uniform p to an array. mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]); describe('A fractal image zooms in and out of focus.'); } function draw() { // Set the shader uniform r to a value that oscillates between 0 and 2. mandelbrot.setUniform('r', sin(frameCount * 0.01) + 1); // Add a quad as a display surface for the shader. quad(-1, -1, 1, -1, 1, 1, -1, 1); } `
` // Note: A "uniform" is a global variable within a shader program. let redGreen; let orangeBlue; let showRedGreen = false; // Load the shader and create two separate p5.Shader objects. function preload() { redGreen = loadShader('assets/shader.vert', 'assets/shader-gradient.frag'); orangeBlue = loadShader('assets/shader.vert', 'assets/shader-gradient.frag'); } function setup() { createCanvas(100, 100, WEBGL); // Initialize the redGreen shader. shader(redGreen); // Set the redGreen shader's center and background color. redGreen.setUniform('colorCenter', [1.0, 0.0, 0.0]); redGreen.setUniform('colorBackground', [0.0, 1.0, 0.0]); // Initialize the orangeBlue shader. shader(orangeBlue); // Set the orangeBlue shader's center and background color. orangeBlue.setUniform('colorCenter', [1.0, 0.5, 0.0]); orangeBlue.setUniform('colorBackground', [0.226, 0.0, 0.615]); describe( 'The scene toggles between two circular gradients when the user double-clicks. An orange and blue gradient vertically, and red and green gradient moves horizontally.' ); } function draw() { // Update the offset values for each shader. // Move orangeBlue vertically. // Move redGreen horizontally. orangeBlue.setUniform('offset', [0, sin(frameCount * 0.01) + 1]); redGreen.setUniform('offset', [sin(frameCount * 0.01), 1]); if (showRedGreen === true) { shader(redGreen); } else { shader(orangeBlue); } // Style the drawing surface. noStroke(); // Add a quad as a drawing surface. quad(-1, -1, 1, -1, 1, 1, -1, 1); } // Toggle between shaders when the user double-clicks. function doubleClicked() { showRedGreen = !showRedGreen; } `

p5

3D

Material

Get the default shader used with lights, materials, and textures.
You can call `baseMaterialShader().modify()` and change any of the following hooks:
HookDescription  
`void beforeVertex`
Called at the start of the vertex shader.  
`vec3 getLocalPosition`
Update the position of vertices before transforms are applied. It takes in `vec3 position` and must return a modified version.  
`vec3 getWorldPosition`
Update the position of vertices after transforms are applied. It takes in `vec3 position` and pust return a modified version.  
`vec3 getLocalNormal`
Update the normal before transforms are applied. It takes in `vec3 normal` and must return a modified version.  
`vec3 getWorldNormal`
Update the normal after transforms are applied. It takes in `vec3 normal` and must return a modified version.  
`vec2 getUV`
Update the texture coordinates. It takes in `vec2 uv` and must return a modified version.  
`vec4 getVertexColor`
Update the color of each vertex. It takes in a `vec4 color` and must return a modified version.  
`void afterVertex`
Called at the end of the vertex shader.  
`void beforeFragment`
Called at the start of the fragment shader.  
`Inputs getPixelInputs`
Update the per-pixel inputs of the material. It takes in an `Inputs` struct, which includes:
    * `vec3 normal`, the direction pointing out of the surface
    * `vec2 texCoord`, a vector where `x` and `y` are between 0 and 1 describing the spot on a texture the pixel is mapped to, as a fraction of the texture size
    * `vec3 ambientLight`, the ambient light color on the vertex
    * `vec4 color`, the base material color of the pixel
    * `vec3 ambientMaterial`, the color of the pixel when affected by ambient light
    * `vec3 specularMaterial`, the color of the pixel when reflecting specular highlights
    * `vec3 emissiveMaterial`, the light color emitted by the pixel
    * `float shininess`, a number representing how sharp specular reflections should be, from 1 to infinity
    * `float metalness`, a number representing how mirrorlike the material should be, between 0 and 1 The struct can be modified and returned.  
`vec4 combineColors`
Take in a `ColorComponents` struct containing all the different components of light, and combining them into a single final color. The struct contains:
    * `vec3 baseColor`, the base color of the pixel
    * `float opacity`, the opacity between 0 and 1 that it should be drawn at
    * `vec3 ambientColor`, the color of the pixel when affected by ambient light
    * `vec3 specularColor`, the color of the pixel when affected by specular reflections
    * `vec3 diffuse`, the amount of diffused light hitting the pixel
    * `vec3 ambient`, the amount of ambient light hitting the pixel
    * `vec3 specular`, the amount of specular reflection hitting the pixel
    * `vec3 emissive`, the amount of light emitted by the pixel  
`vec4 getFinalColor`
Update the final color after mixing. It takes in a `vec4 color` and must return a modified version.  
`void afterFragment`
Called at the end of the fragment shader.  
Most of the time, you will need to write your hooks in GLSL ES version 300. If you are using WebGL 1 instead of 2, write your hooks in GLSL ES 100 instead.
Call `baseMaterialShader().inspectHooks()` to see all the possible hooks and their default implementations.

method

baseMaterialShader

### return
The material shader

p5.Shader

` let myShader; function setup() { createCanvas(200, 200, WEBGL); myShader = baseMaterialShader().modify({ uniforms: { 'float time': () => millis() }, 'vec3 getWorldPosition': `(vec3 pos) { pos.y += 20.0 * sin(time * 0.001 + pos.x * 0.05); return pos; }` }); } function draw() { background(255); shader(myShader); lights(); noStroke(); fill('red'); sphere(50); } `

` let myShader; function setup() { createCanvas(200, 200, WEBGL); myShader = baseMaterialShader().modify({ declarations: 'vec3 myNormal;', 'Inputs getPixelInputs': `(Inputs inputs) { myNormal = inputs.normal; return inputs; }`, 'vec4 getFinalColor': `(vec4 color) { return mix( vec4(1.0, 1.0, 1.0, 1.0), color, abs(dot(myNormal, vec3(0.0, 0.0, 1.0))) ); }` }); } function draw() { background(255); rotateY(millis() * 0.001); shader(myShader); lights(); noStroke(); fill('red'); torus(30); } `

` let myShader; let environment; function preload() { environment = loadImage('assets/outdoor_spheremap.jpg'); } function setup() { createCanvas(200, 200, WEBGL); myShader = baseMaterialShader().modify({ 'Inputs getPixelInputs': `(Inputs inputs) { float factor = sin( inputs.texCoord.x * ${TWO_PI} + inputs.texCoord.y * ${TWO_PI} ) * 0.4 + 0.5; inputs.shininess = mix(1., 100., factor); inputs.metalness = factor; return inputs; }` }); } function draw() { panorama(environment); ambientLight(100); imageLight(environment); rotateY(millis() * 0.001); shader(myShader); noStroke(); fill(255); specularMaterial(150); sphere(50); } `

` let myShader; function setup() { createCanvas(200, 200, WEBGL); myShader = baseMaterialShader().modify({ 'Inputs getPixelInputs': `(Inputs inputs) { vec3 newNormal = inputs.normal; // Simple bump mapping: adjust the normal based on position newNormal.x += 0.2 * sin( sin( inputs.texCoord.y * ${TWO_PI} * 10.0 + inputs.texCoord.x * ${TWO_PI} * 25.0 ) ); newNormal.y += 0.2 * sin( sin( inputs.texCoord.x * ${TWO_PI} * 10.0 + inputs.texCoord.y * ${TWO_PI} * 25.0 ) ); inputs.normal = normalize(newNormal); return inputs; }` }); } function draw() { background(255); shader(myShader); ambientLight(150); pointLight( 255, 255, 255, 100*cos(frameCount*0.04), -50, 100*sin(frameCount*0.04) ); noStroke(); fill('red'); shininess(200); specularMaterial(255); sphere(50); } `

p5

3D

Material

Get the shader used by `normalMaterial()`.
You can call `baseNormalShader().modify()` and change any of the following hooks:
Hook Description  
`void beforeVertex` Called at the start of the vertex shader.  
`vec3 getLocalPosition` Update the position of vertices before transforms are applied. It takes in `vec3 position` and must return a modified version.  
`vec3 getWorldPosition` Update the position of vertices after transforms are applied. It takes in `vec3 position` and pust return a modified version.  
`vec3 getLocalNormal` Update the normal before transforms are applied. It takes in `vec3 normal` and must return a modified version.  
`vec3 getWorldNormal` Update the normal after transforms are applied. It takes in `vec3 normal` and must return a modified version.  
`vec2 getUV` Update the texture coordinates. It takes in `vec2 uv` and must return a modified version.  
`vec4 getVertexColor` Update the color of each vertex. It takes in a `vec4 color` and must return a modified version.  
`void afterVertex` Called at the end of the vertex shader.  
`void beforeFragment` Called at the start of the fragment shader.  
`vec4 getFinalColor` Update the final color after mixing. It takes in a `vec4 color` and must return a modified version.  
`void afterFragment` Called at the end of the fragment shader.  
Most of the time, you will need to write your hooks in GLSL ES version 300. If you are using WebGL 1 instead of 2, write your hooks in GLSL ES 100 instead.
Call `baseNormalShader().inspectHooks()` to see all the possible hooks and their default implementations.

method

baseNormalShader

### return
The `normalMaterial` shader

p5.Shader

` let myShader; function setup() { createCanvas(200, 200, WEBGL); myShader = baseNormalShader().modify({ uniforms: { 'float time': () => millis() }, 'vec3 getWorldPosition': `(vec3 pos) { pos.y += 20. * sin(time * 0.001 + pos.x * 0.05); return pos; }` }); } function draw() { background(255); shader(myShader); noStroke(); sphere(50); } `

` let myShader; function setup() { createCanvas(200, 200, WEBGL); myShader = baseNormalShader().modify({ 'vec3 getWorldNormal': '(vec3 normal) { return abs(normal); }', 'vec4 getFinalColor': `(vec4 color) { // Map the r, g, and b values of the old normal to new colors // instead of just red, green, and blue: vec3 newColor = color.r * vec3(89.0, 240.0, 232.0) / 255.0 + color.g * vec3(240.0, 237.0, 89.0) / 255.0 + color.b * vec3(205.0, 55.0, 222.0) / 255.0; newColor = newColor / (color.r + color.g + color.b); return vec4(newColor, 1.0) * color.a; }` }); } function draw() { background(255); shader(myShader); noStroke(); rotateX(frameCount * 0.01); rotateY(frameCount * 0.015); box(100); } `

p5

3D

Material

Get the shader used when no lights or materials are applied.
You can call `baseColorShader().modify()` and change any of the following hooks:
Hook Description  
`void beforeVertex` Called at the start of the vertex shader.  
`vec3 getLocalPosition` Update the position of vertices before transforms are applied. It takes in `vec3 position` and must return a modified version.  
`vec3 getWorldPosition` Update the position of vertices after transforms are applied. It takes in `vec3 position` and pust return a modified version.  
`vec3 getLocalNormal` Update the normal before transforms are applied. It takes in `vec3 normal` and must return a modified version.  
`vec3 getWorldNormal` Update the normal after transforms are applied. It takes in `vec3 normal` and must return a modified version.  
`vec2 getUV` Update the texture coordinates. It takes in `vec2 uv` and must return a modified version.  
`vec4 getVertexColor` Update the color of each vertex. It takes in a `vec4 color` and must return a modified version.  
`void afterVertex` Called at the end of the vertex shader.  
`void beforeFragment` Called at the start of the fragment shader.  
`vec4 getFinalColor` Update the final color after mixing. It takes in a `vec4 color` and must return a modified version.  
`void afterFragment` Called at the end of the fragment shader.  
Most of the time, you will need to write your hooks in GLSL ES version 300. If you are using WebGL 1 instead of 2, write your hooks in GLSL ES 100 instead.
Call `baseColorShader().inspectHooks()` to see all the possible hooks and their default implementations.

method

baseColorShader

### return
The color shader

p5.Shader

` let myShader; function setup() { createCanvas(200, 200, WEBGL); myShader = baseColorShader().modify({ uniforms: { 'float time': () => millis() }, 'vec3 getWorldPosition': `(vec3 pos) { pos.y += 20. * sin(time * 0.001 + pos.x * 0.05); return pos; }` }); } function draw() { background(255); shader(myShader); noStroke(); fill('red'); circle(0, 0, 50); } `

p5

3D

Material

Get the shader used when drawing the strokes of shapes.
You can call `baseStrokeShader().modify()` and change any of the following hooks:
HookDescription  
`void beforeVertex`
Called at the start of the vertex shader.  
`vec3 getLocalPosition`
Update the position of vertices before transforms are applied. It takes in `vec3 position` and must return a modified version.  
`vec3 getWorldPosition`
Update the position of vertices after transforms are applied. It takes in `vec3 position` and pust return a modified version.  
`float getStrokeWeight`
Update the stroke weight. It takes in `float weight` and pust return a modified version.  
`vec2 getLineCenter`
Update the center of the line. It takes in `vec2 center` and must return a modified version.  
`vec2 getLinePosition`
Update the position of each vertex on the edge of the line. It takes in `vec2 position` and must return a modified version.  
`vec4 getVertexColor`
Update the color of each vertex. It takes in a `vec4 color` and must return a modified version.  
`void afterVertex`
Called at the end of the vertex shader.  
`void beforeFragment`
Called at the start of the fragment shader.  
`Inputs getPixelInputs`
Update the inputs to the shader. It takes in a struct `Inputs inputs`, which includes:
    * `vec4 color`, the color of the stroke
    * `vec2 tangent`, the direction of the stroke in screen space
    * `vec2 center`, the coordinate of the center of the stroke in screen space p5.js pixels
    * `vec2 position`, the coordinate of the current pixel in screen space p5.js pixels
    * `float strokeWeight`, the thickness of the stroke in p5.js pixels  
`bool shouldDiscard`
Caps and joins are made by discarded pixels in the fragment shader to carve away unwanted areas. Use this to change this logic. It takes in a `bool willDiscard` and must return a modified version.  
`vec4 getFinalColor`
Update the final color after mixing. It takes in a `vec4 color` and must return a modified version.  
`void afterFragment`
Called at the end of the fragment shader.  
Most of the time, you will need to write your hooks in GLSL ES version 300. If you are using WebGL 1 instead of 2, write your hooks in GLSL ES 100 instead.
Call `baseStrokeShader().inspectHooks()` to see all the possible hooks and their default implementations.

method

baseStrokeShader

### return
The stroke shader

p5.Shader

` let myShader; function setup() { createCanvas(200, 200, WEBGL); myShader = baseStrokeShader().modify({ 'Inputs getPixelInputs': `(Inputs inputs) { float opacity = 1.0 - smoothstep( 0.0, 15.0, length(inputs.position - inputs.center) ); inputs.color *= opacity; return inputs; }` }); } function draw() { background(255); shader(myShader); strokeWeight(30); line( -width/3, sin(millis()*0.001) * height/4, width/3, sin(millis()*0.001 + 1) * height/4 ); } `

` let myShader; function setup() { createCanvas(200, 200, WEBGL); myShader = baseStrokeShader().modify({ uniforms: { 'float time': () => millis() }, declarations: 'vec3 myPosition;', 'vec3 getWorldPosition': `(vec3 pos) { myPosition = pos; return pos; }`, 'float getStrokeWeight': `(float w) { // Add a somewhat random offset to the weight // that varies based on position and time float scale = 0.8 + 0.2*sin(10.0 * sin( floor(time/250.) + myPosition.x*0.01 + myPosition.y*0.01 )); return w * scale; }` }); } function draw() { background(255); shader(myShader); myShader.setUniform('time', millis()); strokeWeight(10); beginShape(); for (let i = 0; i <= 50; i++) { let r = map(i, 0, 50, 0, width/3); let x = r*cos(i*0.2); let y = r*sin(i*0.2); vertex(x, y); } endShape(); } `

` let myShader; function setup() { createCanvas(200, 200, WEBGL); myShader = baseStrokeShader().modify({ 'float random': `(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * .1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }`, 'Inputs getPixelInputs': `(Inputs inputs) { // Replace alpha in the color with dithering by // randomly setting pixel colors to 0 based on opacity float a = inputs.color.a; inputs.color.a = 1.0; inputs.color *= random(inputs.position.xy) > a ? 0.0 : 1.0; return inputs; }` }); } function draw() { background(255); shader(myShader); strokeWeight(10); beginShape(); for (let i = 0; i <= 50; i++) { stroke( 0, 255 * map(i, 0, 20, 0, 1, true) * map(i, 30, 50, 1, 0, true) ); vertex( map(i, 0, 50, -1, 1) * width/3, 50 * sin(i/10 + frameCount/100) ); } endShape(); } `

p5

3D

Material

Restores the default shaders.
`resetShader()` deactivates any shaders previously applied by shader().
Note: Shaders can only be used in WebGL mode.

method

resetShader

` // Create a string with the vertex shader program. // The vertex shader is called for each vertex. let vertSrc = ` attribute vec3 aPosition; attribute vec2 aTexCoord; uniform mat4 uProjectionMatrix; uniform mat4 uModelViewMatrix; varying vec2 vTexCoord; void main() { vTexCoord = aTexCoord; vec4 position = vec4(aPosition, 1.0); gl_Position = uProjectionMatrix * uModelViewMatrix * position; } `; // Create a string with the fragment shader program. // The fragment shader is called for each pixel. let fragSrc = ` precision mediump float; varying vec2 vTexCoord; void main() { vec2 uv = vTexCoord; vec3 color = vec3(uv.x, uv.y, min(uv.x + uv.y, 1.0)); gl_FragColor = vec4(color, 1.0); } `; let myShader; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Shader object. myShader = createShader(vertSrc, fragSrc); describe( 'Two rotating cubes on a gray background. The left one has a blue-purple gradient on each face. The right one is red.' ); } function draw() { background(200); // Draw a box using the p5.Shader. // shader() sets the active shader to myShader. shader(myShader); push(); translate(-25, 0, 0); rotateX(frameCount * 0.01); rotateY(frameCount * 0.01); box(width / 4); pop(); // Draw a box using the default fill shader. // resetShader() restores the default fill shader. resetShader(); fill(255, 0, 0); push(); translate(25, 0, 0); rotateX(frameCount * 0.01); rotateY(frameCount * 0.01); box(width / 4); pop(); } `

p5

3D

Material

Sets the texture that will be used on shapes.
A texture is like a skin that wraps around a shape. `texture()` works with built-in shapes, such as square() and sphere(), and custom shapes created with functions such as buildGeometry(). To texture a geometry created with beginShape(), uv coordinates must be passed to each vertex() call.
The parameter, `tex`, is the texture to apply. `texture()` can use a range of sources including images, videos, and offscreen renderers such as p5.Graphics and p5.Framebuffer objects.
To texture a geometry created with beginShape(), you will need to specify uv coordinates in vertex().
Note: `texture()` can only be used in WebGL mode.

method

texture

tex

media to use as the texture.

p5.Image|p5.MediaElement|p5.Graphics|p5.Texture|p5.Framebuffer|p5.FramebufferTexture

` let img; // Load an image and create a p5.Image object. function preload() { img = loadImage('assets/laDefense.jpg'); } function setup() { createCanvas(100, 100, WEBGL); describe('A spinning cube with an image of a ceiling on each face.'); } function draw() { background(0); // Rotate around the x-, y-, and z-axes. rotateZ(frameCount * 0.01); rotateX(frameCount * 0.01); rotateY(frameCount * 0.01); // Apply the image as a texture. texture(img); // Draw the box. box(50); } `
` let pg; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Graphics object. pg = createGraphics(100, 100); // Draw a circle to the p5.Graphics object. pg.background(200); pg.circle(50, 50, 30); describe('A spinning cube with circle at the center of each face.'); } function draw() { background(0); // Rotate around the x-, y-, and z-axes. rotateZ(frameCount * 0.01); rotateX(frameCount * 0.01); rotateY(frameCount * 0.01); // Apply the p5.Graphics object as a texture. texture(pg); // Draw the box. box(50); } `
` let vid; // Load a video and create a p5.MediaElement object. function preload() { vid = createVideo('assets/fingers.mov'); } function setup() { createCanvas(100, 100, WEBGL); // Hide the video. vid.hide(); // Set the video to loop. vid.loop(); describe('A rectangle with video as texture'); } function draw() { background(0); // Rotate around the y-axis. rotateY(frameCount * 0.01); // Apply the video as a texture. texture(vid); // Draw the rectangle. rect(-40, -40, 80, 80); } `
` let vid; // Load a video and create a p5.MediaElement object. function preload() { vid = createVideo('assets/fingers.mov'); } function setup() { createCanvas(100, 100, WEBGL); // Hide the video. vid.hide(); // Set the video to loop. vid.loop(); describe('A rectangle with video as texture'); } function draw() { background(0); // Rotate around the y-axis. rotateY(frameCount * 0.01); // Set the texture mode. textureMode(NORMAL); // Apply the video as a texture. texture(vid); // Draw a custom shape using uv coordinates. beginShape(); vertex(-40, -40, 0, 0); vertex(40, -40, 1, 0); vertex(40, 40, 1, 1); vertex(-40, 40, 0, 1); endShape(); } `

p5

3D

Material

Changes the coordinate system used for textures when they’re applied to custom shapes.
In order for texture() to work, a shape needs a way to map the points on its surface to the pixels in an image. Built-in shapes such as rect() and box() already have these texture mappings based on their vertices. Custom shapes created with vertex() require texture mappings to be passed as uv coordinates.
Each call to vertex() must include 5 arguments, as in `vertex(x, y, z, u, v)`, to map the vertex at coordinates `(x, y, z)` to the pixel at coordinates `(u, v)` within an image. For example, the corners of a rectangular image are mapped to the corners of a rectangle by default:
    // Apply the image as a texture.
    texture(img);
    
    // Draw the rectangle.
    rect(0, 0, 30, 50);
    
If the image in the code snippet above has dimensions of 300 x 500 pixels, the same result could be achieved as follows:
    // Apply the image as a texture.
    texture(img);
    
    // Draw the rectangle.
    beginShape();
    
    // Top-left.
    // u: 0, v: 0
    vertex(0, 0, 0, 0, 0);
    
    // Top-right.
    // u: 300, v: 0
    vertex(30, 0, 0, 300, 0);
    
    // Bottom-right.
    // u: 300, v: 500
    vertex(30, 50, 0, 300, 500);
    
    // Bottom-left.
    // u: 0, v: 500
    vertex(0, 50, 0, 0, 500);
    
    endShape();
    
`textureMode()` changes the coordinate system for uv coordinates.
The parameter, `mode`, accepts two possible constants. If `NORMAL` is passed, as in `textureMode(NORMAL)`, then the texture’s uv coordinates can be provided in the range 0 to 1 instead of the image’s dimensions. This can be helpful for using the same code for multiple images of different sizes. For example, the code snippet above could be rewritten as follows:
    // Set the texture mode to use normalized coordinates.
    textureMode(NORMAL);
    
    // Apply the image as a texture.
    texture(img);
    
    // Draw the rectangle.
    beginShape();
    
    // Top-left.
    // u: 0, v: 0
    vertex(0, 0, 0, 0, 0);
    
    // Top-right.
    // u: 1, v: 0
    vertex(30, 0, 0, 1, 0);
    
    // Bottom-right.
    // u: 1, v: 1
    vertex(30, 50, 0, 1, 1);
    
    // Bottom-left.
    // u: 0, v: 1
    vertex(0, 50, 0, 0, 1);
    
    endShape();
    
By default, `mode` is `IMAGE`, which scales uv coordinates to the dimensions of the image. Calling `textureMode(IMAGE)` applies the default.
Note: `textureMode()` can only be used in WebGL mode.

method

textureMode

mode

either IMAGE or NORMAL.

Constant

` let img; // Load an image and create a p5.Image object. function preload() { img = loadImage('assets/laDefense.jpg'); } function setup() { createCanvas(100, 100, WEBGL); describe('An image of a ceiling against a black background.'); } function draw() { background(0); // Apply the image as a texture. texture(img); // Draw the custom shape. // Use the image's width and height as uv coordinates. beginShape(); vertex(-30, -30, 0, 0); vertex(30, -30, img.width, 0); vertex(30, 30, img.width, img.height); vertex(-30, 30, 0, img.height); endShape(); } `
` let img; // Load an image and create a p5.Image object. function preload() { img = loadImage('assets/laDefense.jpg'); } function setup() { createCanvas(100, 100, WEBGL); describe('An image of a ceiling against a black background.'); } function draw() { background(0); // Set the texture mode. textureMode(NORMAL); // Apply the image as a texture. texture(img); // Draw the custom shape. // Use normalized uv coordinates. beginShape(); vertex(-30, -30, 0, 0); vertex(30, -30, 1, 0); vertex(30, 30, 1, 1); vertex(-30, 30, 0, 1); endShape(); } `

p5

3D

Material

Changes the way textures behave when a shape’s uv coordinates go beyond the texture.
In order for texture() to work, a shape needs a way to map the points on its surface to the pixels in an image. Built-in shapes such as rect() and box() already have these texture mappings based on their vertices. Custom shapes created with vertex() require texture mappings to be passed as uv coordinates.
Each call to vertex() must include 5 arguments, as in `vertex(x, y, z, u, v)`, to map the vertex at coordinates `(x, y, z)` to the pixel at coordinates `(u, v)` within an image. For example, the corners of a rectangular image are mapped to the corners of a rectangle by default:
    // Apply the image as a texture.
    texture(img);
    
    // Draw the rectangle.
    rect(0, 0, 30, 50);
    
If the image in the code snippet above has dimensions of 300 x 500 pixels, the same result could be achieved as follows:
    // Apply the image as a texture.
    texture(img);
    
    // Draw the rectangle.
    beginShape();
    
    // Top-left.
    // u: 0, v: 0
    vertex(0, 0, 0, 0, 0);
    
    // Top-right.
    // u: 300, v: 0
    vertex(30, 0, 0, 300, 0);
    
    // Bottom-right.
    // u: 300, v: 500
    vertex(30, 50, 0, 300, 500);
    
    // Bottom-left.
    // u: 0, v: 500
    vertex(0, 50, 0, 0, 500);
    
    endShape();
    
`textureWrap()` controls how textures behave when their uv's go beyond the texture. Doing so can produce interesting visual effects such as tiling. For example, the custom shape above could have u-coordinates are greater than the image’s width:
    // Apply the image as a texture.
    texture(img);
    
    // Draw the rectangle.
    beginShape();
    vertex(0, 0, 0, 0, 0);
    
    // Top-right.
    // u: 600
    vertex(30, 0, 0, 600, 0);
    
    // Bottom-right.
    // u: 600
    vertex(30, 50, 0, 600, 500);
    
    vertex(0, 50, 0, 0, 500);
    endShape();
    
The u-coordinates of 600 are greater than the texture image’s width of 300. This creates interesting possibilities.
The first parameter, `wrapX`, accepts three possible constants. If `CLAMP` is passed, as in `textureWrap(CLAMP)`, the pixels at the edge of the texture will extend to the shape’s edges. If `REPEAT` is passed, as in `textureWrap(REPEAT)`, the texture will tile repeatedly until reaching the shape’s edges. If `MIRROR` is passed, as in `textureWrap(MIRROR)`, the texture will tile repeatedly until reaching the shape’s edges, flipping its orientation between tiles. By default, textures `CLAMP`.
The second parameter, `wrapY`, is optional. It accepts the same three constants, `CLAMP`, `REPEAT`, and `MIRROR`. If one of these constants is passed, as in `textureWRAP(MIRROR, REPEAT)`, then the texture will `MIRROR` horizontally and `REPEAT` vertically. By default, `wrapY` will be set to the same value as `wrapX`.
Note: `textureWrap()` can only be used in WebGL mode.

method

textureWrap

wrapX

either CLAMP, REPEAT, or MIRROR

Constant

wrapY

either CLAMP, REPEAT, or MIRROR

Constant

` let img; function preload() { img = loadImage('assets/rockies128.jpg'); } function setup() { createCanvas(100, 100, WEBGL); describe( 'An image of a landscape occupies the top-left corner of a square. Its edge colors smear to cover the other thre quarters of the square.' ); } function draw() { background(0); // Set the texture mode. textureMode(NORMAL); // Set the texture wrapping. // Note: CLAMP is the default mode. textureWrap(CLAMP); // Apply the image as a texture. texture(img); // Style the shape. noStroke(); // Draw the shape. // Use uv coordinates > 1. beginShape(); vertex(-30, -30, 0, 0, 0); vertex(30, -30, 0, 2, 0); vertex(30, 30, 0, 2, 2); vertex(-30, 30, 0, 0, 2); endShape(); } `
` let img; function preload() { img = loadImage('assets/rockies128.jpg'); } function setup() { createCanvas(100, 100, WEBGL); describe('Four identical images of a landscape arranged in a grid.'); } function draw() { background(0); // Set the texture mode. textureMode(NORMAL); // Set the texture wrapping. textureWrap(REPEAT); // Apply the image as a texture. texture(img); // Style the shape. noStroke(); // Draw the shape. // Use uv coordinates > 1. beginShape(); vertex(-30, -30, 0, 0, 0); vertex(30, -30, 0, 2, 0); vertex(30, 30, 0, 2, 2); vertex(-30, 30, 0, 0, 2); endShape(); } `
` let img; function preload() { img = loadImage('assets/rockies128.jpg'); } function setup() { createCanvas(100, 100, WEBGL); describe( 'Four identical images of a landscape arranged in a grid. The images are reflected horizontally and vertically, creating a kaleidoscope effect.' ); } function draw() { background(0); // Set the texture mode. textureMode(NORMAL); // Set the texture wrapping. textureWrap(MIRROR); // Apply the image as a texture. texture(img); // Style the shape. noStroke(); // Draw the shape. // Use uv coordinates > 1. beginShape(); vertex(-30, -30, 0, 0, 0); vertex(30, -30, 0, 2, 0); vertex(30, 30, 0, 2, 2); vertex(-30, 30, 0, 0, 2); endShape(); } `
` let img; function preload() { img = loadImage('assets/rockies128.jpg'); } function setup() { createCanvas(100, 100, WEBGL); describe( 'Four identical images of a landscape arranged in a grid. The top row and bottom row are reflections of each other.' ); } function draw() { background(0); // Set the texture mode. textureMode(NORMAL); // Set the texture wrapping. textureWrap(REPEAT, MIRROR); // Apply the image as a texture. texture(img); // Style the shape. noStroke(); // Draw the shape. // Use uv coordinates > 1. beginShape(); vertex(-30, -30, 0, 0, 0); vertex(30, -30, 0, 2, 0); vertex(30, 30, 0, 2, 2); vertex(-30, 30, 0, 0, 2); endShape(); } `

p5

3D

Material

Sets the current material as a normal material.
A normal material sets surfaces facing the x-axis to red, those facing the y-axis to green, and those facing the z-axis to blue. Normal material isn't affected by light. It’s often used as a placeholder material when debugging.
Note: `normalMaterial()` can only be used in WebGL mode.

method

normalMaterial

` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A multicolor torus drawn on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Style the torus. normalMaterial(); // Draw the torus. torus(30); } `

p5

3D

Material

Sets the ambient color of shapes’ surface material.
The `ambientMaterial()` color sets the components of the ambientLight() color that shapes will reflect. For example, calling `ambientMaterial(255, 255, 0)` would cause a shape to reflect red and green light, but not blue light.
`ambientMaterial()` can be called three ways with different parameters to set the material’s color.
The first way to call `ambientMaterial()` has one parameter, `gray`. Grayscale values between 0 and 255, as in `ambientMaterial(50)`, can be passed to set the material’s color. Higher grayscale values make shapes appear brighter.
The second way to call `ambientMaterial()` has one parameter, `color`. A p5.Color object, an array of color values, or a CSS color string, as in `ambientMaterial('magenta')`, can be passed to set the material’s color.
The third way to call `ambientMaterial()` has three parameters, `v1`, `v2`, and `v3`. RGB, HSB, or HSL values, as in `ambientMaterial(255, 0, 0)`, can be passed to set the material’s colors. Color values will be interpreted using the current colorMode().
Note: `ambientMaterial()` can only be used in WebGL mode.

method

ambientMaterial

` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A magenta cube drawn on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Turn on a magenta ambient light. ambientLight(255, 0, 255); // Draw the box. box(); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A purple cube drawn on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Turn on a magenta ambient light. ambientLight(255, 0, 255); // Add a dark gray ambient material. ambientMaterial(150); // Draw the box. box(); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A red cube drawn on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Turn on a magenta ambient light. ambientLight(255, 0, 255); // Add a yellow ambient material using RGB values. ambientMaterial(255, 255, 0); // Draw the box. box(); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A red cube drawn on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Turn on a magenta ambient light. ambientLight(255, 0, 255); // Add a yellow ambient material using a p5.Color object. let c = color(255, 255, 0); ambientMaterial(c); // Draw the box. box(); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A red cube drawn on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Turn on a magenta ambient light. ambientLight(255, 0, 255); // Add a yellow ambient material using a color string. ambientMaterial('yellow'); // Draw the box. box(); } `
` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A yellow cube drawn on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Turn on a white ambient light. ambientLight(255, 255, 255); // Add a yellow ambient material using a color string. ambientMaterial('yellow'); // Draw the box. box(); } `

p5

3D

Material

v1

red or hue value in the current colorMode().

Number

v2

green or saturation value in the current colorMode().

Number

v3

blue, brightness, or lightness value in the current colorMode().

Number

gray

grayscale value between 0 (black) and 255 (white).

Number

color

color as a p5.Color object, an array of color values, or a CSS string.

p5.Color|Number[]|String

Sets the emissive color of shapes’ surface material.
The `emissiveMaterial()` color sets a color shapes display at full strength, regardless of lighting. This can give the appearance that a shape is glowing. However, emissive materials don’t actually emit light that can affect surrounding objects.
`emissiveMaterial()` can be called three ways with different parameters to set the material’s color.
The first way to call `emissiveMaterial()` has one parameter, `gray`. Grayscale values between 0 and 255, as in `emissiveMaterial(50)`, can be passed to set the material’s color. Higher grayscale values make shapes appear brighter.
The second way to call `emissiveMaterial()` has one parameter, `color`. A p5.Color object, an array of color values, or a CSS color string, as in `emissiveMaterial('magenta')`, can be passed to set the material’s color.
The third way to call `emissiveMaterial()` has four parameters, `v1`, `v2`, `v3`, and `alpha`. `alpha` is optional. RGBA, HSBA, or HSLA values can be passed to set the material’s colors, as in `emissiveMaterial(255, 0, 0)` or `emissiveMaterial(255, 0, 0, 30)`. Color values will be interpreted using the current colorMode().
Note: `emissiveMaterial()` can only be used in WebGL mode.

method

emissiveMaterial

` // Click and drag the mouse to view the scene from different angles. function setup() { createCanvas(100, 100, WEBGL); describe('A red cube drawn on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Turn on a white ambient light. ambientLight(255, 255, 255); // Add a red emissive material using RGB values. emissiveMaterial(255, 0, 0); // Draw the box. box(); } `

p5

3D

Material

v1

red or hue value in the current colorMode().

Number

v2

green or saturation value in the current colorMode().

Number

v3

blue, brightness, or lightness value in the current colorMode().

Number

alpha

alpha value in the current colorMode().

Number

gray

grayscale value between 0 (black) and 255 (white).

Number

color

color as a p5.Color object, an array of color values, or a CSS string.

p5.Color|Number[]|String

Sets the specular color of shapes’ surface material.
The `specularMaterial()` color sets the components of light color that glossy coats on shapes will reflect. For example, calling `specularMaterial(255, 255, 0)` would cause a shape to reflect red and green light, but not blue light.
Unlike ambientMaterial(), `specularMaterial()` will reflect the full color of light sources including directionalLight(), pointLight(), and spotLight(). This is what gives it shapes their "shiny" appearance. The material’s shininess can be controlled by the shininess() function.
`specularMaterial()` can be called three ways with different parameters to set the material’s color.
The first way to call `specularMaterial()` has one parameter, `gray`. Grayscale values between 0 and 255, as in `specularMaterial(50)`, can be passed to set the material’s color. Higher grayscale values make shapes appear brighter.
The second way to call `specularMaterial()` has one parameter, `color`. A p5.Color> object, an array of color values, or a CSS color string, as in `specularMaterial('magenta')`, can be passed to set the material’s color.
The third way to call `specularMaterial()` has four parameters, `v1`, `v2`, `v3`, and `alpha`. `alpha` is optional. RGBA, HSBA, or HSLA values can be passed to set the material’s colors, as in `specularMaterial(255, 0, 0)` or `specularMaterial(255, 0, 0, 30)`. Color values will be interpreted using the current colorMode().

method

specularMaterial

` // Click and drag the mouse to view the scene from different angles. // Double-click the canvas to apply a specular material. let isGlossy = false; function setup() { createCanvas(100, 100, WEBGL); describe('A red torus drawn on a gray background. It becomes glossy when the user double-clicks.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Turn on a white point light at the top-right. pointLight(255, 255, 255, 30, -40, 30); // Add a glossy coat if the user has double-clicked. if (isGlossy === true) { specularMaterial(255); shininess(50); } // Style the torus. noStroke(); fill(255, 0, 0); // Draw the torus. torus(30); } // Make the torus glossy when the user double-clicks. function doubleClicked() { isGlossy = true; } `
` // Click and drag the mouse to view the scene from different angles. // Double-click the canvas to apply a specular material. let isGlossy = false; function setup() { createCanvas(100, 100, WEBGL); describe( 'A red torus drawn on a gray background. It becomes glossy and reflects green light when the user double-clicks.' ); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Turn on a white point light at the top-right. pointLight(255, 255, 255, 30, -40, 30); // Add a glossy green coat if the user has double-clicked. if (isGlossy === true) { specularMaterial(0, 255, 0); shininess(50); } // Style the torus. noStroke(); fill(255, 0, 0); // Draw the torus. torus(30); } // Make the torus glossy when the user double-clicks. function doubleClicked() { isGlossy = true; } `
` // Click and drag the mouse to view the scene from different angles. // Double-click the canvas to apply a specular material. let isGlossy = false; function setup() { createCanvas(100, 100, WEBGL); describe( 'A red torus drawn on a gray background. It becomes glossy and reflects green light when the user double-clicks.' ); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Turn on a white point light at the top-right. pointLight(255, 255, 255, 30, -40, 30); // Add a glossy green coat if the user has double-clicked. if (isGlossy === true) { // Create a p5.Color object. let c = color('green'); specularMaterial(c); shininess(50); } // Style the torus. noStroke(); fill(255, 0, 0); // Draw the torus. torus(30); } // Make the torus glossy when the user double-clicks. function doubleClicked() { isGlossy = true; } `
` // Click and drag the mouse to view the scene from different angles. // Double-click the canvas to apply a specular material. let isGlossy = false; function setup() { createCanvas(100, 100, WEBGL); describe( 'A red torus drawn on a gray background. It becomes glossy and reflects green light when the user double-clicks.' ); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Turn on a white point light at the top-right. pointLight(255, 255, 255, 30, -40, 30); // Add a glossy green coat if the user has double-clicked. if (isGlossy === true) { specularMaterial('#00FF00'); shininess(50); } // Style the torus. noStroke(); fill(255, 0, 0); // Draw the torus. torus(30); } // Make the torus glossy when the user double-clicks. function doubleClicked() { isGlossy = true; } `

p5

3D

Material

gray

grayscale value between 0 (black) and 255 (white).

Number

alpha

alpha value in the current current colorMode().

Number

v1

red or hue value in the current colorMode().

Number

v2

green or saturation value in the current colorMode().

Number

v3

blue, brightness, or lightness value in the current colorMode().

Number

alpha



Number

color

color as a p5.Color object, an array of color values, or a CSS string.

p5.Color|Number[]|String

Sets the amount of gloss ("shininess") of a specularMaterial().
Shiny materials focus reflected light more than dull materials. `shininess()` affects the way materials reflect light sources including directionalLight(), pointLight(), and spotLight().
The parameter, `shine`, is a number that sets the amount of shininess. `shine` must be greater than 1, which is its default value.

method

shininess

shine

amount of shine.

Number

` function setup() { createCanvas(100, 100, WEBGL); describe( 'Two red spheres drawn on a gray background. White light reflects from their surfaces as the mouse moves. The right sphere is shinier than the left sphere.' ); } function draw() { background(200); // Turn on a red ambient light. ambientLight(255, 0, 0); // Get the mouse's coordinates. let mx = mouseX - 50; let my = mouseY - 50; // Turn on a white point light that follows the mouse. pointLight(255, 255, 255, mx, my, 50); // Style the sphere. noStroke(); // Add a specular material with a grayscale value. specularMaterial(255); // Draw the left sphere with low shininess. translate(-25, 0, 0); shininess(10); sphere(20); // Draw the right sphere with high shininess. translate(50, 0, 0); shininess(100); sphere(20); } `

p5

3D

Material

Sets the amount of "metalness" of a specularMaterial().
`metalness()` can make materials appear more metallic. It affects the way materials reflect light sources including affects the way materials reflect light sources including directionalLight(), pointLight(), spotLight(), and imageLight().
The parameter, `metallic`, is a number that sets the amount of metalness. `metallic` must be greater than 1, which is its default value. Higher values, such as `metalness(100)`, make specular materials appear more metallic.

method

metalness

metallic

amount of metalness.

Number

` function setup() { createCanvas(100, 100, WEBGL); describe( 'Two blue spheres drawn on a gray background. White light reflects from their surfaces as the mouse moves. The right sphere is more metallic than the left sphere.' ); } function draw() { background(200); // Turn on an ambient light. ambientLight(200); // Get the mouse's coordinates. let mx = mouseX - 50; let my = mouseY - 50; // Turn on a white point light that follows the mouse. pointLight(255, 255, 255, mx, my, 50); // Style the spheres. noStroke(); fill(30, 30, 255); specularMaterial(255); shininess(20); // Draw the left sphere with low metalness. translate(-25, 0, 0); metalness(1); sphere(20); // Draw the right sphere with high metalness. translate(50, 0, 0); metalness(50); sphere(20); } `
` // Click and drag the mouse to view the scene from different angles. let img; function preload() { img = loadImage('assets/outdoor_spheremap.jpg'); } function setup() { createCanvas(100 ,100 ,WEBGL); describe( 'Two spheres floating above a landscape. The surface of the spheres reflect the landscape. The right sphere is more reflective than the left sphere.' ); } function draw() { // Add the panorama. panorama(img); // Enable orbiting with the mouse. orbitControl(); // Use the image as a light source. imageLight(img); // Style the spheres. noStroke(); specularMaterial(50); shininess(200); // Draw the left sphere with low metalness. translate(-25, 0, 0); metalness(1); sphere(20); // Draw the right sphere with high metalness. translate(50, 0, 0); metalness(50); sphere(20); } `

p5

3D

Material

Sets the position and orientation of the current camera in a 3D sketch.
`camera()` allows objects to be viewed from different angles. It has nine parameters that are all optional.
The first three parameters, `x`, `y`, and `z`, are the coordinates of the camera’s position. For example, calling `camera(0, 0, 0)` places the camera at the origin `(0, 0, 0)`. By default, the camera is placed at `(0, 0, 800)`.
The next three parameters, `centerX`, `centerY`, and `centerZ` are the coordinates of the point where the camera faces. For example, calling `camera(0, 0, 0, 10, 20, 30)` places the camera at the origin `(0, 0, 0)` and points it at `(10, 20, 30)`. By default, the camera points at the origin `(0, 0, 0)`.
The last three parameters, `upX`, `upY`, and `upZ` are the components of the "up" vector. The "up" vector orients the camera’s y-axis. For example, calling `camera(0, 0, 0, 10, 20, 30, 0, -1, 0)` places the camera at the origin `(0, 0, 0)`, points it at `(10, 20, 30)`, and sets the "up" vector to `(0, -1, 0)` which is like holding it upside-down. By default, the "up" vector is `(0, 1, 0)`.
Note: `camera()` can only be used in WebGL mode.

method

camera

x

x-coordinate of the camera. Defaults to 0.

Number

y

y-coordinate of the camera. Defaults to 0.

Number

z

z-coordinate of the camera. Defaults to 800.

Number

centerX

x-coordinate of the point the camera faces. Defaults to 0.

Number

centerY

y-coordinate of the point the camera faces. Defaults to 0.

Number

centerZ

z-coordinate of the point the camera faces. Defaults to 0.

Number

upX

x-component of the camera’s "up" vector. Defaults to 0.

Number

upY

y-component of the camera’s "up" vector. Defaults to 1.

Number

upZ

z-component of the camera’s "up" vector. Defaults to 0.

Number

` function setup() { createCanvas(100, 100, WEBGL); describe('A white cube on a gray background.'); } function draw() { background(200); // Move the camera to the top-right. camera(200, -400, 800); // Draw the box. box(); } `
` function setup() { createCanvas(100, 100, WEBGL); describe('A white cube apperas to sway left and right on a gray background.'); } function draw() { background(200); // Calculate the camera's x-coordinate. let x = 400 * cos(frameCount * 0.01); // Orbit the camera around the box. camera(x, -400, 800); // Draw the box. box(); } `
` // Adjust the range sliders to change the camera's position. let xSlider; let ySlider; let zSlider; function setup() { createCanvas(100, 100, WEBGL); // Create slider objects to set the camera's coordinates. xSlider = createSlider(-400, 400, 400); xSlider.position(0, 100); xSlider.size(100); ySlider = createSlider(-400, 400, -200); ySlider.position(0, 120); ySlider.size(100); zSlider = createSlider(0, 1600, 800); zSlider.position(0, 140); zSlider.size(100); describe( 'A white cube drawn against a gray background. Three range sliders appear beneath the image. The camera position changes when the user moves the sliders.' ); } function draw() { background(200); // Get the camera's coordinates from the sliders. let x = xSlider.value(); let y = ySlider.value(); let z = zSlider.value(); // Move the camera. camera(x, y, z); // Draw the box. box(); } `

p5

3D

Camera

Sets a perspective projection for the current camera in a 3D sketch.
In a perspective projection, shapes that are further from the camera appear smaller than shapes that are near the camera. This technique, called foreshortening, creates realistic 3D scenes. It’s applied by default in WebGL mode.
`perspective()` changes the camera’s perspective by changing its viewing frustum. The frustum is the volume of space that’s visible to the camera. Its shape is a pyramid with its top cut off. The camera is placed where the top of the pyramid should be and views everything between the frustum’s top (near) plane and its bottom (far) plane.
The first parameter, `fovy`, is the camera’s vertical field of view. It’s an angle that describes how tall or narrow a view the camera has. For example, calling `perspective(0.5)` sets the camera’s vertical field of view to 0.5 radians. By default, `fovy` is calculated based on the sketch’s height and the camera’s default z-coordinate, which is 800. The formula for the default `fovy` is `2 * atan(height / 2 / 800)`.
The second parameter, `aspect`, is the camera’s aspect ratio. It’s a number that describes the ratio of the top plane’s width to its height. For example, calling `perspective(0.5, 1.5)` sets the camera’s field of view to 0.5 radians and aspect ratio to 1.5, which would make shapes appear thinner on a square canvas. By default, aspect is set to `width / height`.
The third parameter, `near`, is the distance from the camera to the near plane. For example, calling `perspective(0.5, 1.5, 100)` sets the camera’s field of view to 0.5 radians, its aspect ratio to 1.5, and places the near plane 100 pixels from the camera. Any shapes drawn less than 100 pixels from the camera won’t be visible. By default, near is set to `0.1 * 800`, which is 1/10th the default distance between the camera and the origin.
The fourth parameter, `far`, is the distance from the camera to the far plane. For example, calling `perspective(0.5, 1.5, 100, 10000)` sets the camera’s field of view to 0.5 radians, its aspect ratio to 1.5, places the near plane 100 pixels from the camera, and places the far plane 10,000 pixels from the camera. Any shapes drawn more than 10,000 pixels from the camera won’t be visible. By default, far is set to `10 * 800`, which is 10 times the default distance between the camera and the origin.
Note: `perspective()` can only be used in WebGL mode.

method

perspective

fovy

camera frustum vertical field of view. Defaults to `2 * atan(height / 2 / 800)`.

Number

aspect

camera frustum aspect ratio. Defaults to `width / height`.

Number

near

distance from the camera to the near clipping plane. Defaults to `0.1 * 800`.

Number

far

distance from the camera to the far clipping plane. Defaults to `10 * 800`.

Number

` // Double-click to squeeze the box. let isSqueezed = false; function setup() { createCanvas(100, 100, WEBGL); describe('A white rectangular prism on a gray background. The box appears to become thinner when the user double-clicks.'); } function draw() { background(200); // Place the camera at the top-right. camera(400, -400, 800); if (isSqueezed === true) { // Set fovy to 0.2. // Set aspect to 1.5. perspective(0.2, 1.5); } // Draw the box. box(); } // Change the camera's perspective when the user double-clicks. function doubleClicked() { isSqueezed = true; } `
` function setup() { createCanvas(100, 100, WEBGL); describe('A white rectangular prism on a gray background. The prism moves away from the camera until it disappears.'); } function draw() { background(200); // Place the camera at the top-right. camera(400, -400, 800); // Set fovy to 0.2. // Set aspect to 1.5. // Set near to 600. // Set far to 1200. perspective(0.2, 1.5, 600, 1200); // Move the origin away from the camera. let x = -frameCount; let y = frameCount; let z = -2 * frameCount; translate(x, y, z); // Draw the box. box(); } `

p5

3D

Camera

Enables or disables perspective for lines in 3D sketches.
In WebGL mode, lines can be drawn with a thinner stroke when they’re further from the camera. Doing so gives them a more realistic appearance.
By default, lines are drawn differently based on the type of perspective being used:
    * `perspective()` and `frustum()` simulate a realistic perspective. In these modes, stroke weight is affected by the line’s distance from the camera. Doing so results in a more natural appearance. `perspective()` is the default mode for 3D sketches.
    * `ortho()` doesn’t simulate a realistic perspective. In this mode, stroke weights are consistent regardless of the line’s distance from the camera. Doing so results in a more predictable and consistent appearance.
`linePerspective()` can override the default line drawing mode.
The parameter, `enable`, is optional. It’s a `Boolean` value that sets the way lines are drawn. If `true` is passed, as in `linePerspective(true)`, then lines will appear thinner when they are further from the camera. If `false` is passed, as in `linePerspective(false)`, then lines will have consistent stroke weights regardless of their distance from the camera. By default, `linePerspective()` is enabled.
Calling `linePerspective()` without passing an argument returns `true` if it's enabled and `false` if not.
Note: `linePerspective()` can only be used in WebGL mode.

method

linePerspective

` // Double-click the canvas to toggle the line perspective. function setup() { createCanvas(100, 100, WEBGL); describe( 'A white cube with black edges on a gray background. Its edges toggle between thick and thin when the user double-clicks.' ); } function draw() { background(200); // Translate the origin toward the camera. translate(-10, 10, 600); // Rotate the coordinate system. rotateY(-0.1); rotateX(-0.1); // Draw the row of boxes. for (let i = 0; i < 6; i += 1) { translate(0, 0, -40); box(10); } } // Toggle the line perspective when the user double-clicks. function doubleClicked() { let isEnabled = linePerspective(); linePerspective(!isEnabled); } `
` // Double-click the canvas to toggle the line perspective. function setup() { createCanvas(100, 100, WEBGL); describe( 'A row of cubes with black edges on a gray background. Their edges toggle between thick and thin when the user double-clicks.' ); } function draw() { background(200); // Use an orthographic projection. ortho(); // Translate the origin toward the camera. translate(-10, 10, 600); // Rotate the coordinate system. rotateY(-0.1); rotateX(-0.1); // Draw the row of boxes. for (let i = 0; i < 6; i += 1) { translate(0, 0, -40); box(10); } } // Toggle the line perspective when the user double-clicks. function doubleClicked() { let isEnabled = linePerspective(); linePerspective(!isEnabled); } `

p5

3D

Camera

enable

whether to enable line perspective.

Boolean

##### return
whether line perspective is enabled.

Boolean

Sets an orthographic projection for the current camera in a 3D sketch.
In an orthographic projection, shapes with the same size always appear the same size, regardless of whether they are near or far from the camera.
`ortho()` changes the camera’s perspective by changing its viewing frustum from a truncated pyramid to a rectangular prism. The camera is placed in front of the frustum and views everything between the frustum’s near plane and its far plane. `ortho()` has six optional parameters to define the frustum.
The first four parameters, `left`, `right`, `bottom`, and `top`, set the coordinates of the frustum’s sides, bottom, and top. For example, calling `ortho(-100, 100, 200, -200)` creates a frustum that’s 200 pixels wide and 400 pixels tall. By default, these coordinates are set based on the sketch’s width and height, as in `ortho(-width / 2, width / 2, -height / 2, height / 2)`.
The last two parameters, `near` and `far`, set the distance of the frustum’s near and far plane from the camera. For example, calling `ortho(-100, 100, 200, 200, 50, 1000)` creates a frustum that’s 200 pixels wide, 400 pixels tall, starts 50 pixels from the camera, and ends 1,000 pixels from the camera. By default, `near` and `far` are set to 0 and `max(width, height) + 800`, respectively.
Note: `ortho()` can only be used in WebGL mode.

method

ortho

left

x-coordinate of the frustum’s left plane. Defaults to `-width / 2`.

Number

right

x-coordinate of the frustum’s right plane. Defaults to `width / 2`.

Number

bottom

y-coordinate of the frustum’s bottom plane. Defaults to `height / 2`.

Number

top

y-coordinate of the frustum’s top plane. Defaults to `-height / 2`.

Number

near

z-coordinate of the frustum’s near plane. Defaults to 0.

Number

far

z-coordinate of the frustum’s far plane. Defaults to `max(width, height) + 800`.

Number

` function setup() { createCanvas(100, 100, WEBGL); describe('A row of tiny, white cubes on a gray background. All the cubes appear the same size.'); } function draw() { background(200); // Apply an orthographic projection. ortho(); // Translate the origin toward the camera. translate(-10, 10, 600); // Rotate the coordinate system. rotateY(-0.1); rotateX(-0.1); // Draw the row of boxes. for (let i = 0; i < 6; i += 1) { translate(0, 0, -40); box(10); } } `
` function setup() { createCanvas(100, 100, WEBGL); describe('A white cube on a gray background.'); } function draw() { background(200); // Apply an orthographic projection. // Center the frustum. // Set its width and height to 20. // Place its near plane 300 pixels from the camera. // Place its far plane 350 pixels from the camera. ortho(-10, 10, -10, 10, 300, 350); // Translate the origin toward the camera. translate(-10, 10, 600); // Rotate the coordinate system. rotateY(-0.1); rotateX(-0.1); // Draw the row of boxes. for (let i = 0; i < 6; i += 1) { translate(0, 0, -40); box(10); } } `

p5

3D

Camera

Sets the frustum of the current camera in a 3D sketch.
In a frustum projection, shapes that are further from the camera appear smaller than shapes that are near the camera. This technique, called foreshortening, creates realistic 3D scenes.
`frustum()` changes the default camera’s perspective by changing its viewing frustum. The frustum is the volume of space that’s visible to the camera. The frustum’s shape is a pyramid with its top cut off. The camera is placed where the top of the pyramid should be and points towards the base of the pyramid. It views everything within the frustum.
The first four parameters, `left`, `right`, `bottom`, and `top`, set the coordinates of the frustum’s sides, bottom, and top. For example, calling `frustum(-100, 100, 200, -200)` creates a frustum that’s 200 pixels wide and 400 pixels tall. By default, these coordinates are set based on the sketch’s width and height, as in `ortho(-width / 20, width / 20, height / 20, -height / 20)`.
The last two parameters, `near` and `far`, set the distance of the frustum’s near and far plane from the camera. For example, calling `ortho(-100, 100, 200, -200, 50, 1000)` creates a frustum that’s 200 pixels wide, 400 pixels tall, starts 50 pixels from the camera, and ends 1,000 pixels from the camera. By default, near is set to `0.1 * 800`, which is 1/10th the default distance between the camera and the origin. `far` is set to `10 * 800`, which is 10 times the default distance between the camera and the origin.
Note: `frustum()` can only be used in WebGL mode.

method

frustum

left

x-coordinate of the frustum’s left plane. Defaults to `-width / 20`.

Number

right

x-coordinate of the frustum’s right plane. Defaults to `width / 20`.

Number

bottom

y-coordinate of the frustum’s bottom plane. Defaults to `height / 20`.

Number

top

y-coordinate of the frustum’s top plane. Defaults to `-height / 20`.

Number

near

z-coordinate of the frustum’s near plane. Defaults to `0.1 * 800`.

Number

far

z-coordinate of the frustum’s far plane. Defaults to `10 * 800`.

Number

` function setup() { createCanvas(100, 100, WEBGL); describe('A row of white cubes on a gray background.'); } function draw() { background(200); // Apply the default frustum projection. frustum(); // Translate the origin toward the camera. translate(-10, 10, 600); // Rotate the coordinate system. rotateY(-0.1); rotateX(-0.1); // Draw the row of boxes. for (let i = 0; i < 6; i += 1) { translate(0, 0, -40); box(10); } } `
` function setup() { createCanvas(100, 100, WEBGL); describe('A white cube on a gray background.'); } function draw() { background(200); // Adjust the frustum. // Center it. // Set its width and height to 20 pixels. // Place its near plane 300 pixels from the camera. // Place its far plane 350 pixels from the camera. frustum(-10, 10, -10, 10, 300, 350); // Translate the origin toward the camera. translate(-10, 10, 600); // Rotate the coordinate system. rotateY(-0.1); rotateX(-0.1); // Draw the row of boxes. for (let i = 0; i < 6; i += 1) { translate(0, 0, -40); box(10); } } `

p5

3D

Camera

Creates a new p5.Camera object and sets it as the current (active) camera.
The new camera is initialized with a default position `(0, 0, 800)` and a default perspective projection. Its properties can be controlled with p5.Camera methods such as `myCamera.lookAt(0, 0, 0)`.
Note: Every 3D sketch starts with a default camera initialized. This camera can be controlled with the functions camera(), perspective(), ortho(), and frustum() if it's the only camera in the scene.
Note: `createCamera()` can only be used in WebGL mode.

method

createCamera

### return
the new camera.

p5.Camera

` // Double-click to toggle between cameras. let cam1; let cam2; let usingCam1 = true; function setup() { createCanvas(100, 100, WEBGL); // Create the first camera. // Keep its default settings. cam1 = createCamera(); // Create the second camera. // Place it at the top-left. // Point it at the origin. cam2 = createCamera(); cam2.setPosition(400, -400, 800); cam2.lookAt(0, 0, 0); // Set the current camera to cam1. setCamera(cam1); describe('A white cube on a gray background. The camera toggles between frontal and aerial views when the user double-clicks.'); } function draw() { background(200); // Draw the box. box(); } // Toggle the current camera when the user double-clicks. function doubleClicked() { if (usingCam1 === true) { setCamera(cam2); usingCam1 = false; } else { setCamera(cam1); usingCam1 = true; } } `

p5

3D

Camera

The camera’s x-coordinate.
By default, the camera’s x-coordinate is set to 0 in "world" space.

property

eyeX

Number



` let cam; let font; // Load a font and create a p5.Font object. function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Camera object. cam = createCamera(); // Place the camera at the top-center. cam.setPosition(0, -400, 800); // Point the camera at the origin. cam.lookAt(0, 0, 0); describe( 'A white cube on a gray background. The text "eyeX: 0" is written in black beneath it.' ); } function draw() { background(200); // Style the box. fill(255); // Draw the box. box(); // Style the text. textAlign(CENTER); textSize(16); textFont(font); fill(0); // Display the value of eyeX, rounded to the nearest integer. text(`eyeX: ${round(cam.eyeX)}`, 0, 55); } `
` let cam; let font; // Load a font and create a p5.Font object. function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Camera object. cam = createCamera(); // Place the camera at the top-center. cam.setPosition(0, -400, 800); // Point the camera at the origin. cam.lookAt(0, 0, 0); describe( 'A white cube on a gray background. The cube appears to move left and right as the camera moves. The text "eyeX: X" is written in black beneath the cube. X oscillates between -25 and 25.' ); } function draw() { background(200); // Style the box. fill(255); // Draw the box. box(); // Style the text. textAlign(CENTER); textSize(16); textFont(font); fill(0); // Calculate the new x-coordinate. let x = 25 * sin(frameCount * 0.01); // Set the camera's position. cam.setPosition(x, -400, 800); // Display the value of eyeX, rounded to the nearest integer. text(`eyeX: ${round(cam.eyeX)}`, 0, 55); } `

p5.Camera

3D

Camera

The camera’s y-coordinate.
By default, the camera’s y-coordinate is set to 0 in "world" space.

property

eyeY

Number



` let cam; let font; // Load a font and create a p5.Font object. function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Camera object. cam = createCamera(); // Place the camera at the top-center. cam.setPosition(0, -400, 800); // Point the camera at the origin. cam.lookAt(0, 0, 0); describe( 'A white cube on a gray background. The text "eyeY: -400" is written in black beneath it.' ); } function draw() { background(200); // Style the box. fill(255); // Draw the box. box(); // Style the text. textAlign(CENTER); textSize(16); textFont(font); fill(0); // Display the value of eyeY, rounded to the nearest integer. text(`eyeX: ${round(cam.eyeY)}`, 0, 55); } `
` let cam; let font; // Load a font and create a p5.Font object. function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Camera object. cam = createCamera(); // Place the camera at the top-center. cam.setPosition(0, -400, 800); // Point the camera at the origin. cam.lookAt(0, 0, 0); describe( 'A white cube on a gray background. The cube appears to move up and down as the camera moves. The text "eyeY: Y" is written in black beneath the cube. Y oscillates between -374 and -425.' ); } function draw() { background(200); // Style the box. fill(255); // Draw the box. box(); // Style the text. textAlign(CENTER); textSize(16); textFont(font); fill(0); // Calculate the new y-coordinate. let y = 25 * sin(frameCount * 0.01) - 400; // Set the camera's position. cam.setPosition(0, y, 800); // Display the value of eyeY, rounded to the nearest integer. text(`eyeY: ${round(cam.eyeY)}`, 0, 55); } `

p5.Camera

3D

Camera

The camera’s z-coordinate.
By default, the camera’s z-coordinate is set to 800 in "world" space.

property

eyeZ

Number



` let cam; let font; // Load a font and create a p5.Font object. function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Camera object. cam = createCamera(); // Place the camera at the top-center. cam.setPosition(0, -400, 800); // Point the camera at the origin. cam.lookAt(0, 0, 0); describe( 'A white cube on a gray background. The text "eyeZ: 800" is written in black beneath it.' ); } function draw() { background(200); // Style the box. fill(255); // Draw the box. box(); // Style the text. textAlign(CENTER); textSize(16); textFont(font); fill(0); // Display the value of eyeZ, rounded to the nearest integer. text(`eyeZ: ${round(cam.eyeZ)}`, 0, 55); } `
` let cam; let font; // Load a font and create a p5.Font object. function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Camera object. cam = createCamera(); // Place the camera at the top-center. cam.setPosition(0, -400, 800); // Point the camera at the origin. cam.lookAt(0, 0, 0); describe( 'A white cube on a gray background. The cube appears to move forward and back as the camera moves. The text "eyeZ: Z" is written in black beneath the cube. Z oscillates between 700 and 900.' ); } function draw() { background(200); // Style the box. fill(255); // Draw the box. box(); // Style the text. textAlign(CENTER); textSize(16); textFont(font); fill(0); // Calculate the new z-coordinate. let z = 100 * sin(frameCount * 0.01) + 800; // Set the camera's position. cam.setPosition(0, -400, z); // Display the value of eyeZ, rounded to the nearest integer. text(`eyeZ: ${round(cam.eyeZ)}`, 0, 55); } `

p5.Camera

3D

Camera

The x-coordinate of the place where the camera looks.
By default, the camera looks at the origin `(0, 0, 0)` in "world" space, so `myCamera.centerX` is 0.

property

centerX

Number



` let cam; let font; // Load a font and create a p5.Font object. function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Camera object. cam = createCamera(); // Place the camera at the top-center. cam.setPosition(0, -400, 800); // Point the camera at (10, 20, -30). cam.lookAt(10, 20, -30); describe( 'A white cube on a gray background. The text "centerX: 10" is written in black beneath it.' ); } function draw() { background(200); // Style the box. fill(255); // Draw the box. box(); // Style the text. textAlign(CENTER); textSize(16); textFont(font); fill(0); // Display the value of centerX, rounded to the nearest integer. text(`centerX: ${round(cam.centerX)}`, 0, 55); } `
` let cam; let font; // Load a font and create a p5.Font object. function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Camera object. cam = createCamera(); // Place the camera at the top-right. cam.setPosition(100, -400, 800); // Point the camera at (10, 20, -30). cam.lookAt(10, 20, -30); describe( 'A white cube on a gray background. The cube appears to move left and right as the camera shifts its focus. The text "centerX: X" is written in black beneath the cube. X oscillates between -15 and 35.' ); } function draw() { background(200); // Style the box. fill(255); // Draw the box. box(); // Style the text. textAlign(CENTER); textSize(16); textFont(font); fill(0); // Calculate the new x-coordinate. let x = 25 * sin(frameCount * 0.01) + 10; // Point the camera. cam.lookAt(x, 20, -30); // Display the value of centerX, rounded to the nearest integer. text(`centerX: ${round(cam.centerX)}`, 0, 55); } `

p5.Camera

3D

Camera

The y-coordinate of the place where the camera looks.
By default, the camera looks at the origin `(0, 0, 0)` in "world" space, so `myCamera.centerY` is 0.

property

centerY

Number



` let cam; let font; // Load a font and create a p5.Font object. function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Camera object. cam = createCamera(); // Place the camera at the top-center. cam.setPosition(0, -400, 800); // Point the camera at (10, 20, -30). cam.lookAt(10, 20, -30); describe( 'A white cube on a gray background. The text "centerY: 20" is written in black beneath it.' ); } function draw() { background(200); // Style the box. fill(255); // Draw the box. box(); // Style the text. textAlign(CENTER); textSize(16); textFont(font); fill(0); // Display the value of centerY, rounded to the nearest integer. text(`centerY: ${round(cam.centerY)}`, 0, 55); } `
` let cam; let font; // Load a font and create a p5.Font object. function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Camera object. cam = createCamera(); // Place the camera at the top-right. cam.setPosition(100, -400, 800); // Point the camera at (10, 20, -30). cam.lookAt(10, 20, -30); describe( 'A white cube on a gray background. The cube appears to move up and down as the camera shifts its focus. The text "centerY: Y" is written in black beneath the cube. Y oscillates between -5 and 45.' ); } function draw() { background(200); // Style the box. fill(255); // Draw the box. box(); // Style the text. textAlign(CENTER); textSize(16); textFont(font); fill(0); // Calculate the new y-coordinate. let y = 25 * sin(frameCount * 0.01) + 20; // Point the camera. cam.lookAt(10, y, -30); // Display the value of centerY, rounded to the nearest integer. text(`centerY: ${round(cam.centerY)}`, 0, 55); } `

p5.Camera

3D

Camera

The y-coordinate of the place where the camera looks.
By default, the camera looks at the origin `(0, 0, 0)` in "world" space, so `myCamera.centerZ` is 0.

property

centerZ

Number



` let cam; let font; // Load a font and create a p5.Font object. function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Camera object. cam = createCamera(); // Place the camera at the top-center. cam.setPosition(0, -400, 800); // Point the camera at (10, 20, -30). cam.lookAt(10, 20, -30); describe( 'A white cube on a gray background. The text "centerZ: -30" is written in black beneath it.' ); } function draw() { background(200); // Style the box. fill(255); // Draw the box. box(); // Style the text. textAlign(CENTER); textSize(16); textFont(font); fill(0); // Display the value of centerZ, rounded to the nearest integer. text(`centerZ: ${round(cam.centerZ)}`, 0, 55); } `
` let cam; let font; // Load a font and create a p5.Font object. function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Camera object. cam = createCamera(); // Place the camera at the top-right. cam.setPosition(100, -400, 800); // Point the camera at (10, 20, -30). cam.lookAt(10, 20, -30); describe( 'A white cube on a gray background. The cube appears to move forward and back as the camera shifts its focus. The text "centerZ: Z" is written in black beneath the cube. Z oscillates between -55 and -25.' ); } function draw() { background(200); // Style the box. fill(255); // Draw the box. box(); // Style the text. textAlign(CENTER); textSize(16); textFont(font); fill(0); // Calculate the new z-coordinate. let z = 25 * sin(frameCount * 0.01) - 30; // Point the camera. cam.lookAt(10, 20, z); // Display the value of centerZ, rounded to the nearest integer. text(`centerZ: ${round(cam.centerZ)}`, 0, 55); } `

p5.Camera

3D

Camera

The x-component of the camera's "up" vector.
The camera's "up" vector orients its y-axis. By default, the "up" vector is `(0, 1, 0)`, so its x-component is 0 in "local" space.

property

upX

Number



` let cam; let font; // Load a font and create a p5.Font object. function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Camera object. cam = createCamera(); // Place the camera at the top-right: (100, -400, 800) // Point it at the origin: (0, 0, 0) // Set its "up" vector: (0, 1, 0). cam.camera(100, -400, 800, 0, 0, 0, 0, 1, 0); describe( 'A white cube on a gray background. The text "upX: 0" is written in black beneath it.' ); } function draw() { background(200); // Style the box. fill(255); // Draw the box. box(); // Style the text. textAlign(CENTER); textSize(16); textFont(font); fill(0); // Display the value of upX, rounded to the nearest tenth. text(`upX: ${round(cam.upX, 1)}`, 0, 55); } `
` let cam; let font; // Load a font and create a p5.Font object. function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Camera object. cam = createCamera(); // Place the camera at the top-right: (100, -400, 800) // Point it at the origin: (0, 0, 0) // Set its "up" vector: (0, 1, 0). cam.camera(100, -400, 800, 0, 0, 0, 0, 1, 0); describe( 'A white cube on a gray background. The cube appears to rock back and forth. The text "upX: X" is written in black beneath it. X oscillates between -1 and 1.' ); } function draw() { background(200); // Style the box. fill(255); // Draw the box. box(); // Style the text. textAlign(CENTER); textSize(16); textFont(font); fill(0); // Calculate the x-component. let x = sin(frameCount * 0.01); // Update the camera's "up" vector. cam.camera(100, -400, 800, 0, 0, 0, x, 1, 0); // Display the value of upX, rounded to the nearest tenth. text(`upX: ${round(cam.upX, 1)}`, 0, 55); } `

p5.Camera

3D

Camera

The y-component of the camera's "up" vector.
The camera's "up" vector orients its y-axis. By default, the "up" vector is `(0, 1, 0)`, so its y-component is 1 in "local" space.

property

upY

Number



` let cam; let font; // Load a font and create a p5.Font object. function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Camera object. cam = createCamera(); // Place the camera at the top-right: (100, -400, 800) // Point it at the origin: (0, 0, 0) // Set its "up" vector: (0, 1, 0). cam.camera(100, -400, 800, 0, 0, 0, 0, 1, 0); describe( 'A white cube on a gray background. The text "upY: 1" is written in black beneath it.' ); } function draw() { background(200); // Style the box. fill(255); // Draw the box. box(); // Style the text. textAlign(CENTER); textSize(16); textFont(font); fill(0); // Display the value of upY, rounded to the nearest tenth. text(`upY: ${round(cam.upY, 1)}`, 0, 55); } `
` let cam; let font; // Load a font and create a p5.Font object. function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Camera object. cam = createCamera(); // Place the camera at the top-right: (100, -400, 800) // Point it at the origin: (0, 0, 0) // Set its "up" vector: (0, 1, 0). cam.camera(100, -400, 800, 0, 0, 0, 0, 1, 0); describe( 'A white cube on a gray background. The cube flips upside-down periodically. The text "upY: Y" is written in black beneath it. Y oscillates between -1 and 1.' ); } function draw() { background(200); // Style the box. fill(255); // Draw the box. box(); // Style the text. textAlign(CENTER); textSize(16); textFont(font); fill(0); // Calculate the y-component. let y = sin(frameCount * 0.01); // Update the camera's "up" vector. cam.camera(100, -400, 800, 0, 0, 0, 0, y, 0); // Display the value of upY, rounded to the nearest tenth. text(`upY: ${round(cam.upY, 1)}`, 0, 55); } `

p5.Camera

3D

Camera

The z-component of the camera's "up" vector.
The camera's "up" vector orients its y-axis. By default, the "up" vector is `(0, 1, 0)`, so its z-component is 0 in "local" space.

property

upZ

Number



` let cam; let font; // Load a font and create a p5.Font object. function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Camera object. cam = createCamera(); // Place the camera at the top-right: (100, -400, 800) // Point it at the origin: (0, 0, 0) // Set its "up" vector: (0, 1, 0). cam.camera(100, -400, 800, 0, 0, 0, 0, 1, 0); describe( 'A white cube on a gray background. The text "upZ: 0" is written in black beneath it.' ); } function draw() { background(200); // Style the box. fill(255); // Draw the box. box(); // Style the text. textAlign(CENTER); textSize(16); textFont(font); fill(0); // Display the value of upZ, rounded to the nearest tenth. text(`upZ: ${round(cam.upZ, 1)}`, 0, 55); } `
` let cam; let font; // Load a font and create a p5.Font object. function preload() { font = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Camera object. cam = createCamera(); // Place the camera at the top-right: (100, -400, 800) // Point it at the origin: (0, 0, 0) // Set its "up" vector: (0, 1, 0). cam.camera(100, -400, 800, 0, 0, 0, 0, 1, 0); describe( 'A white cube on a gray background. The cube appears to rock back and forth. The text "upZ: Z" is written in black beneath it. Z oscillates between -1 and 1.' ); } function draw() { background(200); // Style the box. fill(255); // Draw the box. box(); // Style the text. textAlign(CENTER); textSize(16); textFont(font); fill(0); // Calculate the z-component. let z = sin(frameCount * 0.01); // Update the camera's "up" vector. cam.camera(100, -400, 800, 0, 0, 0, 0, 1, z); // Display the value of upZ, rounded to the nearest tenth. text(`upZ: ${round(cam.upZ, 1)}`, 0, 55); } `

p5.Camera

3D

Camera

Sets a perspective projection for the camera.
In a perspective projection, shapes that are further from the camera appear smaller than shapes that are near the camera. This technique, called foreshortening, creates realistic 3D scenes. It’s applied by default in new `p5.Camera` objects.
`myCamera.perspective()` changes the camera’s perspective by changing its viewing frustum. The frustum is the volume of space that’s visible to the camera. The frustum’s shape is a pyramid with its top cut off. The camera is placed where the top of the pyramid should be and points towards the base of the pyramid. It views everything within the frustum.
The first parameter, `fovy`, is the camera’s vertical field of view. It’s an angle that describes how tall or narrow a view the camera has. For example, calling `myCamera.perspective(0.5)` sets the camera’s vertical field of view to 0.5 radians. By default, `fovy` is calculated based on the sketch’s height and the camera’s default z-coordinate, which is 800. The formula for the default `fovy` is `2 * atan(height / 2 / 800)`.
The second parameter, `aspect`, is the camera’s aspect ratio. It’s a number that describes the ratio of the top plane’s width to its height. For example, calling `myCamera.perspective(0.5, 1.5)` sets the camera’s field of view to 0.5 radians and aspect ratio to 1.5, which would make shapes appear thinner on a square canvas. By default, `aspect` is set to `width / height`.
The third parameter, `near`, is the distance from the camera to the near plane. For example, calling `myCamera.perspective(0.5, 1.5, 100)` sets the camera’s field of view to 0.5 radians, its aspect ratio to 1.5, and places the near plane 100 pixels from the camera. Any shapes drawn less than 100 pixels from the camera won’t be visible. By default, `near` is set to `0.1 * 800`, which is 1/10th the default distance between the camera and the origin.
The fourth parameter, `far`, is the distance from the camera to the far plane. For example, calling `myCamera.perspective(0.5, 1.5, 100, 10000)` sets the camera’s field of view to 0.5 radians, its aspect ratio to 1.5, places the near plane 100 pixels from the camera, and places the far plane 10,000 pixels from the camera. Any shapes drawn more than 10,000 pixels from the camera won’t be visible. By default, `far` is set to `10 * 800`, which is 10 times the default distance between the camera and the origin.

method

perspective

fovy

camera frustum vertical field of view. Defaults to `2 * atan(height / 2 / 800)`.

Number

aspect

camera frustum aspect ratio. Defaults to `width / height`.

Number

near

distance from the camera to the near clipping plane. Defaults to `0.1 * 800`.

Number

far

distance from the camera to the far clipping plane. Defaults to `10 * 800`.

Number

` // Double-click to toggle between cameras. let cam1; let cam2; let isDefaultCamera = true; function setup() { createCanvas(100, 100, WEBGL); // Create the first camera. // Keep its default settings. cam1 = createCamera(); // Create the second camera. cam2 = createCamera(); // Place it at the top-right. cam2.camera(400, -400, 800); // Set its fovy to 0.2. // Set its aspect to 1.5. // Set its near to 600. // Set its far to 1200. cam2.perspective(0.2, 1.5, 600, 1200); // Set the current camera to cam1. setCamera(cam1); describe('A white cube on a gray background. The camera toggles between a frontal view and a skewed aerial view when the user double-clicks.'); } function draw() { background(200); // Draw the box. box(); } // Toggle the current camera when the user double-clicks. function doubleClicked() { if (isDefaultCamera === true) { setCamera(cam2); isDefaultCamera = false; } else { setCamera(cam1); isDefaultCamera = true; } } `
` // Double-click to toggle between cameras. let cam1; let cam2; let isDefaultCamera = true; function setup() { createCanvas(100, 100, WEBGL); // Create the first camera. // Keep its default settings. cam1 = createCamera(); // Create the second camera. cam2 = createCamera(); // Place it at the top-right. cam2.camera(400, -400, 800); // Set its fovy to 0.2. // Set its aspect to 1.5. // Set its near to 600. // Set its far to 1200. cam2.perspective(0.2, 1.5, 600, 1200); // Set the current camera to cam1. setCamera(cam1); describe('A white cube moves left and right on a gray background. The camera toggles between a frontal and a skewed aerial view when the user double-clicks.'); } function draw() { background(200); // Translate the origin left and right. let x = 100 * sin(frameCount * 0.01); translate(x, 0, 0); // Draw the box. box(); } // Toggle the current camera when the user double-clicks. function doubleClicked() { if (isDefaultCamera === true) { setCamera(cam2); isDefaultCamera = false; } else { setCamera(cam1); isDefaultCamera = true; } } `

p5.Camera

3D

Camera

Sets an orthographic projection for the camera.
In an orthographic projection, shapes with the same size always appear the same size, regardless of whether they are near or far from the camera.
`myCamera.ortho()` changes the camera’s perspective by changing its viewing frustum from a truncated pyramid to a rectangular prism. The frustum is the volume of space that’s visible to the camera. The camera is placed in front of the frustum and views everything within the frustum. `myCamera.ortho()` has six optional parameters to define the viewing frustum.
The first four parameters, `left`, `right`, `bottom`, and `top`, set the coordinates of the frustum’s sides, bottom, and top. For example, calling `myCamera.ortho(-100, 100, 200, -200)` creates a frustum that’s 200 pixels wide and 400 pixels tall. By default, these dimensions are set based on the sketch’s width and height, as in `myCamera.ortho(-width / 2, width / 2, -height / 2, height / 2)`.
The last two parameters, `near` and `far`, set the distance of the frustum’s near and far plane from the camera. For example, calling `myCamera.ortho(-100, 100, 200, -200, 50, 1000)` creates a frustum that’s 200 pixels wide, 400 pixels tall, starts 50 pixels from the camera, and ends 1,000 pixels from the camera. By default, `near` and `far` are set to 0 and `max(width, height) + 800`, respectively.

method

ortho

left

x-coordinate of the frustum’s left plane. Defaults to `-width / 2`.

Number

right

x-coordinate of the frustum’s right plane. Defaults to `width / 2`.

Number

bottom

y-coordinate of the frustum’s bottom plane. Defaults to `height / 2`.

Number

top

y-coordinate of the frustum’s top plane. Defaults to `-height / 2`.

Number

near

z-coordinate of the frustum’s near plane. Defaults to 0.

Number

far

z-coordinate of the frustum’s far plane. Defaults to `max(width, height) + 800`.

Number

` // Double-click to toggle between cameras. let cam1; let cam2; let isDefaultCamera = true; function setup() { createCanvas(100, 100, WEBGL); // Create the first camera. // Keep its default settings. cam1 = createCamera(); // Create the second camera. cam2 = createCamera(); // Apply an orthographic projection. cam2.ortho(); // Set the current camera to cam1. setCamera(cam1); describe('A row of white cubes against a gray background. The camera toggles between a perspective and an orthographic projection when the user double-clicks.'); } function draw() { background(200); // Translate the origin toward the camera. translate(-10, 10, 500); // Rotate the coordinate system. rotateY(-0.1); rotateX(-0.1); // Draw the row of boxes. for (let i = 0; i < 6; i += 1) { translate(0, 0, -40); box(10); } } // Toggle the current camera when the user double-clicks. function doubleClicked() { if (isDefaultCamera === true) { setCamera(cam2); isDefaultCamera = false; } else { setCamera(cam1); isDefaultCamera = true; } } `
` // Double-click to toggle between cameras. let cam1; let cam2; let isDefaultCamera = true; function setup() { createCanvas(100, 100, WEBGL); // Create the first camera. // Keep its default settings. cam1 = createCamera(); // Create the second camera. cam2 = createCamera(); // Apply an orthographic projection. cam2.ortho(); // Set the current camera to cam1. setCamera(cam1); describe('A row of white cubes slither like a snake against a gray background. The camera toggles between a perspective and an orthographic projection when the user double-clicks.'); } function draw() { background(200); // Translate the origin toward the camera. translate(-10, 10, 500); // Rotate the coordinate system. rotateY(-0.1); rotateX(-0.1); // Draw the row of boxes. for (let i = 0; i < 6; i += 1) { push(); // Calculate the box's coordinates. let x = 10 * sin(frameCount * 0.02 + i * 0.6); let z = -40 * i; // Translate the origin. translate(x, 0, z); // Draw the box. box(10); pop(); } } // Toggle the current camera when the user double-clicks. function doubleClicked() { if (isDefaultCamera === true) { setCamera(cam2); isDefaultCamera = false; } else { setCamera(cam1); isDefaultCamera = true; } } `

p5.Camera

3D

Camera

Sets the camera's frustum.
In a frustum projection, shapes that are further from the camera appear smaller than shapes that are near the camera. This technique, called foreshortening, creates realistic 3D scenes.
`myCamera.frustum()` changes the camera’s perspective by changing its viewing frustum. The frustum is the volume of space that’s visible to the camera. The frustum’s shape is a pyramid with its top cut off. The camera is placed where the top of the pyramid should be and points towards the base of the pyramid. It views everything within the frustum.
The first four parameters, `left`, `right`, `bottom`, and `top`, set the coordinates of the frustum’s sides, bottom, and top. For example, calling `myCamera.frustum(-100, 100, 200, -200)` creates a frustum that’s 200 pixels wide and 400 pixels tall. By default, these coordinates are set based on the sketch’s width and height, as in `myCamera.frustum(-width / 20, width / 20, height / 20, -height / 20)`.
The last two parameters, `near` and `far`, set the distance of the frustum’s near and far plane from the camera. For example, calling `myCamera.frustum(-100, 100, 200, -200, 50, 1000)` creates a frustum that’s 200 pixels wide, 400 pixels tall, starts 50 pixels from the camera, and ends 1,000 pixels from the camera. By default, near is set to `0.1 * 800`, which is 1/10th the default distance between the camera and the origin. `far` is set to `10 * 800`, which is 10 times the default distance between the camera and the origin.

method

frustum

left

x-coordinate of the frustum’s left plane. Defaults to `-width / 20`.

Number

right

x-coordinate of the frustum’s right plane. Defaults to `width / 20`.

Number

bottom

y-coordinate of the frustum’s bottom plane. Defaults to `height / 20`.

Number

top

y-coordinate of the frustum’s top plane. Defaults to `-height / 20`.

Number

near

z-coordinate of the frustum’s near plane. Defaults to `0.1 * 800`.

Number

far

z-coordinate of the frustum’s far plane. Defaults to `10 * 800`.

Number

` // Double-click to toggle between cameras. let cam1; let cam2; let isDefaultCamera = true; function setup() { createCanvas(100, 100, WEBGL); // Create the first camera. // Keep its default settings. cam1 = createCamera(); // Create the second camera. cam2 = createCamera(); // Adjust the frustum. // Center it. // Set its width and height to 20 pixels. // Place its near plane 300 pixels from the camera. // Place its far plane 350 pixels from the camera. cam2.frustum(-10, 10, -10, 10, 300, 350); // Set the current camera to cam1. setCamera(cam1); describe( 'A row of white cubes against a gray background. The camera zooms in on one cube when the user double-clicks.' ); } function draw() { background(200); // Translate the origin toward the camera. translate(-10, 10, 600); // Rotate the coordinate system. rotateY(-0.1); rotateX(-0.1); // Draw the row of boxes. for (let i = 0; i < 6; i += 1) { translate(0, 0, -40); box(10); } } // Toggle the current camera when the user double-clicks. function doubleClicked() { if (isDefaultCamera === true) { setCamera(cam2); isDefaultCamera = false; } else { setCamera(cam1); isDefaultCamera = true; } } `

p5.Camera

3D

Camera

Rotates the camera in a clockwise/counter-clockwise direction.
Rolling rotates the camera without changing its orientation. The rotation happens in the camera’s "local" space.
The parameter, `angle`, is the angle the camera should rotate. Passing a positive angle, as in `myCamera.roll(0.001)`, rotates the camera in counter-clockwise direction. Passing a negative angle, as in `myCamera.roll(-0.001)`, rotates the camera in clockwise direction.
Note: Angles are interpreted based on the current angleMode().

method

roll

angle

amount to rotate camera in current angleMode units.

Number

` let cam; let delta = 0.01; function setup() { createCanvas(100, 100, WEBGL); normalMaterial(); // Create a p5.Camera object. cam = createCamera(); } function draw() { background(200); // Roll camera according to angle 'delta' cam.roll(delta); translate(0, 0, 0); box(20); translate(0, 25, 0); box(20); translate(0, 26, 0); box(20); translate(0, 27, 0); box(20); translate(0, 28, 0); box(20); translate(0,29, 0); box(20); translate(0, 30, 0); box(20); } `

camera view rotates in counter clockwise direction with vertically stacked boxes in front of it.

p5.Camera

3D

Camera

Rotates the camera left and right.
Panning rotates the camera without changing its position. The rotation happens in the camera’s "local" space.
The parameter, `angle`, is the angle the camera should rotate. Passing a positive angle, as in `myCamera.pan(0.001)`, rotates the camera to the right. Passing a negative angle, as in `myCamera.pan(-0.001)`, rotates the camera to the left.
Note: Angles are interpreted based on the current angleMode().

method

pan

angle

amount to rotate in the current angleMode().

Number

` let cam; let delta = 0.001; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Camera object. cam = createCamera(); // Place the camera at the top-center. cam.setPosition(0, -400, 800); // Point the camera at the origin. cam.lookAt(0, 0, 0); describe( 'A white cube on a gray background. The cube goes in and out of view as the camera pans left and right.' ); } function draw() { background(200); // Pan with the camera. cam.pan(delta); // Switch directions every 120 frames. if (frameCount % 120 === 0) { delta *= -1; } // Draw the box. box(); } `

p5.Camera

3D

Camera

Rotates the camera up and down.
Tilting rotates the camera without changing its position. The rotation happens in the camera’s "local" space.
The parameter, `angle`, is the angle the camera should rotate. Passing a positive angle, as in `myCamera.tilt(0.001)`, rotates the camera down. Passing a negative angle, as in `myCamera.tilt(-0.001)`, rotates the camera up.
Note: Angles are interpreted based on the current angleMode().

method

tilt

angle

amount to rotate in the current angleMode().

Number

` let cam; let delta = 0.001; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Camera object. cam = createCamera(); // Place the camera at the top-center. cam.setPosition(0, -400, 800); // Point the camera at the origin. cam.lookAt(0, 0, 0); describe( 'A white cube on a gray background. The cube goes in and out of view as the camera tilts up and down.' ); } function draw() { background(200); // Pan with the camera. cam.tilt(delta); // Switch directions every 120 frames. if (frameCount % 120 === 0) { delta *= -1; } // Draw the box. box(); } `

p5.Camera

3D

Camera

Points the camera at a location.
`myCamera.lookAt()` changes the camera’s orientation without changing its position.
The parameters, `x`, `y`, and `z`, are the coordinates in "world" space where the camera should point. For example, calling `myCamera.lookAt(10, 20, 30)` points the camera at the coordinates `(10, 20, 30)`.

method

lookAt

x

x-coordinate of the position where the camera should look in "world" space.

Number

y

y-coordinate of the position where the camera should look in "world" space.

Number

z

z-coordinate of the position where the camera should look in "world" space.

Number

` // Double-click to look at a different cube. let cam; let isLookingLeft = true; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Camera object. cam = createCamera(); // Place the camera at the top-center. cam.setPosition(0, -400, 800); // Point the camera at the origin. cam.lookAt(-30, 0, 0); describe( 'A red cube and a blue cube on a gray background. The camera switches focus between the cubes when the user double-clicks.' ); } function draw() { background(200); // Draw the box on the left. push(); // Translate the origin to the left. translate(-30, 0, 0); // Style the box. fill(255, 0, 0); // Draw the box. box(20); pop(); // Draw the box on the right. push(); // Translate the origin to the right. translate(30, 0, 0); // Style the box. fill(0, 0, 255); // Draw the box. box(20); pop(); } // Change the camera's focus when the user double-clicks. function doubleClicked() { if (isLookingLeft === true) { cam.lookAt(30, 0, 0); isLookingLeft = false; } else { cam.lookAt(-30, 0, 0); isLookingLeft = true; } } `

p5.Camera

3D

Camera

Sets the position and orientation of the camera.
`myCamera.camera()` allows objects to be viewed from different angles. It has nine parameters that are all optional.
The first three parameters, `x`, `y`, and `z`, are the coordinates of the camera’s position in "world" space. For example, calling `myCamera.camera(0, 0, 0)` places the camera at the origin `(0, 0, 0)`. By default, the camera is placed at `(0, 0, 800)`.
The next three parameters, `centerX`, `centerY`, and `centerZ` are the coordinates of the point where the camera faces in "world" space. For example, calling `myCamera.camera(0, 0, 0, 10, 20, 30)` places the camera at the origin `(0, 0, 0)` and points it at `(10, 20, 30)`. By default, the camera points at the origin `(0, 0, 0)`.
The last three parameters, `upX`, `upY`, and `upZ` are the components of the "up" vector in "local" space. The "up" vector orients the camera’s y-axis. For example, calling `myCamera.camera(0, 0, 0, 10, 20, 30, 0, -1, 0)` places the camera at the origin `(0, 0, 0)`, points it at `(10, 20, 30)`, and sets the "up" vector to `(0, -1, 0)` which is like holding it upside-down. By default, the "up" vector is `(0, 1, 0)`.

method

camera

x

x-coordinate of the camera. Defaults to 0.

Number

y

y-coordinate of the camera. Defaults to 0.

Number

z

z-coordinate of the camera. Defaults to 800.

Number

centerX

x-coordinate of the point the camera faces. Defaults to 0.

Number

centerY

y-coordinate of the point the camera faces. Defaults to 0.

Number

centerZ

z-coordinate of the point the camera faces. Defaults to 0.

Number

upX

x-component of the camera’s "up" vector. Defaults to 0.

Number

upY

x-component of the camera’s "up" vector. Defaults to 1.

Number

upZ

z-component of the camera’s "up" vector. Defaults to 0.

Number

` // Double-click to toggle between cameras. let cam1; let cam2; let isDefaultCamera = true; function setup() { createCanvas(100, 100, WEBGL); // Create the first camera. // Keep its default settings. cam1 = createCamera(); // Create the second camera. cam2 = createCamera(); // Place it at the top-right: (1200, -600, 100) // Point it at the row of boxes: (-10, -10, 400) // Set its "up" vector to the default: (0, 1, 0) cam2.camera(1200, -600, 100, -10, -10, 400, 0, 1, 0); // Set the current camera to cam1. setCamera(cam1); describe( 'A row of white cubes against a gray background. The camera toggles between a frontal and an aerial view when the user double-clicks.' ); } function draw() { background(200); // Translate the origin toward the camera. translate(-10, 10, 500); // Rotate the coordinate system. rotateY(-0.1); rotateX(-0.1); // Draw the row of boxes. for (let i = 0; i < 6; i += 1) { translate(0, 0, -30); box(10); } } // Toggle the current camera when the user double-clicks. function doubleClicked() { if (isDefaultCamera === true) { setCamera(cam2); isDefaultCamera = false; } else { setCamera(cam1); isDefaultCamera = true; } } `
` // Double-click to toggle between cameras. let cam1; let cam2; let isDefaultCamera = true; function setup() { createCanvas(100, 100, WEBGL); // Create the first camera. // Keep its default settings. cam1 = createCamera(); // Create the second camera. cam2 = createCamera(); // Place it at the right: (1200, 0, 100) // Point it at the row of boxes: (-10, -10, 400) // Set its "up" vector to the default: (0, 1, 0) cam2.camera(1200, 0, 100, -10, -10, 400, 0, 1, 0); // Set the current camera to cam1. setCamera(cam1); describe( 'A row of white cubes against a gray background. The camera toggles between a static frontal view and an orbiting view when the user double-clicks.' ); } function draw() { background(200); // Update cam2's position. let x = 1200 * cos(frameCount * 0.01); let y = -600 * sin(frameCount * 0.01); cam2.camera(x, y, 100, -10, -10, 400, 0, 1, 0); // Translate the origin toward the camera. translate(-10, 10, 500); // Rotate the coordinate system. rotateY(-0.1); rotateX(-0.1); // Draw the row of boxes. for (let i = 0; i < 6; i += 1) { translate(0, 0, -30); box(10); } } // Toggle the current camera when the user double-clicks. function doubleClicked() { if (isDefaultCamera === true) { setCamera(cam2); isDefaultCamera = false; } else { setCamera(cam1); isDefaultCamera = true; } } `

p5.Camera

3D

Camera

Moves the camera along its "local" axes without changing its orientation.
The parameters, `x`, `y`, and `z`, are the distances the camera should move. For example, calling `myCamera.move(10, 20, 30)` moves the camera 10 pixels to the right, 20 pixels down, and 30 pixels backward in its "local" space.

method

move

x

distance to move along the camera’s "local" x-axis.

Number

y

distance to move along the camera’s "local" y-axis.

Number

z

distance to move along the camera’s "local" z-axis.

Number

` // Click the canvas to begin detecting key presses. let cam; function setup() { createCanvas(100, 100, WEBGL); // Create the first camera. // Keep its default settings. cam = createCamera(); // Place the camera at the top-right. cam.setPosition(400, -400, 800); // Point it at the origin. cam.lookAt(0, 0, 0); describe( 'A white cube drawn against a gray background. The cube appears to move when the user presses certain keys.' ); } function draw() { background(200); // Move the camera along its "local" axes // when the user presses certain keys. if (keyIsPressed === true) { // Move horizontally. if (keyCode === LEFT_ARROW) { cam.move(-1, 0, 0); } if (keyCode === RIGHT_ARROW) { cam.move(1, 0, 0); } // Move vertically. if (keyCode === UP_ARROW) { cam.move(0, -1, 0); } if (keyCode === DOWN_ARROW) { cam.move(0, 1, 0); } // Move in/out of the screen. if (key === 'i') { cam.move(0, 0, -1); } if (key === 'o') { cam.move(0, 0, 1); } } // Draw the box. box(); } `

p5.Camera

3D

Camera

Sets the camera’s position in "world" space without changing its orientation.
The parameters, `x`, `y`, and `z`, are the coordinates where the camera should be placed. For example, calling `myCamera.setPosition(10, 20, 30)` places the camera at coordinates `(10, 20, 30)` in "world" space.

method

setPosition

x

x-coordinate in "world" space.

Number

y

y-coordinate in "world" space.

Number

z

z-coordinate in "world" space.

Number

` // Double-click to toggle between cameras. let cam1; let cam2; let isDefaultCamera = true; function setup() { createCanvas(100, 100, WEBGL); // Create the first camera. // Keep its default settings. cam1 = createCamera(); // Create the second camera. cam2 = createCamera(); // Place it closer to the origin. cam2.setPosition(0, 0, 600); // Set the current camera to cam1. setCamera(cam1); describe( 'A row of white cubes against a gray background. The camera toggles the amount of zoom when the user double-clicks.' ); } function draw() { background(200); // Translate the origin toward the camera. translate(-10, 10, 500); // Rotate the coordinate system. rotateY(-0.1); rotateX(-0.1); // Draw the row of boxes. for (let i = 0; i < 6; i += 1) { translate(0, 0, -30); box(10); } } // Toggle the current camera when the user double-clicks. function doubleClicked() { if (isDefaultCamera === true) { setCamera(cam2); isDefaultCamera = false; } else { setCamera(cam1); isDefaultCamera = true; } } `
` // Double-click to toggle between cameras. let cam1; let cam2; let isDefaultCamera = true; function setup() { createCanvas(100, 100, WEBGL); // Create the first camera. // Keep its default settings. cam1 = createCamera(); // Create the second camera. cam2 = createCamera(); // Place it closer to the origin. cam2.setPosition(0, 0, 600); // Set the current camera to cam1. setCamera(cam1); describe( 'A row of white cubes against a gray background. The camera toggles between a static view and a view that zooms in and out when the user double-clicks.' ); } function draw() { background(200); // Update cam2's z-coordinate. let z = 100 * sin(frameCount * 0.01) + 700; cam2.setPosition(0, 0, z); // Translate the origin toward the camera. translate(-10, 10, 500); // Rotate the coordinate system. rotateY(-0.1); rotateX(-0.1); // Draw the row of boxes. for (let i = 0; i < 6; i += 1) { translate(0, 0, -30); box(10); } } // Toggle the current camera when the user double-clicks. function doubleClicked() { if (isDefaultCamera === true) { setCamera(cam2); isDefaultCamera = false; } else { setCamera(cam1); isDefaultCamera = true; } } `

p5.Camera

3D

Camera

Sets the camera’s position, orientation, and projection by copying another camera.
The parameter, `cam`, is the `p5.Camera` object to copy. For example, calling `cam2.set(cam1)` will set `cam2` using `cam1`’s configuration.

method

set

cam

camera to copy.

p5.Camera

` // Double-click to "reset" the camera zoom. let cam1; let cam2; function setup() { createCanvas(100, 100, WEBGL); // Create the first camera. cam1 = createCamera(); // Place the camera at the top-right. cam1.setPosition(400, -400, 800); // Point it at the origin. cam1.lookAt(0, 0, 0); // Create the second camera. cam2 = createCamera(); // Copy cam1's configuration. cam2.set(cam1); describe( 'A white cube drawn against a gray background. The camera slowly moves forward. The camera resets when the user double-clicks.' ); } function draw() { background(200); // Update cam2's position. cam2.move(0, 0, -1); // Draw the box. box(); } // "Reset" the camera when the user double-clicks. function doubleClicked() { cam2.set(cam1); }

p5.Camera

3D

Camera

Sets the camera’s position and orientation to values that are in-between those of two other cameras.
`myCamera.slerp()` uses spherical linear interpolation to calculate a position and orientation that’s in-between two other cameras. Doing so is helpful for transitioning smoothly between two perspectives.
The first two parameters, `cam0` and `cam1`, are the `p5.Camera` objects that should be used to set the current camera.
The third parameter, `amt`, is the amount to interpolate between `cam0` and `cam1`. 0.0 keeps the camera’s position and orientation equal to `cam0`’s, 0.5 sets them halfway between `cam0`’s and `cam1`’s , and 1.0 sets the position and orientation equal to `cam1`’s.
For example, calling `myCamera.slerp(cam0, cam1, 0.1)` sets cam’s position and orientation very close to `cam0`’s. Calling `myCamera.slerp(cam0, cam1, 0.9)` sets cam’s position and orientation very close to `cam1`’s.
Note: All of the cameras must use the same projection.

method

slerp

cam0

first camera.

p5.Camera

cam1

second camera.

p5.Camera

amt

amount of interpolation between 0.0 (`cam0`) and 1.0 (`cam1`).

Number

` let cam; let cam0; let cam1; function setup() { createCanvas(100, 100, WEBGL); // Create the main camera. // Keep its default settings. cam = createCamera(); // Create the first camera. // Keep its default settings. cam0 = createCamera(); // Create the second camera. cam1 = createCamera(); // Place it at the top-right. cam1.setPosition(400, -400, 800); // Point it at the origin. cam1.lookAt(0, 0, 0); // Set the current camera to cam. setCamera(cam); describe('A white cube drawn against a gray background. The camera slowly oscillates between a frontal view and an aerial view.'); } function draw() { background(200); // Calculate the amount to interpolate between cam0 and cam1. let amt = 0.5 * sin(frameCount * 0.01) + 0.5; // Update the main camera's position and orientation. cam.slerp(cam0, cam1, amt); box(); } `

p5.Camera

3D

Camera

Sets the current (active) camera of a 3D sketch.
`setCamera()` allows for switching between multiple cameras created with createCamera().
Note: `setCamera()` can only be used in WebGL mode.

method

setCamera

cam

camera that should be made active.

p5.Camera

` // Double-click to toggle between cameras. let cam1; let cam2; let usingCam1 = true; function setup() { createCanvas(100, 100, WEBGL); // Create the first camera. // Keep its default settings. cam1 = createCamera(); // Create the second camera. // Place it at the top-left. // Point it at the origin. cam2 = createCamera(); cam2.setPosition(400, -400, 800); cam2.lookAt(0, 0, 0); // Set the current camera to cam1. setCamera(cam1); describe('A white cube on a gray background. The camera toggles between frontal and aerial views when the user double-clicks.'); } function draw() { background(200); // Draw the box. box(); } // Toggle the current camera when the user double-clicks. function doubleClicked() { if (usingCam1 === true) { setCamera(cam2); usingCam1 = false; } else { setCamera(cam1); usingCam1 = true; } } `

p5

3D

Camera

An array containing the color of each pixel in the framebuffer.
myBuffer.loadPixels() must be called before accessing the `myBuffer.pixels` array. myBuffer.updatePixels() must be called after any changes are made.
Note: Updating pixels via this property is slower than drawing to the framebuffer directly. Consider using a p5.Shader object instead of looping over `myBuffer.pixels`.

property

pixels

Number[]

` function setup() { createCanvas(100, 100, WEBGL); background(200); // Create a p5.Framebuffer object. let myBuffer = createFramebuffer(); // Load the pixels array. myBuffer.loadPixels(); // Get the number of pixels in the // top half of the framebuffer. let numPixels = myBuffer.pixels.length / 2; // Set the framebuffer's top half to pink. for (let i = 0; i < numPixels; i += 4) { myBuffer.pixels[i] = 255; myBuffer.pixels[i + 1] = 102; myBuffer.pixels[i + 2] = 204; myBuffer.pixels[i + 3] = 255; } // Update the pixels array. myBuffer.updatePixels(); // Draw the p5.Framebuffer object to the canvas. image(myBuffer, -50, -50); describe('A pink rectangle above a gray rectangle.'); } `

p5.Framebuffer

Rendering

Resizes the framebuffer to a given width and height.
The parameters, `width` and `height`, set the dimensions of the framebuffer. For example, calling `myBuffer.resize(300, 500)` resizes the framebuffer to 300×500 pixels, then sets `myBuffer.width` to 300 and `myBuffer.height` 500.

method

resize

width

width of the framebuffer.

Number

height

height of the framebuffer.

Number

` let myBuffer; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Framebuffer object. myBuffer = createFramebuffer(); describe('A multicolor sphere on a white surface. The image grows larger or smaller when the user moves the mouse, revealing a gray background.'); } function draw() { background(200); // Draw to the p5.Framebuffer object. myBuffer.begin(); background(255); normalMaterial(); sphere(20); myBuffer.end(); // Display the p5.Framebuffer object. image(myBuffer, -50, -50); } // Resize the p5.Framebuffer object when the // user moves the mouse. function mouseMoved() { myBuffer.resize(mouseX, mouseY); } `

p5.Framebuffer

Rendering

Sets the framebuffer's pixel density or returns its current density.
Computer displays are grids of little lights called pixels. A display's pixel density describes how many pixels it packs into an area. Displays with smaller pixels have a higher pixel density and create sharper images.
The parameter, `density`, is optional. If a number is passed, as in `myBuffer.pixelDensity(1)`, it sets the framebuffer's pixel density. By default, the framebuffer's pixel density will match that of the canvas where it was created. All canvases default to match the display's pixel density.
Calling `myBuffer.pixelDensity()` without an argument returns its current pixel density.

method

pixelDensity

density

pixel density to set.

Number

### return
current pixel density.

Number

` let myBuffer; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Framebuffer object. myBuffer = createFramebuffer(); describe("A white circle on a gray canvas. The circle's edge become fuzzy while the user presses and holds the mouse."); } function draw() { // Draw to the p5.Framebuffer object. myBuffer.begin(); background(200); circle(0, 0, 40); myBuffer.end(); // Display the p5.Framebuffer object. image(myBuffer, -50, -50); } // Decrease the pixel density when the user // presses the mouse. function mousePressed() { myBuffer.pixelDensity(1); } // Increase the pixel density when the user // releases the mouse. function mouseReleased() { myBuffer.pixelDensity(2); } `
` let myBuffer; let myFont; // Load a font and create a p5.Font object. function preload() { myFont = loadFont('assets/inconsolata.otf'); } function setup() { createCanvas(100, 100, WEBGL); background(200); // Create a p5.Framebuffer object. myBuffer = createFramebuffer(); // Get the p5.Framebuffer object's pixel density. let d = myBuffer.pixelDensity(); // Style the text. textAlign(CENTER, CENTER); textFont(myFont); textSize(16); fill(0); // Display the pixel density. text(`Density: ${d}`, 0, 0); describe(`The text "Density: ${d}" written in black on a gray background.`); } `

p5.Framebuffer

Rendering

Toggles the framebuffer's autosizing mode or returns the current mode.
By default, the framebuffer automatically resizes to match the canvas that created it. Calling `myBuffer.autoSized(false)` disables this behavior and calling `myBuffer.autoSized(true)` re-enables it.
Calling `myBuffer.autoSized()` without an argument returns `true` if the framebuffer automatically resizes and `false` if not.

method

autoSized

autoSized

whether to automatically resize the framebuffer to match the canvas.

Boolean

### return
current autosize setting.

Boolean

` // Double-click to toggle the autosizing mode. let myBuffer; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Framebuffer object. myBuffer = createFramebuffer(); describe('A multicolor sphere on a gray background. The image resizes when the user moves the mouse.'); } function draw() { background(50); // Draw to the p5.Framebuffer object. myBuffer.begin(); background(200); normalMaterial(); sphere(width / 4); myBuffer.end(); // Display the p5.Framebuffer object. image(myBuffer, -width / 2, -height / 2); } // Resize the canvas when the user moves the mouse. function mouseMoved() { let w = constrain(mouseX, 0, 100); let h = constrain(mouseY, 0, 100); resizeCanvas(w, h); } // Toggle autoSizing when the user double-clicks. // Note: opened an issue to fix(?) this. function doubleClicked() { let isAuto = myBuffer.autoSized(); myBuffer.autoSized(!isAuto); } `

p5.Framebuffer

Rendering

Creates a new p5.Camera object to use with the framebuffer.
The new camera is initialized with a default position `(0, 0, 800)` and a default perspective projection. Its properties can be controlled with p5.Camera methods such as `myCamera.lookAt(0, 0, 0)`.
Framebuffer cameras should be created between calls to myBuffer.begin() and myBuffer.end() like so:
    let myCamera;
    
    myBuffer.begin();
    
    // Create the camera for the framebuffer.
    myCamera = myBuffer.createCamera();
    
    myBuffer.end();
    
Calling setCamera() updates the framebuffer's projection using the camera. resetMatrix() must also be called for the view to change properly:
    myBuffer.begin();
    
    // Set the camera for the framebuffer.
    setCamera(myCamera);
    
    // Reset all transformations.
    resetMatrix();
    
    // Draw stuff...
    
    myBuffer.end();
    

method

createCamera

### return
new camera.

p5.Camera

` // Double-click to toggle between cameras. let myBuffer; let cam1; let cam2; let usingCam1 = true; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Framebuffer object. myBuffer = createFramebuffer(); // Create the cameras between begin() and end(). myBuffer.begin(); // Create the first camera. // Keep its default settings. cam1 = myBuffer.createCamera(); // Create the second camera. // Place it at the top-left. // Point it at the origin. cam2 = myBuffer.createCamera(); cam2.setPosition(400, -400, 800); cam2.lookAt(0, 0, 0); myBuffer.end(); describe( 'A white cube on a gray background. The camera toggles between frontal and aerial views when the user double-clicks.' ); } function draw() { // Draw to the p5.Framebuffer object. myBuffer.begin(); background(200); // Set the camera. if (usingCam1 === true) { setCamera(cam1); } else { setCamera(cam2); } // Reset all transformations. resetMatrix(); // Draw the box. box(); myBuffer.end(); // Display the p5.Framebuffer object. image(myBuffer, -50, -50); } // Toggle the current camera when the user double-clicks. function doubleClicked() { if (usingCam1 === true) { usingCam1 = false; } else { usingCam1 = true; } } `

p5.Framebuffer

Rendering

Deletes the framebuffer from GPU memory.
Calling `myBuffer.remove()` frees the GPU memory used by the framebuffer. The framebuffer also uses a bit of memory on the CPU which can be freed like so:
    // Delete the framebuffer from GPU memory.
    myBuffer.remove();
    
    // Delete the framebuffer from CPU memory.
    myBuffer = undefined;
    
Note: All variables that reference the framebuffer must be assigned the value `undefined` to delete the framebuffer from CPU memory. If any variable still refers to the framebuffer, then it won't be garbage collected.

method

remove

` // Double-click to remove the p5.Framebuffer object. let myBuffer; function setup() { createCanvas(100, 100, WEBGL); // Create an options object. let options = { width: 60, height: 60 }; // Create a p5.Framebuffer object and // configure it using options. myBuffer = createFramebuffer(options); describe('A white circle at the center of a dark gray square disappears when the user double-clicks.'); } function draw() { background(200); // Display the p5.Framebuffer object if // it's available. if (myBuffer) { // Draw to the p5.Framebuffer object. myBuffer.begin(); background(100); circle(0, 0, 20); myBuffer.end(); image(myBuffer, -30, -30); } } // Remove the p5.Framebuffer object when the // the user double-clicks. function doubleClicked() { // Delete the framebuffer from GPU memory. myBuffer.remove(); // Delete the framebuffer from CPU memory. myBuffer = undefined; } `

p5.Framebuffer

Rendering

Begins drawing shapes to the framebuffer.
`myBuffer.begin()` and myBuffer.end() allow shapes to be drawn to the framebuffer. `myBuffer.begin()` begins drawing to the framebuffer and myBuffer.end() stops drawing to the framebuffer. Changes won't be visible until the framebuffer is displayed as an image or texture.

method

begin

` let myBuffer; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Framebuffer object. myBuffer = createFramebuffer(); describe('An empty gray canvas. The canvas gets darker and a rotating, multicolor torus appears while the user presses and holds the mouse.'); } function draw() { background(200); // Start drawing to the p5.Framebuffer object. myBuffer.begin(); background(50); rotateY(frameCount * 0.01); normalMaterial(); torus(30); // Stop drawing to the p5.Framebuffer object. myBuffer.end(); // Display the p5.Framebuffer object while // the user presses the mouse. if (mouseIsPressed === true) { image(myBuffer, -50, -50); } } `

p5.Framebuffer

Rendering

Stops drawing shapes to the framebuffer.
myBuffer.begin() and `myBuffer.end()` allow shapes to be drawn to the framebuffer. myBuffer.begin() begins drawing to the framebuffer and `myBuffer.end()` stops drawing to the framebuffer. Changes won't be visible until the framebuffer is displayed as an image or texture.

method

end

` let myBuffer; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Framebuffer object. myBuffer = createFramebuffer(); describe('An empty gray canvas. The canvas gets darker and a rotating, multicolor torus appears while the user presses and holds the mouse.'); } function draw() { background(200); // Start drawing to the p5.Framebuffer object. myBuffer.begin(); background(50); rotateY(frameCount * 0.01); normalMaterial(); torus(30); // Stop drawing to the p5.Framebuffer object. myBuffer.end(); // Display the p5.Framebuffer object while // the user presses the mouse. if (mouseIsPressed === true) { image(myBuffer, -50, -50); } } `

p5.Framebuffer

Rendering

Draws to the framebuffer by calling a function that contains drawing instructions.
The parameter, `callback`, is a function with the drawing instructions for the framebuffer. For example, calling `myBuffer.draw(myFunction)` will call a function named `myFunction()` to draw to the framebuffer. Doing so has the same effect as the following:
    myBuffer.begin();
    myFunction();
    myBuffer.end();
    

method

draw

callback

function that draws to the framebuffer.

Function

` // Click the canvas to display the framebuffer. let myBuffer; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Framebuffer object. myBuffer = createFramebuffer(); describe('An empty gray canvas. The canvas gets darker and a rotating, multicolor torus appears while the user presses and holds the mouse.'); } function draw() { background(200); // Draw to the p5.Framebuffer object. myBuffer.draw(bagel); // Display the p5.Framebuffer object while // the user presses the mouse. if (mouseIsPressed === true) { image(myBuffer, -50, -50); } } // Draw a rotating, multicolor torus. function bagel() { background(50); rotateY(frameCount * 0.01); normalMaterial(); torus(30); } `

p5.Framebuffer

Rendering

Loads the current value of each pixel in the framebuffer into its pixels array.
`myBuffer.loadPixels()` must be called before reading from or writing to myBuffer.pixels.

method

loadPixels

` function setup() { createCanvas(100, 100, WEBGL); background(200); // Create a p5.Framebuffer object. let myBuffer = createFramebuffer(); // Load the pixels array. myBuffer.loadPixels(); // Get the number of pixels in the // top half of the framebuffer. let numPixels = myBuffer.pixels.length / 2; // Set the framebuffer's top half to pink. for (let i = 0; i < numPixels; i += 4) { myBuffer.pixels[i] = 255; myBuffer.pixels[i + 1] = 102; myBuffer.pixels[i + 2] = 204; myBuffer.pixels[i + 3] = 255; } // Update the pixels array. myBuffer.updatePixels(); // Draw the p5.Framebuffer object to the canvas. image(myBuffer, -50, -50); describe('A pink rectangle above a gray rectangle.'); } `

p5.Framebuffer

Rendering

Gets a pixel or a region of pixels from the framebuffer.
`myBuffer.get()` is easy to use but it's not as fast as myBuffer.pixels. Use myBuffer.pixels to read many pixel values.
The version of `myBuffer.get()` with no parameters returns the entire framebuffer as a a p5.Image object.
The version of `myBuffer.get()` with two parameters interprets them as coordinates. It returns an array with the `[R, G, B, A]` values of the pixel at the given point.
The version of `myBuffer.get()` with four parameters interprets them as coordinates and dimensions. It returns a subsection of the framebuffer as a p5.Image object. The first two parameters are the coordinates for the upper-left corner of the subsection. The last two parameters are the width and height of the subsection.

method

get

### return
subsection as a p5.Image object.

p5.Image

p5.Framebuffer

Rendering

x

x-coordinate of the pixel. Defaults to 0.

Number

y

y-coordinate of the pixel. Defaults to 0.

Number

w

width of the subsection to be returned.

Number

h

height of the subsection to be returned.

Number

##### return
subsection as a p5.Image object.

p5.Image

##### return
entire framebuffer as a p5.Image object.

p5.Image

x



Number

y



Number

##### return
color of the pixel at `(x, y)` as an array of color values `[R, G, B, A]`.

Number[]

Updates the framebuffer with the RGBA values in the pixels array.
`myBuffer.updatePixels()` only needs to be called after changing values in the myBuffer.pixels array. Such changes can be made directly after calling myBuffer.loadPixels().

method

updatePixels

` function setup() { createCanvas(100, 100, WEBGL); background(200); // Create a p5.Framebuffer object. let myBuffer = createFramebuffer(); // Load the pixels array. myBuffer.loadPixels(); // Get the number of pixels in the // top half of the framebuffer. let numPixels = myBuffer.pixels.length / 2; // Set the framebuffer's top half to pink. for (let i = 0; i < numPixels; i += 4) { myBuffer.pixels[i] = 255; myBuffer.pixels[i + 1] = 102; myBuffer.pixels[i + 2] = 204; myBuffer.pixels[i + 3] = 255; } // Update the pixels array. myBuffer.updatePixels(); // Draw the p5.Framebuffer object to the canvas. image(myBuffer, -50, -50); describe('A pink rectangle above a gray rectangle.'); } `

p5.Framebuffer

Rendering

An object that stores the framebuffer's color data.
Each framebuffer uses a WebGLTexture object internally to store its color data. The `myBuffer.color` property makes it possible to pass this data directly to other functions. For example, calling `texture(myBuffer.color)` or `myShader.setUniform('colorTexture', myBuffer.color)` may be helpful for advanced use cases.
Note: By default, a framebuffer's y-coordinates are flipped compared to images and videos. It's easy to flip a framebuffer's y-coordinates as needed when applying it as a texture. For example, calling `plane(myBuffer.width, -myBuffer.height)` will flip the framebuffer.

property

color

p5.FramebufferTexture

` function setup() { createCanvas(100, 100, WEBGL); background(200); // Create a p5.Framebuffer object. let myBuffer = createFramebuffer(); // Start drawing to the p5.Framebuffer object. myBuffer.begin(); triangle(-25, 25, 0, -25, 25, 25); // Stop drawing to the p5.Framebuffer object. myBuffer.end(); // Use the p5.Framebuffer object's WebGLTexture. texture(myBuffer.color); // Style the plane. noStroke(); // Draw the plane. plane(myBuffer.width, myBuffer.height); describe('A white triangle on a gray background.'); } `

p5.Framebuffer

Rendering

An object that stores the framebuffer's depth data.
Each framebuffer uses a WebGLTexture object internally to store its depth data. The `myBuffer.depth` property makes it possible to pass this data directly to other functions. For example, calling `texture(myBuffer.depth)` or `myShader.setUniform('depthTexture', myBuffer.depth)` may be helpful for advanced use cases.
Note: By default, a framebuffer's y-coordinates are flipped compared to images and videos. It's easy to flip a framebuffer's y-coordinates as needed when applying it as a texture. For example, calling `plane(myBuffer.width, -myBuffer.height)` will flip the framebuffer.

property

depth

p5.FramebufferTexture

` // Note: A "uniform" is a global variable within a shader program. // Create a string with the vertex shader program. // The vertex shader is called for each vertex. let vertSrc = ` precision highp float; attribute vec3 aPosition; attribute vec2 aTexCoord; uniform mat4 uModelViewMatrix; uniform mat4 uProjectionMatrix; varying vec2 vTexCoord; void main() { vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0); gl_Position = uProjectionMatrix * viewModelPosition; vTexCoord = aTexCoord; } `; // Create a string with the fragment shader program. // The fragment shader is called for each pixel. let fragSrc = ` precision highp float; varying vec2 vTexCoord; uniform sampler2D depth; void main() { // Get the pixel's depth value. float depthVal = texture2D(depth, vTexCoord).r; // Set the pixel's color based on its depth. gl_FragColor = mix( vec4(0., 0., 0., 1.), vec4(1., 0., 1., 1.), depthVal); } `; let myBuffer; let myShader; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Framebuffer object. myBuffer = createFramebuffer(); // Create a p5.Shader object. myShader = createShader(vertSrc, fragSrc); // Compile and apply the shader. shader(myShader); describe('The shadow of a box rotates slowly against a magenta background.'); } function draw() { // Draw to the p5.Framebuffer object. myBuffer.begin(); background(255); rotateX(frameCount * 0.01); box(20, 20, 80); myBuffer.end(); // Set the shader's depth uniform using // the framebuffer's depth texture. myShader.setUniform('depth', myBuffer.depth); // Style the plane. noStroke(); // Draw the plane. plane(myBuffer.width, myBuffer.height); } `

p5.Framebuffer

Rendering

An array with the geometry's vertices.
The geometry's vertices are stored as p5.Vector objects in the `myGeometry.vertices` array. The geometry's first vertex is the p5.Vector object at `myGeometry.vertices[0]`, its second vertex is `myGeometry.vertices[1]`, its third vertex is `myGeometry.vertices[2]`, and so on.

property

vertices

` // Click and drag the mouse to view the scene from different angles. let myGeometry; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Geometry object. myGeometry = new p5.Geometry(); // Create p5.Vector objects to position the vertices. let v0 = createVector(-40, 0, 0); let v1 = createVector(0, -40, 0); let v2 = createVector(40, 0, 0); // Add the vertices to the p5.Geometry object's vertices array. myGeometry.vertices.push(v0, v1, v2); describe('A white triangle drawn on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Draw the p5.Geometry object. model(myGeometry); } `
` // Click and drag the mouse to view the scene from different angles. let myGeometry; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Geometry object. beginGeometry(); torus(30, 15, 10, 8); myGeometry = endGeometry(); describe('A white torus rotates slowly against a dark gray background. Red spheres mark its vertices.'); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Rotate the coordinate system. rotateY(frameCount * 0.01); // Style the p5.Geometry object. fill(255); stroke(0); // Display the p5.Geometry object. model(myGeometry); // Style the vertices. fill(255, 0, 0); noStroke(); // Iterate over the vertices array. for (let v of myGeometry.vertices) { // Draw a sphere to mark the vertex. push(); translate(v); sphere(2.5); pop(); } } `

p5.Geometry

Shape

3D Primitives

An array with the vectors that are normal to the geometry's vertices.
A face's orientation is defined by its normal vector which points out of the face and is normal (perpendicular) to the surface. Calling `myGeometry.computeNormals()` first calculates each face's normal vector. Then it calculates the normal vector for each vertex by averaging the normal vectors of the faces surrounding the vertex. The vertex normals are stored as p5.Vector objects in the `myGeometry.vertexNormals` array.

property

vertexNormals

` // Click and drag the mouse to view the scene from different angles. let myGeometry; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Geometry object. beginGeometry(); torus(30, 15, 10, 8); myGeometry = endGeometry(); // Compute the vertex normals. myGeometry.computeNormals(); describe( 'A white torus rotates against a dark gray background. Red lines extend outward from its vertices.' ); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Rotate the coordinate system. rotateY(frameCount * 0.01); // Style the p5.Geometry object. stroke(0); // Display the p5.Geometry object. model(myGeometry); // Style the normal vectors. stroke(255, 0, 0); // Iterate over the vertices and vertexNormals arrays. for (let i = 0; i < myGeometry.vertices.length; i += 1) { // Get the vertex p5.Vector object. let v = myGeometry.vertices[i]; // Get the vertex normal p5.Vector object. let n = myGeometry.vertexNormals[i]; // Calculate a point along the vertex normal. let p = p5.Vector.mult(n, 8); // Draw the vertex normal as a red line. push(); translate(v); line(0, 0, 0, p.x, p.y, p.z); pop(); } } `
` // Click and drag the mouse to view the scene from different angles. let myGeometry; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Geometry object. myGeometry = new p5.Geometry(); // Create p5.Vector objects to position the vertices. let v0 = createVector(-40, 0, 0); let v1 = createVector(0, -40, 0); let v2 = createVector(0, 40, 0); let v3 = createVector(40, 0, 0); // Add the vertices to the p5.Geometry object's vertices array. myGeometry.vertices.push(v0, v1, v2, v3); // Compute the faces array. myGeometry.computeFaces(); // Compute the surface normals. myGeometry.computeNormals(); describe('A red square drawn on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Add a white point light. pointLight(255, 255, 255, 0, 0, 10); // Style the p5.Geometry object. noStroke(); fill(255, 0, 0); // Display the p5.Geometry object. model(myGeometry); } `

p5.Geometry

Shape

3D Primitives

An array that lists which of the geometry's vertices form each of its faces.
All 3D shapes are made by connecting sets of points called vertices. A geometry's surface is formed by connecting vertices to form triangles that are stitched together. Each triangular patch on the geometry's surface is called a face.
The geometry's vertices are stored as p5.Vector objects in the myGeometry.vertices array. The geometry's first vertex is the p5.Vector object at `myGeometry.vertices[0]`, its second vertex is `myGeometry.vertices[1]`, its third vertex is `myGeometry.vertices[2]`, and so on.
For example, a geometry made from a rectangle has two faces because a rectangle is made by joining two triangles. `myGeometry.faces` for a rectangle would be the two-dimensional array `[[0, 1, 2], [2, 1, 3]]`. The first face, `myGeometry.faces[0]`, is the array `[0, 1, 2]` because it's formed by connecting `myGeometry.vertices[0]`, `myGeometry.vertices[1]`,and `myGeometry.vertices[2]`. The second face, `myGeometry.faces[1]`, is the array `[2, 1, 3]` because it's formed by connecting `myGeometry.vertices[2]`, `myGeometry.vertices[1]`,and `myGeometry.vertices[3]`.

property

faces

` // Click and drag the mouse to view the scene from different angles. let myGeometry; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Geometry object. beginGeometry(); sphere(); myGeometry = endGeometry(); describe("A sphere drawn on a gray background. The sphere's surface is a grayscale patchwork of triangles."); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Style the p5.Geometry object. noStroke(); // Set a random seed. randomSeed(1234); // Iterate over the faces array. for (let face of myGeometry.faces) { // Style the face. let g = random(0, 255); fill(g); // Draw the face. beginShape(); // Iterate over the vertices that form the face. for (let f of face) { // Get the vertex's p5.Vector object. let v = myGeometry.vertices[f]; vertex(v.x, v.y, v.z); } endShape(); } } `

p5.Geometry

Shape

3D Primitives

An array that lists the texture coordinates for each of the geometry's vertices.
In order for texture() to work, the geometry needs a way to map the points on its surface to the pixels in a rectangular image that's used as a texture. The geometry's vertex at coordinates `(x, y, z)` maps to the texture image's pixel at coordinates `(u, v)`.
The `myGeometry.uvs` array stores the `(u, v)` coordinates for each vertex in the order it was added to the geometry. For example, the first vertex, `myGeometry.vertices[0]`, has its `(u, v)` coordinates stored at `myGeometry.uvs[0]` and `myGeometry.uvs[1]`.

property

uvs

` let img; // Load the image and create a p5.Image object. function preload() { img = loadImage('assets/laDefense.jpg'); } function setup() { createCanvas(100, 100, WEBGL); background(200); // Create p5.Geometry objects. let geom1 = buildGeometry(createShape); let geom2 = buildGeometry(createShape); // Left (original). push(); translate(-25, 0, 0); texture(img); noStroke(); model(geom1); pop(); // Set geom2's texture coordinates. geom2.uvs = [0.25, 0.25, 0.75, 0.25, 0.25, 0.75, 0.75, 0.75]; // Right (zoomed in). push(); translate(25, 0, 0); texture(img); noStroke(); model(geom2); pop(); describe( 'Two photos of a ceiling on a gray background. The photo on the right zooms in to the center of the photo.' ); } function createShape() { plane(40); } `

p5.Geometry

Shape

3D Primitives

Calculates the position and size of the smallest box that contains the geometry.
A bounding box is the smallest rectangular prism that contains the entire geometry. It's defined by the box's minimum and maximum coordinates along each axis, as well as the size (length) and offset (center).
Calling `myGeometry.calculateBoundingBox()` returns an object with four properties that describe the bounding box:
    // Get myGeometry's bounding box.
    let bbox = myGeometry.calculateBoundingBox();
    
    // Print the bounding box to the console.
    console.log(bbox);
    
    // {
    //  // The minimum coordinate along each axis.
    //  min: { x: -1, y: -2, z: -3 },
    //
    //  // The maximum coordinate along each axis.
    //  max: { x: 1, y: 2, z: 3},
    //
    //  // The size (length) along each axis.
    //  size: { x: 2, y: 4, z: 6},
    //
    //  // The offset (center) along each axis.
    //  offset: { x: 0, y: 0, z: 0}
    // }
    

method

calculateBoundingBox

### return
bounding box of the geometry.

Object

` // Click and drag the mouse to view the scene from different angles. let particles; function setup() { createCanvas(100, 100, WEBGL); // Create a new p5.Geometry object with random spheres. particles = buildGeometry(createParticles); describe('Ten white spheres placed randomly against a gray background. A box encloses the spheres.'); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Style the particles. noStroke(); fill(255); // Draw the particles. model(particles); // Calculate the bounding box. let bbox = particles.calculateBoundingBox(); // Translate to the bounding box's center. translate(bbox.offset.x, bbox.offset.y, bbox.offset.z); // Style the bounding box. stroke(255); noFill(); // Draw the bounding box. box(bbox.size.x, bbox.size.y, bbox.size.z); } function createParticles() { for (let i = 0; i < 10; i += 1) { // Calculate random coordinates. let x = randomGaussian(0, 15); let y = randomGaussian(0, 15); let z = randomGaussian(0, 15); push(); // Translate to the particle's coordinates. translate(x, y, z); // Draw the particle. sphere(3); pop(); } } `

p5.Geometry

Shape

3D Primitives

Removes the geometry’s internal colors.
`p5.Geometry` objects can be created with "internal colors" assigned to vertices or the entire shape. When a geometry has internal colors, fill() has no effect. Calling `myGeometry.clearColors()` allows the fill() function to apply color to the geometry.

method

clearColors

` function setup() { createCanvas(100, 100, WEBGL); background(200); // Create a p5.Geometry object. // Set its internal color to red. beginGeometry(); fill(255, 0, 0); plane(20); let myGeometry = endGeometry(); // Style the shape. noStroke(); // Draw the p5.Geometry object (center). model(myGeometry); // Translate the origin to the bottom-right. translate(25, 25, 0); // Try to fill the geometry with green. fill(0, 255, 0); // Draw the geometry again (bottom-right). model(myGeometry); // Clear the geometry's colors. myGeometry.clearColors(); // Fill the geometry with blue. fill(0, 0, 255); // Translate the origin up. translate(0, -50, 0); // Draw the geometry again (top-right). model(myGeometry); describe( 'Three squares drawn against a gray background. Red squares are at the center and the bottom-right. A blue square is at the top-right.' ); } `

p5.Geometry

Shape

3D Primitives

The `saveObj()` function exports `p5.Geometry` objects as 3D models in the Wavefront .obj file format. This way, you can use the 3D shapes you create in p5.js in other software for rendering, animation, 3D printing, or more.
The exported .obj file will include the faces and vertices of the `p5.Geometry`, as well as its texture coordinates and normals, if it has them.

method

saveObj

fileName

The name of the file to save the model as. If not specified, the default file name will be 'model.obj'.

String

'model.obj'

` let myModel; let saveBtn; function setup() { createCanvas(200, 200, WEBGL); myModel = buildGeometry(() => { for (let i = 0; i < 5; i++) { push(); translate( random(-75, 75), random(-75, 75), random(-75, 75) ); sphere(random(5, 50)); pop(); } }); saveBtn = createButton('Save .obj'); saveBtn.mousePressed(() => myModel.saveObj()); describe('A few spheres rotating in space'); } function draw() { background(0); noStroke(); lights(); rotateX(millis() * 0.001); rotateY(millis() * 0.002); model(myModel); } `

p5.Geometry

Shape

3D Primitives

The `saveStl()` function exports `p5.Geometry` objects as 3D models in the STL stereolithography file format. This way, you can use the 3D shapes you create in p5.js in other software for rendering, animation, 3D printing, or more.
The exported .stl file will include the faces, vertices, and normals of the `p5.Geometry`.
By default, this method saves a text-based .stl file. Alternatively, you can save a more compact but less human-readable binary .stl file by passing `{ binary: true }` as a second parameter.

method

saveStl

fileName

The name of the file to save the model as. If not specified, the default file name will be 'model.stl'.

String

'model.stl'

options

Optional settings. Options can include a boolean `binary` property, which controls whether or not a binary .stl file is saved. It defaults to false.

Object

` let myModel; let saveBtn1; let saveBtn2; function setup() { createCanvas(200, 200, WEBGL); myModel = buildGeometry(() => { for (let i = 0; i < 5; i++) { push(); translate( random(-75, 75), random(-75, 75), random(-75, 75) ); sphere(random(5, 50)); pop(); } }); saveBtn1 = createButton('Save .stl'); saveBtn1.mousePressed(function() { myModel.saveStl(); }); saveBtn2 = createButton('Save binary .stl'); saveBtn2.mousePressed(function() { myModel.saveStl('model.stl', { binary: true }); }); describe('A few spheres rotating in space'); } function draw() { background(0); noStroke(); lights(); rotateX(millis() * 0.001); rotateY(millis() * 0.002); model(myModel); } `

p5.Geometry

Shape

3D Primitives

Flips the geometry’s texture u-coordinates.
In order for texture() to work, the geometry needs a way to map the points on its surface to the pixels in a rectangular image that's used as a texture. The geometry's vertex at coordinates `(x, y, z)` maps to the texture image's pixel at coordinates `(u, v)`.
The myGeometry.uvs array stores the `(u, v)` coordinates for each vertex in the order it was added to the geometry. Calling `myGeometry.flipU()` flips a geometry's u-coordinates so that the texture appears mirrored horizontally.
For example, a plane's four vertices are added clockwise starting from the top-left corner. Here's how calling `myGeometry.flipU()` would change a plane's texture coordinates:
    // Print the original texture coordinates.
    // Output: [0, 0, 1, 0, 0, 1, 1, 1]
    console.log(myGeometry.uvs);
    
    // Flip the u-coordinates.
    myGeometry.flipU();
    
    // Print the flipped texture coordinates.
    // Output: [1, 0, 0, 0, 1, 1, 0, 1]
    console.log(myGeometry.uvs);
    
    // Notice the swaps:
    // Top vertices: [0, 0, 1, 0] --> [1, 0, 0, 0]
    // Bottom vertices: [0, 1, 1, 1] --> [1, 1, 0, 1]
    

method

flipU

` let img; function preload() { img = loadImage('assets/laDefense.jpg'); } function setup() { createCanvas(100, 100, WEBGL); background(200); // Create p5.Geometry objects. let geom1 = buildGeometry(createShape); let geom2 = buildGeometry(createShape); // Flip geom2's U texture coordinates. geom2.flipU(); // Left (original). push(); translate(-25, 0, 0); texture(img); noStroke(); model(geom1); pop(); // Right (flipped). push(); translate(25, 0, 0); texture(img); noStroke(); model(geom2); pop(); describe( 'Two photos of a ceiling on a gray background. The photos are mirror images of each other.' ); } function createShape() { plane(40); } `

p5.Geometry

Shape

3D Primitives

Flips the geometry’s texture v-coordinates.
In order for texture() to work, the geometry needs a way to map the points on its surface to the pixels in a rectangular image that's used as a texture. The geometry's vertex at coordinates `(x, y, z)` maps to the texture image's pixel at coordinates `(u, v)`.
The myGeometry.uvs array stores the `(u, v)` coordinates for each vertex in the order it was added to the geometry. Calling `myGeometry.flipV()` flips a geometry's v-coordinates so that the texture appears mirrored vertically.
For example, a plane's four vertices are added clockwise starting from the top-left corner. Here's how calling `myGeometry.flipV()` would change a plane's texture coordinates:
    // Print the original texture coordinates.
    // Output: [0, 0, 1, 0, 0, 1, 1, 1]
    console.log(myGeometry.uvs);
    
    // Flip the v-coordinates.
    myGeometry.flipV();
    
    // Print the flipped texture coordinates.
    // Output: [0, 1, 1, 1, 0, 0, 1, 0]
    console.log(myGeometry.uvs);
    
    // Notice the swaps:
    // Left vertices: [0, 0] <--> [1, 0]
    // Right vertices: [1, 0] <--> [1, 1]
    

method

flipV

` let img; function preload() { img = loadImage('assets/laDefense.jpg'); } function setup() { createCanvas(100, 100, WEBGL); background(200); // Create p5.Geometry objects. let geom1 = buildGeometry(createShape); let geom2 = buildGeometry(createShape); // Flip geom2's V texture coordinates. geom2.flipV(); // Left (original). push(); translate(-25, 0, 0); texture(img); noStroke(); model(geom1); pop(); // Right (flipped). push(); translate(25, 0, 0); texture(img); noStroke(); model(geom2); pop(); describe( 'Two photos of a ceiling on a gray background. The photos are mirror images of each other.' ); } function createShape() { plane(40); } `

p5.Geometry

Shape

3D Primitives

Computes the geometry's faces using its vertices.
All 3D shapes are made by connecting sets of points called vertices. A geometry's surface is formed by connecting vertices to form triangles that are stitched together. Each triangular patch on the geometry's surface is called a face. `myGeometry.computeFaces()` performs the math needed to define each face based on the distances between vertices.
The geometry's vertices are stored as p5.Vector objects in the myGeometry.vertices array. The geometry's first vertex is the p5.Vector object at `myGeometry.vertices[0]`, its second vertex is `myGeometry.vertices[1]`, its third vertex is `myGeometry.vertices[2]`, and so on.
Calling `myGeometry.computeFaces()` fills the myGeometry.faces array with three-element arrays that list the vertices that form each face. For example, a geometry made from a rectangle has two faces because a rectangle is made by joining two triangles. myGeometry.faces for a rectangle would be the two-dimensional array `[[0, 1, 2], [2, 1, 3]]`. The first face, `myGeometry.faces[0]`, is the array `[0, 1, 2]` because it's formed by connecting `myGeometry.vertices[0]`, `myGeometry.vertices[1]`,and `myGeometry.vertices[2]`. The second face, `myGeometry.faces[1]`, is the array `[2, 1, 3]` because it's formed by connecting `myGeometry.vertices[2]`, `myGeometry.vertices[1]`, and `myGeometry.vertices[3]`.
Note: `myGeometry.computeFaces()` only works when geometries have four or more vertices.

method

computeFaces

` // Click and drag the mouse to view the scene from different angles. let myGeometry; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Geometry object. myGeometry = new p5.Geometry(); // Create p5.Vector objects to position the vertices. let v0 = createVector(-40, 0, 0); let v1 = createVector(0, -40, 0); let v2 = createVector(0, 40, 0); let v3 = createVector(40, 0, 0); // Add the vertices to myGeometry's vertices array. myGeometry.vertices.push(v0, v1, v2, v3); // Compute myGeometry's faces array. myGeometry.computeFaces(); describe('A red square drawn on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Style the shape. noStroke(); fill(255, 0, 0); // Draw the p5.Geometry object. model(myGeometry); } `
` // Click and drag the mouse to view the scene from different angles. let myGeometry; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Geometry object using a callback function. myGeometry = new p5.Geometry(1, 1, createShape); describe('A red square drawn on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Style the shape. noStroke(); fill(255, 0, 0); // Draw the p5.Geometry object. model(myGeometry); } function createShape() { // Create p5.Vector objects to position the vertices. let v0 = createVector(-40, 0, 0); let v1 = createVector(0, -40, 0); let v2 = createVector(0, 40, 0); let v3 = createVector(40, 0, 0); // Add the vertices to the p5.Geometry object's vertices array. this.vertices.push(v0, v1, v2, v3); // Compute the faces array. this.computeFaces(); } `

p5.Geometry

Shape

3D Primitives

Calculates the normal vector for each vertex on the geometry.
All 3D shapes are made by connecting sets of points called vertices. A geometry's surface is formed by connecting vertices to create triangles that are stitched together. Each triangular patch on the geometry's surface is called a face. `myGeometry.computeNormals()` performs the math needed to orient each face. Orientation is important for lighting and other effects.
A face's orientation is defined by its normal vector which points out of the face and is normal (perpendicular) to the surface. Calling `myGeometry.computeNormals()` first calculates each face's normal vector. Then it calculates the normal vector for each vertex by averaging the normal vectors of the faces surrounding the vertex. The vertex normals are stored as p5.Vector objects in the myGeometry.vertexNormals array.
The first parameter, `shadingType`, is optional. Passing the constant `FLAT`, as in `myGeometry.computeNormals(FLAT)`, provides neighboring faces with their own copies of the vertices they share. Surfaces appear tiled with flat shading. Passing the constant `SMOOTH`, as in `myGeometry.computeNormals(SMOOTH)`, makes neighboring faces reuse their shared vertices. Surfaces appear smoother with smooth shading. By default, `shadingType` is `FLAT`.
The second parameter, `options`, is also optional. If an object with a `roundToPrecision` property is passed, as in `myGeometry.computeNormals(SMOOTH, { roundToPrecision: 5 })`, it sets the number of decimal places to use for calculations. By default, `roundToPrecision` uses 3 decimal places.

method

computeNormals

shadingType

shading type. either FLAT or SMOOTH. Defaults to `FLAT`.

String

options

shading options.

Object

` // Click and drag the mouse to view the scene from different angles. let myGeometry; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Geometry object. beginGeometry(); torus(); myGeometry = endGeometry(); // Compute the vertex normals. myGeometry.computeNormals(); describe( "A white torus drawn on a dark gray background. Red lines extend outward from the torus' vertices." ); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Rotate the coordinate system. rotateX(1); // Style the helix. stroke(0); // Display the helix. model(myGeometry); // Style the normal vectors. stroke(255, 0, 0); // Iterate over the vertices and vertexNormals arrays. for (let i = 0; i < myGeometry.vertices.length; i += 1) { // Get the vertex p5.Vector object. let v = myGeometry.vertices[i]; // Get the vertex normal p5.Vector object. let n = myGeometry.vertexNormals[i]; // Calculate a point along the vertex normal. let p = p5.Vector.mult(n, 5); // Draw the vertex normal as a red line. push(); translate(v); line(0, 0, 0, p.x, p.y, p.z); pop(); } } `
` // Click and drag the mouse to view the scene from different angles. let myGeometry; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Geometry object using a callback function. myGeometry = new p5.Geometry(); // Create p5.Vector objects to position the vertices. let v0 = createVector(-40, 0, 0); let v1 = createVector(0, -40, 0); let v2 = createVector(0, 40, 0); let v3 = createVector(40, 0, 0); // Add the vertices to the p5.Geometry object's vertices array. myGeometry.vertices.push(v0, v1, v2, v3); // Compute the faces array. myGeometry.computeFaces(); // Compute the surface normals. myGeometry.computeNormals(); describe('A red square drawn on a gray background.'); } function draw() { background(200); // Enable orbiting with the mouse. orbitControl(); // Add a white point light. pointLight(255, 255, 255, 0, 0, 10); // Style the p5.Geometry object. noStroke(); fill(255, 0, 0); // Draw the p5.Geometry object. model(myGeometry); } `
` // Click and drag the mouse to view the scene from different angles. let myGeometry; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Geometry object. myGeometry = buildGeometry(createShape); // Compute normals using default (FLAT) shading. myGeometry.computeNormals(FLAT); describe('A white, helical structure drawn on a dark gray background. Its faces appear faceted.'); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Rotate the coordinate system. rotateX(1); // Style the helix. noStroke(); // Display the helix. model(myGeometry); } function createShape() { // Create a helical shape. beginShape(); for (let i = 0; i < TWO_PI * 3; i += 0.5) { let x = 30 * cos(i); let y = 30 * sin(i); let z = map(i, 0, TWO_PI * 3, -40, 40); vertex(x, y, z); } endShape(); } `
` // Click and drag the mouse to view the scene from different angles. let myGeometry; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Geometry object. myGeometry = buildGeometry(createShape); // Compute normals using smooth shading. myGeometry.computeNormals(SMOOTH); describe('A white, helical structure drawn on a dark gray background.'); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Rotate the coordinate system. rotateX(1); // Style the helix. noStroke(); // Display the helix. model(myGeometry); } function createShape() { // Create a helical shape. beginShape(); for (let i = 0; i < TWO_PI * 3; i += 0.5) { let x = 30 * cos(i); let y = 30 * sin(i); let z = map(i, 0, TWO_PI * 3, -40, 40); vertex(x, y, z); } endShape(); } `
` // Click and drag the mouse to view the scene from different angles. let myGeometry; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Geometry object. myGeometry = buildGeometry(createShape); // Create an options object. let options = { roundToPrecision: 5 }; // Compute normals using smooth shading. myGeometry.computeNormals(SMOOTH, options); describe('A white, helical structure drawn on a dark gray background.'); } function draw() { background(50); // Enable orbiting with the mouse. orbitControl(); // Turn on the lights. lights(); // Rotate the coordinate system. rotateX(1); // Style the helix. noStroke(); // Display the helix. model(myGeometry); } function createShape() { // Create a helical shape. beginShape(); for (let i = 0; i < TWO_PI * 3; i += 0.5) { let x = 30 * cos(i); let y = 30 * sin(i); let z = map(i, 0, TWO_PI * 3, -40, 40); vertex(x, y, z); } endShape(); } `

p5.Geometry

Shape

3D Primitives

Transforms the geometry's vertices to fit snugly within a 100×100×100 box centered at the origin.
Calling `myGeometry.normalize()` translates the geometry's vertices so that they're centered at the origin `(0, 0, 0)`. Then it scales the vertices so that they fill a 100×100×100 box. As a result, small geometries will grow and large geometries will shrink.
Note: `myGeometry.normalize()` only works when called in the setup() function.

method

normalize

` let myGeometry; function setup() { createCanvas(100, 100, WEBGL); // Create a very small torus. beginGeometry(); torus(1, 0.25); myGeometry = endGeometry(); // Normalize the torus so its vertices fill // the range [-100, 100]. myGeometry.normalize(); describe('A white torus rotates slowly against a dark gray background.'); } function draw() { background(50); // Turn on the lights. lights(); // Rotate around the y-axis. rotateY(frameCount * 0.01); // Style the torus. noStroke(); // Draw the torus. model(myGeometry); } `

p5.Geometry

Shape

3D Primitives

Welcome to RendererGL Immediate Mode. Immediate mode is used for drawing custom shapes from a set of vertices. Immediate Mode is activated when you call beginShape() & de-activated when you call endShape(). Immediate mode is a style of programming borrowed from OpenGL's (now-deprecated) immediate mode. It differs from p5.js' default, Retained Mode, which caches geometries and buffers on the CPU to reduce the number of webgl draw calls. Retained mode is more efficient & performative, however, Immediate Mode is useful for sketching quick geometric ideas.

p5

Math

End shape drawing and render vertices to screen.

p5

Math

geometry

The model whose resources will be freed

p5.Geometry

p5

Math

Set attributes for the WebGL Drawing context. This is a way of adjusting how the WebGL renderer works to fine-tune the display and performance.
Note that this will reinitialize the drawing context if called after the WebGL canvas is made.
If an object is passed as the parameter, all attributes not declared in the object will be set to defaults.
The available attributes are:   
alpha - indicates if the canvas contains an alpha buffer default is true
depth - indicates whether the drawing buffer has a depth buffer of at least 16 bits - default is true
stencil - indicates whether the drawing buffer has a stencil buffer of at least 8 bits
antialias - indicates whether or not to perform anti-aliasing default is false (true in Safari)
premultipliedAlpha - indicates that the page compositor will assume the drawing buffer contains colors with pre-multiplied alpha default is true
preserveDrawingBuffer - if true the buffers will not be cleared and and will preserve their values until cleared or overwritten by author (note that p5 clears automatically on draw loop) default is true
perPixelLighting - if true, per-pixel lighting will be used in the lighting shader otherwise per-vertex lighting is used. default is true.
version - either 1 or 2, to specify which WebGL version to ask for. By default, WebGL 2 will be requested. If WebGL2 is not available, it will fall back to WebGL 1. You can check what version is used with by looking at the global `webglVersion` property.

method

setAttributes

` function setup() { createCanvas(100, 100, WEBGL); } function draw() { background(255); push(); rotateZ(frameCount * 0.02); rotateX(frameCount * 0.02); rotateY(frameCount * 0.02); fill(0, 0, 0); box(50); pop(); } `
  
Now with the antialias attribute set to true.   

` function setup() { setAttributes('antialias', true); createCanvas(100, 100, WEBGL); } function draw() { background(255); push(); rotateZ(frameCount * 0.02); rotateX(frameCount * 0.02); rotateY(frameCount * 0.02); fill(0, 0, 0); box(50); pop(); } `
` // press the mouse button to disable perPixelLighting function setup() { createCanvas(100, 100, WEBGL); noStroke(); fill(255); } let lights = [ { c: '#f00', t: 1.12, p: 1.91, r: 0.2 }, { c: '#0f0', t: 1.21, p: 1.31, r: 0.2 }, { c: '#00f', t: 1.37, p: 1.57, r: 0.2 }, { c: '#ff0', t: 1.12, p: 1.91, r: 0.7 }, { c: '#0ff', t: 1.21, p: 1.31, r: 0.7 }, { c: '#f0f', t: 1.37, p: 1.57, r: 0.7 } ]; function draw() { let t = millis() / 1000 + 1000; background(0); directionalLight(color('#222'), 1, 1, 1); for (let i = 0; i < lights.length; i++) { let light = lights[i]; pointLight( color(light.c), p5.Vector.fromAngles(t * light.t, t * light.p, width * light.r) ); } specularMaterial(255); sphere(width * 0.1); rotateX(t * 0.77); rotateY(t * 0.83); rotateZ(t * 0.91); torus(width * 0.3, width * 0.07, 24, 10); } function mousePressed() { setAttributes('perPixelLighting', false); noStroke(); fill(255); } function mouseReleased() { setAttributes('perPixelLighting', true); noStroke(); fill(255); } `

a rotating cube with smoother edges

p5

Rendering

Rendering

key

Name of attribute

String

value

New value of named attribute

Boolean

obj

object with key-value pairs

Object

Shaders are written in GLSL, but there are different versions of GLSL that it might be written in.
Calling this method on a `p5.Shader` will return the GLSL version it uses, either `100 es` or `300 es`. WebGL 1 shaders will only use `100 es`, and WebGL 2 shaders may use either.

### return
The GLSL version used by the shader.

String

p5.Shader

3D

Material

Logs the hooks available in this shader, and their current implementation.
Each shader may let you override bits of its behavior. Each bit is called a hook. A hook is either for the vertex shader, if it affects the position of vertices, or in the fragment shader, if it affects the pixel color. This method logs those values to the console, letting you know what you are able to use in a call to `modify()`.
For example, this shader will produce the following output:
    myShader = baseMaterialShader().modify({
      declarations: 'uniform float time;',
      'vec3 getWorldPosition': `(vec3 pos) {
        pos.y += 20. * sin(time * 0.001 + pos.x * 0.05);
        return pos;
      }`
    });
    myShader.inspectHooks();
    
    ==== Vertex shader hooks: ====
    void beforeVertex() {}
    vec3 getLocalPosition(vec3 position) { return position; }
    [MODIFIED] vec3 getWorldPosition(vec3 pos) {
          pos.y += 20. * sin(time * 0.001 + pos.x * 0.05);
          return pos;
        }
    vec3 getLocalNormal(vec3 normal) { return normal; }
    vec3 getWorldNormal(vec3 normal) { return normal; }
    vec2 getUV(vec2 uv) { return uv; }
    vec4 getVertexColor(vec4 color) { return color; }
    void afterVertex() {}
    
    ==== Fragment shader hooks: ====
    void beforeFragment() {}
    Inputs getPixelInputs(Inputs inputs) { return inputs; }
    vec4 combineColors(ColorComponents components) {
                    vec4 color = vec4(0.);
                    color.rgb += components.diffuse * components.baseColor;
                    color.rgb += components.ambient * components.ambientColor;
                    color.rgb += components.specular * components.specularColor;
                    color.rgb += components.emissive;
                    color.a = components.opacity;
                    return color;
                  }
    vec4 getFinalColor(vec4 color) { return color; }
    void afterFragment() {}
    

method

inspectHooks

p5.Shader

3D

Material

Returns a new shader, based on the original, but with custom snippets of shader code replacing default behaviour.
Each shader may let you override bits of its behavior. Each bit is called a hook. A hook is either for the vertex shader, if it affects the position of vertices, or in the fragment shader, if it affects the pixel color. You can inspect the different hooks available by calling `yourShader.inspectHooks()`. You can also read the reference for the default material, normal material, color, line, and point shaders to see what hooks they have available.
`modify()` takes one parameter, `hooks`, an object with the hooks you want to override. Each key of the `hooks` object is the name of a hook, and the value is a string with the GLSL code for your hook.
If you supply functions that aren't existing hooks, they will get added at the start of the shader as helper functions so that you can use them in your hooks.
To add new uniforms to your shader, you can pass in a `uniforms` object containing the type and name of the uniform as the key, and a default value or function returning a default value as its value. These will be automatically set when the shader is set with `shader(yourShader)`.
You can also add a `declarations` key, where the value is a GLSL string declaring custom uniform variables, globals, and functions shared between hooks. To add declarations just in a vertex or fragment shader, add `vertexDeclarations` and `fragmentDeclarations` keys.

method

modify

hooks

The hooks in the shader to replace.

Object

### return


p5.Shader

` let myShader; function setup() { createCanvas(200, 200, WEBGL); myShader = baseMaterialShader().modify({ uniforms: { 'float time': () => millis() }, 'vec3 getWorldPosition': `(vec3 pos) { pos.y += 20. * sin(time * 0.001 + pos.x * 0.05); return pos; }` }); } function draw() { background(255); shader(myShader); lights(); noStroke(); fill('red'); sphere(50); } `

` let myShader; function setup() { createCanvas(200, 200, WEBGL); myShader = baseMaterialShader().modify({ // Manually specifying a uniform declarations: 'uniform float time;', 'vec3 getWorldPosition': `(vec3 pos) { pos.y += 20. * sin(time * 0.001 + pos.x * 0.05); return pos; }` }); } function draw() { background(255); shader(myShader); myShader.setUniform('time', millis()); lights(); noStroke(); fill('red'); sphere(50); } `

p5.Shader

3D

Material

Copies the shader from one drawing context to another.
Each `p5.Shader` object must be compiled by calling shader() before it can run. Compilation happens in a drawing context which is usually the main canvas or an instance of p5.Graphics. A shader can only be used in the context where it was compiled. The `copyToContext()` method compiles the shader again and copies it to another drawing context where it can be reused.
The parameter, `context`, is the drawing context where the shader will be used. The shader can be copied to an instance of p5.Graphics, as in `myShader.copyToContext(pg)`. The shader can also be copied from a p5.Graphics object to the main canvas using the `window` variable, as in `myShader.copyToContext(window)`.
Note: A p5.Shader object created with createShader(), createFilterShader(), or loadShader() can be used directly with a p5.Framebuffer object created with createFramebuffer(). Both objects have the same context as the main canvas.

method

copyToContext

context

WebGL context for the copied shader.

p5|p5.Graphics

### return
new shader compiled for the target context.

p5.Shader

` // Note: A "uniform" is a global variable within a shader program. // Create a string with the vertex shader program. // The vertex shader is called for each vertex. let vertSrc = ` precision highp float; uniform mat4 uModelViewMatrix; uniform mat4 uProjectionMatrix; attribute vec3 aPosition; attribute vec2 aTexCoord; varying vec2 vTexCoord; void main() { vTexCoord = aTexCoord; vec4 positionVec4 = vec4(aPosition, 1.0); gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4; } `; // Create a string with the fragment shader program. // The fragment shader is called for each pixel. let fragSrc = ` precision mediump float; varying vec2 vTexCoord; void main() { vec2 uv = vTexCoord; vec3 color = vec3(uv.x, uv.y, min(uv.x + uv.y, 1.0)); gl_FragColor = vec4(color, 1.0);\ } `; let pg; function setup() { createCanvas(100, 100, WEBGL); background(200); // Create a p5.Shader object. let original = createShader(vertSrc, fragSrc); // Compile the p5.Shader object. shader(original); // Create a p5.Graphics object. pg = createGraphics(50, 50, WEBGL); // Copy the original shader to the p5.Graphics object. let copied = original.copyToContext(pg); // Apply the copied shader to the p5.Graphics object. pg.shader(copied); // Style the display surface. pg.noStroke(); // Add a display surface for the shader. pg.plane(50, 50); describe('A square with purple-blue gradient on its surface drawn against a gray background.'); } function draw() { background(200); // Draw the p5.Graphics object to the main canvas. image(pg, -25, -25); } `
` // Note: A "uniform" is a global variable within a shader program. // Create a string with the vertex shader program. // The vertex shader is called for each vertex. let vertSrc = ` precision highp float; uniform mat4 uModelViewMatrix; uniform mat4 uProjectionMatrix; attribute vec3 aPosition; attribute vec2 aTexCoord; varying vec2 vTexCoord; void main() { vTexCoord = aTexCoord; vec4 positionVec4 = vec4(aPosition, 1.0); gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4; } `; // Create a string with the fragment shader program. // The fragment shader is called for each pixel. let fragSrc = ` precision mediump float; varying vec2 vTexCoord; void main() { vec2 uv = vTexCoord; vec3 color = vec3(uv.x, uv.y, min(uv.x + uv.y, 1.0)); gl_FragColor = vec4(color, 1.0); } `; let copied; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Graphics object. let pg = createGraphics(25, 25, WEBGL); // Create a p5.Shader object. let original = pg.createShader(vertSrc, fragSrc); // Compile the p5.Shader object. pg.shader(original); // Copy the original shader to the main canvas. copied = original.copyToContext(window); // Apply the copied shader to the main canvas. shader(copied); describe('A rotating cube with a purple-blue gradient on its surface drawn against a gray background.'); } function draw() { background(200); // Rotate around the x-, y-, and z-axes. rotateX(frameCount * 0.01); rotateY(frameCount * 0.01); rotateZ(frameCount * 0.01); // Draw the box. box(50); } `

p5.Shader

3D

Material

Sets the shader’s uniform (global) variables.
Shader programs run on the computer’s graphics processing unit (GPU). They live in part of the computer’s memory that’s completely separate from the sketch that runs them. Uniforms are global variables within a shader program. They provide a way to pass values from a sketch running on the CPU to a shader program running on the GPU.
The first parameter, `uniformName`, is a string with the uniform’s name. For the shader above, `uniformName` would be `'r'`.
The second parameter, `data`, is the value that should be used to set the uniform. For example, calling `myShader.setUniform('r', 0.5)` would set the `r` uniform in the shader above to `0.5`. data should match the uniform’s type. Numbers, strings, booleans, arrays, and many types of images can all be passed to a shader with `setUniform()`.

method

setUniform

uniformName

name of the uniform. Must match the name used in the vertex and fragment shaders.

String

data

value to assign to the uniform. Must match the uniform’s data type.

Boolean|Number|Number[]|p5.Image|p5.Graphics|p5.MediaElement|p5.Texture

` // Note: A "uniform" is a global variable within a shader program. // Create a string with the vertex shader program. // The vertex shader is called for each vertex. let vertSrc = ` precision highp float; uniform mat4 uModelViewMatrix; uniform mat4 uProjectionMatrix; attribute vec3 aPosition; attribute vec2 aTexCoord; varying vec2 vTexCoord; void main() { vTexCoord = aTexCoord; vec4 positionVec4 = vec4(aPosition, 1.0); gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4; } `; // Create a string with the fragment shader program. // The fragment shader is called for each pixel. let fragSrc = ` precision mediump float; uniform float r; void main() { gl_FragColor = vec4(r, 1.0, 1.0, 1.0); } `; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Shader object. let myShader = createShader(vertSrc, fragSrc); // Apply the p5.Shader object. shader(myShader); // Set the r uniform to 0.5. myShader.setUniform('r', 0.5); // Style the drawing surface. noStroke(); // Add a plane as a drawing surface for the shader. plane(100, 100); describe('A cyan square.'); } `
` // Note: A "uniform" is a global variable within a shader program. // Create a string with the vertex shader program. // The vertex shader is called for each vertex. let vertSrc = ` precision highp float; uniform mat4 uModelViewMatrix; uniform mat4 uProjectionMatrix; attribute vec3 aPosition; attribute vec2 aTexCoord; varying vec2 vTexCoord; void main() { vTexCoord = aTexCoord; vec4 positionVec4 = vec4(aPosition, 1.0); gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4; } `; // Create a string with the fragment shader program. // The fragment shader is called for each pixel. let fragSrc = ` precision mediump float; uniform float r; void main() { gl_FragColor = vec4(r, 1.0, 1.0, 1.0); } `; let myShader; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Shader object. myShader = createShader(vertSrc, fragSrc); // Compile and apply the p5.Shader object. shader(myShader); describe('A square oscillates color between cyan and white.'); } function draw() { background(200); // Style the drawing surface. noStroke(); // Update the r uniform. let nextR = 0.5 * (sin(frameCount * 0.01) + 1); myShader.setUniform('r', nextR); // Add a plane as a drawing surface. plane(100, 100); } `
` // Note: A "uniform" is a global variable within a shader program. // Create a string with the vertex shader program. // The vertex shader is called for each vertex. let vertSrc = ` precision highp float; uniform mat4 uModelViewMatrix; uniform mat4 uProjectionMatrix; attribute vec3 aPosition; attribute vec2 aTexCoord; varying vec2 vTexCoord; void main() { vTexCoord = aTexCoord; vec4 positionVec4 = vec4(aPosition, 1.0); gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4; } `; // Create a string with the fragment shader program. // The fragment shader is called for each pixel. let fragSrc = ` precision highp float; uniform vec2 p; uniform float r; const int numIterations = 500; varying vec2 vTexCoord; void main() { vec2 c = p + gl_FragCoord.xy * r; vec2 z = c; float n = 0.0; for (int i = numIterations; i > 0; i--) { if (z.x * z.x + z.y * z.y > 4.0) { n = float(i) / float(numIterations); break; } z = vec2(z.x * z.x - z.y * z.y, 2.0 * z.x * z.y) + c; } gl_FragColor = vec4( 0.5 - cos(n * 17.0) / 2.0, 0.5 - cos(n * 13.0) / 2.0, 0.5 - cos(n * 23.0) / 2.0, 1.0 ); } `; let mandelbrot; function setup() { createCanvas(100, 100, WEBGL); // Create a p5.Shader object. mandelbrot = createShader(vertSrc, fragSrc); // Compile and apply the p5.Shader object. shader(mandelbrot); // Set the shader uniform p to an array. // p is the center point of the Mandelbrot image. mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]); describe('A fractal image zooms in and out of focus.'); } function draw() { // Set the shader uniform r to a value that oscillates // between 0 and 0.005. // r is the size of the image in Mandelbrot-space. let radius = 0.005 * (sin(frameCount * 0.01) + 1); mandelbrot.setUniform('r', radius); // Style the drawing surface. noStroke(); // Add a plane as a drawing surface. plane(100, 100); } `

p5.Shader

3D

Material

p5.sound

3D

p5.sound https://p5js.org/reference/#/libraries/p5.sound
From the Processing Foundation and contributors https://github.com/processing/p5.js-sound/graphs/contributors
MIT License (MIT) https://github.com/processing/p5.js-sound/blob/master/LICENSE
Some of the many audio libraries & resources that inspire p5.sound:
    * TONE.js (c) Yotam Mann. Licensed under The MIT License (MIT). https://github.com/TONEnoTONE/Tone.js
    * buzz.js (c) Jay Salvat. Licensed under The MIT License (MIT). http://buzz.jaysalvat.com/
    * Boris Smus Web Audio API book, 2013. Licensed under the Apache License http://www.apache.org/licenses/LICENSE-2.0
    * wavesurfer.js https://github.com/katspaugh/wavesurfer.js
    * Web Audio Components by Jordan Santell https://github.com/web-audio-components
    * Wilm Thoben's Sound library for Processing https://github.com/processing/processing/tree/master/java/libraries/sound
Web Audio API: http://w3.org/TR/webaudio/

p5.sound

p5.sound

p5.sound

Returns the Audio Context for this sketch. Useful for users who would like to dig deeper into the Web Audio API .
Some browsers require users to startAudioContext with a user gesture, such as touchStarted in the example below.

method

getAudioContext

### return
AudioContext for this sketch

Object

` function draw() { background(255); textAlign(CENTER); if (getAudioContext().state !== 'running') { text('click to start audio', width/2, height/2); } else { text('audio is enabled', width/2, height/2); } } function touchStarted() { if (getAudioContext().state !== 'running') { getAudioContext().resume(); } var synth = new p5.MonoSynth(); synth.play('A4', 0.5, 0, 0.2); } 
`

p5

p5.sound

p5.sound

It is not only a good practice to give users control over starting audio. This policy is enforced by many web browsers, including iOS and Google Chrome, which create the Web Audio API's Audio Context in a suspended state.
In these browser-specific policies, sound will not play until a user interaction event (i.e. `mousePressed()`) explicitly resumes the AudioContext, or starts an audio node. This can be accomplished by calling `start()` on a `p5.Oscillator`, ` play()` on a `p5.SoundFile`, or simply `userStartAudio()`.
`userStartAudio()` starts the AudioContext on a user gesture. The default behavior will enable audio on any mouseUp or touchEnd event. It can also be placed in a specific interaction function, such as `mousePressed()` as in the example below. This method utilizes StartAudioContext , a library by Yotam Mann (MIT Licence, 2016).

elements

This argument can be an Element, Selector String, NodeList, p5.Element, jQuery Element, or an Array of any of those.

Element|Array

callback

Callback to invoke when the AudioContext has started

Function

### return
Returns a Promise that resolves when the AudioContext state is 'running'

Promise

method

userStartAudio

` function setup() { // mimics the autoplay policy getAudioContext().suspend(); let mySynth = new p5.MonoSynth(); // This won't play until the context has resumed mySynth.play('A6'); } function draw() { background(220); textAlign(CENTER, CENTER); text(getAudioContext().state, width/2, height/2); } function mousePressed() { userStartAudio(); } `

p5

p5.sound

p5.sound

This module has shims

p5

p5.sound

p5.sound

Determine which filetypes are supported (inspired by buzz.js) The audio element (el) will only be used to test browser support for various audio formats

p5

p5.sound

p5.sound

Returns a number representing the output volume for sound in this sketch.

method

getOutputVolume

### return
Output volume for sound in this sketch. Should be between 0.0 (silence) and 1.0.

Number

p5

p5.sound

p5.sound

Scale the output of all sound in this sketch
Scaled between 0.0 (silence) and 1.0 (full volume). 1.0 is the maximum amplitude of a digital sound, so multiplying by greater than 1.0 may cause digital distortion. To fade, provide a `rampTime` parameter. For more complex fades, see the Envelope class. 
Alternately, you can pass in a signal source such as an oscillator to modulate the amplitude with an audio signal.
How This Works: When you load the p5.sound module, it creates a single instance of p5sound. All sound objects in this module output to p5sound before reaching your computer's output. So if you change the amplitude of p5sound, it impacts all of the sound in this module.
If no value is provided, returns a Web Audio API Gain Node

method

outputVolume

volume

Volume (amplitude) between 0.0 and 1.0 or modulating signal/oscillator

Number|Object

rampTime

Fade for t seconds

Number

timeFromNow

Schedule this event to happen at t seconds in the future

Number

p5

p5.sound

p5.sound

`p5.soundOut` is the p5.sound final output bus. It sends output to the destination of this window's web audio context. It contains Web Audio API nodes including a dyanmicsCompressor (`.limiter`), and Gain Nodes for `.input` and `.output`.

property

soundOut

Object

p5

p5.sound

p5.sound

p5

p5.sound

p5.sound

Returns a number representing the sample rate, in samples per second, of all sound objects in this audio context. It is determined by the sampling rate of your operating system's sound card, and it is not currently possile to change. It is often 44100, or twice the range of human hearing.

method

sampleRate

### return
samplerate samples per second

Number

p5

p5.sound

p5.sound

Returns the closest MIDI note value for a given frequency.

method

freqToMidi

frequency

A freqeuncy, for example, the "A" above Middle C is 440Hz

Number

### return
MIDI note value

Number

p5

p5.sound

p5.sound

Returns the frequency value of a MIDI note value. General MIDI treats notes as integers where middle C is 60, C# is 61, D is 62 etc. Useful for generating musical frequencies with oscillators.

method

midiToFreq

midiNote

The number of a MIDI note

Number

### return
Frequency value of the given MIDI note

Number

` let midiNotes = [60, 64, 67, 72]; let noteIndex = 0; let midiVal, freq; function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(startSound); osc = new p5.TriOsc(); env = new p5.Envelope(); } function draw() { background(220); text('tap to play', 10, 20); if (midiVal) { text('MIDI: ' + midiVal, 10, 40); text('Freq: ' + freq, 10, 60); } } function startSound() { // see also: userStartAudio(); osc.start(); midiVal = midiNotes[noteIndex % midiNotes.length]; freq = midiToFreq(midiVal); osc.freq(freq); env.ramp(osc, 0, 1.0, 0); noteIndex++; } `

p5

p5.sound

p5.sound

List the SoundFile formats that you will include. LoadSound will search your directory for these extensions, and will pick a format that is compatable with the client's web browser. Here is a free online file converter.

method

soundFormats

formats

i.e. 'mp3', 'wav', 'ogg'

String

` function preload() { // set the global sound formats soundFormats('mp3', 'ogg'); // load either beatbox.mp3, or .ogg, depending on browser mySound = loadSound('assets/beatbox.mp3'); } function setup() { let cnv = createCanvas(100, 100); background(220); text('sound loaded! tap to play', 10, 20, width - 20); cnv.mousePressed(function() { mySound.play(); }); } `

p5

p5.sound

p5.sound

Used by Osc and Envelope to chain signal math

p5

p5.sound

p5.sound

Save a p5.SoundFile as a .wav file. The browser will prompt the user to download the file to their device. For uploading audio to a server, use `p5.SoundFile.saveBlob`.

method

saveSound

soundFile

p5.SoundFile that you wish to save

p5.SoundFile

fileName

name of the resulting .wav file.

String

p5

p5.sound

p5.sound

Returns true if the sound file finished loading successfully.

method

isLoaded

### return


Boolean

p5.SoundFile

p5.sound

p5.sound

Play the p5.SoundFile

method

play

startTime

(optional) schedule playback to start (in seconds from now).

Number

rate

(optional) playback rate

Number

amp

(optional) amplitude (volume) of playback

Number

cueStart

(optional) cue start time in seconds

Number

duration

(optional) duration of playback in seconds

Number

p5.SoundFile

p5.sound

p5.sound

p5.SoundFile has two play modes: `restart` and `sustain`. Play Mode determines what happens to a p5.SoundFile if it is triggered while in the middle of playback. In sustain mode, playback will continue simultaneous to the new playback. In restart mode, play() will stop playback and start over. With untilDone, a sound will play only if it's not already playing. Sustain is the default mode.

method

playMode

str

'restart' or 'sustain' or 'untilDone'

String

` let mySound; function preload(){ mySound = loadSound('assets/Damscray_DancingTiger.mp3'); } function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(canvasPressed); noFill(); rect(0, height/2, width - 1, height/2 - 1); rect(0, 0, width - 1, height/2); textAlign(CENTER, CENTER); fill(20); text('restart', width/2, 1 * height/4); text('sustain', width/2, 3 * height/4); } function canvasPressed() { if (mouseX < height/2) { mySound.playMode('restart'); } else { mySound.playMode('sustain'); } mySound.play(); } `

p5.SoundFile

p5.sound

p5.sound

Pauses a file that is currently playing. If the file is not playing, then nothing will happen.
After pausing, .play() will resume from the paused position. If p5.SoundFile had been set to loop before it was paused, it will continue to loop after it is unpaused with .play().

method

pause

startTime

(optional) schedule event to occur seconds from now

Number

` let soundFile; function preload() { soundFormats('ogg', 'mp3'); soundFile = loadSound('assets/Damscray_-_Dancing_Tiger_02.mp3'); } function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(canvasPressed); background(220); text('tap to play, release to pause', 10, 20, width - 20); } function canvasPressed() { soundFile.loop(); background(0, 200, 50); } function mouseReleased() { soundFile.pause(); background(220); } `

p5.SoundFile

p5.sound

p5.sound

Loop the p5.SoundFile. Accepts optional parameters to set the playback rate, playback volume, loopStart, loopEnd.

method

loop

startTime

(optional) schedule event to occur seconds from now

Number

rate

(optional) playback rate

Number

amp

(optional) playback volume

Number

cueLoopStart

(optional) startTime in seconds

Number

duration

(optional) loop duration in seconds

Number

` let soundFile; let loopStart = 0.5; let loopDuration = 0.2; function preload() { soundFormats('ogg', 'mp3'); soundFile = loadSound('assets/Damscray_-_Dancing_Tiger_02.mp3'); } function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(canvasPressed); background(220); text('tap to play, release to pause', 10, 20, width - 20); } function canvasPressed() { soundFile.loop(); background(0, 200, 50); } function mouseReleased() { soundFile.pause(); background(220); } `

p5.SoundFile

p5.sound

p5.sound

Set a p5.SoundFile's looping flag to true or false. If the sound is currently playing, this change will take effect when it reaches the end of the current playback.

method

setLoop

Boolean

set looping to true or false

Boolean

p5.SoundFile

p5.sound

p5.sound

Returns 'true' if a p5.SoundFile is currently looping and playing, 'false' if not.

method

isLooping

### return


Boolean

p5.SoundFile

p5.sound

p5.sound

Returns true if a p5.SoundFile is playing, false if not (i.e. paused or stopped).

method

isPlaying

### return


Boolean

p5.SoundFile

p5.sound

p5.sound

Returns true if a p5.SoundFile is paused, false if not (i.e. playing or stopped).

method

isPaused

### return


Boolean

p5.SoundFile

p5.sound

p5.sound

Stop soundfile playback.

method

stop

startTime

(optional) schedule event to occur in seconds from now

Number

p5.SoundFile

p5.sound

p5.sound

Set the stereo panning of a p5.sound object to a floating point number between -1.0 (left) and 1.0 (right). Default is 0.0 (center).

method

pan

panValue

Set the stereo panner

Number

timeFromNow

schedule this event to happen seconds from now

Number

` let ballX = 0; let soundFile; function preload() { soundFormats('ogg', 'mp3'); soundFile = loadSound('assets/beatbox.mp3'); } function draw() { let cnv = createCanvas(100, 100); cnv.mousePressed(canvasPressed); background(220); ballX = constrain(mouseX, 0, width); ellipse(ballX, height/2, 20, 20); } function canvasPressed(){ // map the ball's x location to a panning degree // between -1.0 (left) and 1.0 (right) let panning = map(ballX, 0., width,-1.0, 1.0); soundFile.pan(panning); soundFile.play(); } 
`

p5.SoundFile

p5.sound

p5.sound

Returns the current stereo pan position (-1.0 to 1.0)

method

getPan

### return
Returns the stereo pan setting of the Oscillator as a number between -1.0 (left) and 1.0 (right). 0.0 is center and default.

Number

p5.SoundFile

p5.sound

p5.sound

Set the playback rate of a sound file. Will change the speed and the pitch. Values less than zero will reverse the audio buffer.

method

rate

playbackRate

Set the playback rate. 1.0 is normal, .5 is half-speed, 2.0 is twice as fast. Values less than zero play backwards.

Number

` let mySound; function preload() { mySound = loadSound('assets/Damscray_DancingTiger.mp3'); } function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(canvasPressed); } function canvasPressed() { mySound.loop(); } function mouseReleased() { mySound.pause(); } function draw() { background(220); // Set the rate to a range between 0.1 and 4 // Changing the rate also alters the pitch let playbackRate = map(mouseY, 0.1, height, 2, 0); playbackRate = constrain(playbackRate, 0.01, 4); mySound.rate(playbackRate); line(0, mouseY, width, mouseY); text('rate: ' + round(playbackRate * 100) + '%', 10, 20); } `

p5.SoundFile

p5.sound

p5.sound

Multiply the output volume (amplitude) of a sound file between 0.0 (silence) and 1.0 (full volume). 1.0 is the maximum amplitude of a digital sound, so multiplying by greater than 1.0 may cause digital distortion. To fade, provide a `rampTime` parameter. For more complex fades, see the Envelope class.
Alternately, you can pass in a signal source such as an oscillator to modulate the amplitude with an audio signal.

method

setVolume

volume

Volume (amplitude) between 0.0 and 1.0 or modulating signal/oscillator

Number|Object

rampTime

Fade for t seconds

Number

timeFromNow

Schedule this event to happen at t seconds in the future

Number

p5.SoundFile

p5.sound

p5.sound

Returns the duration of a sound file in seconds.

method

duration

### return
The duration of the soundFile in seconds.

Number

p5.SoundFile

p5.sound

p5.sound

Return the current position of the p5.SoundFile playhead, in seconds. Time is relative to the normal buffer direction, so if `reverseBuffer` has been called, currentTime will count backwards.

method

currentTime

### return
currentTime of the soundFile in seconds.

Number

p5.SoundFile

p5.sound

p5.sound

Move the playhead of a soundfile that is currently playing to a new position and a new duration, in seconds. If none are given, will reset the file to play entire duration from start to finish. To set the position of a soundfile that is not currently playing, use the `play` or `loop` methods.

method

jump

cueTime

cueTime of the soundFile in seconds.

Number

duration

duration in seconds.

Number

p5.SoundFile

p5.sound

p5.sound

Return the number of channels in a sound file. For example, Mono = 1, Stereo = 2.

method

channels

### return
[channels]

Number

p5.SoundFile

p5.sound

p5.sound

Return the sample rate of the sound file.

method

sampleRate

### return
[sampleRate]

Number

p5.SoundFile

p5.sound

p5.sound

Return the number of samples in a sound file. Equal to sampleRate * duration.

method

frames

### return
[sampleCount]

Number

p5.SoundFile

p5.sound

p5.sound

Returns an array of amplitude peaks in a p5.SoundFile that can be used to draw a static waveform. Scans through the p5.SoundFile's audio buffer to find the greatest amplitudes. Accepts one parameter, 'length', which determines size of the array. Larger arrays result in more precise waveform visualizations.
Inspired by Wavesurfer.js.

method

getPeaks

length

length is the size of the returned array. Larger length results in more precision. Defaults to 5*width of the browser window.

Number

### return
Array of peaks.

Float32Array

p5.SoundFile

p5.sound

p5.sound

Reverses the p5.SoundFile's buffer source. Playback must be handled separately (see example).

method

reverseBuffer

` let drum; function preload() { drum = loadSound('assets/drum.mp3'); } function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(canvasPressed); background(220); text('tap to play', 20, 20); } function canvasPressed() { drum.stop(); drum.reverseBuffer(); drum.play(); } `

p5.SoundFile

p5.sound

p5.sound

Schedule an event to be called when the soundfile reaches the end of a buffer. If the soundfile is playing through once, this will be called when it ends. If it is looping, it will be called when stop is called.

method

onended

callback

function to call when the soundfile has ended.

Function

p5.SoundFile

p5.sound

p5.sound

Connects the output of a p5sound object to input of another p5.sound object. For example, you may connect a p5.SoundFile to an FFT or an Effect. If no parameter is given, it will connect to the main output. Most p5sound objects connect to the master output when they are created.

method

connect

object

Audio object that accepts an input

Object

p5.SoundFile

p5.sound

p5.sound

Disconnects the output of this p5sound object.

method

disconnect

p5.SoundFile

p5.sound

p5.sound

p5.SoundFile

p5.sound

p5.sound

Reset the source for this SoundFile to a new path (URL).

method

setPath

path

path to audio file

String

callback

Callback

Function

p5.SoundFile

p5.sound

p5.sound

Replace the current Audio Buffer with a new Buffer.

method

setBuffer

buf

Array of Float32 Array(s). 2 Float32 Arrays will create a stereo source. 1 will create a mono source.

Array

p5.SoundFile

p5.sound

p5.sound

Schedule events to trigger every time a MediaElement (audio/video) reaches a playback cue point.
Accepts a callback function, a time (in seconds) at which to trigger the callback, and an optional parameter for the callback.
Time will be passed as the first parameter to the callback function, and param will be the second parameter.

method

addCue

time

Time in seconds, relative to this media element's playback. For example, to trigger an event every time playback reaches two seconds, pass in the number 2. This will be passed as the first parameter to the callback function.

Number

callback

Name of a function that will be called at the given time. The callback will receive time and (optionally) param as its two parameters.

Function

value

An object to be passed as the second parameter to the callback function.

Object

### return
id ID of this cue, useful for removeCue(id)

Number

` let mySound; function preload() { mySound = loadSound('assets/Damscray_DancingTiger.mp3'); } function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(canvasPressed); background(220); text('tap to play', 10, 20); // schedule calls to changeText mySound.addCue(0, changeText, "hello" ); mySound.addCue(0.5, changeText, "hello," ); mySound.addCue(1, changeText, "hello, p5!"); mySound.addCue(1.5, changeText, "hello, p5!!"); mySound.addCue(2, changeText, "hello, p5!!!!!"); } function changeText(val) { background(220); text(val, 10, 20); } function canvasPressed() { mySound.play(); } `

p5.SoundFile

p5.sound

p5.sound

Remove a callback based on its ID. The ID is returned by the addCue method.

method

removeCue

id

ID of the cue, as returned by addCue

Number

p5.SoundFile

p5.sound

p5.sound

Remove all of the callbacks that had originally been scheduled via the addCue method.

method

clearCues

p5.SoundFile

p5.sound

p5.sound

Save a p5.SoundFile as a .wav file. The browser will prompt the user to download the file to their device. To upload a file to a server, see getBlob

method

save

fileName

name of the resulting .wav file.

String

` let mySound; function preload() { mySound = loadSound('assets/doorbell.mp3'); } function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(canvasPressed); background(220); text('tap to download', 10, 20); } function canvasPressed() { mySound.save('my cool filename'); } `

p5.SoundFile

p5.sound

p5.sound

This method is useful for sending a SoundFile to a server. It returns the .wav-encoded audio data as a "Blob". A Blob is a file-like data object that can be uploaded to a server with an http request. We'll use the `httpDo` options object to send a POST request with some specific options: we encode the request as `multipart/form-data`, and attach the blob as one of the form values using `FormData`.

method

getBlob

### return
A file-like data object

Blob

` function preload() { mySound = loadSound('assets/doorbell.mp3'); } function setup() { noCanvas(); let soundBlob = mySound.getBlob(); // Now we can send the blob to a server... let serverUrl = 'https://jsonplaceholder.typicode.com/posts'; let httpRequestOptions = { method: 'POST', body: new FormData().append('soundBlob', soundBlob), headers: new Headers({ 'Content-Type': 'multipart/form-data' }) }; httpDo(serverUrl, httpRequestOptions); // We can also create an `ObjectURL` pointing to the Blob let blobUrl = URL.createObjectURL(soundBlob); // The `` Element accepts Object URL's createAudio(blobUrl).showControls(); createDiv(); // The ObjectURL exists as long as this tab is open let input = createInput(blobUrl); input.attribute('readonly', true); input.mouseClicked(function() { input.elt.select() }); } `

p5.SoundFile

p5.sound

p5.sound

loadSound() returns a new p5.SoundFile from a specified path. If called during preload(), the p5.SoundFile will be ready to play in time for setup() and draw(). If called outside of preload, the p5.SoundFile will not be ready immediately, so loadSound accepts a callback as the second parameter. Using a  local server is recommended when loading external files.

method

loadSound

path

Path to the sound file, or an array with paths to soundfiles in multiple formats i.e. ['sound.ogg', 'sound.mp3']. Alternately, accepts an object: either from the HTML5 File API, or a p5.File.

String|Array

successCallback

Name of a function to call once file loads

Function

errorCallback

Name of a function to call if there is an error loading the file.

Function

whileLoading

Name of a function to call while file is loading. This function will receive the percentage loaded so far, from 0.0 to 1.0.

Function

### return
Returns a p5.SoundFile

SoundFile

` let mySound; function preload() { soundFormats('mp3', 'ogg'); mySound = loadSound('assets/doorbell'); } function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(canvasPressed); background(220); text('tap here to play', 10, 20); } function canvasPressed() { // playing a sound file on a user gesture // is equivalent to `userStartAudio()` mySound.play(); } `

p5

p5.sound

p5.sound

Connects to the p5sound instance (main output) by default. Optionally, you can pass in a specific source (i.e. a soundfile).

method

setInput

snd

set the sound source (optional, defaults to main output)

SoundObject|undefined

smoothing

a range between 0.0 and 1.0 to smooth amplitude readings

Number|undefined

` function preload(){ sound1 = loadSound('assets/beat.mp3'); sound2 = loadSound('assets/drum.mp3'); } function setup(){ cnv = createCanvas(100, 100); cnv.mouseClicked(toggleSound); amplitude = new p5.Amplitude(); amplitude.setInput(sound2); } function draw() { background(220); text('tap to play', 20, 20); let level = amplitude.getLevel(); let size = map(level, 0, 1, 0, 200); ellipse(width/2, height/2, size, size); } function toggleSound(){ if (sound1.isPlaying() && sound2.isPlaying()) { sound1.stop(); sound2.stop(); } else { sound1.play(); sound2.play(); } } `

p5.Amplitude

p5.sound

p5.sound

Returns a single Amplitude reading at the moment it is called. For continuous readings, run in the draw loop.

method

getLevel

channel

Optionally return only channel 0 (left) or 1 (right)

Number

### return
Amplitude as a number between 0.0 and 1.0

Number

` function preload(){ sound = loadSound('assets/beat.mp3'); } function setup() { let cnv = createCanvas(100, 100); cnv.mouseClicked(toggleSound); amplitude = new p5.Amplitude(); } function draw() { background(220, 150); textAlign(CENTER); text('tap to play', width/2, 20); let level = amplitude.getLevel(); let size = map(level, 0, 1, 0, 200); ellipse(width/2, height/2, size, size); } function toggleSound(){ if (sound.isPlaying()) { sound.stop(); } else { sound.play(); } } `

p5.Amplitude

p5.sound

p5.sound

Determines whether the results of Amplitude.process() will be Normalized. To normalize, Amplitude finds the difference the loudest reading it has processed and the maximum amplitude of 1.0. Amplitude adds this difference to all values to produce results that will reliably map between 0.0 and 1.0. However, if a louder moment occurs, the amount that Normalize adds to all the values will change. Accepts an optional boolean parameter (true or false). Normalizing is off by default.

method

toggleNormalize

boolean

set normalize to true (1) or false (0)

Boolean

p5.Amplitude

p5.sound

p5.sound

Smooth Amplitude analysis by averaging with the last analysis frame. Off by default.

method

smooth

set

smoothing from 0.0 <= 1

Number

p5.Amplitude

p5.sound

p5.sound

Set the input source for the FFT analysis. If no source is provided, FFT will analyze all sound in the sketch.

method

setInput

source

p5.sound object (or web audio API source node)

Object

p5.FFT

p5.sound

p5.sound

Returns an array of amplitude values (between -1.0 and +1.0) that represent a snapshot of amplitude readings in a single buffer. Length will be equal to bins (defaults to 1024). Can be used to draw the waveform of a sound.

method

waveform

bins

Must be a power of two between 16 and 1024. Defaults to 1024.

Number

precision

If any value is provided, will return results in a Float32 Array which is more precise than a regular array.

String

### return
Array Array of amplitude values (-1 to 1) over time. Array length = bins.

Array

p5.FFT

p5.sound

p5.sound

Returns an array of amplitude values (between 0 and 255) across the frequency spectrum. Length is equal to FFT bins (1024 by default). The array indices correspond to frequencies (i.e. pitches), from the lowest to the highest that humans can hear. Each value represents amplitude at that slice of the frequency spectrum. Must be called prior to using `getEnergy()`.

method

analyze

bins

Must be a power of two between 16 and 1024. Defaults to 1024.

Number

scale

If "dB," returns decibel float measurements between -140 and 0 (max). Otherwise returns integers from 0-255.

Number

### return
spectrum Array of energy (amplitude/volume) values across the frequency spectrum. Lowest energy (silence) = 0, highest possible is 255.

Array

` let osc, fft; function setup(){ let cnv = createCanvas(100,100); cnv.mousePressed(startSound); osc = new p5.Oscillator(); osc.amp(0); fft = new p5.FFT(); } function draw(){ background(220); let freq = map(mouseX, 0, windowWidth, 20, 10000); freq = constrain(freq, 1, 20000); osc.freq(freq); let spectrum = fft.analyze(); noStroke(); fill(255, 0, 255); for (let i = 0; i< spectrum.length; i++){ let x = map(i, 0, spectrum.length, 0, width); let h = -height + map(spectrum[i], 0, 255, height, 0); rect(x, height, width / spectrum.length, h ); } stroke(255); if (!osc.started) { text('tap here and drag to change frequency', 10, 20, width - 20); } else { text(round(freq)+'Hz', 10, 20); } } function startSound() { osc.start(); osc.amp(0.5, 0.2); } function mouseReleased() { osc.amp(0, 0.2); } `

p5.FFT

p5.sound

p5.sound

Returns the amount of energy (volume) at a specific  frequency, or the average amount of energy between two frequencies. Accepts Number(s) corresponding to frequency (in Hz), or a "string" corresponding to predefined frequency ranges ("bass", "lowMid", "mid", "highMid", "treble"). Returns a range between 0 (no energy/volume at that frequency) and 255 (maximum energy). NOTE: analyze() must be called prior to getEnergy(). analyze() tells the FFT to analyze frequency data, and getEnergy() uses the results to determine the value at a specific frequency or range of frequencies.

method

getEnergy

frequency1

Will return a value representing energy at this frequency. Alternately, the strings "bass", "lowMid" "mid", "highMid", and "treble" will return predefined frequency ranges.

Number|String

frequency2

If a second frequency is given, will return average amount of energy that exists between the two frequencies.

Number

### return
Energy Energy (volume/amplitude) from 0 and 255.

Number

p5.FFT

p5.sound

p5.sound

Returns the  spectral centroid of the input signal. NOTE: analyze() must be called prior to getCentroid(). Analyze() tells the FFT to analyze frequency data, and getCentroid() uses the results determine the spectral centroid.

method

getCentroid

### return
Spectral Centroid Frequency of the spectral centroid in Hz.

Number

` function setup(){ cnv = createCanvas(100,100); cnv.mousePressed(userStartAudio); sound = new p5.AudioIn(); sound.start(); fft = new p5.FFT(); sound.connect(fft); } function draw() { if (getAudioContext().state !== 'running') { background(220); text('tap here and enable mic to begin', 10, 20, width - 20); return; } let centroidplot = 0.0; let spectralCentroid = 0; background(0); stroke(0,255,0); let spectrum = fft.analyze(); fill(0,255,0); // spectrum is green //draw the spectrum for (let i = 0; i < spectrum.length; i++){ let x = map(log(i), 0, log(spectrum.length), 0, width); let h = map(spectrum[i], 0, 255, 0, height); let rectangle_width = (log(i+1)-log(i))*(width/log(spectrum.length)); rect(x, height, rectangle_width, -h ) } let nyquist = 22050; // get the centroid spectralCentroid = fft.getCentroid(); // the mean_freq_index calculation is for the display. let mean_freq_index = spectralCentroid/(nyquist/spectrum.length); centroidplot = map(log(mean_freq_index), 0, log(spectrum.length), 0, width); stroke(255,0,0); // the line showing where the centroid is will be red rect(centroidplot, 0, width / spectrum.length, height) noStroke(); fill(255,255,255); // text is white text('centroid: ', 10, 20); text(round(spectralCentroid)+' Hz', 10, 40); } `

p5.FFT

p5.sound

p5.sound

Smooth FFT analysis by averaging with the last analysis frame.

method

smooth

smoothing

0.0 < smoothing < 1.0. Defaults to 0.8.

Number

p5.FFT

p5.sound

p5.sound

Returns an array of average amplitude values for a given number of frequency bands split equally. N defaults to 16. NOTE: analyze() must be called prior to linAverages(). Analyze() tells the FFT to analyze frequency data, and linAverages() uses the results to group them into a smaller set of averages.

method

linAverages

N

Number of returned frequency groups

Number

### return
linearAverages Array of average amplitude values for each group

Array

p5.FFT

p5.sound

p5.sound

Returns an array of average amplitude values of the spectrum, for a given set of  Octave Bands NOTE: analyze() must be called prior to logAverages(). Analyze() tells the FFT to analyze frequency data, and logAverages() uses the results to group them into a smaller set of averages.

method

logAverages

octaveBands

Array of Octave Bands objects for grouping

Array

### return
logAverages Array of average amplitude values for each group

Array

p5.FFT

p5.sound

p5.sound

Calculates and Returns the 1/N Octave Bands N defaults to 3 and minimum central frequency to 15.625Hz. (1/3 Octave Bands ~= 31 Frequency Bands) Setting fCtr0 to a central value of a higher octave will ignore the lower bands and produce less frequency groups.

method

getOctaveBands

N

Specifies the 1/N type of generated octave bands

Number

fCtr0

Minimum central frequency for the lowest band

Number

### return
octaveBands Array of octave band objects with their bounds

Array

p5.FFT

p5.sound

p5.sound

Start an oscillator.
Starting an oscillator on a user gesture will enable audio in browsers that have a strict autoplay policy, including Chrome and most mobile devices. See also: `userStartAudio()`.

method

start

time

startTime in seconds from now.

Number

frequency

frequency in Hz.

Number

p5.Oscillator

p5.sound

p5.sound

Stop an oscillator. Accepts an optional parameter to determine how long (in seconds from now) until the oscillator stops.

method

stop

secondsFromNow

Time, in seconds from now.

Number

p5.Oscillator

p5.sound

p5.sound

Set the amplitude between 0 and 1.0. Or, pass in an object such as an oscillator to modulate amplitude with an audio signal.

method

amp

vol

between 0 and 1.0 or a modulating signal/oscillator

Number|Object

rampTime

create a fade that lasts rampTime

Number

timeFromNow

schedule this event to happen seconds from now

Number

### return
gain If no value is provided, returns the Web Audio API AudioParam that controls this oscillator's gain/amplitude/volume)

AudioParam

p5.Oscillator

p5.sound

p5.sound

Returns the value of output gain

method

getAmp

### return
Amplitude value between 0.0 and 1.0

Number

p5.Oscillator

p5.sound

p5.sound

Set frequency of an oscillator to a value. Or, pass in an object such as an oscillator to modulate the frequency with an audio signal.

method

freq

Frequency

Frequency in Hz or modulating signal/oscillator

Number|Object

rampTime

Ramp time (in seconds)

Number

timeFromNow

Schedule this event to happen at x seconds from now

Number

### return
Frequency If no value is provided, returns the Web Audio API AudioParam that controls this oscillator's frequency

AudioParam

` let osc; function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(playOscillator); osc = new p5.Oscillator(300); background(220); text('tap to play', 20, 20); } function playOscillator() { osc.start(); osc.amp(0.5); // start at 700Hz osc.freq(700); // ramp to 60Hz over 0.7 seconds osc.freq(60, 0.7); osc.amp(0, 0.1, 0.7); } `

p5.Oscillator

p5.sound

p5.sound

Returns the value of frequency of oscillator

method

getFreq

### return
Frequency of oscillator in Hertz

Number

p5.Oscillator

p5.sound

p5.sound

Set type to 'sine', 'triangle', 'sawtooth' or 'square'.

method

setType

type

'sine', 'triangle', 'sawtooth' or 'square'.

String

p5.Oscillator

p5.sound

p5.sound

Returns current type of oscillator eg. 'sine', 'triangle', 'sawtooth' or 'square'.

method

getType

### return
type of oscillator eg . 'sine', 'triangle', 'sawtooth' or 'square'.

String

p5.Oscillator

p5.sound

p5.sound

Connect to a p5.sound / Web Audio object.

method

connect

unit

A p5.sound or Web Audio object

Object

p5.Oscillator

p5.sound

p5.sound

Disconnect all outputs

method

disconnect

p5.Oscillator

p5.sound

p5.sound

Pan between Left (-1) and Right (1)

method

pan

panning

Number between -1 and 1

Number

timeFromNow

schedule this event to happen seconds from now

Number

p5.Oscillator

p5.sound

p5.sound

Returns the current value of panPosition , between Left (-1) and Right (1)

method

getPan

### return
panPosition of oscillator , between Left (-1) and Right (1)

Number

p5.Oscillator

p5.sound

p5.sound

Set the phase of an oscillator between 0.0 and 1.0. In this implementation, phase is a delay time based on the oscillator's current frequency.

method

phase

phase

float between 0.0 and 1.0

Number

p5.Oscillator

p5.sound

p5.sound

Add a value to the p5.Oscillator's output amplitude, and return the oscillator. Calling this method again will override the initial add() with a new value.

method

add

number

Constant number to add

Number

### return
Oscillator Returns this oscillator with scaled output

p5.Oscillator

p5.Oscillator

p5.sound

p5.sound

Multiply the p5.Oscillator's output amplitude by a fixed value (i.e. turn it up!). Calling this method again will override the initial mult() with a new value.

method

mult

number

Constant number to multiply

Number

### return
Oscillator Returns this oscillator with multiplied output

p5.Oscillator

p5.Oscillator

p5.sound

p5.sound

Scale this oscillator's amplitude values to a given range, and return the oscillator. Calling this method again will override the initial scale() with new values.

method

scale

inMin

input range minumum

Number

inMax

input range maximum

Number

outMin

input range minumum

Number

outMax

input range maximum

Number

### return
Oscillator Returns this oscillator with scaled output

p5.Oscillator

p5.Oscillator

p5.sound

p5.sound

Time until envelope reaches attackLevel

property

attackTime

p5.Envelope

p5.sound

p5.sound

Level once attack is complete.

property

attackLevel

p5.Envelope

p5.sound

p5.sound

Time until envelope reaches decayLevel.

property

decayTime

p5.Envelope

p5.sound

p5.sound

Level after decay. The envelope will sustain here until it is released.

property

decayLevel

p5.Envelope

p5.sound

p5.sound

Duration of the release portion of the envelope.

property

releaseTime

p5.Envelope

p5.sound

p5.sound

Level at the end of the release.

property

releaseLevel

p5.Envelope

p5.sound

p5.sound

Reset the envelope with a series of time/value pairs.

method

set

attackTime

Time (in seconds) before level reaches attackLevel

Number

attackLevel

Typically an amplitude between 0.0 and 1.0

Number

decayTime

Time

Number

decayLevel

Amplitude (In a standard ADSR envelope, decayLevel = sustainLevel)

Number

releaseTime

Release Time (in seconds)

Number

releaseLevel

Amplitude

Number

` let attackTime; let l1 = 0.7; // attack level 0.0 to 1.0 let t2 = 0.3; // decay time in seconds let l2 = 0.1; // decay level 0.0 to 1.0 let l3 = 0.2; // release time in seconds let env, triOsc; function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(playSound); env = new p5.Envelope(); triOsc = new p5.Oscillator('triangle'); } function draw() { background(220); text('tap here to play', 5, 20); attackTime = map(mouseX, 0, width, 0.0, 1.0); text('attack time: ' + attackTime, 5, height - 20); } // mouseClick triggers envelope if over canvas function playSound() { env.set(attackTime, l1, t2, l2, l3); triOsc.start(); env.play(triOsc); } `

p5.Envelope

p5.sound

p5.sound

Set values like a traditional  ADSR envelope .

method

setADSR

attackTime

Time (in seconds before envelope reaches Attack Level

Number

decayTime

Time (in seconds) before envelope reaches Decay/Sustain Level

Number

susRatio

Ratio between attackLevel and releaseLevel, on a scale from 0 to 1, where 1.0 = attackLevel, 0.0 = releaseLevel. The susRatio determines the decayLevel and the level at which the sustain portion of the envelope will sustain. For example, if attackLevel is 0.4, releaseLevel is 0, and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is increased to 1.0 (using `setRange`), then decayLevel would increase proportionally, to become 0.5.

Number

releaseTime

Time in seconds from now (defaults to 0)

Number

` let attackLevel = 1.0; let releaseLevel = 0; let attackTime = 0.001; let decayTime = 0.2; let susPercent = 0.2; let releaseTime = 0.5; let env, triOsc; function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(playEnv); env = new p5.Envelope(); triOsc = new p5.Oscillator('triangle'); triOsc.amp(env); triOsc.freq(220); } function draw() { background(220); text('tap here to play', 5, 20); attackTime = map(mouseX, 0, width, 0, 1.0); text('attack time: ' + attackTime, 5, height - 40); } function playEnv() { triOsc.start(); env.setADSR(attackTime, decayTime, susPercent, releaseTime); env.play(); } `

p5.Envelope

p5.sound

p5.sound

Set max (attackLevel) and min (releaseLevel) of envelope.

method

setRange

aLevel

attack level (defaults to 1)

Number

rLevel

release level (defaults to 0)

Number

` let attackLevel = 1.0; let releaseLevel = 0; let attackTime = 0.001; let decayTime = 0.2; let susPercent = 0.2; let releaseTime = 0.5; let env, triOsc; function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(playEnv); env = new p5.Envelope(); triOsc = new p5.Oscillator('triangle'); triOsc.amp(env); triOsc.freq(220); } function draw() { background(220); text('tap here to play', 5, 20); attackLevel = map(mouseY, height, 0, 0, 1.0); text('attack level: ' + attackLevel, 5, height - 20); } function playEnv() { triOsc.start(); env.setRange(attackLevel, releaseLevel); env.play(); } `

p5.Envelope

p5.sound

p5.sound

Assign a parameter to be controlled by this envelope. If a p5.Sound object is given, then the p5.Envelope will control its output gain. If multiple inputs are provided, the env will control all of them.

method

setInput

inputs

A p5.sound object or Web Audio Param.

Object

p5.Envelope

p5.sound

p5.sound

Set whether the envelope ramp is linear (default) or exponential. Exponential ramps can be useful because we perceive amplitude and frequency logarithmically.

method

setExp

isExp

true is exponential, false is linear

Boolean

p5.Envelope

p5.sound

p5.sound

Play tells the envelope to start acting on a given input. If the input is a p5.sound object (i.e. AudioIn, Oscillator, SoundFile), then Envelope will control its output volume. Envelopes can also be used to control any  Web Audio Audio Param.

method

play

unit

A p5.sound object or Web Audio Param.

Object

startTime

time from now (in seconds) at which to play

Number

sustainTime

time to sustain before releasing the envelope

Number

` let attackLevel = 1.0; let releaseLevel = 0; let attackTime = 0.001; let decayTime = 0.2; let susPercent = 0.2; let releaseTime = 0.5; let env, triOsc; function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(playEnv); env = new p5.Envelope(); triOsc = new p5.Oscillator('triangle'); triOsc.amp(env); triOsc.freq(220); triOsc.start(); } function draw() { background(220); text('tap here to play', 5, 20); attackTime = map(mouseX, 0, width, 0, 1.0); attackLevel = map(mouseY, height, 0, 0, 1.0); text('attack time: ' + attackTime, 5, height - 40); text('attack level: ' + attackLevel, 5, height - 20); } function playEnv() { // ensure that audio is enabled userStartAudio(); env.setADSR(attackTime, decayTime, susPercent, releaseTime); env.setRange(attackLevel, releaseLevel); env.play(); } `

p5.Envelope

p5.sound

p5.sound

Trigger the Attack, and Decay portion of the Envelope. Similar to holding down a key on a piano, but it will hold the sustain level until you let go. Input can be any p5.sound object, or a  Web Audio Param.

method

triggerAttack

unit

p5.sound Object or Web Audio Param

Object

secondsFromNow

time from now (in seconds)

Number

` let attackTime = 0.001; let decayTime = 0.2; let susPercent = 0.3; let releaseTime = 0.4; let env, triOsc; function setup() { let cnv = createCanvas(100, 100); background(220); textAlign(CENTER); textSize(10); text('tap to triggerAttack', width/2, height/2); env = new p5.Envelope(); env.setADSR(attackTime, decayTime, susPercent, releaseTime); env.setRange(1.0, 0.0); triOsc = new p5.Oscillator('triangle'); triOsc.freq(220); cnv.mousePressed(envAttack); } function envAttack() { background(0, 255, 255); text('release to release', width/2, height/2); // ensures audio is enabled. See also: `userStartAudio` triOsc.start(); env.triggerAttack(triOsc); } function mouseReleased() { background(220); text('tap to triggerAttack', width/2, height/2); env.triggerRelease(triOsc); } `

p5.Envelope

p5.sound

p5.sound

Trigger the Release of the Envelope. This is similar to releasing the key on a piano and letting the sound fade according to the release level and release time.

method

triggerRelease

unit

p5.sound Object or Web Audio Param

Object

secondsFromNow

time to trigger the release

Number

` let attackTime = 0.001; let decayTime = 0.2; let susPercent = 0.3; let releaseTime = 0.4; let env, triOsc; function setup() { let cnv = createCanvas(100, 100); background(220); textAlign(CENTER); textSize(10); text('tap to triggerAttack', width/2, height/2); env = new p5.Envelope(); env.setADSR(attackTime, decayTime, susPercent, releaseTime); env.setRange(1.0, 0.0); triOsc = new p5.Oscillator('triangle'); triOsc.freq(220); cnv.mousePressed(envAttack); } function envAttack() { background(0, 255, 255); text('release to release', width/2, height/2); // ensures audio is enabled. See also: `userStartAudio` triOsc.start(); env.triggerAttack(triOsc); } function mouseReleased() { background(220); text('tap to triggerAttack', width/2, height/2); env.triggerRelease(triOsc); } `

p5.Envelope

p5.sound

p5.sound

Exponentially ramp to a value using the first two values from `setADSR(attackTime, decayTime)` as  time constants for simple exponential ramps. If the value is higher than current value, it uses attackTime, while a decrease uses decayTime.

method

ramp

unit

p5.sound Object or Web Audio Param

Object

secondsFromNow

When to trigger the ramp

Number

v

Target value

Number

v2

Second target value

Number

` let env, osc, amp; let attackTime = 0.001; let decayTime = 0.2; let attackLevel = 1; let decayLevel = 0; function setup() { let cnv = createCanvas(100, 100); fill(0,255,0); noStroke(); env = new p5.Envelope(); env.setADSR(attackTime, decayTime); osc = new p5.Oscillator(); osc.amp(env); amp = new p5.Amplitude(); cnv.mousePressed(triggerRamp); } function triggerRamp() { // ensures audio is enabled. See also: `userStartAudio` osc.start(); env.ramp(osc, 0, attackLevel, decayLevel); } function draw() { background(20); text('tap to play', 10, 20); let h = map(amp.getLevel(), 0, 0.4, 0, height);; rect(0, height, width, -h); } `

p5.Envelope

p5.sound

p5.sound

Add a value to the p5.Oscillator's output amplitude, and return the oscillator. Calling this method again will override the initial add() with new values.

method

add

number

Constant number to add

Number

### return
Envelope Returns this envelope with scaled output

p5.Envelope

p5.Envelope

p5.sound

p5.sound

Multiply the p5.Envelope's output amplitude by a fixed value. Calling this method again will override the initial mult() with new values.

method

mult

number

Constant number to multiply

Number

### return
Envelope Returns this envelope with scaled output

p5.Envelope

p5.Envelope

p5.sound

p5.sound

Scale this envelope's amplitude values to a given range, and return the envelope. Calling this method again will override the initial scale() with new values.

method

scale

inMin

input range minumum

Number

inMax

input range maximum

Number

outMin

input range minumum

Number

outMax

input range maximum

Number

### return
Envelope Returns this envelope with scaled output

p5.Envelope

p5.Envelope

p5.sound

p5.sound

Set type of noise to 'white', 'pink' or 'brown'. White is the default.

method

setType

type

'white', 'pink' or 'brown'

String

p5.Noise

p5.sound

p5.sound

Set the width of a Pulse object (an oscillator that implements Pulse Width Modulation).

method

width

width

Width between the pulses (0 to 1.0, defaults to 0)

Number

p5.Pulse

p5.sound

p5.sound

property

input

GainNode

p5.AudioIn

p5.sound

p5.sound

property

output

GainNode

p5.AudioIn

p5.sound

p5.sound

property

stream

MediaStream|null

p5.AudioIn

p5.sound

p5.sound

property

mediaStream

MediaStreamAudioSourceNode|null

p5.AudioIn

p5.sound

p5.sound

property

currentSource

Number|null

p5.AudioIn

p5.sound

p5.sound

Client must allow browser to access their microphone / audioin source. Default: false. Will become true when the client enables access.

property

enabled

Boolean

p5.AudioIn

p5.sound

p5.sound

Input amplitude, connect to it by default but not to master out

property

amplitude

p5.Amplitude

p5.AudioIn

p5.sound

p5.sound

Start processing audio input. This enables the use of other AudioIn methods like getLevel(). Note that by default, AudioIn is not connected to p5.sound's output. So you won't hear anything unless you use the connect() method.  

Certain browsers limit access to the user's microphone. For example, Chrome only allows access from localhost and over https. For this reason, you may want to include an errorCallback—a function that is called in case the browser won't provide mic access.

method

start

successCallback

Name of a function to call on success.

Function

errorCallback

Name of a function to call if there was an error. For example, some browsers do not support getUserMedia.

Function

p5.AudioIn

p5.sound

p5.sound

Turn the AudioIn off. If the AudioIn is stopped, it cannot getLevel(). If re-starting, the user may be prompted for permission access.

method

stop

p5.AudioIn

p5.sound

p5.sound

Connect to an audio unit. If no parameter is provided, will connect to the main output (i.e. your speakers).  


method

connect

unit

An object that accepts audio input, such as an FFT

Object

p5.AudioIn

p5.sound

p5.sound

Disconnect the AudioIn from all audio units. For example, if connect() had been called, disconnect() will stop sending signal to your speakers.  


method

disconnect

p5.AudioIn

p5.sound

p5.sound

Read the Amplitude (volume level) of an AudioIn. The AudioIn class contains its own instance of the Amplitude class to help make it easy to get a microphone's volume level. Accepts an optional smoothing value (0.0 < 1.0). NOTE: AudioIn must .start() before using .getLevel().  


method

getLevel

smoothing

Smoothing is 0.0 by default. Smooths values based on previous values.

Number

### return
Volume level (between 0.0 and 1.0)

Number

p5.AudioIn

p5.sound

p5.sound

Set amplitude (volume) of a mic input between 0 and 1.0.   


method

amp

vol

between 0 and 1.0

Number

time

ramp time (optional)

Number

p5.AudioIn

p5.sound

p5.sound

Returns a list of available input sources. This is a wrapper for  MediaDevices.enumerateDevices() - Web APIs | MDN and it returns a Promise.

method

getSources

successCallback

This callback function handles the sources when they have been enumerated. The callback function receives the deviceList array as its only argument

Function

errorCallback

This optional callback receives the error message as its argument.

Function

### return
Returns a Promise that can be used in place of the callbacks, similar to the enumerateDevices() method

Promise

` let audioIn; function setup(){ text('getting sources...', 0, 20); audioIn = new p5.AudioIn(); audioIn.getSources(gotSources); } function gotSources(deviceList) { if (deviceList.length > 0) { //set the source to the first item in the deviceList array audioIn.setSource(0); let currentSource = deviceList[audioIn.currentSource]; text('set source to: ' + currentSource.deviceId, 5, 20, width); } } `

p5.AudioIn

p5.sound

p5.sound

Set the input source. Accepts a number representing a position in the array returned by getSources(). This is only available in browsers that support  navigator.mediaDevices.enumerateDevices()

method

setSource

num

position of input source in the array

Number

` let audioIn; function setup(){ text('getting sources...', 0, 20); audioIn = new p5.AudioIn(); audioIn.getSources(gotSources); } function gotSources(deviceList) { if (deviceList.length > 0) { //set the source to the first item in the deviceList array audioIn.setSource(0); let currentSource = deviceList[audioIn.currentSource]; text('set source to: ' + currentSource.deviceId, 5, 20, width); } } `

p5.AudioIn

p5.sound

p5.sound

In classes that extend p5.Effect, connect effect nodes to the wet parameter

p5.Effect

p5.sound

p5.sound

Set the output volume of the filter.

method

amp

vol

amplitude between 0 and 1.0

Number

rampTime

create a fade that lasts until rampTime

Number

tFromNow

schedule this event to happen in tFromNow seconds

Number

p5.Effect

p5.sound

p5.sound

Link effects together in a chain Example usage: filter.chain(reverb, delay, panner); May be used with an open-ended number of arguments

method

chain

arguments

Chain together multiple sound objects

Object

p5.Effect

p5.sound

p5.sound

Adjust the dry/wet value.

method

drywet

fade

The desired drywet value (0 - 1.0)

Number

p5.Effect

p5.sound

p5.sound

Send output to a p5.js-sound, Web Audio Node, or use signal to control an AudioParam

method

connect

unit



Object

p5.Effect

p5.sound

p5.sound

Disconnect all output.

method

disconnect

p5.Effect

p5.sound

p5.sound

The p5.Filter is built with a  Web Audio BiquadFilter Node.

property

biquadFilter

DelayNode

p5.Filter

p5.sound

p5.sound

Filter an audio signal according to a set of filter parameters.

method

process

Signal

An object that outputs audio

Object

freq

Frequency in Hz, from 10 to 22050

Number

res

Resonance/Width of the filter frequency from 0.001 to 1000

Number

p5.Filter

p5.sound

p5.sound

Set the frequency and the resonance of the filter.

method

set

freq

Frequency in Hz, from 10 to 22050

Number

res

Resonance (Q) from 0.001 to 1000

Number

timeFromNow

schedule this event to happen seconds from now

Number

p5.Filter

p5.sound

p5.sound

Set the filter frequency, in Hz, from 10 to 22050 (the range of human hearing, although in reality most people hear in a narrower range).

method

freq

freq

Filter Frequency

Number

timeFromNow

schedule this event to happen seconds from now

Number

### return
value Returns the current frequency value

Number

p5.Filter

p5.sound

p5.sound

Controls either width of a bandpass frequency, or the resonance of a low/highpass cutoff frequency.

method

res

res

Resonance/Width of filter freq from 0.001 to 1000

Number

timeFromNow

schedule this event to happen seconds from now

Number

### return
value Returns the current res value

Number

p5.Filter

p5.sound

p5.sound

Controls the gain attribute of a Biquad Filter. This is distinctly different from .amp() which is inherited from p5.Effect .amp() controls the volume via the output gain node p5.Filter.gain() controls the gain parameter of a Biquad Filter node.

method

gain

gain



Number

### return
Returns the current or updated gain value

Number

p5.Filter

p5.sound

p5.sound

Toggle function. Switches between the specified type and allpass

method

toggle

### return
[Toggle value]

Boolean

p5.Filter

p5.sound

p5.sound

Set the type of a p5.Filter. Possible types include: "lowpass" (default), "highpass", "bandpass", "lowshelf", "highshelf", "peaking", "notch", "allpass".

method

setType

t



String

p5.Filter

p5.sound

p5.sound

The p5.EQ is built with abstracted p5.Filter objects. To modify any bands, use methods of the  p5.Filter API, especially `gain` and `freq`. Bands are stored in an array, with indices 0 - 3, or 0 - 7

property

bands

Array

p5.EQ

p5.sound

p5.sound

Process an input by connecting it to the EQ

method

process

src

Audio source

Object

p5.EQ

p5.sound

p5.sound

Web Audio Spatial Panner Node
Properties include  
Panning Model : "equal power" or "HRTF"  
DistanceModel : "linear", "inverse", or "exponential"

property

panner

AudioNode

p5.Panner3D

p5.sound

p5.sound

Connect an audio sorce

method

process

src

Input source

Object

p5.Panner3D

p5.sound

p5.sound

Set the X,Y,Z position of the Panner

method

set

xVal



Number

yVal



Number

zVal



Number

time



Number

### return
Updated x, y, z values as an array

Array

p5.Panner3D

p5.sound

p5.sound

Getter and setter methods for position coordinates

method

positionX

### return
updated coordinate value

Number

p5.Panner3D

p5.sound

p5.sound

Getter and setter methods for position coordinates

method

positionY

### return
updated coordinate value

Number

p5.Panner3D

p5.sound

p5.sound

Getter and setter methods for position coordinates

method

positionZ

### return
updated coordinate value

Number

p5.Panner3D

p5.sound

p5.sound

Set the X,Y,Z position of the Panner

method

orient

xVal



Number

yVal



Number

zVal



Number

time



Number

### return
Updated x, y, z values as an array

Array

p5.Panner3D

p5.sound

p5.sound

Getter and setter methods for orient coordinates

method

orientX

### return
updated coordinate value

Number

p5.Panner3D

p5.sound

p5.sound

Getter and setter methods for orient coordinates

method

orientY

### return
updated coordinate value

Number

p5.Panner3D

p5.sound

p5.sound

Getter and setter methods for orient coordinates

method

orientZ

### return
updated coordinate value

Number

p5.Panner3D

p5.sound

p5.sound

Set the rolloff factor and max distance

method

setFalloff

maxDistance



Number

rolloffFactor



Number

p5.Panner3D

p5.sound

p5.sound

Maxium distance between the source and the listener

method

maxDist

maxDistance



Number

### return
updated value

Number

p5.Panner3D

p5.sound

p5.sound

How quickly the volume is reduced as the source moves away from the listener

method

rollof

rolloffFactor



Number

### return
updated value

Number

p5.Panner3D

p5.sound

p5.sound

The p5.Delay is built with two  Web Audio Delay Nodes, one for each stereo channel.

property

leftDelay

DelayNode

p5.Delay

p5.sound

p5.sound

The p5.Delay is built with two  Web Audio Delay Nodes, one for each stereo channel.

property

rightDelay

DelayNode

p5.Delay

p5.sound

p5.sound

Add delay to an audio signal according to a set of delay parameters.

method

process

Signal

An object that outputs audio

Object

delayTime

Time (in seconds) of the delay/echo. Some browsers limit delayTime to 1 second.

Number

feedback

sends the delay back through itself in a loop that decreases in volume each time.

Number

lowPass

Cutoff frequency. Only frequencies below the lowPass will be part of the delay.

Number

p5.Delay

p5.sound

p5.sound

Set the delay (echo) time, in seconds. Usually this value will be a floating point number between 0.0 and 1.0.

method

delayTime

delayTime

Time (in seconds) of the delay

Number

p5.Delay

p5.sound

p5.sound

Feedback occurs when Delay sends its signal back through its input in a loop. The feedback amount determines how much signal to send each time through the loop. A feedback greater than 1.0 is not desirable because it will increase the overall output each time through the loop, creating an infinite feedback loop. The default value is 0.5

method

feedback

feedback

0.0 to 1.0, or an object such as an Oscillator that can be used to modulate this param

Number|Object

### return
Feedback value

Number

p5.Delay

p5.sound

p5.sound

Set a lowpass filter frequency for the delay. A lowpass filter will cut off any frequencies higher than the filter frequency.

method

filter

cutoffFreq

A lowpass filter will cut off any frequencies higher than the filter frequency.

Number|Object

res

Resonance of the filter frequency cutoff, or an object (i.e. a p5.Oscillator) that can be used to modulate this parameter. High numbers (i.e. 15) will produce a resonance, low numbers (i.e. .2) will produce a slope.

Number|Object

p5.Delay

p5.sound

p5.sound

Choose a preset type of delay. 'pingPong' bounces the signal from the left to the right channel to produce a stereo effect. Any other parameter will revert to the default delay setting.

method

setType

type

'pingPong' (1) or 'default' (0)

String|Number

p5.Delay

p5.sound

p5.sound

Set the output level of the delay effect.

method

amp

volume

amplitude between 0 and 1.0

Number

rampTime

create a fade that lasts rampTime

Number

timeFromNow

schedule this event to happen seconds from now

Number

p5.Delay

p5.sound

p5.sound

Send output to a p5.sound or web audio object

method

connect

unit



Object

p5.Delay

p5.sound

p5.sound

Disconnect all output.

method

disconnect

p5.Delay

p5.sound

p5.sound

Connect a source to the reverb, and assign reverb parameters.

method

process

src

p5.sound / Web Audio object with a sound output.

Object

seconds

Duration of the reverb, in seconds. Min: 0, Max: 10. Defaults to 3.

Number

decayRate

Percentage of decay with each echo. Min: 0, Max: 100. Defaults to 2.

Number

reverse

Play the reverb backwards or forwards.

Boolean

p5.Reverb

p5.sound

p5.sound

Set the reverb settings. Similar to .process(), but without assigning a new input.

method

set

seconds

Duration of the reverb, in seconds. Min: 0, Max: 10. Defaults to 3.

Number

decayRate

Percentage of decay with each echo. Min: 0, Max: 100. Defaults to 2.

Number

reverse

Play the reverb backwards or forwards.

Boolean

p5.Reverb

p5.sound

p5.sound

Set the output level of the reverb effect.

method

amp

volume

amplitude between 0 and 1.0

Number

rampTime

create a fade that lasts rampTime

Number

timeFromNow

schedule this event to happen seconds from now

Number

p5.Reverb

p5.sound

p5.sound

Send output to a p5.sound or web audio object

method

connect

unit



Object

p5.Reverb

p5.sound

p5.sound

Disconnect all output.

method

disconnect

p5.Reverb

p5.sound

p5.sound

Internally, the p5.Convolver uses the a  Web Audio Convolver Node.

property

convolverNode

ConvolverNode

p5.Convolver

p5.sound

p5.sound

If you load multiple impulse files using the .addImpulse method, they will be stored as Objects in this Array. Toggle between them with the `toggleImpulse(id)` method.

property

impulses

Array

p5.Convolver

p5.sound

p5.sound

Connect a source to the convolver.

method

process

src

p5.sound / Web Audio object with a sound output.

Object

` let cVerb, sound; function preload() { // We have both MP3 and OGG versions of all sound assets soundFormats('ogg', 'mp3'); // Try replacing 'bx-spring' with other soundfiles like // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox' cVerb = createConvolver('assets/bx-spring.mp3'); // Try replacing 'Damscray_DancingTiger' with // 'beat', 'doorbell', lucky_dragons_-_power_melody' sound = loadSound('assets/Damscray_DancingTiger.mp3'); } function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(playSound); background(220); text('tap to play', 20, 20); // disconnect from main output... sound.disconnect(); // ...and process with cVerb // so that we only hear the convolution cVerb.process(sound); } function playSound() { sound.play(); } `

p5.Convolver

p5.sound

p5.sound

Load and assign a new Impulse Response to the p5.Convolver. The impulse is added to the `.impulses` array. Previous impulses can be accessed with the `.toggleImpulse(id)` method.

method

addImpulse

path

path to a sound file

String

callback

function (optional)

Function

errorCallback

function (optional)

Function

p5.Convolver

p5.sound

p5.sound

Similar to .addImpulse, except that the `.impulses` Array is reset to save memory. A new `.impulses` array is created with this impulse as the only item.

method

resetImpulse

path

path to a sound file

String

callback

function (optional)

Function

errorCallback

function (optional)

Function

p5.Convolver

p5.sound

p5.sound

If you have used `.addImpulse()` to add multiple impulses to a p5.Convolver, then you can use this method to toggle between the items in the `.impulses` Array. Accepts a parameter to identify which impulse you wish to use, identified either by its original filename (String) or by its position in the `.impulses ` Array (Number).  
You can access the objects in the .impulses Array directly. Each Object has two attributes: an `.audioBuffer` (type: Web Audio  AudioBuffer) and a `.name`, a String that corresponds with the original filename.

method

toggleImpulse

id

Identify the impulse by its original filename (String), or by its position in the `.impulses` Array (Number).

String|Number

p5.Convolver

p5.sound

p5.sound

Create a p5.Convolver. Accepts a path to a soundfile that will be used to generate an impulse response.

method

createConvolver

path

path to a sound file

String

callback

function to call if loading is successful. The object will be passed in as the argument to the callback function.

Function

errorCallback

function to call if loading is not successful. A custom error will be passed in as the argument to the callback function.

Function

### return


p5.Convolver

` let cVerb, sound; function preload() { // We have both MP3 and OGG versions of all sound assets soundFormats('ogg', 'mp3'); // Try replacing 'bx-spring' with other soundfiles like // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox' cVerb = createConvolver('assets/bx-spring.mp3'); // Try replacing 'Damscray_DancingTiger' with // 'beat', 'doorbell', lucky_dragons_-_power_melody' sound = loadSound('assets/Damscray_DancingTiger.mp3'); } function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(playSound); background(220); text('tap to play', 20, 20); // disconnect from main output... sound.disconnect(); // ...and process with cVerb // so that we only hear the convolution cVerb.process(sound); } function playSound() { sound.play(); } `

p5

p5.sound

p5.sound

Set the global tempo, in beats per minute, for all p5.Parts. This method will impact all active p5.Parts.

method

setBPM

BPM

Beats Per Minute

Number

rampTime

Seconds from now

Number

p5

p5.sound

p5.sound

Array of values to pass into the callback at each step of the phrase. Depending on the callback function's requirements, these values may be numbers, strings, or an object with multiple parameters. Zero (0) indicates a rest.

property

sequence

Array

p5.Phrase

p5.sound

p5.sound

Set the tempo of this part, in Beats Per Minute.

method

setBPM

BPM

Beats Per Minute

Number

rampTime

Seconds from now

Number

p5.Part

p5.sound

p5.sound

Returns the tempo, in Beats Per Minute, of this part.

method

getBPM

### return


Number

p5.Part

p5.sound

p5.sound

Start playback of this part. It will play through all of its phrases at a speed determined by setBPM.

method

start

time

seconds from now

Number

p5.Part

p5.sound

p5.sound

Loop playback of this part. It will begin looping through all of its phrases at a speed determined by setBPM.

method

loop

time

seconds from now

Number

p5.Part

p5.sound

p5.sound

Tell the part to stop looping.

method

noLoop

p5.Part

p5.sound

p5.sound

Stop the part and cue it to step 0. Playback will resume from the begining of the Part when it is played again.

method

stop

time

seconds from now

Number

p5.Part

p5.sound

p5.sound

Pause the part. Playback will resume from the current step.

method

pause

time

seconds from now

Number

p5.Part

p5.sound

p5.sound

Add a p5.Phrase to this Part.

method

addPhrase

phrase

reference to a p5.Phrase

p5.Phrase

p5.Part

p5.sound

p5.sound

Remove a phrase from this part, based on the name it was given when it was created.

method

removePhrase

phraseName



String

p5.Part

p5.sound

p5.sound

Get a phrase from this part, based on the name it was given when it was created. Now you can modify its array.

method

getPhrase

phraseName



String

p5.Part

p5.sound

p5.sound

Find all sequences with the specified name, and replace their patterns with the specified array.

method

replaceSequence

phraseName



String

sequence

Array of values to pass into the callback at each step of the phrase.

Array

p5.Part

p5.sound

p5.sound

Set the function that will be called at every step. This will clear the previous function.

method

onStep

callback

The name of the callback you want to fire on every beat/tatum.

Function

p5.Part

p5.sound

p5.sound

Start playback of the score.

method

start

p5.Score

p5.sound

p5.sound

Stop playback of the score.

method

stop

p5.Score

p5.sound

p5.sound

Pause playback of the score.

method

pause

p5.Score

p5.sound

p5.sound

Loop playback of the score.

method

loop

p5.Score

p5.sound

p5.sound

Stop looping playback of the score. If it is currently playing, this will go into effect after the current round of playback completes.

method

noLoop

p5.Score

p5.sound

p5.sound

Set the tempo for all parts in the score

method

setBPM

BPM

Beats Per Minute

Number

rampTime

Seconds from now

Number

p5.Score

p5.sound

p5.sound

Getters and Setters, setting any parameter will result in a change in the clock's frequency, that will be reflected after the next callback beats per minute (defaults to 60)

property

bpm

Number

p5.SoundLoop

p5.sound

p5.sound

number of quarter notes in a measure (defaults to 4)

property

timeSignature

Number

p5.SoundLoop

p5.sound

p5.sound

length of the loops interval

property

interval

Number|String

p5.SoundLoop

p5.sound

p5.sound

how many times the callback has been called so far

property

iterations

Number



p5.SoundLoop

p5.sound

p5.sound

musicalTimeMode uses Tone.Time convention true if string, false if number

property

musicalTimeMode

Boolean

p5.SoundLoop

p5.sound

p5.sound

musicalTimeMode variables modify these only when the interval is specified in musicalTime format as a string

p5.SoundLoop

p5.sound

p5.sound

Set a limit to the number of loops to play. defaults to Infinity

property

maxIterations

Number

p5.SoundLoop

p5.sound

p5.sound

Do not initiate the callback if timeFromNow is < 0 This ususually occurs for a few milliseconds when the page is not fully loaded
The callback should only be called until maxIterations is reached

p5.SoundLoop

p5.sound

p5.sound

Start the loop

method

start

timeFromNow

schedule a starting time

Number

p5.SoundLoop

p5.sound

p5.sound

Stop the loop

method

stop

timeFromNow

schedule a stopping time

Number

p5.SoundLoop

p5.sound

p5.sound

Pause the loop

method

pause

timeFromNow

schedule a pausing time

Number

p5.SoundLoop

p5.sound

p5.sound

Synchronize loops. Use this method to start two or more loops in synchronization or to start a loop in synchronization with a loop that is already playing This method will schedule the implicit loop in sync with the explicit master loop i.e. loopToStart.syncedStart(loopToSyncWith)

method

syncedStart

otherLoop

a p5.SoundLoop to sync with

Object

timeFromNow

Start the loops in sync after timeFromNow seconds

Number

p5.SoundLoop

p5.sound

p5.sound

The p5.Compressor is built with a Web Audio Dynamics Compressor Node 

property

compressor

AudioNode

p5.Compressor

p5.sound

p5.sound

Performs the same function as .connect, but also accepts optional parameters to set compressor's audioParams

method

process

src

Sound source to be connected

Object

attack

The amount of time (in seconds) to reduce the gain by 10dB, default = .003, range 0 - 1

Number

knee

A decibel value representing the range above the threshold where the curve smoothly transitions to the "ratio" portion. default = 30, range 0 - 40

Number

ratio

The amount of dB change in input for a 1 dB change in output default = 12, range 1 - 20

Number

threshold

The decibel value above which the compression will start taking effect default = -24, range -100 - 0

Number

release

The amount of time (in seconds) to increase the gain by 10dB default = .25, range 0 - 1

Number

p5.Compressor

p5.sound

p5.sound

Set the parameters of a compressor.

method

set

attack

The amount of time (in seconds) to reduce the gain by 10dB, default = .003, range 0 - 1

Number

knee

A decibel value representing the range above the threshold where the curve smoothly transitions to the "ratio" portion. default = 30, range 0 - 40

Number

ratio

The amount of dB change in input for a 1 dB change in output default = 12, range 1 - 20

Number

threshold

The decibel value above which the compression will start taking effect default = -24, range -100 - 0

Number

release

The amount of time (in seconds) to increase the gain by 10dB default = .25, range 0 - 1

Number

p5.Compressor

p5.sound

p5.sound

Get current attack or set value w/ time ramp

method

attack

attack

Attack is the amount of time (in seconds) to reduce the gain by 10dB, default = .003, range 0 - 1

Number

time

Assign time value to schedule the change in value

Number

p5.Compressor

p5.sound

p5.sound

Get current knee or set value w/ time ramp

method

knee

knee

A decibel value representing the range above the threshold where the curve smoothly transitions to the "ratio" portion. default = 30, range 0 - 40

Number

time

Assign time value to schedule the change in value

Number

p5.Compressor

p5.sound

p5.sound

Get current ratio or set value w/ time ramp

method

ratio

ratio

The amount of dB change in input for a 1 dB change in output default = 12, range 1 - 20

Number

time

Assign time value to schedule the change in value

Number

p5.Compressor

p5.sound

p5.sound

Get current threshold or set value w/ time ramp

method

threshold

threshold

The decibel value above which the compression will start taking effect default = -24, range -100 - 0

Number

time

Assign time value to schedule the change in value

Number

p5.Compressor

p5.sound

p5.sound

Get current release or set value w/ time ramp

method

release

release

The amount of time (in seconds) to increase the gain by 10dB default = .25, range 0 - 1

Number

time

Assign time value to schedule the change in value

Number

p5.Compressor

p5.sound

p5.sound

Return the current reduction value

method

reduction

### return
Value of the amount of gain reduction that is applied to the signal

Number

p5.Compressor

p5.sound

p5.sound

isDetected is set to true when a peak is detected.

attribute

isDetected

Boolean

false

p5.PeakDetect

p5.sound

p5.sound

The update method is run in the draw loop.
Accepts an FFT object. You must call .analyze() on the FFT object prior to updating the peakDetect because it relies on a completed FFT analysis.

method

update

fftObject

A p5.FFT object

p5.FFT

p5.PeakDetect

p5.sound

p5.sound

onPeak accepts two arguments: a function to call when a peak is detected. The value of the peak, between 0.0 and 1.0, is passed to the callback.

method

onPeak

callback

Name of a function that will be called when a peak is detected.

Function

val

Optional value to pass into the function when a peak is detected.

Object

` var cnv, soundFile, fft, peakDetect; var ellipseWidth = 0; function preload() { soundFile = loadSound('assets/beat.mp3'); } function setup() { cnv = createCanvas(100,100); textAlign(CENTER); fft = new p5.FFT(); peakDetect = new p5.PeakDetect(); setupSound(); // when a beat is detected, call triggerBeat() peakDetect.onPeak(triggerBeat); } function draw() { background(0); fill(255); text('click to play', width/2, height/2); fft.analyze(); peakDetect.update(fft); ellipseWidth *= 0.95; ellipse(width/2, height/2, ellipseWidth, ellipseWidth); } // this function is called by peakDetect.onPeak function triggerBeat() { ellipseWidth = 50; } // mouseclick starts/stops sound function setupSound() { cnv.mouseClicked( function() { if (soundFile.isPlaying() ) { soundFile.stop(); } else { soundFile.play(); } }); } `

p5.PeakDetect

p5.sound

p5.sound

Connect a specific device to the p5.SoundRecorder. If no parameter is given, p5.SoundRecorer will record all audible p5.sound from your sketch.

method

setInput

unit

p5.sound object or a web audio unit that outputs sound

Object

p5.SoundRecorder

p5.sound

p5.sound

Start recording. To access the recording, provide a p5.SoundFile as the first parameter. The p5.SoundRecorder will send its recording to that p5.SoundFile for playback once recording is complete. Optional parameters include duration (in seconds) of the recording, and a callback function that will be called once the complete recording has been transfered to the p5.SoundFile.

method

record

soundFile

p5.SoundFile

p5.SoundFile

duration

Time (in seconds)

Number

callback

The name of a function that will be called once the recording completes

Function

p5.SoundRecorder

p5.sound

p5.sound

Stop the recording. Once the recording is stopped, the results will be sent to the p5.SoundFile that was given on .record(), and if a callback function was provided on record, that function will be called.

method

stop

p5.SoundRecorder

p5.sound

p5.sound

The p5.Distortion is built with a  Web Audio WaveShaper Node.

property

WaveShaperNode

AudioNode

p5.Distortion

p5.sound

p5.sound

Process a sound source, optionally specify amount and oversample values.

method

process

amount

Unbounded distortion amount. Normal values range from 0-1.

Number

0.25

oversample

'none', '2x', or '4x'.

String

'none'

p5.Distortion

p5.sound

p5.sound

Set the amount and oversample of the waveshaper distortion.

method

set

amount

Unbounded distortion amount. Normal values range from 0-1.

Number

0.25

oversample

'none', '2x', or '4x'.

String

'none'

p5.Distortion

p5.sound

p5.sound

Return the distortion amount, typically between 0-1.

method

getAmount

### return
Unbounded distortion amount. Normal values range from 0-1.

Number

p5.Distortion

p5.sound

p5.sound

Return the oversampling.

method

getOversample

### return
Oversample can either be 'none', '2x', or '4x'.

String

p5.Distortion

p5.sound

p5.sound

Connect a source to the gain node.

method

setInput

src

p5.sound / Web Audio object with a sound output.

Object

p5.Gain

p5.sound

p5.sound

Send output to a p5.sound or web audio object

method

connect

unit



Object

p5.Gain

p5.sound

p5.sound

Disconnect all output.

method

disconnect

p5.Gain

p5.sound

p5.sound

Set the output level of the gain node.

method

amp

volume

amplitude between 0 and 1.0

Number

rampTime

create a fade that lasts rampTime

Number

timeFromNow

schedule this event to happen seconds from now

Number

p5.Gain

p5.sound

p5.sound

Connect to p5 objects or Web Audio Nodes

method

connect

unit



Object

p5.AudioVoice

p5.sound

p5.sound

Disconnect from soundOut

method

disconnect

p5.AudioVoice

p5.sound

p5.sound

Getters and Setters

property

attack

Number

p5.MonoSynth

p5.sound

p5.sound

property

decay

Number

p5.MonoSynth

p5.sound

p5.sound

property

sustain

Number

p5.MonoSynth

p5.sound

p5.sound

property

release

Number

p5.MonoSynth

p5.sound

p5.sound

Play tells the MonoSynth to start playing a note. This method schedules the calling of .triggerAttack and .triggerRelease.

method

play

note

the note you want to play, specified as a frequency in Hertz (Number) or as a midi value in Note/Octave format ("C4", "Eb3"...etc") See  Tone. Defaults to 440 hz.

String | Number

velocity

velocity of the note to play (ranging from 0 to 1)

Number

secondsFromNow

time from now (in seconds) at which to play

Number

sustainTime

time to sustain before releasing the envelope. Defaults to 0.15 seconds.

Number

` let monoSynth; function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(playSynth); background(220); textAlign(CENTER); text('tap to play', width/2, height/2); monoSynth = new p5.MonoSynth(); } function playSynth() { userStartAudio(); let note = random(['Fb4', 'G4']); // note velocity (volume, from 0 to 1) let velocity = random(); // time from now (in seconds) let time = 0; // note duration (in seconds) let dur = 1/6; monoSynth.play(note, velocity, time, dur); } `

p5.MonoSynth

p5.sound

p5.sound

Trigger the Attack, and Decay portion of the Envelope. Similar to holding down a key on a piano, but it will hold the sustain level until you let go.

note

the note you want to play, specified as a frequency in Hertz (Number) or as a midi value in Note/Octave format ("C4", "Eb3"...etc") See  Tone. Defaults to 440 hz

String | Number

velocity

velocity of the note to play (ranging from 0 to 1)

Number

secondsFromNow

time from now (in seconds) at which to play

Number

method

triggerAttack

` let monoSynth; function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(triggerAttack); background(220); text('tap here for attack, let go to release', 5, 20, width - 20); monoSynth = new p5.MonoSynth(); } function triggerAttack() { userStartAudio(); monoSynth.triggerAttack("E3"); } function mouseReleased() { monoSynth.triggerRelease(); } `

p5.MonoSynth

p5.sound

p5.sound

Trigger the release of the Envelope. This is similar to releasing the key on a piano and letting the sound fade according to the release level and release time.

secondsFromNow

time to trigger the release

Number

method

triggerRelease

` let monoSynth; function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(triggerAttack); background(220); text('tap here for attack, let go to release', 5, 20, width - 20); monoSynth = new p5.MonoSynth(); } function triggerAttack() { userStartAudio(); monoSynth.triggerAttack("E3"); } function mouseReleased() { monoSynth.triggerRelease(); } `

p5.MonoSynth

p5.sound

p5.sound

Set values like a traditional  ADSR envelope .

method

setADSR

attackTime

Time (in seconds before envelope reaches Attack Level

Number

decayTime

Time (in seconds) before envelope reaches Decay/Sustain Level

Number

susRatio

Ratio between attackLevel and releaseLevel, on a scale from 0 to 1, where 1.0 = attackLevel, 0.0 = releaseLevel. The susRatio determines the decayLevel and the level at which the sustain portion of the envelope will sustain. For example, if attackLevel is 0.4, releaseLevel is 0, and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is increased to 1.0 (using `setRange`), then decayLevel would increase proportionally, to become 0.5.

Number

releaseTime

Time in seconds from now (defaults to 0)

Number

p5.MonoSynth

p5.sound

p5.sound

MonoSynth amp

method

amp

vol

desired volume

Number

rampTime

Time to reach new volume

Number

### return
new volume value

Number

p5.MonoSynth

p5.sound

p5.sound

Connect to a p5.sound / Web Audio object.

method

connect

unit

A p5.sound or Web Audio object

Object

p5.MonoSynth

p5.sound

p5.sound

Disconnect all outputs

method

disconnect

p5.MonoSynth

p5.sound

p5.sound

Get rid of the MonoSynth and free up its resources / memory.

method

dispose

p5.MonoSynth

p5.sound

p5.sound

An object that holds information about which notes have been played and which notes are currently being played. New notes are added as keys on the fly. While a note has been attacked, but not released, the value of the key is the audiovoice which is generating that note. When notes are released, the value of the key becomes undefined.

property

notes

p5.PolySynth

p5.sound

p5.sound

A PolySynth must have at least 1 voice, defaults to 8

property

polyvalue

p5.PolySynth

p5.sound

p5.sound

Monosynth that generates the sound for each note that is triggered. The p5.PolySynth defaults to using the p5.MonoSynth as its voice.

property

AudioVoice

p5.PolySynth

p5.sound

p5.sound

Play a note by triggering noteAttack and noteRelease with sustain time

method

play

note

midi note to play (ranging from 0 to 127 - 60 being a middle C)

Number

velocity

velocity of the note to play (ranging from 0 to 1)

Number

secondsFromNow

time from now (in seconds) at which to play

Number

sustainTime

time to sustain before releasing the envelope

Number

` let polySynth; function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(playSynth); background(220); text('click to play', 20, 20); polySynth = new p5.PolySynth(); } function playSynth() { userStartAudio(); // note duration (in seconds) let dur = 1.5; // time from now (in seconds) let time = 0; // velocity (volume, from 0 to 1) let vel = 0.1; // notes can overlap with each other polySynth.play('G2', vel, 0, dur); polySynth.play('C3', vel, time += 1/3, dur); polySynth.play('G3', vel, time += 1/3, dur); } `

p5.PolySynth

p5.sound

p5.sound

noteADSR sets the envelope for a specific note that has just been triggered. Using this method modifies the envelope of whichever audiovoice is being used to play the desired note. The envelope should be reset before noteRelease is called in order to prevent the modified envelope from being used on other notes.

method

noteADSR

note

Midi note on which ADSR should be set.

Number

attackTime

Time (in seconds before envelope reaches Attack Level

Number

decayTime

Time (in seconds) before envelope reaches Decay/Sustain Level

Number

susRatio

Ratio between attackLevel and releaseLevel, on a scale from 0 to 1, where 1.0 = attackLevel, 0.0 = releaseLevel. The susRatio determines the decayLevel and the level at which the sustain portion of the envelope will sustain. For example, if attackLevel is 0.4, releaseLevel is 0, and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is increased to 1.0 (using `setRange`), then decayLevel would increase proportionally, to become 0.5.

Number

releaseTime

Time in seconds from now (defaults to 0)

Number

p5.PolySynth

p5.sound

p5.sound

Set the PolySynths global envelope. This method modifies the envelopes of each monosynth so that all notes are played with this envelope.

method

setADSR

attackTime

Time (in seconds before envelope reaches Attack Level

Number

decayTime

Time (in seconds) before envelope reaches Decay/Sustain Level

Number

susRatio

Ratio between attackLevel and releaseLevel, on a scale from 0 to 1, where 1.0 = attackLevel, 0.0 = releaseLevel. The susRatio determines the decayLevel and the level at which the sustain portion of the envelope will sustain. For example, if attackLevel is 0.4, releaseLevel is 0, and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is increased to 1.0 (using `setRange`), then decayLevel would increase proportionally, to become 0.5.

Number

releaseTime

Time in seconds from now (defaults to 0)

Number

p5.PolySynth

p5.sound

p5.sound

Trigger the Attack, and Decay portion of a MonoSynth. Similar to holding down a key on a piano, but it will hold the sustain level until you let go.

method

noteAttack

note

midi note on which attack should be triggered.

Number

velocity

velocity of the note to play (ranging from 0 to 1)/

Number

secondsFromNow

time from now (in seconds)

Number

` let polySynth = new p5.PolySynth(); let pitches = ['G', 'D', 'G', 'C']; let octaves = [2, 3, 4]; function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(playChord); background(220); text('tap to play', 20, 20); } function playChord() { userStartAudio(); // play a chord: multiple notes at the same time for (let i = 0; i < 4; i++) { let note = random(pitches) + random(octaves); polySynth.noteAttack(note, 0.1); } } function mouseReleased() { // release all voices polySynth.noteRelease(); } `

p5.PolySynth

p5.sound

p5.sound

Trigger the Release of an AudioVoice note. This is similar to releasing the key on a piano and letting the sound fade according to the release level and release time.

method

noteRelease

note

midi note on which attack should be triggered. If no value is provided, all notes will be released.

Number

secondsFromNow

time to trigger the release

Number

` let polySynth = new p5.PolySynth(); let pitches = ['G', 'D', 'G', 'C']; let octaves = [2, 3, 4]; function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(playChord); background(220); text('tap to play', 20, 20); } function playChord() { userStartAudio(); // play a chord: multiple notes at the same time for (let i = 0; i < 4; i++) { let note = random(pitches) + random(octaves); polySynth.noteAttack(note, 0.1); } } function mouseReleased() { // release all voices polySynth.noteRelease(); } `

p5.PolySynth

p5.sound

p5.sound

Connect to a p5.sound / Web Audio object.

method

connect

unit

A p5.sound or Web Audio object

Object

p5.PolySynth

p5.sound

p5.sound

Disconnect all outputs

method

disconnect

p5.PolySynth

p5.sound

p5.sound

Get rid of the MonoSynth and free up its resources / memory.

method

dispose

p5.PolySynth

p5.sound

p5.sound

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

unknown tag: alt

unknown tag: alt

unknown tag: alt

unknown tag: alt

unknown tag: alt

unknown tag: alt

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

unknown tag: alt

replacing incorrect tag: function with method

replacing incorrect tag: returns with return

unknown tag: name

unknown tag: name

unknown tag: name

unknown tag: name

unknown tag: alt

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

unknown tag: name

unknown tag: name

unknown tag: name

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

unknown tag: name

unknown tag: name

replacing incorrect tag: returns with return

unknown tag: name

unknown tag: name

unknown tag: name

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

unknown tag: name

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

unknown tag: alt

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

unknown tag: name

unknown tag: name

unknown tag: name

unknown tag: name

replacing incorrect tag: returns with return

param name missing: {Number}

param name missing: {p5.Vector}

param name missing: {p5.Vector}

param name missing: {p5.Vector}

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

unknown tag: alt

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

unknown tag: alt

unknown tag: alt

unknown tag: alt

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: function with method

replacing incorrect tag: returns with return

replacing incorrect tag: function with method

replacing incorrect tag: function with method

replacing incorrect tag: function with method

replacing incorrect tag: function with method

replacing incorrect tag: function with method

replacing incorrect tag: returns with return

replacing incorrect tag: function with method

replacing incorrect tag: function with method

replacing incorrect tag: function with method

replacing incorrect tag: params with param

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

replacing incorrect tag: returns with return

Missing item type Conversions adapted from . 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.

Missing item type Convert an HSBA array to HSLA.

Missing item type Convert an HSBA array to RGBA.

Missing item type Convert an HSLA array to HSBA.

Missing item type Convert an HSLA array to RGBA. We need to change basis from HSLA to something that can be more easily be projected onto RGBA. We will choose hue and brightness as our first two components, and pick a convenient third one ('zest') so that we don't need to calculate formal HSBA saturation.

Missing item type Convert an RGBA array to HSBA.

Missing item type Convert an RGBA array to HSLA.

Missing item type CSS named colors.

Missing item type 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.

Missing item type Full color string patterns. The capture groups are necessary.

Missing item type Hue is the same in HSB and HSL, but the maximum value may be different. This function will return the HSB-normalized saturation when supplied with an HSB color object, but will default to the HSL-normalized saturation otherwise.

Missing item type Saturation is scaled differently in HSB and HSL. This function will return the HSB saturation when supplied with an HSB color object, but will default to the HSL saturation otherwise.

Missing item type For a number of different inputs, returns a color formatted as [r, g, b, a] arrays, with each component normalized between 0 and 1.

Missing item type For HSB and HSL, interpret the gray level as a brightness/lightness value (they are equivalent when chroma is zero). For RGB, normalize the gray level according to the blue maximum.

Missing item type

Missing item type Prints out all the colors in the color pallete with white text. For color blindness testing.

Missing item type

Missing item type

Missing item type

Missing item type Given an Error object, extract the most information from it.

Missing item type

Missing item type This function does 3 things: 1. Bounds the desired start/stop angles for an arc (in radians) so that: 0 <= start < TWO_PI ; start <= stop < start + TWO_PI This means that the arc rendering functions don't have to be concerned with what happens if stop is smaller than start, or if the arc 'goes round more than once', etc.: they can just start at start and increase until stop and the correct arc will be drawn. 2. Optionally adjusts the angles within each quadrant to counter the naive scaling of the underlying ellipse up from the unit circle. Without this, the angles become arbitrary when width != height: 45 degrees might be drawn at 5 degrees on a 'wide' ellipse, or at 85 degrees on a 'tall' ellipse. 3. Flags up when start and stop correspond to the same place on the underlying ellipse. This is useful if you want to do something special there (like rendering a whole ellipse instead).

Missing item type Returns the current framerate.

Missing item type 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 rate is 60 frames per second. Calling `frameRate()` with no arguments returns the current frame rate.

Missing item type Called upon each p5 instantiation instead of module import due to the possibility of the window being resized when no sketch is active.

Missing item type

Missing item type _globalInit TODO: ??? if sketch is on window assume "global" mode and instantiate p5 automatically otherwise do nothing

Missing item type This is our i18next "backend" plugin. It tries to fetch languages from a CDN.

Missing item type Set up our translation function, with loaded languages

Missing item type Returns a list of languages we have translations loaded for

Missing item type Returns the current language selected for translation

Missing item type Sets the current language for translation Returns a promise that resolved when loading is finished, or rejects if it fails.

Missing item type

Missing item type

Missing item type

Missing item type

Missing item type

Missing item type Helper fxn for sharing pixel methods

Missing item type Resize our canvas element.

Missing item type Helper function to check font type (system or otf)

Missing item type Helper fxn to measure ascent and descent. Adapted from http://stackoverflow.com/a/25355178

Missing item type p5.Renderer2D The 2D graphics canvas renderer class. extends p5.Renderer

Missing item type args[0] is expected to be renderer args[1] is expected to be canvas

Missing item type private helper function to handle the user passing in objects during construction or calls to create()

Missing item type private helper function to ensure that the user passed in valid values for the Dictionary type

Missing item type private helper function to ensure that the user passed in valid values for the Dictionary type

Missing item type private helper function for finding lowest or highest value the argument 'flip' is used to flip the comparison arrow from 'less than' to 'greater than'

Missing item type private helper function for finding lowest or highest key the argument 'flip' is used to flip the comparison arrow from 'less than' to 'greater than'

Missing item type Helper function for select and selectAll

Missing item type Helper function for getElement and getElements.

Missing item type Helpers for create methods.

Missing item type

Missing item type

Missing item type

Missing item type

Missing item type

Missing item type

Missing item type

Missing item type _updatePAccelerations updates the pAcceleration values

Missing item type The onblur function is called when the user is no longer focused on the p5 element. Because the keyup events will not fire if the user is not focused on the element we must assume all keys currently down have been released.

Missing item type The _areDownKeys function returns a boolean true if any keys pressed and a false if no keys are currently pressed. Helps avoid instances where multiple keys are pressed simultaneously and releasing a single key will then switch the keyIsPressed property to true.

Missing item type This module defines the filters for use with image buffers. This module is basically a collection of functions stored in an object as opposed to modules. The functions are destructive, modifying the passed in canvas rather than creating a copy. Generally speaking users of this module will use the Filters.apply method on a canvas to create an effect. A number of functions are borrowed/adapted from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/ or the java processing implementation.

Missing item type Returns the pixel buffer for a canvas.

Missing item type Returns a 32-bit number containing ARGB data at the ith pixel in the 1D array containing pixels data.

Missing item type Modifies pixels RGBA values to values contained in the data object.

Missing item type Returns the ImageData object for a canvas. https://developer.mozilla.org/en-US/docs/Web/API/ImageData

Missing item type Returns a blank ImageData object.

Missing item type Applys a filter function to a canvas. The difference between this and the actual filter functions defined below is that the filter functions generally modify the pixel buffer but do not actually put that data back to the canvas (where it would actually update what is visible). By contrast this method does make the changes actually visible in the canvas. The apply method is the method that callers of this module would generally use. It has been separated from the actual filters to support an advanced use case of creating a filter chain that executes without actually updating the canvas in between everystep.

Missing item type Converts the image to black and white pixels depending if they are above or below the threshold defined by the level parameter. The parameter must be between 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used. Borrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/

Missing item type Converts any colors in the image to grayscale equivalents. No parameter is used. Borrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/

Missing item type Sets the alpha channel to entirely opaque. No parameter is used.

Missing item type Sets each pixel to its inverse value. No parameter is used.

Missing item type Limits each channel of the image to the number of colors specified as the parameter. The parameter can be set to values between 2 and 255, but results are most noticeable in the lower ranges. Adapted from java based processing implementation

Missing item type Increases the bright areas in an image.

Missing item type Reduces the bright areas in an image. Similar to `dilate()`, but updates the output color based on the lowest luminance value.

Missing item type This module defines the p5 methods for the p5.Image class for drawing images to the main display canvas.

Missing item type Helper function for loading GIF-based images

Missing item type

Missing item type

Missing item type

Missing item type Validates clipping params. Per drawImage spec sWidth and sHight cannot be negative or greater than image intrinsic width and height

Missing item type Apply the current tint color to the input image, return the resulting canvas.

Missing item type This module defines the p5.Image class and P5 methods for drawing images to the main display canvas.

Missing item type Helper function for animating GIF-based images with time

Missing item type Helper fxn for sharing pixel methods

Missing item type Generate a blob of file data as a url to prepare for download. Accepts an array of data, a filename, and an extension (optional). This is a private function because it does not do any formatting, but it is used by saveStrings, saveJSON, saveTable etc.

Missing item type Returns a file extension, or another string if the provided parameter has no extension.

Missing item type Returns true if the browser is Safari, false if not. Safari makes trouble for downloading files.

Missing item type Helper function, a callback for download that deletes an invisible anchor element from the DOM once the file has been automatically downloaded.

Missing item type Table Options Generic class for handling tabular data, typically from a CSV, TSV, or other sort of spreadsheet file. CSV files are  comma separated values, often with the data in quotes. TSV files use tabs as separators, and usually don't bother with the quotes. File names should end with .csv if they're comma separated. A rough "spec" for CSV can be found here. To load files, use the loadTable method. To save tables to your computer, use the save method or the saveTable method. Possible options include: 
    * csv - parse the table as comma-separated values 
    * tsv - parse the table as tab-separated values 
    * header - this table has a header (title) row 

Missing item type

Missing item type

Missing item type Multiplies a vector by a scalar and returns a new vector.

Missing item type Rotates the vector (only 2D vectors) by the given angle; magnitude remains the same. Returns a new vector.

Missing item type Divides a vector by a scalar and returns a new vector.

Missing item type Calculates the dot product of two vectors.

Missing item type Calculates the cross product of two vectors.

Missing item type Calculates the Euclidean distance between two points (considering a point as a vector object).

Missing item type Linear interpolate a vector to another vector and return the result as a new vector.

Missing item type Performs spherical linear interpolation with the other vector and returns the resulting vector. This works in both 3D and 2D. As for 2D, the result of slerping between 2D vectors is always a 2D vector.

Missing item type Calculates the magnitude (length) of the vector and returns the result as a float (this is simply the equation `sqrt(x*x + y*y + z*z)`.)

Missing item type Calculates the squared magnitude of the vector and returns the result as a float (this is simply the equation (x\*x + y\*y + z\*z).) Faster if the real length is not required in the case of comparing vectors, etc.

Missing item type Normalize the vector to length 1 (make it a unit vector).

Missing item type Limit the magnitude of the vector to the value used for the max parameter.

Missing item type Set the magnitude of the vector to the value used for the len parameter.

Missing item type Calculate the angle of rotation for this vector (only 2D vectors). p5.Vectors created using createVector() will take the current angleMode into consideration, and give the angle in radians or degrees accordingly.

Missing item type Calculates and returns the angle between two vectors. This function will take the angleMode on v1 into consideration, and give the angle in radians or degrees accordingly.

Missing item type Reflect a vector about a normal to a line in 2D, or about a normal to a plane in 3D.

Missing item type Return a representation of this vector as a float array. This is only for temporary use. If used in any other fashion, the contents should be copied by using the p5.Vector.copy() method to copy into your own vector.

Missing item type Equality check against a p5.Vector

Missing item type Helper function for clampToZero

Missing item type Helper function to measure ascent and descent.

Missing item type Returns the set of opentype glyphs for the supplied string. Note that there is not a strict one-to-one mapping between characters and glyphs, so the list of returned glyphs can be larger or smaller than the length of the given string.

Missing item type Returns an opentype path for the supplied string and position.

Missing item type

Missing item type Draws a point, a coordinate in space at the dimension of one pixel, given x, y and z coordinates. The color of the point is determined by the current stroke, while the point size is determined by current stroke weight.

Missing item type Draw a line given two points

Missing item type

Missing item type

Missing item type

Missing item type

Missing item type Adds geometry from the renderer's immediate mode into the builder's combined geometry.

Missing item type Adds geometry from the renderer's retained mode into the builder's combined geometry.

Missing item type Cleans up the state of the renderer and returns the combined geometry that was built.

Missing item type Keeps track of how many custom geometry objects have been made so that each can be assigned a unique ID.

Missing item type Parse OBJ lines into model. For reference, this is what a simple model of a square might look like: v -0.5 -0.5 0.5 v -0.5 -0.5 -0.5 v -0.5 0.5 -0.5 v -0.5 0.5 0.5 f 4 3 2 1

Missing item type STL files can be of two types, ASCII and Binary, We need to convert the arrayBuffer to an array of strings, to parse it as an ASCII file.

Missing item type This function checks if the file is in ASCII format or in Binary format It is done by searching keyword `solid` at the start of the file. An ASCII STL data must begin with `solid` as the first six bytes. However, ASCII STLs lacking the SPACE after the `d` are known to be plentiful. So, check the first 5 bytes for `solid`. Several encodings, such as UTF-8, precede the text with up to 5 bytes: https://en.wikipedia.org/wiki/Byte_order_mark#Byte_order_marks_by_encoding Search for `solid` to start anywhere after those prefixes.

Missing item type This function matches the `query` at the provided `offset`

Missing item type This function parses the Binary STL files. https://en.wikipedia.org/wiki/STL_%28file_format%29#Binary_STL Currently there is no support for the colors provided in STL files.

Missing item type ASCII STL file starts with `solid 'nameOfFile'` Then contain the normal of the face, starting with `facet normal` Next contain a keyword indicating the start of face vertex, `outer loop` Next comes the three vertex, starting with `vertex x y z` Vertices ends with `endloop` Face ends with `endfacet` Next face starts with `facet normal` The end of the file is indicated by `endsolid`

Missing item type

Missing item type

Missing item type An internal class to store data that will be sent to a p5.RenderBuffer. Those need to eventually go into a Float32Array, so this class provides a variable-length array container backed by a Float32Array so that it can be sent to the GPU without allocating a new array each frame. Like a C++ vector, its fixed-length Float32Array backing its contents will double in size when it goes over its capacity.

Missing item type Returns a Float32Array window sized to the exact length of the data

Missing item type A "soft" clear, which keeps the underlying storage size the same, but empties the contents of its dataArray()

Missing item type Can be used to scale a DataArray back down to fit its contents.

Missing item type A full reset, which allocates a new underlying Float32Array at its initial length

Missing item type Adds values to the DataArray, expanding its internal storage to accommodate the new items.

Missing item type Returns a copy of the data from the index `from`, inclusive, to the index `to`, exclusive

Missing item type Returns a mutable Float32Array window from the index `from`, inclusive, to the index `to`, exclusive

Missing item type Expand capacity of the internal storage until it can fit a target size

Missing item type Checks the capabilities of the current WebGL environment to see if the settings supplied by the user are capable of being fulfilled. If they are not, warnings will be logged and the settings will be changed to something close that can be fulfilled.

Missing item type Creates new textures and renderbuffers given the current size of the framebuffer.

Missing item type To create a WebGL texture, one needs to supply three pieces of information: the type (the data type each channel will be stored as, e.g. int or float), the format (the color channels that will each be stored in the previously specified type, e.g. rgb or rgba), and the internal format (the specifics of how data for each channel, in the aforementioned type, will be packed together, such as how many bits to use, e.g. RGBA32F or RGB565.) The format and channels asked for by the user hint at what these values need to be, and the WebGL version affects what options are avaiable. This method returns the values for these three properties, given the framebuffer's settings.

Missing item type To create a WebGL texture, one needs to supply three pieces of information: the type (the data type each channel will be stored as, e.g. int or float), the format (the color channels that will each be stored in the previously specified type, e.g. rgb or rgba), and the internal format (the specifics of how data for each channel, in the aforementioned type, will be packed together, such as how many bits to use, e.g. RGBA32F or RGB565.) This method takes into account the settings asked for by the user and returns values for these three properties that can be used for the texture storing depth information.

Missing item type A method that will be called when recreating textures. If the framebuffer is auto-sized, it will update its width, height, and density properties.

Missing item type Called when the canvas that the framebuffer is attached to resizes. If the framebuffer is auto-sized, it will update its textures to match the new size.

Missing item type Called when the size of the framebuffer has changed (either by being manually updated or from auto-size updates when its canvas changes size.) Old textures and renderbuffers will be deleted, and then recreated with the new size.

Missing item type Given a raw texture wrapper, delete its stored texture from WebGL memory, and remove it from p5's list of active textures.

Missing item type Averages the vertex normals. Used in curved surfaces

Missing item type Averages pole normals. Used in spherical primitives

Missing item type Create a 2D array for establishing stroke connections

Missing item type Converts each line segment into the vertices and vertex attributes needed to turn the line into a polygon on screen. This will include: - Two triangles line segment to create a rectangle - Two triangles per endpoint to create a stroke cap rectangle. A fragment shader is responsible for displaying the appropriate cap style within that rectangle. - Four triangles per join between adjacent line segments, creating a quad on either side of the join, perpendicular to the lines. A vertex shader will discard the quad in the "elbow" of the join, and a fragment shader will display the appropriate join style within the remaining quad.

Missing item type Adds the vertices and vertex attributes for two triangles making a rectangle for a straight line segment. A vertex shader is responsible for picking proper coordinates on the screen given the centerline positions, the tangent, and the side of the centerline each vertex belongs to. Sides follow the following scheme: -1 -1 o-------------o | | o-------------o 1 1

Missing item type Adds the vertices and vertex attributes for two triangles representing the stroke cap of a line. A fragment shader is responsible for displaying the appropriate cap style within the rectangle they make. The lineSides buffer will include the following values for the points on the cap rectangle: -1 -2 -----------o---o | | -----------o---o 1 2

Missing item type Adds the vertices and vertex attributes for four triangles representing a join between two adjacent line segments. This creates a quad on either side of the shared vertex of the two line segments, with each quad perpendicular to the lines. A vertex shader will discard all but the quad in the "elbow" of the join, and a fragment shader will display the appropriate join style within the remaining quad. The lineSides buffer will include the following values for the points on the join rectangles: -1 -2 -------------o----o | | 1 o----o----o -3 | | 0 | --------o----o | 2| 3 | | | | |

Missing item type

Missing item type PRIVATE

Missing item type This is similar to quaternion multiplication but when multipying vector with quaternion the multiplication can be simplified to the below formula. This was taken from the below stackexchange link https://gamedev.stackexchange.com/questions/28395/rotating-vector3-by-a-quaternion/50545#50545

Missing item type Enables and binds the buffers used by shader when the appropriate data exists in geometry. Must always be done prior to drawing geometry in WebGL.

Missing item type Welcome to RendererGL Immediate Mode. Immediate mode is used for drawing custom shapes from a set of vertices. Immediate Mode is activated when you call beginShape() & de-activated when you call endShape(). Immediate mode is a style of programming borrowed from OpenGL's (now-deprecated) immediate mode. It differs from p5.js' default, Retained Mode, which caches geometries and buffers on the CPU to reduce the number of webgl draw calls. Retained mode is more efficient & performative, however, Immediate Mode is useful for sketching quick geometric ideas.

Missing item type End shape drawing and render vertices to screen.

Missing item type Called from endShape(). This function calculates the stroke vertices for custom shapes and tesselates shapes when applicable.

Missing item type Called from _processVertices(). This function calculates the stroke vertices for custom shapes and tesselates shapes when applicable.

Missing item type Called from _processVertices() when applicable. This function tesselates immediateMode.geometry.

Missing item type Called from endShape(). Responsible for calculating normals, setting shader uniforms, enabling all appropriate buffers, applying color blend, and drawing the fill geometry.

Missing item type Called from endShape(). Responsible for calculating normals, setting shader uniforms, enabling all appropriate buffers, applying color blend, and drawing the stroke geometry.

Missing item type

Missing item type initializes buffer defaults. runs each time a new geometry is registered

Missing item type creates a buffers object that holds the WebGL render buffers for a geometry.

Missing item type Draws buffers given a geometry key ID

Missing item type

Missing item type

Missing item type model view, projection, & normal matrices

Missing item type [background description]

Missing item type

Missing item type [resize description]

Missing item type clears color and depth buffers with r,g,b,a

Missing item type Resets all depth information so that nothing previously drawn will occlude anything subsequently drawn.

Missing item type [translate description]

Missing item type Scales the Model View Matrix by a vector

Missing item type TODO(dave): un-private this when there is a way to actually override the shader used for points Get the shader used when drawing points with `point()`. You can call `pointShader().modify()` and change any of the following hooks: - `void beforeVertex`: Called at the start of the vertex shader. - `vec3 getLocalPosition`: Update the position of vertices before transforms are applied. It takes in `vec3 position` and must return a modified version. - `vec3 getWorldPosition`: Update the position of vertices after transforms are applied. It takes in `vec3 position` and pust return a modified version. - `float getPointSize`: Update the size of the point. It takes in `float size` and must return a modified version. - `void afterVertex`: Called at the end of the vertex shader. - `void beforeFragment`: Called at the start of the fragment shader. - `bool shouldDiscard`: Points are drawn inside a square, with the corners discarded in the fragment shader to create a circle. Use this to change this logic. It takes in a `bool willDiscard` and must return a modified version. - `vec4 getFinalColor`: Update the final color after mixing. It takes in a `vec4 color` and must return a modified version. - `void afterFragment`: Called at the end of the fragment shader. Call `pointShader().inspectHooks()` to see all the possible hooks and their default implementations.

Missing item type turn a two dimensional array into one dimensional array

Missing item type turn a p5.Vector Array into a one dimensional number array

Missing item type ensures that p5 is using a 3d renderer. throws an error if not.

Missing item type Shaders are written in GLSL, but there are different versions of GLSL that it might be written in. Calling this method on a `p5.Shader` will return the GLSL version it uses, either `100 es` or `300 es`. WebGL 1 shaders will only use `100 es`, and WebGL 2 shaders may use either.

Missing item type

Missing item type

Missing item type

Missing item type p5.sound https://p5js.org/reference/#/libraries/p5.sound From the Processing Foundation and contributors https://github.com/processing/p5.js-sound/graphs/contributors MIT License (MIT) https://github.com/processing/p5.js-sound/blob/master/LICENSE Some of the many audio libraries & resources that inspire p5.sound: - TONE.js (c) Yotam Mann. Licensed under The MIT License (MIT). https://github.com/TONEnoTONE/Tone.js - buzz.js (c) Jay Salvat. Licensed under The MIT License (MIT). http://buzz.jaysalvat.com/ - Boris Smus Web Audio API book, 2013. Licensed under the Apache License http://www.apache.org/licenses/LICENSE-2.0 - wavesurfer.js https://github.com/katspaugh/wavesurfer.js - Web Audio Components by Jordan Santell https://github.com/web-audio-components - Wilm Thoben's Sound library for Processing https://github.com/processing/processing/tree/master/java/libraries/sound Web Audio API: http://w3.org/TR/webaudio/

Missing item type This module has shims

Missing item type Determine which filetypes are supported (inspired by buzz.js) The audio element (el) will only be used to test browser support for various audio formats

Missing item type

Missing item type Used by Osc and Envelope to chain signal math

Missing item type This is a helper function that the p5.SoundFile calls to load itself. Accepts a callback (the name of another function) as an optional parameter.

Missing item type Stop playback on all of this soundfile's sources.

Missing item type

Missing item type The p5.Effect class is built using Tone.js CrossFade

Missing item type In classes that extend p5.Effect, connect effect nodes to the wet parameter

Missing item type EQFilter extends p5.Filter with constraints necessary for the p5.EQ

Missing item type Inspired by Simple Reverb by Jordan Santell https://github.com/web-audio-components/simple-reverb/blob/master/index.js Utility function for building an impulse response based on the module parameters.

Missing item type Private method to load a buffer as an Impulse Response, assign it to the convolverNode, and add to the Array of .impulses.

Missing item type musicalTimeMode variables modify these only when the interval is specified in musicalTime format as a string

Missing item type Do not initiate the callback if timeFromNow is < 0 This ususually occurs for a few milliseconds when the page is not fully loaded The callback should only be called until maxIterations is reached

Missing item type callback invoked when the recording is over

Missing item type Private method to ensure accurate values of this._voicesInUse Any time a new value is scheduled, it is necessary to increment all subsequent scheduledValues after attack, and decrement all subsequent scheduledValues after release

Missing item type

# consts
p5.describe

p5.describeElement

p5.textOutput

p5.gridOutput

p5.describe

p5.describeElement

p5.textOutput

p5.gridOutput

p5.colorMode

p5.colorMode

p5.colorMode

p5.arc

p5.arc

p5.arc

p5.ellipseMode

p5.rectMode

p5.imageMode

p5.textAlign

p5.ellipseMode

p5.rectMode

p5.ellipseMode

p5.rectMode

p5.imageMode

p5.ellipseMode

p5.rectMode

p5.imageMode

p5.strokeCap

p5.strokeJoin

p5.strokeCap

p5.strokeCap

p5.strokeJoin

p5.strokeJoin

p5.beginShape

p5.beginShape

p5.beginShape

p5.beginShape

p5.beginShape

p5.beginShape

p5.beginShape

p5.beginShape

p5.endShape

p5.cursor

p5.cursor

p5.cursor

p5.cursor

p5.cursor

p5.cursor

p5.createCanvas

p5.createGraphics

p5.createCanvas

p5.createGraphics

p5.blendMode

p5.Image.blend

p5.blend

p5.blendMode

p5.Image.blend

p5.blend

p5.blendMode

p5.Image.blend

p5.blend

p5.blendMode

p5.Image.blend

p5.blend

p5.blendMode

p5.Image.blend

p5.blend

p5.blendMode

p5.Image.blend

p5.blend

p5.blendMode

p5.Image.blend

p5.blend

p5.blendMode

p5.Image.blend

p5.blend

p5.blendMode

p5.Image.blend

p5.blend

p5.blendMode

p5.Image.blend

p5.blend

p5.blendMode

p5.Image.blend

p5.blend

p5.blendMode

p5.Image.blend

p5.blend

p5.blendMode

p5.Image.blend

p5.blend

p5.blendMode

p5.Image.blend

p5.blend

p5.blendMode

p5.blendMode

p5.createCapture

p5.createCapture

p5.Image.filter

p5.filter

p5.Image.filter

p5.filter

p5.Image.filter

p5.filter

p5.Image.filter

p5.filter

p5.Image.filter

p5.filter

p5.Image.filter

p5.filter

p5.Image.filter

p5.filter

p5.Image.filter

p5.filter

p5.Image.blend

p5.blend

p5.textStyle

p5.textureMode

p5.angleMode

p5.angleMode

p5.textAlign

p5.textAlign

p5.textAlign

p5.textAlign

p5.textAlign

p5.textStyle

p5.textStyle

p5.textStyle

p5.textWrap

p5.textWrap

p5.textureMode

p5.textureWrap

p5.textureWrap

p5.textureWrap

