>> try changing them.\n myGeometry = new p5.Geometry(48, 2, createShape);\n}\n\nfunction draw() {\n background(50);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n lights();\n\n // Style the p5.Geometry object.\n strokeWeight(0.2);\n\n // Draw the p5.Geometry object.\n model(myGeometry);\n}\n\nfunction createShape() {\n // \"this\" refers to the p5.Geometry object being created.\n\n // Define the Möbius strip with a few parameters.\n let spread = 0.1;\n let radius = 30;\n let stripWidth = 15;\n let xInterval = 4 * PI / this.detailX;\n let yOffset = -stripWidth / 2;\n let yInterval = stripWidth / this.detailY;\n\n for (let j = 0; j <= this.detailY; j += 1) {\n // Calculate the \"vertical\" point along the strip.\n let v = yOffset + yInterval * j;\n\n for (let i = 0; i <= this.detailX; i += 1) {\n // Calculate the angle of rotation around the strip.\n let u = i * xInterval;\n\n // Calculate the coordinates of the vertex.\n let x = (radius + v * cos(u / 2)) * cos(u) - sin(u / 2) * 2 * spread;\n let y = (radius + v * cos(u / 2)) * sin(u);\n if (u < TWO_PI) {\n y += sin(u) * spread;\n } else {\n y -= sin(u) * spread;\n }\n let z = v * sin(u / 2) + sin(u / 4) * 4 * spread;\n\n // Create a p5.Vector object to position the vertex.\n let vert = createVector(x, y, z);\n\n // Add the vertex to the p5.Geometry object's vertices array.\n this.vertices.push(vert);\n }\n }\n\n // Compute the faces array.\n this.computeFaces();\n\n // Compute the surface normals to help with lighting.\n this.computeNormals();\n}\n\n"]]],"methods":[0,{"calculateBoundingBox":[0,{"description":[0,"
Calculates the position and size of the smallest box that contains the geometry.
\nA bounding box is the smallest rectangular prism that contains the entire\ngeometry. It's defined by the box's minimum and maximum coordinates along\neach axis, as well as the size (length) and offset (center).
\nCalling myGeometry.calculateBoundingBox()
returns an object with four\nproperties that describe the bounding box:
// Get myGeometry's bounding box.\nlet bbox = myGeometry.calculateBoundingBox();\n\n// Print the bounding box to the console.\nconsole.log(bbox);\n\n// {\n// // The minimum coordinate along each axis.\n// min: { x: -1, y: -2, z: -3 },\n//\n// // The maximum coordinate along each axis.\n// max: { x: 1, y: 2, z: 3},\n//\n// // The size (length) along each axis.\n// size: { x: 2, y: 4, z: 6},\n//\n// // The offset (center) along each axis.\n// offset: { x: 0, y: 0, z: 0}\n// }\n
\n"],"path":[0,"p5.Geometry/calculateBoundingBox"]}],"clearColors":[0,{"description":[0,"Removes the geometry’s internal colors.
\np5.Geometry
objects can be created with \"internal colors\" assigned to\nvertices or the entire shape. When a geometry has internal colors,\nfill() has no effect. Calling\nmyGeometry.clearColors()
allows the\nfill() function to apply color to the geometry.
The saveObj()
function exports p5.Geometry
objects as\n3D models in the Wavefront .obj file format.\nThis way, you can use the 3D shapes you create in p5.js in other software\nfor rendering, animation, 3D printing, or more.
The exported .obj file will include the faces and vertices of the p5.Geometry
,\nas well as its texture coordinates and normals, if it has them.
The saveStl()
function exports p5.Geometry
objects as\n3D models in the STL stereolithography file format.\nThis way, you can use the 3D shapes you create in p5.js in other software\nfor 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\nbut less human-readable binary .stl file by passing { binary: true }
as a second parameter.
Flips the geometry’s texture u-coordinates.
\nIn order for texture() to work, the geometry\nneeds a way to map the points on its surface to the pixels in a rectangular\nimage that's used as a texture. The geometry's vertex at coordinates\n(x, y, z)
maps to the texture image's pixel at coordinates (u, v)
.
The myGeometry.uvs array stores the\n(u, v)
coordinates for each vertex in the order it was added to the\ngeometry. Calling myGeometry.flipU()
flips a geometry's u-coordinates\nso that the texture appears mirrored horizontally.
For example, a plane's four vertices are added clockwise starting from the\ntop-left corner. Here's how calling myGeometry.flipU()
would change a\nplane's texture coordinates:
// Print the original texture coordinates.\n// Output: [0, 0, 1, 0, 0, 1, 1, 1]\nconsole.log(myGeometry.uvs);\n\n// Flip the u-coordinates.\nmyGeometry.flipU();\n\n// Print the flipped texture coordinates.\n// Output: [1, 0, 0, 0, 1, 1, 0, 1]\nconsole.log(myGeometry.uvs);\n\n// Notice the swaps:\n// Top vertices: [0, 0, 1, 0] --> [1, 0, 0, 0]\n// Bottom vertices: [0, 1, 1, 1] --> [1, 1, 0, 1]\n
\n"],"path":[0,"p5.Geometry/flipU"]}],"flipV":[0,{"description":[0,"Flips the geometry’s texture v-coordinates.
\nIn order for texture() to work, the geometry\nneeds a way to map the points on its surface to the pixels in a rectangular\nimage that's used as a texture. The geometry's vertex at coordinates\n(x, y, z)
maps to the texture image's pixel at coordinates (u, v)
.
The myGeometry.uvs array stores the\n(u, v)
coordinates for each vertex in the order it was added to the\ngeometry. Calling myGeometry.flipV()
flips a geometry's v-coordinates\nso that the texture appears mirrored vertically.
For example, a plane's four vertices are added clockwise starting from the\ntop-left corner. Here's how calling myGeometry.flipV()
would change a\nplane's texture coordinates:
// Print the original texture coordinates.\n// Output: [0, 0, 1, 0, 0, 1, 1, 1]\nconsole.log(myGeometry.uvs);\n\n// Flip the v-coordinates.\nmyGeometry.flipV();\n\n// Print the flipped texture coordinates.\n// Output: [0, 1, 1, 1, 0, 0, 1, 0]\nconsole.log(myGeometry.uvs);\n\n// Notice the swaps:\n// Left vertices: [0, 0] <--> [1, 0]\n// Right vertices: [1, 0] <--> [1, 1]\n
\n"],"path":[0,"p5.Geometry/flipV"]}],"computeFaces":[0,{"description":[0,"Computes the geometry's faces using its vertices.
\nAll 3D shapes are made by connecting sets of points called vertices. A\ngeometry's surface is formed by connecting vertices to form triangles that\nare stitched together. Each triangular patch on the geometry's surface is\ncalled a face. myGeometry.computeFaces()
performs the math needed to\ndefine each face based on the distances between vertices.
The geometry's vertices are stored as p5.Vector\nobjects in the myGeometry.vertices\narray. The geometry's first vertex is the\np5.Vector object at myGeometry.vertices[0]
,\nits second vertex is myGeometry.vertices[1]
, its third vertex is\nmyGeometry.vertices[2]
, and so on.
Calling myGeometry.computeFaces()
fills the\nmyGeometry.faces array with three-element\narrays that list the vertices that form each face. For example, a geometry\nmade from a rectangle has two faces because a rectangle is made by joining\ntwo triangles. myGeometry.faces for a\nrectangle would be the two-dimensional array\n[[0, 1, 2], [2, 1, 3]]
. The first face, myGeometry.faces[0]
, is the\narray [0, 1, 2]
because it's formed by connecting\nmyGeometry.vertices[0]
, myGeometry.vertices[1]
,and\nmyGeometry.vertices[2]
. The second face, myGeometry.faces[1]
, is the\narray [2, 1, 3]
because it's formed by connecting\nmyGeometry.vertices[2]
, myGeometry.vertices[1]
, and\nmyGeometry.vertices[3]
.
Note: myGeometry.computeFaces()
only works when geometries have four or more vertices.
Calculates the normal vector for each vertex on the geometry.
\nAll 3D shapes are made by connecting sets of points called vertices. A\ngeometry's surface is formed by connecting vertices to create triangles\nthat are stitched together. Each triangular patch on the geometry's\nsurface is called a face. myGeometry.computeNormals()
performs the\nmath needed to orient each face. Orientation is important for lighting\nand other effects.
A face's orientation is defined by its normal vector which points out\nof the face and is normal (perpendicular) to the surface. Calling\nmyGeometry.computeNormals()
first calculates each face's normal vector.\nThen it calculates the normal vector for each vertex by averaging the\nnormal vectors of the faces surrounding the vertex. The vertex normals\nare stored as p5.Vector objects in the\nmyGeometry.vertexNormals array.
The first parameter, shadingType
, is optional. Passing the constant\nFLAT
, as in myGeometry.computeNormals(FLAT)
, provides neighboring\nfaces with their own copies of the vertices they share. Surfaces appear\ntiled with flat shading. Passing the constant SMOOTH
, as in\nmyGeometry.computeNormals(SMOOTH)
, makes neighboring faces reuse their\nshared vertices. Surfaces appear smoother with smooth shading. By\ndefault, shadingType
is FLAT
.
The second parameter, options
, is also optional. If an object with a\nroundToPrecision
property is passed, as in\nmyGeometry.computeNormals(SMOOTH, { roundToPrecision: 5 })
, it sets the\nnumber of decimal places to use for calculations. By default,\nroundToPrecision
uses 3 decimal places.
Transforms the geometry's vertices to fit snugly within a 100×100×100 box\ncentered at the origin.
\nCalling myGeometry.normalize()
translates the geometry's vertices so that\nthey're centered at the origin (0, 0, 0)
. Then it scales the vertices so\nthat they fill a 100×100×100 box. As a result, small geometries will grow\nand large geometries will shrink.
Note: myGeometry.normalize()
only works when called in the\nsetup() function.
An array with the geometry's vertices.
\nThe geometry's vertices are stored as\np5.Vector objects in the myGeometry.vertices
\narray. The geometry's first vertex is the\np5.Vector object at myGeometry.vertices[0]
,\nits second vertex is myGeometry.vertices[1]
, its third vertex is\nmyGeometry.vertices[2]
, and so on.
An array with the vectors that are normal to the geometry's vertices.
\nA face's orientation is defined by its normal vector which points out\nof the face and is normal (perpendicular) to the surface. Calling\nmyGeometry.computeNormals()
first calculates each face's normal\nvector. Then it calculates the normal vector for each vertex by\naveraging the normal vectors of the faces surrounding the vertex. The\nvertex normals are stored as p5.Vector\nobjects in the myGeometry.vertexNormals
array.
An array that lists which of the geometry's vertices form each of its\nfaces.
\nAll 3D shapes are made by connecting sets of points called vertices. A\ngeometry's surface is formed by connecting vertices to form triangles\nthat are stitched together. Each triangular patch on the geometry's\nsurface is called a face.
\nThe geometry's vertices are stored as\np5.Vector objects in the\nmyGeometry.vertices array. The\ngeometry's first vertex is the p5.Vector\nobject at myGeometry.vertices[0]
, its second vertex is\nmyGeometry.vertices[1]
, its third vertex is myGeometry.vertices[2]
,\nand so on.
For example, a geometry made from a rectangle has two faces because a\nrectangle is made by joining two triangles. myGeometry.faces
for a\nrectangle would be the two-dimensional array [[0, 1, 2], [2, 1, 3]]
.\nThe first face, myGeometry.faces[0]
, is the array [0, 1, 2]
because\nit's formed by connecting myGeometry.vertices[0]
,\nmyGeometry.vertices[1]
,and myGeometry.vertices[2]
. The second face,\nmyGeometry.faces[1]
, is the array [2, 1, 3]
because it's formed by\nconnecting myGeometry.vertices[2]
, myGeometry.vertices[1]
,and\nmyGeometry.vertices[3]
.
An array that lists the texture coordinates for each of the geometry's\nvertices.
\nIn order for texture() to work, the geometry\nneeds a way to map the points on its surface to the pixels in a\nrectangular image that's used as a texture. The geometry's vertex at\ncoordinates (x, y, z)
maps to the texture image's pixel at coordinates\n(u, v)
.
The myGeometry.uvs
array stores the (u, v)
coordinates for each\nvertex in the order it was added to the geometry. For example, the\nfirst vertex, myGeometry.vertices[0]
, has its (u, v)
coordinates\nstored at myGeometry.uvs[0]
and myGeometry.uvs[1]
.
Calculates the position and size of the smallest box that contains the geometry.
\nA bounding box is the smallest rectangular prism that contains the entire\ngeometry. It's defined by the box's minimum and maximum coordinates along\neach axis, as well as the size (length) and offset (center).
\nCalling myGeometry.calculateBoundingBox()
returns an object with four\nproperties that describe the bounding box:
// Get myGeometry's bounding box.\nlet bbox = myGeometry.calculateBoundingBox();\n\n// Print the bounding box to the console.\nconsole.log(bbox);\n\n// {\n// // The minimum coordinate along each axis.\n// min: { x: -1, y: -2, z: -3 },\n//\n// // The maximum coordinate along each axis.\n// max: { x: 1, y: 2, z: 3},\n//\n// // The size (length) along each axis.\n// size: { x: 2, y: 4, z: 6},\n//\n// // The offset (center) along each axis.\n// offset: { x: 0, y: 0, z: 0}\n// }\n
\n"],"line":[0,682],"itemtype":[0,"method"],"class":[0,"p5.Geometry"],"chainable":[0,false],"return":[0,{"description":[0,"bounding box of the geometry."],"type":[0,"Object"]}],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n\nlet particles;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a new p5.Geometry object with random spheres.\n particles = buildGeometry(createParticles);\n\n describe('Ten white spheres placed randomly against a gray background. A box encloses the spheres.');\n}\n\nfunction draw() {\n background(50);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n lights();\n\n // Style the particles.\n noStroke();\n fill(255);\n\n // Draw the particles.\n model(particles);\n\n // Calculate the bounding box.\n let bbox = particles.calculateBoundingBox();\n\n // Translate to the bounding box's center.\n translate(bbox.offset.x, bbox.offset.y, bbox.offset.z);\n\n // Style the bounding box.\n stroke(255);\n noFill();\n\n // Draw the bounding box.\n box(bbox.size.x, bbox.size.y, bbox.size.z);\n}\n\nfunction createParticles() {\n for (let i = 0; i < 10; i += 1) {\n // Calculate random coordinates.\n let x = randomGaussian(0, 15);\n let y = randomGaussian(0, 15);\n let z = randomGaussian(0, 15);\n\n push();\n // Translate to the particle's coordinates.\n translate(x, y, z);\n // Draw the particle.\n sphere(3);\n pop();\n }\n}\n
\nRemoves the geometry’s internal colors.
\np5.Geometry
objects can be created with \"internal colors\" assigned to\nvertices or the entire shape. When a geometry has internal colors,\nfill() has no effect. Calling\nmyGeometry.clearColors()
allows the\nfill() function to apply color to the geometry.
\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n // Create a p5.Geometry object.\n // Set its internal color to red.\n beginGeometry();\n fill(255, 0, 0);\n plane(20);\n let myGeometry = endGeometry();\n\n // Style the shape.\n noStroke();\n\n // Draw the p5.Geometry object (center).\n model(myGeometry);\n\n // Translate the origin to the bottom-right.\n translate(25, 25, 0);\n\n // Try to fill the geometry with green.\n fill(0, 255, 0);\n\n // Draw the geometry again (bottom-right).\n model(myGeometry);\n\n // Clear the geometry's colors.\n myGeometry.clearColors();\n\n // Fill the geometry with blue.\n fill(0, 0, 255);\n\n // Translate the origin up.\n translate(0, -50, 0);\n\n // Draw the geometry again (top-right).\n model(myGeometry);\n\n describe(\n '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.'\n );\n}\n
\nComputes the geometry's faces using its vertices.
\nAll 3D shapes are made by connecting sets of points called vertices. A\ngeometry's surface is formed by connecting vertices to form triangles that\nare stitched together. Each triangular patch on the geometry's surface is\ncalled a face. myGeometry.computeFaces()
performs the math needed to\ndefine each face based on the distances between vertices.
The geometry's vertices are stored as p5.Vector\nobjects in the myGeometry.vertices\narray. The geometry's first vertex is the\np5.Vector object at myGeometry.vertices[0]
,\nits second vertex is myGeometry.vertices[1]
, its third vertex is\nmyGeometry.vertices[2]
, and so on.
Calling myGeometry.computeFaces()
fills the\nmyGeometry.faces array with three-element\narrays that list the vertices that form each face. For example, a geometry\nmade from a rectangle has two faces because a rectangle is made by joining\ntwo triangles. myGeometry.faces for a\nrectangle would be the two-dimensional array\n[[0, 1, 2], [2, 1, 3]]
. The first face, myGeometry.faces[0]
, is the\narray [0, 1, 2]
because it's formed by connecting\nmyGeometry.vertices[0]
, myGeometry.vertices[1]
,and\nmyGeometry.vertices[2]
. The second face, myGeometry.faces[1]
, is the\narray [2, 1, 3]
because it's formed by connecting\nmyGeometry.vertices[2]
, myGeometry.vertices[1]
, and\nmyGeometry.vertices[3]
.
Note: myGeometry.computeFaces()
only works when geometries have four or more vertices.
\n// Click and drag the mouse to view the scene from different angles.\n\nlet myGeometry;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Geometry object.\n myGeometry = new p5.Geometry();\n\n // Create p5.Vector objects to position the vertices.\n let v0 = createVector(-40, 0, 0);\n let v1 = createVector(0, -40, 0);\n let v2 = createVector(0, 40, 0);\n let v3 = createVector(40, 0, 0);\n\n // Add the vertices to myGeometry's vertices array.\n myGeometry.vertices.push(v0, v1, v2, v3);\n\n // Compute myGeometry's faces array.\n myGeometry.computeFaces();\n\n describe('A red square drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n lights();\n\n // Style the shape.\n noStroke();\n fill(255, 0, 0);\n\n // Draw the p5.Geometry object.\n model(myGeometry);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nlet myGeometry;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Geometry object using a callback function.\n myGeometry = new p5.Geometry(1, 1, createShape);\n\n describe('A red square drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n lights();\n\n // Style the shape.\n noStroke();\n fill(255, 0, 0);\n\n // Draw the p5.Geometry object.\n model(myGeometry);\n}\n\nfunction createShape() {\n // Create p5.Vector objects to position the vertices.\n let v0 = createVector(-40, 0, 0);\n let v1 = createVector(0, -40, 0);\n let v2 = createVector(0, 40, 0);\n let v3 = createVector(40, 0, 0);\n\n // Add the vertices to the p5.Geometry object's vertices array.\n this.vertices.push(v0, v1, v2, v3);\n\n // Compute the faces array.\n this.computeFaces();\n}\n
\nCalculates the normal vector for each vertex on the geometry.
\nAll 3D shapes are made by connecting sets of points called vertices. A\ngeometry's surface is formed by connecting vertices to create triangles\nthat are stitched together. Each triangular patch on the geometry's\nsurface is called a face. myGeometry.computeNormals()
performs the\nmath needed to orient each face. Orientation is important for lighting\nand other effects.
A face's orientation is defined by its normal vector which points out\nof the face and is normal (perpendicular) to the surface. Calling\nmyGeometry.computeNormals()
first calculates each face's normal vector.\nThen it calculates the normal vector for each vertex by averaging the\nnormal vectors of the faces surrounding the vertex. The vertex normals\nare stored as p5.Vector objects in the\nmyGeometry.vertexNormals array.
The first parameter, shadingType
, is optional. Passing the constant\nFLAT
, as in myGeometry.computeNormals(FLAT)
, provides neighboring\nfaces with their own copies of the vertices they share. Surfaces appear\ntiled with flat shading. Passing the constant SMOOTH
, as in\nmyGeometry.computeNormals(SMOOTH)
, makes neighboring faces reuse their\nshared vertices. Surfaces appear smoother with smooth shading. By\ndefault, shadingType
is FLAT
.
The second parameter, options
, is also optional. If an object with a\nroundToPrecision
property is passed, as in\nmyGeometry.computeNormals(SMOOTH, { roundToPrecision: 5 })
, it sets the\nnumber of decimal places to use for calculations. By default,\nroundToPrecision
uses 3 decimal places.
shading type. either FLAT or SMOOTH. Defaults to FLAT
.
shading options.
\n"],"type":[0,"Object"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Geometry"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n\nlet myGeometry;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Geometry object.\n beginGeometry();\n torus();\n myGeometry = endGeometry();\n\n // Compute the vertex normals.\n myGeometry.computeNormals();\n\n describe(\n \"A white torus drawn on a dark gray background. Red lines extend outward from the torus' vertices.\"\n );\n}\n\nfunction draw() {\n background(50);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n lights();\n\n // Rotate the coordinate system.\n rotateX(1);\n\n // Style the helix.\n stroke(0);\n\n // Display the helix.\n model(myGeometry);\n\n // Style the normal vectors.\n stroke(255, 0, 0);\n\n // Iterate over the vertices and vertexNormals arrays.\n for (let i = 0; i < myGeometry.vertices.length; i += 1) {\n\n // Get the vertex p5.Vector object.\n let v = myGeometry.vertices[i];\n\n // Get the vertex normal p5.Vector object.\n let n = myGeometry.vertexNormals[i];\n\n // Calculate a point along the vertex normal.\n let p = p5.Vector.mult(n, 5);\n\n // Draw the vertex normal as a red line.\n push();\n translate(v);\n line(0, 0, 0, p.x, p.y, p.z);\n pop();\n }\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nlet myGeometry;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Geometry object using a callback function.\n myGeometry = new p5.Geometry();\n\n // Create p5.Vector objects to position the vertices.\n let v0 = createVector(-40, 0, 0);\n let v1 = createVector(0, -40, 0);\n let v2 = createVector(0, 40, 0);\n let v3 = createVector(40, 0, 0);\n\n // Add the vertices to the p5.Geometry object's vertices array.\n myGeometry.vertices.push(v0, v1, v2, v3);\n\n // Compute the faces array.\n myGeometry.computeFaces();\n\n // Compute the surface normals.\n myGeometry.computeNormals();\n\n describe('A red square drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Add a white point light.\n pointLight(255, 255, 255, 0, 0, 10);\n\n // Style the p5.Geometry object.\n noStroke();\n fill(255, 0, 0);\n\n // Draw the p5.Geometry object.\n model(myGeometry);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nlet myGeometry;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Geometry object.\n myGeometry = buildGeometry(createShape);\n\n // Compute normals using default (FLAT) shading.\n myGeometry.computeNormals(FLAT);\n\n describe('A white, helical structure drawn on a dark gray background. Its faces appear faceted.');\n}\n\nfunction draw() {\n background(50);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n lights();\n\n // Rotate the coordinate system.\n rotateX(1);\n\n // Style the helix.\n noStroke();\n\n // Display the helix.\n model(myGeometry);\n}\n\nfunction createShape() {\n // Create a helical shape.\n beginShape();\n for (let i = 0; i < TWO_PI * 3; i += 0.5) {\n let x = 30 * cos(i);\n let y = 30 * sin(i);\n let z = map(i, 0, TWO_PI * 3, -40, 40);\n vertex(x, y, z);\n }\n endShape();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nlet myGeometry;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Geometry object.\n myGeometry = buildGeometry(createShape);\n\n // Compute normals using smooth shading.\n myGeometry.computeNormals(SMOOTH);\n\n describe('A white, helical structure drawn on a dark gray background.');\n}\n\nfunction draw() {\n background(50);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n lights();\n\n // Rotate the coordinate system.\n rotateX(1);\n\n // Style the helix.\n noStroke();\n\n // Display the helix.\n model(myGeometry);\n}\n\nfunction createShape() {\n // Create a helical shape.\n beginShape();\n for (let i = 0; i < TWO_PI * 3; i += 0.5) {\n let x = 30 * cos(i);\n let y = 30 * sin(i);\n let z = map(i, 0, TWO_PI * 3, -40, 40);\n vertex(x, y, z);\n }\n endShape();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nlet myGeometry;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Geometry object.\n myGeometry = buildGeometry(createShape);\n\n // Create an options object.\n let options = { roundToPrecision: 5 };\n\n // Compute normals using smooth shading.\n myGeometry.computeNormals(SMOOTH, options);\n\n describe('A white, helical structure drawn on a dark gray background.');\n}\n\nfunction draw() {\n background(50);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n lights();\n\n // Rotate the coordinate system.\n rotateX(1);\n\n // Style the helix.\n noStroke();\n\n // Display the helix.\n model(myGeometry);\n}\n\nfunction createShape() {\n // Create a helical shape.\n beginShape();\n for (let i = 0; i < TWO_PI * 3; i += 0.5) {\n let x = 30 * cos(i);\n let y = 30 * sin(i);\n let z = map(i, 0, TWO_PI * 3, -40, 40);\n vertex(x, y, z);\n }\n endShape();\n}\n
\nAn array that lists which of the geometry's vertices form each of its\nfaces.
\nAll 3D shapes are made by connecting sets of points called vertices. A\ngeometry's surface is formed by connecting vertices to form triangles\nthat are stitched together. Each triangular patch on the geometry's\nsurface is called a face.
\nThe geometry's vertices are stored as\np5.Vector objects in the\nmyGeometry.vertices array. The\ngeometry's first vertex is the p5.Vector\nobject at myGeometry.vertices[0]
, its second vertex is\nmyGeometry.vertices[1]
, its third vertex is myGeometry.vertices[2]
,\nand so on.
For example, a geometry made from a rectangle has two faces because a\nrectangle is made by joining two triangles. myGeometry.faces
for a\nrectangle would be the two-dimensional array [[0, 1, 2], [2, 1, 3]]
.\nThe first face, myGeometry.faces[0]
, is the array [0, 1, 2]
because\nit's formed by connecting myGeometry.vertices[0]
,\nmyGeometry.vertices[1]
,and myGeometry.vertices[2]
. The second face,\nmyGeometry.faces[1]
, is the array [2, 1, 3]
because it's formed by\nconnecting myGeometry.vertices[2]
, myGeometry.vertices[1]
,and\nmyGeometry.vertices[3]
.
\n// Click and drag the mouse to view the scene from different angles.\n\nlet myGeometry;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Geometry object.\n beginGeometry();\n sphere();\n myGeometry = endGeometry();\n\n describe(\"A sphere drawn on a gray background. The sphere's surface is a grayscale patchwork of triangles.\");\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n lights();\n\n // Style the p5.Geometry object.\n noStroke();\n\n // Set a random seed.\n randomSeed(1234);\n\n // Iterate over the faces array.\n for (let face of myGeometry.faces) {\n\n // Style the face.\n let g = random(0, 255);\n fill(g);\n\n // Draw the face.\n beginShape();\n // Iterate over the vertices that form the face.\n for (let f of face) {\n // Get the vertex's p5.Vector object.\n let v = myGeometry.vertices[f];\n vertex(v.x, v.y, v.z);\n }\n endShape();\n\n }\n}\n
\nFlips the geometry’s texture u-coordinates.
\nIn order for texture() to work, the geometry\nneeds a way to map the points on its surface to the pixels in a rectangular\nimage that's used as a texture. The geometry's vertex at coordinates\n(x, y, z)
maps to the texture image's pixel at coordinates (u, v)
.
The myGeometry.uvs array stores the\n(u, v)
coordinates for each vertex in the order it was added to the\ngeometry. Calling myGeometry.flipU()
flips a geometry's u-coordinates\nso that the texture appears mirrored horizontally.
For example, a plane's four vertices are added clockwise starting from the\ntop-left corner. Here's how calling myGeometry.flipU()
would change a\nplane's texture coordinates:
// Print the original texture coordinates.\n// Output: [0, 0, 1, 0, 0, 1, 1, 1]\nconsole.log(myGeometry.uvs);\n\n// Flip the u-coordinates.\nmyGeometry.flipU();\n\n// Print the flipped texture coordinates.\n// Output: [1, 0, 0, 0, 1, 1, 0, 1]\nconsole.log(myGeometry.uvs);\n\n// Notice the swaps:\n// Top vertices: [0, 0, 1, 0] --> [1, 0, 0, 0]\n// Bottom vertices: [0, 1, 1, 1] --> [1, 1, 0, 1]\n
\n"],"line":[0,1150],"itemtype":[0,"method"],"class":[0,"p5.Geometry"],"chainable":[0,false],"example":[1,[[0,"\n\nlet img;\n\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n // Create p5.Geometry objects.\n let geom1 = buildGeometry(createShape);\n let geom2 = buildGeometry(createShape);\n\n // Flip geom2's U texture coordinates.\n geom2.flipU();\n\n // Left (original).\n push();\n translate(-25, 0, 0);\n texture(img);\n noStroke();\n model(geom1);\n pop();\n\n // Right (flipped).\n push();\n translate(25, 0, 0);\n texture(img);\n noStroke();\n model(geom2);\n pop();\n\n describe(\n 'Two photos of a ceiling on a gray background. The photos are mirror images of each other.'\n );\n}\n\nfunction createShape() {\n plane(40);\n}\n
\nFlips the geometry’s texture v-coordinates.
\nIn order for texture() to work, the geometry\nneeds a way to map the points on its surface to the pixels in a rectangular\nimage that's used as a texture. The geometry's vertex at coordinates\n(x, y, z)
maps to the texture image's pixel at coordinates (u, v)
.
The myGeometry.uvs array stores the\n(u, v)
coordinates for each vertex in the order it was added to the\ngeometry. Calling myGeometry.flipV()
flips a geometry's v-coordinates\nso that the texture appears mirrored vertically.
For example, a plane's four vertices are added clockwise starting from the\ntop-left corner. Here's how calling myGeometry.flipV()
would change a\nplane's texture coordinates:
// Print the original texture coordinates.\n// Output: [0, 0, 1, 0, 0, 1, 1, 1]\nconsole.log(myGeometry.uvs);\n\n// Flip the v-coordinates.\nmyGeometry.flipV();\n\n// Print the flipped texture coordinates.\n// Output: [0, 1, 1, 1, 0, 0, 1, 0]\nconsole.log(myGeometry.uvs);\n\n// Notice the swaps:\n// Left vertices: [0, 0] <--> [1, 0]\n// Right vertices: [1, 0] <--> [1, 1]\n
\n"],"line":[0,1245],"itemtype":[0,"method"],"class":[0,"p5.Geometry"],"chainable":[0,false],"example":[1,[[0,"\n\nlet img;\n\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n // Create p5.Geometry objects.\n let geom1 = buildGeometry(createShape);\n let geom2 = buildGeometry(createShape);\n\n // Flip geom2's V texture coordinates.\n geom2.flipV();\n\n // Left (original).\n push();\n translate(-25, 0, 0);\n texture(img);\n noStroke();\n model(geom1);\n pop();\n\n // Right (flipped).\n push();\n translate(25, 0, 0);\n texture(img);\n noStroke();\n model(geom2);\n pop();\n\n describe(\n 'Two photos of a ceiling on a gray background. The photos are mirror images of each other.'\n );\n}\n\nfunction createShape() {\n plane(40);\n}\n
\nTransforms the geometry's vertices to fit snugly within a 100×100×100 box\ncentered at the origin.
\nCalling myGeometry.normalize()
translates the geometry's vertices so that\nthey're centered at the origin (0, 0, 0)
. Then it scales the vertices so\nthat they fill a 100×100×100 box. As a result, small geometries will grow\nand large geometries will shrink.
Note: myGeometry.normalize()
only works when called in the\nsetup() function.
\nlet myGeometry;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a very small torus.\n beginGeometry();\n torus(1, 0.25);\n myGeometry = endGeometry();\n\n // Normalize the torus so its vertices fill\n // the range [-100, 100].\n myGeometry.normalize();\n\n describe('A white torus rotates slowly against a dark gray background.');\n}\n\nfunction draw() {\n background(50);\n\n // Turn on the lights.\n lights();\n\n // Rotate around the y-axis.\n rotateY(frameCount * 0.01);\n\n // Style the torus.\n noStroke();\n\n // Draw the torus.\n model(myGeometry);\n}\n
\nThe saveObj()
function exports p5.Geometry
objects as\n3D models in the Wavefront .obj file format.\nThis way, you can use the 3D shapes you create in p5.js in other software\nfor rendering, animation, 3D printing, or more.
The exported .obj file will include the faces and vertices of the p5.Geometry
,\nas well as its texture coordinates and normals, if it has them.
The name of the file to save the model as.\n If not specified, the default file name will be 'model.obj'.
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Geometry"],"chainable":[0,false],"example":[1,[[0,"\n\nlet myModel;\nlet saveBtn;\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myModel = buildGeometry(() => {\n for (let i = 0; i < 5; i++) {\n push();\n translate(\n random(-75, 75),\n random(-75, 75),\n random(-75, 75)\n );\n sphere(random(5, 50));\n pop();\n }\n });\n\n saveBtn = createButton('Save .obj');\n saveBtn.mousePressed(() => myModel.saveObj());\n\n describe('A few spheres rotating in space');\n}\n\nfunction draw() {\n background(0);\n noStroke();\n lights();\n rotateX(millis() * 0.001);\n rotateY(millis() * 0.002);\n model(myModel);\n}\n
\nThe saveStl()
function exports p5.Geometry
objects as\n3D models in the STL stereolithography file format.\nThis way, you can use the 3D shapes you create in p5.js in other software\nfor 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\nbut less human-readable binary .stl file by passing { binary: true }
as a second parameter.
The name of the file to save the model as.\n If not specified, the default file name will be 'model.stl'.
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"options"],"description":[0,"Optional settings. Options can include a boolean binary
property, which\ncontrols whether or not a binary .stl file is saved. It defaults to false.
\nlet myModel;\nlet saveBtn1;\nlet saveBtn2;\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myModel = buildGeometry(() => {\n for (let i = 0; i < 5; i++) {\n push();\n translate(\n random(-75, 75),\n random(-75, 75),\n random(-75, 75)\n );\n sphere(random(5, 50));\n pop();\n }\n });\n\n saveBtn1 = createButton('Save .stl');\n saveBtn1.mousePressed(function() {\n myModel.saveStl();\n });\n saveBtn2 = createButton('Save binary .stl');\n saveBtn2.mousePressed(function() {\n myModel.saveStl('model.stl', { binary: true });\n });\n\n describe('A few spheres rotating in space');\n}\n\nfunction draw() {\n background(0);\n noStroke();\n lights();\n rotateX(millis() * 0.001);\n rotateY(millis() * 0.002);\n model(myModel);\n}\n
\nAn array that lists the texture coordinates for each of the geometry's\nvertices.
\nIn order for texture() to work, the geometry\nneeds a way to map the points on its surface to the pixels in a\nrectangular image that's used as a texture. The geometry's vertex at\ncoordinates (x, y, z)
maps to the texture image's pixel at coordinates\n(u, v)
.
The myGeometry.uvs
array stores the (u, v)
coordinates for each\nvertex in the order it was added to the geometry. For example, the\nfirst vertex, myGeometry.vertices[0]
, has its (u, v)
coordinates\nstored at myGeometry.uvs[0]
and myGeometry.uvs[1]
.
\nlet img;\n\n// Load the image and create a p5.Image object.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n // Create p5.Geometry objects.\n let geom1 = buildGeometry(createShape);\n let geom2 = buildGeometry(createShape);\n\n // Left (original).\n push();\n translate(-25, 0, 0);\n texture(img);\n noStroke();\n model(geom1);\n pop();\n\n // Set geom2's texture coordinates.\n geom2.uvs = [0.25, 0.25, 0.75, 0.25, 0.25, 0.75, 0.75, 0.75];\n\n // Right (zoomed in).\n push();\n translate(25, 0, 0);\n texture(img);\n noStroke();\n model(geom2);\n pop();\n\n describe(\n 'Two photos of a ceiling on a gray background. The photo on the right zooms in to the center of the photo.'\n );\n}\n\nfunction createShape() {\n plane(40);\n}\n
\nAn array with the vectors that are normal to the geometry's vertices.
\nA face's orientation is defined by its normal vector which points out\nof the face and is normal (perpendicular) to the surface. Calling\nmyGeometry.computeNormals()
first calculates each face's normal\nvector. Then it calculates the normal vector for each vertex by\naveraging the normal vectors of the faces surrounding the vertex. The\nvertex normals are stored as p5.Vector\nobjects in the myGeometry.vertexNormals
array.
\n// Click and drag the mouse to view the scene from different angles.\n\nlet myGeometry;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Geometry object.\n beginGeometry();\n torus(30, 15, 10, 8);\n myGeometry = endGeometry();\n\n // Compute the vertex normals.\n myGeometry.computeNormals();\n\n describe(\n 'A white torus rotates against a dark gray background. Red lines extend outward from its vertices.'\n );\n}\n\nfunction draw() {\n background(50);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n lights();\n\n // Rotate the coordinate system.\n rotateY(frameCount * 0.01);\n\n // Style the p5.Geometry object.\n stroke(0);\n\n // Display the p5.Geometry object.\n model(myGeometry);\n\n // Style the normal vectors.\n stroke(255, 0, 0);\n\n // Iterate over the vertices and vertexNormals arrays.\n for (let i = 0; i < myGeometry.vertices.length; i += 1) {\n\n // Get the vertex p5.Vector object.\n let v = myGeometry.vertices[i];\n\n // Get the vertex normal p5.Vector object.\n let n = myGeometry.vertexNormals[i];\n\n // Calculate a point along the vertex normal.\n let p = p5.Vector.mult(n, 8);\n\n // Draw the vertex normal as a red line.\n push();\n translate(v);\n line(0, 0, 0, p.x, p.y, p.z);\n pop();\n }\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nlet myGeometry;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Geometry object.\n myGeometry = new p5.Geometry();\n\n // Create p5.Vector objects to position the vertices.\n let v0 = createVector(-40, 0, 0);\n let v1 = createVector(0, -40, 0);\n let v2 = createVector(0, 40, 0);\n let v3 = createVector(40, 0, 0);\n\n // Add the vertices to the p5.Geometry object's vertices array.\n myGeometry.vertices.push(v0, v1, v2, v3);\n\n // Compute the faces array.\n myGeometry.computeFaces();\n\n // Compute the surface normals.\n myGeometry.computeNormals();\n\n describe('A red square drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Add a white point light.\n pointLight(255, 255, 255, 0, 0, 10);\n\n // Style the p5.Geometry object.\n noStroke();\n fill(255, 0, 0);\n\n // Display the p5.Geometry object.\n model(myGeometry);\n}\n
\nAn array with the geometry's vertices.
\nThe geometry's vertices are stored as\np5.Vector objects in the myGeometry.vertices
\narray. The geometry's first vertex is the\np5.Vector object at myGeometry.vertices[0]
,\nits second vertex is myGeometry.vertices[1]
, its third vertex is\nmyGeometry.vertices[2]
, and so on.
\n// Click and drag the mouse to view the scene from different angles.\n\nlet myGeometry;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Geometry object.\n myGeometry = new p5.Geometry();\n\n // Create p5.Vector objects to position the vertices.\n let v0 = createVector(-40, 0, 0);\n let v1 = createVector(0, -40, 0);\n let v2 = createVector(40, 0, 0);\n\n // Add the vertices to the p5.Geometry object's vertices array.\n myGeometry.vertices.push(v0, v1, v2);\n\n describe('A white triangle drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Draw the p5.Geometry object.\n model(myGeometry);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nlet myGeometry;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Geometry object.\n beginGeometry();\n torus(30, 15, 10, 8);\n myGeometry = endGeometry();\n\n describe('A white torus rotates slowly against a dark gray background. Red spheres mark its vertices.');\n}\n\nfunction draw() {\n background(50);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n lights();\n\n // Rotate the coordinate system.\n rotateY(frameCount * 0.01);\n\n // Style the p5.Geometry object.\n fill(255);\n stroke(0);\n\n // Display the p5.Geometry object.\n model(myGeometry);\n\n // Style the vertices.\n fill(255, 0, 0);\n noStroke();\n\n // Iterate over the vertices array.\n for (let v of myGeometry.vertices) {\n // Draw a sphere to mark the vertex.\n push();\n translate(v);\n sphere(2.5);\n pop();\n }\n}\n
\nGets the alpha (transparency) value of a color.
\nalpha()
extracts the alpha value from a\np5.Color object, an array of color components, or\na CSS color string.
p5.Color object, array of\n color components, or CSS color string.
\n"],"type":[0,"p5.Color|Number[]|String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"the alpha value."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let c = color(0, 126, 255, 102);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'alphaValue' to 102.\n let alphaValue = alpha(c);\n\n // Draw the right rectangle.\n fill(alphaValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light blue and the right one is charcoal gray.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a color array.\n let c = [0, 126, 255, 102];\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'alphaValue' to 102.\n let alphaValue = alpha(c);\n\n // Draw the left rectangle.\n fill(alphaValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light blue and the right one is charcoal gray.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a CSS color string.\n let c = 'rgba(0, 126, 255, 0.4)';\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'alphaValue' to 102.\n let alphaValue = alpha(c);\n\n // Draw the right rectangle.\n fill(alphaValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light blue and the right one is charcoal gray.');\n}\n
\nGets the blue value of a color.
\nblue()
extracts the blue value from a\np5.Color object, an array of color components, or\na CSS color string.
By default, blue()
returns a color's blue value in the range 0\nto 255. If the colorMode() is set to RGB, it\nreturns the blue value in the given range.
p5.Color object, array of\n color components, or CSS color string.
\n"],"type":[0,"p5.Color|Number[]|String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"the blue value."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object using RGB values.\n let c = color(175, 100, 220);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'blueValue' to 220.\n let blueValue = blue(c);\n\n // Draw the right rectangle.\n fill(0, 0, blueValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is royal blue.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a color array.\n let c = [175, 100, 220];\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'blueValue' to 220.\n let blueValue = blue(c);\n\n // Draw the right rectangle.\n fill(0, 0, blueValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is royal blue.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a CSS color string.\n let c = 'rgb(175, 100, 220)';\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'blueValue' to 220.\n let blueValue = blue(c);\n\n // Draw the right rectangle.\n fill(0, 0, blueValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is royal blue.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use RGB color with values in the range 0-100.\n colorMode(RGB, 100);\n\n // Create a p5.Color object using RGB values.\n let c = color(69, 39, 86);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'blueValue' to 86.\n let blueValue = blue(c);\n\n // Draw the right rectangle.\n fill(0, 0, blueValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is royal blue.');\n}\n
\nGets the brightness value of a color.
\nbrightness()
extracts the HSB brightness value from a\np5.Color object, an array of color components, or\na CSS color string.
By default, brightness()
returns a color's HSB brightness in the range 0\nto 100. If the colorMode() is set to HSB, it\nreturns the brightness value in the given range.
p5.Color object, array of\n color components, or CSS color string.
\n"],"type":[0,"p5.Color|Number[]|String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"the brightness value."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use HSB color.\n colorMode(HSB);\n\n // Create a p5.Color object.\n let c = color(0, 50, 100);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'brightValue' to 100.\n let brightValue = brightness(c);\n\n // Draw the right rectangle.\n fill(brightValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is white.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use HSB color.\n colorMode(HSB);\n\n // Create a color array.\n let c = [0, 50, 100];\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'brightValue' to 100.\n let brightValue = brightness(c);\n\n // Draw the right rectangle.\n fill(brightValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is white.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use HSB color.\n colorMode(HSB);\n\n // Create a CSS color string.\n let c = 'rgb(255, 128, 128)';\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'brightValue' to 100.\n let brightValue = brightness(c);\n\n // Draw the right rectangle.\n fill(brightValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is white.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use HSB color with values in the range 0-255.\n colorMode(HSB, 255);\n\n // Create a p5.Color object.\n let c = color(0, 127, 255);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'brightValue' to 255.\n let brightValue = brightness(c);\n\n // Draw the right rectangle.\n fill(brightValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is white.');\n}\n
\nCreates a p5.Color object.
\nBy default, the parameters are interpreted as RGB values. Calling\ncolor(255, 204, 0)
will return a bright yellow color. The way these\nparameters are interpreted may be changed with the\ncolorMode() function.
The version of color()
with one parameter interprets the value one of two\nways. If the parameter is a number, it's interpreted as a grayscale value.\nIf 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\ngrayscale value. The second parameter sets the alpha (transparency) value.
The version of color()
with three parameters interprets them as RGB, HSB,\nor HSL colors, depending on the current colorMode()
.
The version of color()
with four parameters interprets them as RGBA, HSBA,\nor HSLA colors, depending on the current colorMode()
. The last parameter\nsets the alpha (transparency) value.
number specifying value between white and black.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"alpha"],"description":[0,"alpha value relative to current color range\n (default is 0-255).
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,"red or hue value relative to\n the current color range.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,"green or saturation value\n relative to the current color range.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,"blue or brightness value\n relative to the current color range.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"alpha"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"value"],"description":[0,"a color string.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"values"],"description":[0,"an array containing the red, green, blue,\n and alpha components of the color.
\n"],"type":[0,"Number[]"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,""],"type":[0,"p5.Color"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"resulting color."],"type":[0,"p5.Color"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object using RGB values.\n let c = color(255, 204, 0);\n\n // Draw the square.\n fill(c);\n noStroke();\n square(30, 20, 55);\n\n describe('A yellow square on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object using RGB values.\n let c1 = color(255, 204, 0);\n\n // Draw the left circle.\n fill(c1);\n noStroke();\n circle(25, 25, 80);\n\n // Create a p5.Color object using a grayscale value.\n let c2 = color(65);\n\n // Draw the right circle.\n fill(c2);\n circle(75, 75, 80);\n\n describe(\n 'Two circles on a gray canvas. The circle in the top-left corner is yellow and the one at the bottom-right is gray.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object using a named color.\n let c = color('magenta');\n\n // Draw the square.\n fill(c);\n noStroke();\n square(20, 20, 60);\n\n describe('A magenta square on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object using a hex color code.\n let c1 = color('#0f0');\n\n // Draw the left rectangle.\n fill(c1);\n noStroke();\n rect(0, 10, 45, 80);\n\n // Create a p5.Color object using a hex color code.\n let c2 = color('#00ff00');\n\n // Draw the right rectangle.\n fill(c2);\n rect(55, 10, 45, 80);\n\n describe('Two bright green rectangles on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object using a RGB color string.\n let c1 = color('rgb(0, 0, 255)');\n\n // Draw the top-left square.\n fill(c1);\n square(10, 10, 35);\n\n // Create a p5.Color object using a RGB color string.\n let c2 = color('rgb(0%, 0%, 100%)');\n\n // Draw the top-right square.\n fill(c2);\n square(55, 10, 35);\n\n // Create a p5.Color object using a RGBA color string.\n let c3 = color('rgba(0, 0, 255, 1)');\n\n // Draw the bottom-left square.\n fill(c3);\n square(10, 55, 35);\n\n // Create a p5.Color object using a RGBA color string.\n let c4 = color('rgba(0%, 0%, 100%, 1)');\n\n // Draw the bottom-right square.\n fill(c4);\n square(55, 55, 35);\n\n describe('Four blue squares in the corners of a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object using a HSL color string.\n let c1 = color('hsl(160, 100%, 50%)');\n\n // Draw the left rectangle.\n noStroke();\n fill(c1);\n rect(0, 10, 45, 80);\n\n // Create a p5.Color object using a HSLA color string.\n let c2 = color('hsla(160, 100%, 50%, 0.5)');\n\n // Draw the right rectangle.\n fill(c2);\n rect(55, 10, 45, 80);\n\n describe('Two sea green rectangles. A darker rectangle on the left and a brighter one on the right.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object using a HSB color string.\n let c1 = color('hsb(160, 100%, 50%)');\n\n // Draw the left rectangle.\n noStroke();\n fill(c1);\n rect(0, 10, 45, 80);\n\n // Create a p5.Color object using a HSBA color string.\n let c2 = color('hsba(160, 100%, 50%, 0.5)');\n\n // Draw the right rectangle.\n fill(c2);\n rect(55, 10, 45, 80);\n\n describe('Two green rectangles. A darker rectangle on the left and a brighter one on the right.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object using RGB values.\n let c1 = color(50, 55, 100);\n\n // Draw the left rectangle.\n fill(c1);\n rect(0, 10, 45, 80);\n\n // Switch the color mode to HSB.\n colorMode(HSB, 100);\n\n // Create a p5.Color object using HSB values.\n let c2 = color(50, 55, 100);\n\n // Draw the right rectangle.\n fill(c2);\n rect(55, 10, 45, 80);\n\n describe('Two blue rectangles. A darker rectangle on the left and a brighter one on the right.');\n}\n
\nGets the green value of a color.
\ngreen()
extracts the green value from a\np5.Color object, an array of color components, or\na CSS color string.
By default, green()
returns a color's green value in the range 0\nto 255. If the colorMode() is set to RGB, it\nreturns the green value in the given range.
p5.Color object, array of\n color components, or CSS color string.
\n"],"type":[0,"p5.Color|Number[]|String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"the green value."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let c = color(175, 100, 220);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'greenValue' to 100.\n let greenValue = green(c);\n\n // Draw the right rectangle.\n fill(0, greenValue, 0);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is dark green.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a color array.\n let c = [175, 100, 220];\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'greenValue' to 100.\n let greenValue = green(c);\n\n // Draw the right rectangle.\n fill(0, greenValue, 0);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is dark green.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a CSS color string.\n let c = 'rgb(175, 100, 220)';\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'greenValue' to 100.\n let greenValue = green(c);\n\n // Draw the right rectangle.\n fill(0, greenValue, 0);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is dark green.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use RGB color with values in the range 0-100.\n colorMode(RGB, 100);\n\n // Create a p5.Color object using RGB values.\n let c = color(69, 39, 86);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'greenValue' to 39.\n let greenValue = green(c);\n\n // Draw the right rectangle.\n fill(0, greenValue, 0);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is dark green.');\n}\n
\nGets the hue value of a color.
\nhue()
extracts the hue value from a\np5.Color object, an array of color components, or\na CSS color string.
Hue describes a color's position on the color wheel. By default, hue()
\nreturns a color's HSL hue in the range 0 to 360. If the\ncolorMode() is set to HSB or HSL, it returns the hue\nvalue in the given mode.
p5.Color object, array of\n color components, or CSS color string.
\n"],"type":[0,"p5.Color|Number[]|String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"the hue value."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use HSL color.\n colorMode(HSL);\n\n // Create a p5.Color object.\n let c = color(0, 50, 100);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 20, 35, 60);\n\n // Set 'hueValue' to 0.\n let hueValue = hue(c);\n\n // Draw the right rectangle.\n fill(hueValue);\n rect(50, 20, 35, 60);\n\n describe(\n 'Two rectangles. The rectangle on the left is salmon pink and the one on the right is black.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use HSL color.\n colorMode(HSL);\n\n // Create a color array.\n let c = [0, 50, 100];\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 20, 35, 60);\n\n // Set 'hueValue' to 0.\n let hueValue = hue(c);\n\n // Draw the right rectangle.\n fill(hueValue);\n rect(50, 20, 35, 60);\n\n describe(\n 'Two rectangles. The rectangle on the left is salmon pink and the one on the right is black.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use HSL color.\n colorMode(HSL);\n\n // Create a CSS color string.\n let c = 'rgb(255, 128, 128)';\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 20, 35, 60);\n\n // Set 'hueValue' to 0.\n let hueValue = hue(c);\n\n // Draw the right rectangle.\n fill(hueValue);\n rect(50, 20, 35, 60);\n\n describe(\n 'Two rectangles. The rectangle on the left is salmon pink and the one on the right is black.'\n );\n}\n
\nBlends two colors to find a third color between them.
\nThe amt
parameter specifies the amount to interpolate between the two\nvalues. 0 is equal to the first color, 0.1 is very near the first color,\n0.5 is halfway between the two colors, and so on. Negative numbers are set\nto 0. Numbers greater than 1 are set to 1. This differs from the behavior of\nlerp. It's necessary because numbers outside of the\ninterval [0, 1] will produce strange and unexpected colors.
The way that colors are interpolated depends on the current\ncolorMode().
\n"],"line":[0,949],"params":[1,[[0,{"name":[0,"c1"],"description":[0,"interpolate from this color (any value created by the color() function).
\n"],"type":[0,"p5.Color"]}],[0,{"name":[0,"c2"],"description":[0,"interpolate to this color (any value created by the color() function).
\n"],"type":[0,"p5.Color"]}],[0,{"name":[0,"amt"],"description":[0,"number between 0 and 1.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"interpolated color."],"type":[0,"p5.Color"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create p5.Color objects to interpolate between.\n let from = color(218, 165, 32);\n let to = color(72, 61, 139);\n\n // Create intermediate colors.\n let interA = lerpColor(from, to, 0.33);\n let interB = lerpColor(from, to, 0.66);\n\n // Draw the left rectangle.\n noStroke();\n fill(from);\n rect(10, 20, 20, 60);\n\n // Draw the left-center rectangle.\n fill(interA);\n rect(30, 20, 20, 60);\n\n // Draw the right-center rectangle.\n fill(interB);\n rect(50, 20, 20, 60);\n\n // Draw the right rectangle.\n fill(to);\n rect(70, 20, 20, 60);\n\n describe(\n 'Four rectangles. From left to right, the rectangles are tan, brown, brownish purple, and purple.'\n );\n}\n
\nGets the lightness value of a color.
\nlightness()
extracts the HSL lightness value from a\np5.Color object, an array of color components, or\na CSS color string.
By default, lightness()
returns a color's HSL lightness in the range 0\nto 100. If the colorMode() is set to HSL, it\nreturns the lightness value in the given range.
p5.Color object, array of\n color components, or CSS color string.
\n"],"type":[0,"p5.Color|Number[]|String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"the lightness value."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Use HSL color.\n colorMode(HSL);\n\n // Create a p5.Color object using HSL values.\n let c = color(0, 100, 75);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'lightValue' to 75.\n let lightValue = lightness(c);\n\n // Draw the right rectangle.\n fill(lightValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is gray.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Use HSL color.\n colorMode(HSL);\n\n // Create a color array.\n let c = [0, 100, 75];\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'lightValue' to 75.\n let lightValue = lightness(c);\n\n // Draw the right rectangle.\n fill(lightValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is gray.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Use HSL color.\n colorMode(HSL);\n\n // Create a CSS color string.\n let c = 'rgb(255, 128, 128)';\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'lightValue' to 75.\n let lightValue = lightness(c);\n\n // Draw the right rectangle.\n fill(lightValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is gray.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Use HSL color with values in the range 0-255.\n colorMode(HSL, 255);\n\n // Create a p5.Color object using HSL values.\n let c = color(0, 255, 191.5);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'lightValue' to 191.5.\n let lightValue = lightness(c);\n\n // Draw the right rectangle.\n fill(lightValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is gray.');\n}\n
\nBlends multiple colors to find a color between them.
\nThe amt
parameter specifies the amount to interpolate between the color\nstops which are colors at each amt
value \"location\" with amt
values\nthat are between 2 color stops interpolating between them based on its relative\ndistance to both.
The way that colors are interpolated depends on the current\ncolorMode().
\n"],"line":[0,1079],"params":[1,[[0,{"name":[0,"colors_stops"],"description":[0,"color stops to interpolate from
\n"],"type":[0,"[p5.Color, Number][]"]}],[0,{"name":[0,"amt"],"description":[0,"number to use to interpolate relative to color stops
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"interpolated color."],"type":[0,"p5.Color"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(400, 400);\n}\n\nfunction draw() {\n // The background goes from white to red to green to blue fill\n background(paletteLerp([\n ['white', 0],\n ['red', 0.05],\n ['green', 0.25],\n ['blue', 1]\n ], millis() / 10000 % 1));\n}\n
\nGets the red value of a color.
\nred()
extracts the red value from a\np5.Color object, an array of color components, or\na CSS color string.
By default, red()
returns a color's red value in the range 0\nto 255. If the colorMode() is set to RGB, it\nreturns the red value in the given range.
p5.Color object, array of\n color components, or CSS color string.
\n"],"type":[0,"p5.Color|Number[]|String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"the red value."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let c = color(175, 100, 220);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'redValue' to 175.\n let redValue = red(c);\n\n // Draw the right rectangle.\n fill(redValue, 0, 0);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is red.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a color array.\n let c = [175, 100, 220];\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'redValue' to 175.\n let redValue = red(c);\n\n // Draw the right rectangle.\n fill(redValue, 0, 0);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is red.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a CSS color string.\n let c = 'rgb(175, 100, 220)';\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'redValue' to 175.\n let redValue = red(c);\n\n // Draw the right rectangle.\n fill(redValue, 0, 0);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is red.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use RGB color with values in the range 0-100.\n colorMode(RGB, 100);\n\n // Create a p5.Color object.\n let c = color(69, 39, 86);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'redValue' to 69.\n let redValue = red(c);\n\n // Draw the right rectangle.\n fill(redValue, 0, 0);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is red.');\n}\n
\nGets the saturation value of a color.
\nsaturation()
extracts the saturation value from a\np5.Color object, an array of color components, or\na CSS color string.
Saturation is scaled differently in HSB and HSL. By default, saturation()
\nreturns a color's HSL saturation in the range 0 to 100. If the\ncolorMode() is set to HSB or HSL, it returns the\nsaturation value in the given mode.
p5.Color object, array of\n color components, or CSS color string.
\n"],"type":[0,"p5.Color|Number[]|String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"the saturation value"],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Use HSB color.\n colorMode(HSB);\n\n // Create a p5.Color object.\n let c = color(0, 50, 100);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'satValue' to 50.\n let satValue = saturation(c);\n\n // Draw the right rectangle.\n fill(satValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is dark gray.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Use HSB color.\n colorMode(HSB);\n\n // Create a color array.\n let c = [0, 50, 100];\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'satValue' to 100.\n let satValue = saturation(c);\n\n // Draw the right rectangle.\n fill(satValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is gray.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Use HSB color.\n colorMode(HSB);\n\n // Create a CSS color string.\n let c = 'rgb(255, 128, 128)';\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'satValue' to 100.\n let satValue = saturation(c);\n\n // Draw the right rectangle.\n fill(satValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is gray.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Use HSL color.\n colorMode(HSL);\n\n // Create a p5.Color object.\n let c = color(0, 100, 75);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'satValue' to 100.\n let satValue = saturation(c);\n\n // Draw the right rectangle.\n fill(satValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is white.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Use HSL color with values in the range 0-255.\n colorMode(HSL, 255);\n\n // Create a p5.Color object.\n let c = color(0, 255, 191.5);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'satValue' to 255.\n let satValue = saturation(c);\n\n // Draw the right rectangle.\n fill(satValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is white.');\n}\n
\nSets the color used for the background of the canvas.
\nBy default, the background is transparent. background()
is typically used\nwithin draw() to clear the display window at the\nbeginning of each frame. It can also be used inside\nsetup() to set the background on the first frame\nof animation.
The version of background()
with one parameter interprets the value one\nof four ways. If the parameter is a Number
, it's interpreted as a grayscale\nvalue. If the parameter is a String
, it's interpreted as a CSS color string.\nRGB, RGBA, HSL, HSLA, hex, and named color strings are supported. If the\nparameter is a p5.Color object, it will be used as\nthe background color. If the parameter is a\np5.Image object, it will be used as the background\nimage.
The version of background()
with two parameters interprets the first one\nas a grayscale value. The second parameter sets the alpha (transparency)\nvalue.
The version of background()
with three parameters interprets them as RGB,\nHSB, or HSL colors, depending on the current\ncolorMode(). By default, colors are specified\nin RGB values. Calling background(255, 204, 0)
sets the background a bright\nyellow color.
any value created by the color() function
\n"],"type":[0,"p5.Color"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"colorstring"],"description":[0,"color string, possible formats include: integer\n rgb() or rgba(), percentage rgb() or rgba(),\n 3-digit hex, 6-digit hex.
\n"],"type":[0,"String"]}],[0,{"name":[0,"a"],"description":[0,"opacity of the background relative to current\n color range (default is 0-255).
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"gray"],"description":[0,"specifies a value between white and black.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"a"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,"red value if color mode is RGB, or hue value if color mode is HSB.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,"green value if color mode is RGB, or saturation value if color mode is HSB.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,"blue value if color mode is RGB, or brightness value if color mode is HSB.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"a"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"values"],"description":[0,"an array containing the red, green, blue\n and alpha components of the color.
\n"],"type":[0,"Number[]"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"image"],"description":[0,"image created with loadImage()\n or createImage(),\n to set as background.\n (must be same size as the sketch window).
\n"],"type":[0,"p5.Image"]}],[0,{"name":[0,"a"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n // A grayscale value.\n background(51);\n\n describe('A canvas with a dark charcoal gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // A grayscale value and an alpha value.\n background(51, 0.4);\n describe('A canvas with a transparent gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // R, G & B values.\n background(255, 204, 0);\n\n describe('A canvas with a yellow background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use HSB color.\n colorMode(HSB);\n\n // H, S & B values.\n background(255, 204, 100);\n\n describe('A canvas with a royal blue background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // A CSS named color.\n background('red');\n\n describe('A canvas with a red background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Three-digit hex RGB notation.\n background('#fae');\n\n describe('A canvas with a pink background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Six-digit hex RGB notation.\n background('#222222');\n\n describe('A canvas with a black background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Integer RGB notation.\n background('rgb(0, 255, 0)');\n\n describe('A canvas with a bright green background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Integer RGBA notation.\n background('rgba(0, 255, 0, 0.25)');\n\n describe('A canvas with a transparent green background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Percentage RGB notation.\n background('rgb(100%, 0%, 10%)');\n\n describe('A canvas with a red background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Percentage RGBA notation.\n background('rgba(100%, 0%, 100%, 0.5)');\n\n describe('A canvas with a transparent purple background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // A p5.Color object.\n let c = color(0, 0, 255);\n background(c);\n\n describe('A canvas with a blue background.');\n}\n
\nStarts defining a shape that will mask any shapes drawn afterward.
\nAny shapes drawn between beginClip()
and\nendClip() will add to the mask shape. The mask\nwill apply to anything drawn after endClip().
The parameter, options
, is optional. If an object with an invert
\nproperty is passed, as in beginClip({ invert: true })
, it will be used to\nset the masking mode. { invert: true }
inverts the mask, creating holes\nin shapes that are masked. invert
is false
by default.
Masks can be contained between the\npush() and pop() functions.\nDoing so allows unmasked shapes to be drawn after masked shapes.
\nMasks can also be defined in a callback function that's passed to\nclip().
\n"],"line":[0,13],"params":[1,[[0,{"name":[0,"options"],"description":[0,"an object containing clip settings.
\n"],"type":[0,"Object"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a mask.\n beginClip();\n triangle(15, 37, 30, 13, 43, 37);\n circle(45, 45, 7);\n endClip();\n\n // Draw a backing shape.\n square(5, 5, 45);\n\n describe('A white triangle and circle on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an inverted mask.\n beginClip({ invert: true });\n triangle(15, 37, 30, 13, 43, 37);\n circle(45, 45, 7);\n endClip();\n\n // Draw a backing shape.\n square(5, 5, 45);\n\n 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.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n noStroke();\n\n // Draw a masked shape.\n push();\n // Create a mask.\n beginClip();\n triangle(15, 37, 30, 13, 43, 37);\n circle(45, 45, 7);\n endClip();\n\n // Draw a backing shape.\n square(5, 5, 45);\n pop();\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Draw an inverted masked shape.\n push();\n // Create an inverted mask.\n beginClip({ invert: true });\n triangle(15, 37, 30, 13, 43, 37);\n circle(45, 45, 7);\n endClip();\n\n // Draw a backing shape.\n square(5, 5, 45);\n pop();\n\n 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.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A silhouette of a rotating torus colored fuchsia.');\n}\n\nfunction draw() {\n background(200);\n\n // Create a mask.\n beginClip();\n push();\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n scale(0.5);\n torus(30, 15);\n pop();\n endClip();\n\n // Draw a backing shape.\n noStroke();\n fill('fuchsia');\n plane(100);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A silhouette of a rotating torus colored with a gradient from cyan to purple.');\n}\n\nfunction draw() {\n background(200);\n\n // Create a mask.\n beginClip();\n push();\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n scale(0.5);\n torus(30, 15);\n pop();\n endClip();\n\n // Draw a backing shape.\n noStroke();\n beginShape(QUAD_STRIP);\n fill(0, 255, 255);\n vertex(-width / 2, -height / 2);\n vertex(width / 2, -height / 2);\n fill(100, 0, 100);\n vertex(-width / 2, height / 2);\n vertex(width / 2, height / 2);\n endShape();\n}\n
\nClears the pixels on the canvas.
\nclear()
makes every pixel 100% transparent. Calling clear()
doesn't\nclear objects created by createX()
functions such as\ncreateGraphics(),\ncreateVideo(), and\ncreateImg(). These objects will remain\nunchanged after calling clear()
and can be redrawn.
In WebGL mode, this function can clear the screen to a specific color. It\ninterprets four numeric parameters as normalized RGBA color values. It also\nclears the depth buffer. If you are not using the WebGL renderer, these\nparameters will have no effect.
\n"],"line":[0,655],"params":[1,[[0,{"name":[0,"r"],"description":[0,"normalized red value.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"g"],"description":[0,"normalized green value.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"b"],"description":[0,"normalized blue value.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"a"],"description":[0,"normalized alpha value.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A gray square. White circles are drawn as the user moves the mouse. The circles disappear when the user presses the mouse.');\n}\n\nfunction draw() {\n circle(mouseX, mouseY, 20);\n}\n\nfunction mousePressed() {\n clear();\n background(200);\n}\n
\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n\n pg = createGraphics(60, 60);\n pg.background(200);\n pg.noStroke();\n pg.circle(pg.width / 2, pg.height / 2, 15);\n image(pg, 20, 20);\n\n describe('A white circle drawn on a gray square. The square gets smaller when the mouse is pressed.');\n}\n\nfunction mousePressed() {\n clear();\n image(pg, 20, 20);\n}\n
\nDefines a shape that will mask any shapes drawn afterward.
\nThe first parameter, callback
, is a function that defines the mask.\nAny shapes drawn in callback
will add to the mask shape. The mask\nwill apply to anything drawn after clip()
is called.
The second parameter, options
, is optional. If an object with an invert
\nproperty is passed, as in beginClip({ invert: true })
, it will be used to\nset the masking mode. { invert: true }
inverts the mask, creating holes\nin shapes that are masked. invert
is false
by default.
Masks can be contained between the\npush() and pop() functions.\nDoing so allows unmasked shapes to be drawn after masked shapes.
\nMasks can also be defined with beginClip()\nand endClip().
\n"],"line":[0,222],"params":[1,[[0,{"name":[0,"callback"],"description":[0,"a function that draws the mask shape.
\n"],"type":[0,"Function"]}],[0,{"name":[0,"options"],"description":[0,"an object containing clip settings.
\n"],"type":[0,"Object"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a mask.\n clip(mask);\n\n // Draw a backing shape.\n square(5, 5, 45);\n\n describe('A white triangle and circle on a gray background.');\n}\n\n// Declare a function that defines the mask.\nfunction mask() {\n triangle(15, 37, 30, 13, 43, 37);\n circle(45, 45, 7);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an inverted mask.\n clip(mask, { invert: true });\n\n // Draw a backing shape.\n square(5, 5, 45);\n\n 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.');\n}\n\n// Declare a function that defines the mask.\nfunction mask() {\n triangle(15, 37, 30, 13, 43, 37);\n circle(45, 45, 7);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n noStroke();\n\n // Draw a masked shape.\n push();\n // Create a mask.\n clip(mask);\n\n // Draw a backing shape.\n square(5, 5, 45);\n pop();\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Draw an inverted masked shape.\n push();\n // Create an inverted mask.\n clip(mask, { invert: true });\n\n // Draw a backing shape.\n square(5, 5, 45);\n pop();\n\n 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.');\n}\n\n// Declare a function that defines the mask.\nfunction mask() {\n triangle(15, 37, 30, 13, 43, 37);\n circle(45, 45, 7);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A silhouette of a rotating torus colored fuchsia.');\n}\n\nfunction draw() {\n background(200);\n\n // Create a mask.\n clip(mask);\n\n // Draw a backing shape.\n noStroke();\n fill('fuchsia');\n plane(100);\n}\n\n// Declare a function that defines the mask.\nfunction mask() {\n push();\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n scale(0.5);\n torus(30, 15);\n pop();\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A silhouette of a rotating torus colored with a gradient from cyan to purple.');\n}\n\nfunction draw() {\n background(200);\n\n // Create a mask.\n clip(mask);\n\n // Draw a backing shape.\n noStroke();\n beginShape(QUAD_STRIP);\n fill(0, 255, 255);\n vertex(-width / 2, -height / 2);\n vertex(width / 2, -height / 2);\n fill(100, 0, 100);\n vertex(-width / 2, height / 2);\n vertex(width / 2, height / 2);\n endShape();\n}\n\n// Declare a function that defines the mask.\nfunction mask() {\n push();\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n scale(0.5);\n torus(30, 15);\n pop();\n}\n
\nChanges the way color values are interpreted.
\nBy default, the Number
parameters for fill(),\nstroke(),\nbackground(), and\ncolor() are defined by values between 0 and 255\nusing the RGB color model. This is equivalent to calling\ncolorMode(RGB, 255)
. Pure red is color(255, 0, 0)
in this model.
Calling colorMode(RGB, 100)
sets colors to use RGB color values\nbetween 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\ninstead of RGB. Pure red is color(0, 100, 100)
in HSB and\ncolor(0, 100, 50)
in HSL.
p5.Color objects remember the mode that they were\ncreated in. Changing modes doesn't affect their appearance.
\n"],"line":[0,733],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"mode"],"description":[0,"either RGB, HSB or HSL, corresponding to\n Red/Green/Blue and Hue/Saturation/Brightness\n (or Lightness).
\n"],"type":[0,"Constant"]}],[0,{"name":[0,"max"],"description":[0,"range for all values.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"mode"],"description":[0,""],"type":[0,"Constant"]}],[0,{"name":[0,"max1"],"description":[0,"range for the red or hue depending on the\n current color mode.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"max2"],"description":[0,"range for the green or saturation depending\n on the current color mode.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"max3"],"description":[0,"range for the blue or brightness/lightness\n depending on the current color mode.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"maxA"],"description":[0,"range for the alpha.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Fill with pure red.\n fill(255, 0, 0);\n\n circle(50, 50, 25);\n\n describe('A gray square with a red circle at its center.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use RGB color with values in the range 0-100.\n colorMode(RGB, 100);\n\n // Fill with pure red.\n fill(100, 0, 0);\n\n circle(50, 50, 25);\n\n describe('A gray square with a red circle at its center.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use HSB color.\n colorMode(HSB);\n\n // Fill with pure red.\n fill(0, 100, 100);\n\n circle(50, 50, 25);\n\n describe('A gray square with a red circle at its center.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use HSL color.\n colorMode(HSL);\n\n // Fill with pure red.\n fill(0, 100, 50);\n\n circle(50, 50, 25);\n\n describe('A gray square with a red circle at its center.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use RGB color with values in the range 0-100.\n colorMode(RGB, 100);\n\n for (let x = 0; x < 100; x += 1) {\n for (let y = 0; y < 100; y += 1) {\n stroke(x, y, 0);\n point(x, y);\n }\n }\n\n describe(\n 'A diagonal green to red gradient from bottom-left to top-right with shading transitioning to black at top-left corner.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use HSB color with values in the range 0-100.\n colorMode(HSB, 100);\n\n for (let x = 0; x < 100; x += 1) {\n for (let y = 0; y < 100; y += 1) {\n stroke(x, y, 100);\n point(x, y);\n }\n }\n\n describe('A rainbow gradient from left-to-right. Brightness transitions to white at the top.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Color object.\n let myColor = color(180, 175, 230);\n background(myColor);\n\n // Use RGB color with values in the range 0-1.\n colorMode(RGB, 1);\n\n // Get the red, green, and blue color components.\n let redValue = red(myColor);\n let greenValue = green(myColor);\n let blueValue = blue(myColor);\n\n // Round the color components for display.\n redValue = round(redValue, 2);\n greenValue = round(greenValue, 2);\n blueValue = round(blueValue, 2);\n\n // Display the color components.\n text(`Red: ${redValue}`, 10, 10, 80, 80);\n text(`Green: ${greenValue}`, 10, 40, 80, 80);\n text(`Blue: ${blueValue}`, 10, 70, 80, 80);\n\n describe('A purple canvas with the red, green, and blue decimal values of the color written on it.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(255);\n\n // Use RGB color with alpha values in the range 0-1.\n colorMode(RGB, 255, 255, 255, 1);\n\n noFill();\n strokeWeight(4);\n stroke(255, 0, 10, 0.3);\n circle(40, 40, 50);\n circle(50, 60, 50);\n\n describe('Two overlapping translucent pink circle outlines.');\n}\n
\nEnds defining a mask that was started with\nbeginClip().
\n"],"line":[0,190],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a mask.\n beginClip();\n triangle(15, 37, 30, 13, 43, 37);\n circle(45, 45, 7);\n endClip();\n\n // Draw a backing shape.\n square(5, 5, 45);\n\n describe('A white triangle and circle on a gray background.');\n}\n
\nStarts using shapes to erase parts of the canvas.
\nAll drawing that follows erase()
will subtract from the canvas, revealing\nthe web page underneath. The erased areas will become transparent, allowing\nthe content behind the canvas to show through. The\nfill(), stroke(), and\nblendMode() have no effect once erase()
is\ncalled.
The erase()
function has two optional parameters. The first parameter\nsets the strength of erasing by the shape's interior. A value of 0 means\nthat no erasing will occur. A value of 255 means that the shape's interior\nwill fully erase the content underneath. The default value is 255\n(full strength).
The second parameter sets the strength of erasing by the shape's edge. A\nvalue of 0 means that no erasing will occur. A value of 255 means that the\nshape's edge will fully erase the content underneath. The default value is\n255 (full strength).
\nTo cancel the erasing effect, use the noErase()\nfunction.
\nerase()
has no effect on drawing done with the\nimage() and\nbackground() functions.
a number (0-255) for the strength of erasing under a shape's interior.\n Defaults to 255, which is full strength.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"strengthStroke"],"description":[0,"a number (0-255) for the strength of erasing under a shape's edge.\n Defaults to 255, which is full strength.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(100, 100, 250);\n\n // Draw a pink square.\n fill(250, 100, 100);\n square(20, 20, 60);\n\n // Erase a circular area.\n erase();\n circle(25, 30, 30);\n noErase();\n\n describe('A purple canvas with a pink square in the middle. A circle is erased from the top-left, leaving a hole.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(100, 100, 250);\n\n // Draw a pink square.\n fill(250, 100, 100);\n square(20, 20, 60);\n\n // Erase a circular area.\n strokeWeight(5);\n erase(150, 255);\n circle(25, 30, 30);\n noErase();\n\n 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.');\n}\n
\nSets the color used to fill shapes.
\nCalling fill(255, 165, 0)
or fill('orange')
means all shapes drawn\nafter the fill command will be filled with the color orange.
The version of fill()
with one parameter interprets the value one of\nthree ways. If the parameter is a Number
, it's interpreted as a grayscale\nvalue. If the parameter is a String
, it's interpreted as a CSS color\nstring. A p5.Color object can also be provided to\nset the fill color.
The version of fill()
with three parameters interprets them as RGB, HSB,\nor HSL colors, depending on the current\ncolorMode(). The default color space is RGB,\nwith each value in the range from 0 to 255.
red value if color mode is RGB or hue value if color mode is HSB.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,"green value if color mode is RGB or saturation value if color mode is HSB.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,"blue value if color mode is RGB or brightness value if color mode is HSB.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"alpha"],"description":[0,"alpha value, controls transparency (0 - transparent, 255 - opaque).
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"value"],"description":[0,"a color string.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"gray"],"description":[0,"a grayscale value.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"alpha"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"values"],"description":[0,"an array containing the red, green, blue &\n and alpha components of the color.
\n"],"type":[0,"Number[]"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"the fill color.
\n"],"type":[0,"p5.Color"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // A grayscale value.\n fill(51);\n square(20, 20, 60);\n\n describe('A dark charcoal gray square with a black outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // R, G & B values.\n fill(255, 204, 0);\n square(20, 20, 60);\n\n describe('A yellow square with a black outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(100);\n\n // Use HSB color.\n colorMode(HSB);\n\n // H, S & B values.\n fill(255, 204, 100);\n square(20, 20, 60);\n\n describe('A royal blue square with a black outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // A CSS named color.\n fill('red');\n square(20, 20, 60);\n\n describe('A red square with a black outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Three-digit hex RGB notation.\n fill('#fae');\n square(20, 20, 60);\n\n describe('A pink square with a black outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Six-digit hex RGB notation.\n fill('#A251FA');\n square(20, 20, 60);\n\n describe('A purple square with a black outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Integer RGB notation.\n fill('rgb(0, 255, 0)');\n square(20, 20, 60);\n\n describe('A bright green square with a black outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Integer RGBA notation.\n fill('rgba(0, 255, 0, 0.25)');\n square(20, 20, 60);\n\n describe('A soft green rectange with a black outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Percentage RGB notation.\n fill('rgb(100%, 0%, 10%)');\n square(20, 20, 60);\n\n describe('A red square with a black outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Percentage RGBA notation.\n fill('rgba(100%, 0%, 100%, 0.5)');\n square(20, 20, 60);\n\n describe('A dark fuchsia square with a black outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // A p5.Color object.\n let c = color(0, 0, 255);\n fill(c);\n square(20, 20, 60);\n\n describe('A blue square with a black outline.');\n}\n
\nEnds erasing that was started with erase().
\nThe fill(), stroke(), and\nblendMode() settings will return to what they\nwere prior to calling erase().
\n"],"line":[0,1678],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(235, 145, 15);\n\n // Draw the left rectangle.\n noStroke();\n fill(30, 45, 220);\n rect(30, 10, 10, 80);\n\n // Erase a circle.\n erase();\n circle(50, 50, 60);\n noErase();\n\n // Draw the right rectangle.\n rect(70, 10, 10, 80);\n\n 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.');\n}\n
\nDisables setting the fill color for shapes.
\nCalling noFill()
is the same as making the fill completely transparent,\nas in fill(0, 0)
. If both noStroke() and\nnoFill()
are called, nothing will be drawn to the screen.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw the top square.\n square(32, 10, 35);\n\n // Draw the bottom square.\n noFill();\n square(32, 55, 35);\n\n describe('A white square on above an empty square. Both squares have black outlines.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A purple cube wireframe spinning on a black canvas.');\n}\n\nfunction draw() {\n background(0);\n\n // Style the box.\n noFill();\n stroke(100, 100, 240);\n\n // Rotate the coordinates.\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n\n // Draw the box.\n box(45);\n}\n
\nDisables drawing points, lines, and the outlines of shapes.
\nCalling noStroke()
is the same as making the stroke completely transparent,\nas in stroke(0, 0)
. If both noStroke()
and\nnoFill() are called, nothing will be drawn to the\nscreen.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n noStroke();\n square(20, 20, 60);\n\n describe('A white square with no outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A pink cube with no edge outlines spinning on a black canvas.');\n}\n\nfunction draw() {\n background(0);\n\n // Style the box.\n noStroke();\n fill(240, 150, 150);\n\n // Rotate the coordinates.\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n\n // Draw the box.\n box(45);\n}\n
\nSets the color used to draw points, lines, and the outlines of shapes.
\nCalling stroke(255, 165, 0)
or stroke('orange')
means all shapes drawn\nafter calling stroke()
will be filled with the color orange. The way\nthese parameters are interpreted may be changed with the\ncolorMode() function.
The version of stroke()
with one parameter interprets the value one of\nthree ways. If the parameter is a Number
, it's interpreted as a grayscale\nvalue. If the parameter is a String
, it's interpreted as a CSS color\nstring. A p5.Color object can also be provided to\nset the stroke color.
The version of stroke()
with two parameters interprets the first one as a\ngrayscale value. The second parameter sets the alpha (transparency) value.
The version of stroke()
with three parameters interprets them as RGB, HSB,\nor HSL colors, depending on the current colorMode()
.
The version of stroke()
with four parameters interprets them as RGBA, HSBA,\nor HSLA colors, depending on the current colorMode()
. The last parameter\nsets the alpha (transparency) value.
red value if color mode is RGB or hue value if color mode is HSB.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,"green value if color mode is RGB or saturation value if color mode is HSB.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,"blue value if color mode is RGB or brightness value if color mode is HSB.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"alpha"],"description":[0,"alpha value, controls transparency (0 - transparent, 255 - opaque).
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"value"],"description":[0,"a color string.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"gray"],"description":[0,"a grayscale value.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"alpha"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"values"],"description":[0,"an array containing the red, green, blue,\n and alpha components of the color.
\n"],"type":[0,"Number[]"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"the stroke color.
\n"],"type":[0,"p5.Color"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // A grayscale value.\n strokeWeight(4);\n stroke(51);\n square(20, 20, 60);\n\n describe('A white square with a dark charcoal gray outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // R, G & B values.\n stroke(255, 204, 0);\n strokeWeight(4);\n square(20, 20, 60);\n\n describe('A white square with a yellow outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use HSB color.\n colorMode(HSB);\n\n // H, S & B values.\n strokeWeight(4);\n stroke(255, 204, 100);\n square(20, 20, 60);\n\n describe('A white square with a royal blue outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // A CSS named color.\n stroke('red');\n strokeWeight(4);\n square(20, 20, 60);\n\n describe('A white square with a red outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Three-digit hex RGB notation.\n stroke('#fae');\n strokeWeight(4);\n square(20, 20, 60);\n\n describe('A white square with a pink outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Six-digit hex RGB notation.\n stroke('#222222');\n strokeWeight(4);\n square(20, 20, 60);\n\n describe('A white square with a black outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Integer RGB notation.\n stroke('rgb(0, 255, 0)');\n strokeWeight(4);\n square(20, 20, 60);\n\n describe('A whiite square with a bright green outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Integer RGBA notation.\n stroke('rgba(0, 255, 0, 0.25)');\n strokeWeight(4);\n square(20, 20, 60);\n\n describe('A white square with a soft green outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Percentage RGB notation.\n stroke('rgb(100%, 0%, 10%)');\n strokeWeight(4);\n square(20, 20, 60);\n\n describe('A white square with a red outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Percentage RGBA notation.\n stroke('rgba(100%, 0%, 100%, 0.5)');\n strokeWeight(4);\n square(20, 20, 60);\n\n describe('A white square with a dark fuchsia outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // A p5.Color object.\n stroke(color(0, 0, 255));\n strokeWeight(4);\n square(20, 20, 60);\n\n describe('A white square with a blue outline.');\n}\n
\nA class to describe a color.
\nEach p5.Color
object stores the color mode\nand level maxes that were active during its construction. These values are\nused to interpret the arguments passed to the object's constructor. They\nalso determine output formatting such as when\nsaturation() is called.
Color is stored internally as an array of ideal RGBA values in floating\npoint form, normalized from 0 to 1. These values are used to calculate the\nclosest screen colors, which are RGBA levels from 0 to 255. Screen colors\nare sent to the renderer.
\nWhen different color representations are calculated, the results are cached\nfor performance. These values are normalized, floating-point numbers.
\nNote: color() is the recommended way to create an\ninstance of this class.
\n"],"line":[0,318],"params":[1,[[0,{"name":[0,"pInst"],"description":[0,"pointer to p5 instance.
\n"],"type":[0,"P5"],"optional":[0,true]}],[0,{"name":[0,"vals"],"description":[0,"an array containing the color values\n for red, green, blue and alpha channel\n or CSS color.
\n"],"type":[0,"Number[]|String"]}]]],"chainable":[0,false],"methods":[0,{"toString":[0,{"description":[0,"Returns the color formatted as a String
.
Calling myColor.toString()
can be useful for debugging, as in\nprint(myColor.toString())
. It's also helpful for using p5.js with other\nlibraries.
The parameter, format
, is optional. If a format string is passed, as in\nmyColor.toString('#rrggbb')
, it will determine how the color string is\nformatted. By default, color strings are formatted as 'rgba(r, g, b, a)'
.
Sets the red component of a color.
\nThe range depends on the colorMode(). In the\ndefault RGB mode it's between 0 and 255.
\n"],"path":[0,"p5.Color/setRed"]}],"setGreen":[0,{"description":[0,"Sets the green component of a color.
\nThe range depends on the colorMode(). In the\ndefault RGB mode it's between 0 and 255.
\n"],"path":[0,"p5.Color/setGreen"]}],"setBlue":[0,{"description":[0,"Sets the blue component of a color.
\nThe range depends on the colorMode(). In the\ndefault RGB mode it's between 0 and 255.
\n"],"path":[0,"p5.Color/setBlue"]}],"setAlpha":[0,{"description":[0,"Sets the alpha (transparency) value of a color.
\nThe range depends on the\ncolorMode(). In the default RGB mode it's\nbetween 0 and 255.
\n"],"path":[0,"p5.Color/setAlpha"]}]}],"isConstructor":[0,true],"path":[0,"p5/p5.Color"]}],"render":[0,null]}],"entries":[1,[[0,{"id":[0,"en/p5.Color/setAlpha.mdx"],"slug":[0,"en/p5color/setalpha"],"body":[0,"\n\n# setAlpha\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"setAlpha()"],"module":[0,"Color"],"submodule":[0,"Creating & Reading"],"file":[0,"src/color/p5.Color.js"],"description":[0,"Sets the alpha (transparency) value of a color.
\nThe range depends on the\ncolorMode(). In the default RGB mode it's\nbetween 0 and 255.
\n"],"line":[0,698],"params":[1,[[0,{"name":[0,"alpha"],"description":[0,"the new alpha value.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Color"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let c = color(255, 128, 128);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 20, 35, 60);\n\n // Change the alpha value.\n c.setAlpha(128);\n\n // Draw the right rectangle.\n fill(c);\n rect(50, 20, 35, 60);\n\n describe('Two rectangles. The left one is salmon pink and the right one is faded pink.');\n}\n
\nSets the blue component of a color.
\nThe range depends on the colorMode(). In the\ndefault RGB mode it's between 0 and 255.
\n"],"line":[0,656],"params":[1,[[0,{"name":[0,"blue"],"description":[0,"the new blue value.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Color"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let c = color(255, 128, 128);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 20, 35, 60);\n\n // Change the blue value.\n c.setBlue(255);\n\n // Draw the right rectangle.\n fill(c);\n rect(50, 20, 35, 60);\n\n describe('Two rectangles. The left one is salmon pink and the right one is pale fuchsia.');\n}\n
\nSets the green component of a color.
\nThe range depends on the colorMode(). In the\ndefault RGB mode it's between 0 and 255.
\n"],"line":[0,614],"params":[1,[[0,{"name":[0,"green"],"description":[0,"the new green value.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Color"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let c = color(255, 128, 128);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 20, 35, 60);\n\n // Change the green value.\n c.setGreen(255);\n\n // Draw the right rectangle.\n fill(c);\n rect(50, 20, 35, 60);\n\n describe('Two rectangles. The left one is salmon pink and the right one is yellow.');\n}\n
\nSets the red component of a color.
\nThe range depends on the colorMode(). In the\ndefault RGB mode it's between 0 and 255.
\n"],"line":[0,572],"params":[1,[[0,{"name":[0,"red"],"description":[0,"the new red value.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Color"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let c = color(255, 128, 128);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 20, 35, 60);\n\n // Change the red value.\n c.setRed(64);\n\n // Draw the right rectangle.\n fill(c);\n rect(50, 20, 35, 60);\n\n describe('Two rectangles. The left one is salmon pink and the right one is teal.');\n}\n
\nReturns the color formatted as a String
.
Calling myColor.toString()
can be useful for debugging, as in\nprint(myColor.toString())
. It's also helpful for using p5.js with other\nlibraries.
The parameter, format
, is optional. If a format string is passed, as in\nmyColor.toString('#rrggbb')
, it will determine how the color string is\nformatted. By default, color strings are formatted as 'rgba(r, g, b, a)'
.
how the color string will be formatted.\nLeaving this empty formats the string as rgba(r, g, b, a).\n'#rgb' '#rgba' '#rrggbb' and '#rrggbbaa' format as hexadecimal color codes.\n'rgb' 'hsb' and 'hsl' return the color formatted in the specified color mode.\n'rgba' 'hsba' and 'hsla' are the same as above but with alpha channels.\n'rgb%' 'hsb%' 'hsl%' 'rgba%' 'hsba%' and 'hsla%' format as percentages.
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Color"],"chainable":[0,false],"return":[0,{"description":[0,"the formatted string."],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let myColor = color('darkorchid');\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the text.\n text(myColor.toString('#rrggbb'), 50, 50);\n\n describe('The text \"#9932cc\" written in purple on a gray background.');\n}\n
\nSets the way text is aligned when text() is called.
\nBy default, calling text('hi', 10, 20)
places the bottom-left corner of\nthe text's bounding box at (10, 20).
The first parameter, horizAlign
, changes the way\ntext() interprets x-coordinates. By default, the\nx-coordinate sets the left edge of the bounding box. textAlign()
accepts\nthe following values for horizAlign
: LEFT
, CENTER
, or RIGHT
.
The second parameter, vertAlign
, is optional. It changes the way\ntext() interprets y-coordinates. By default, the\ny-coordinate sets the bottom edge of the bounding box. textAlign()
\naccepts the following values for vertAlign
: TOP
, BOTTOM
, CENTER
,\nor BASELINE
.
horizontal alignment, either LEFT,\n CENTER, or RIGHT.
\n"],"type":[0,"Constant"]}],[0,{"name":[0,"vertAlign"],"description":[0,"vertical alignment, either TOP,\n BOTTOM, CENTER, or BASELINE.
\n"],"type":[0,"Constant"],"optional":[0,true]}]]]}],[0,{"params":[1,[]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw a vertical line.\n strokeWeight(0.5);\n line(50, 0, 50, 100);\n\n // Top line.\n textSize(16);\n textAlign(RIGHT);\n text('ABCD', 50, 30);\n\n // Middle line.\n textAlign(CENTER);\n text('EFGH', 50, 50);\n\n // Bottom line.\n textAlign(LEFT);\n text('IJKL', 50, 70);\n\n describe('The letters ABCD displayed at top-left, EFGH at center, and IJKL at bottom-right. A vertical line divides the canvas in half.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n strokeWeight(0.5);\n\n // First line.\n line(0, 12, width, 12);\n textAlign(CENTER, TOP);\n text('TOP', 50, 12);\n\n // Second line.\n line(0, 37, width, 37);\n textAlign(CENTER, CENTER);\n text('CENTER', 50, 37);\n\n // Third line.\n line(0, 62, width, 62);\n textAlign(CENTER, BASELINE);\n text('BASELINE', 50, 62);\n\n // Fourth line.\n line(0, 97, width, 97);\n textAlign(CENTER, BOTTOM);\n text('BOTTOM', 50, 97);\n\n describe('The words \"TOP\", \"CENTER\", \"BASELINE\", and \"BOTTOM\" each drawn relative to a horizontal line. Their positions demonstrate different vertical alignments.');\n}\n
\nCalculates the ascent of the current font at its current size.
\nThe ascent represents the distance, in pixels, of the tallest character\nabove the baseline.
\n"],"line":[0,337],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"ascent measured in units of pixels."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nlet font;\n\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textFont(font);\n\n // Different for each font.\n let fontScale = 0.8;\n\n let baseY = 75;\n strokeWeight(0.5);\n\n // Draw small text.\n textSize(24);\n text('dp', 0, baseY);\n\n // Draw baseline and ascent.\n let a = textAscent() * fontScale;\n line(0, baseY, 23, baseY);\n line(23, baseY - a, 23, baseY);\n\n // Draw large text.\n textSize(48);\n text('dp', 45, baseY);\n\n // Draw baseline and ascent.\n a = textAscent() * fontScale;\n line(45, baseY, 91, baseY);\n line(91, baseY - a, 91, baseY);\n\n 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\".');\n}\n
\nCalculates the descent of the current font at its current size.
\nThe descent represents the distance, in pixels, of the character with the\nlongest descender below the baseline.
\n"],"line":[0,396],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"descent measured in units of pixels."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nlet font;\n\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the font.\n textFont(font);\n\n // Different for each font.\n let fontScale = 0.9;\n\n let baseY = 75;\n strokeWeight(0.5);\n\n // Draw small text.\n textSize(24);\n text('dp', 0, baseY);\n\n // Draw baseline and descent.\n let d = textDescent() * fontScale;\n line(0, baseY, 23, baseY);\n line(23, baseY, 23, baseY + d);\n\n // Draw large text.\n textSize(48);\n text('dp', 45, baseY);\n\n // Draw baseline and descent.\n d = textDescent() * fontScale;\n line(45, baseY, 91, baseY);\n line(91, baseY, 91, baseY + d);\n\n 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\".');\n}\n
\nSets the spacing between lines of text when\ntext() is called.
\nNote: Spacing is measured in pixels.
\nCalling textLeading()
without an argument returns the current spacing.
spacing between lines of text in units of pixels.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // \"\\n\" starts a new line of text.\n let lines = 'one\\ntwo';\n\n // Left.\n text(lines, 10, 25);\n\n // Right.\n textLeading(30);\n text(lines, 70, 25);\n\n 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.');\n}\n
\nSets the font size when\ntext() is called.
\nNote: Font size is measured in pixels.
\nCalling textSize()
without an arugment returns the current size.
size of the letters in units of pixels.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Top.\n textSize(12);\n text('Font Size 12', 10, 30);\n\n // Middle.\n textSize(14);\n text('Font Size 14', 10, 60);\n\n // Bottom.\n textSize(16);\n text('Font Size 16', 10, 90);\n\n describe('The text \"Font Size 12\" drawn small, \"Font Size 14\" drawn medium, and \"Font Size 16\" drawn large.');\n}\n
\nSets the style for system fonts when\ntext() is called.
\nThe parameter, style
, can be either NORMAL
, ITALIC
, BOLD
, or\nBOLDITALIC
.
textStyle()
may be overridden by CSS styling. This function doesn't\naffect fonts loaded with loadFont().
styling for text, either NORMAL,\n ITALIC, BOLD or BOLDITALIC.
\n"],"type":[0,"Constant"]}]]]}],[0,{"params":[1,[]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textSize(12);\n textAlign(CENTER);\n\n // First row.\n textStyle(NORMAL);\n text('Normal', 50, 15);\n\n // Second row.\n textStyle(ITALIC);\n text('Italic', 50, 40);\n\n // Third row.\n textStyle(BOLD);\n text('Bold', 50, 65);\n\n // Fourth row.\n textStyle(BOLDITALIC);\n text('Bold Italic', 50, 90);\n\n describe('The words \"Normal\" displayed normally, \"Italic\" in italic, \"Bold\" in bold, and \"Bold Italic\" in bold italics.');\n}\n
\nCalculates the maximum width of a string of text drawn when\ntext() is called.
\n"],"line":[0,253],"params":[1,[[0,{"name":[0,"str"],"description":[0,"string of text to measure.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"width measured in units of pixels."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textSize(28);\n strokeWeight(0.5);\n\n // Calculate the text width.\n let s = 'yoyo';\n let w = textWidth(s);\n\n // Display the text.\n text(s, 22, 55);\n\n // Underline the text.\n line(22, 55, 22 + w, 55);\n\n describe('The word \"yoyo\" underlined.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textSize(28);\n strokeWeight(0.5);\n\n // Calculate the text width.\n // \"\\n\" starts a new line.\n let s = 'yo\\nyo';\n let w = textWidth(s);\n\n // Display the text.\n text(s, 22, 55);\n\n // Underline the text.\n line(22, 55, 22 + w, 55);\n\n describe('The word \"yo\" written twice, one copy beneath the other. The words are divided by a horizontal line.');\n}\n
\nSets the style for wrapping text when\ntext() is called.
\nThe parameter, style
, can be one of the following values:
WORD
starts new lines of text at spaces. If a string of text doesn't\nhave spaces, it may overflow the text box and the canvas. This is the\ndefault 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\nexample, calling text('Have a wonderful day', 0, 10, 100)
sets the\nmaximum width to 100 pixels.
Calling textWrap()
without an argument returns the current style.
text wrapping style, either WORD or CHAR.
\n"],"type":[0,"Constant"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"style"],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textSize(20);\n textWrap(WORD);\n\n // Display the text.\n text('Have a wonderful day', 0, 10, 100);\n\n describe('The text \"Have a wonderful day\" written across three lines.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textSize(20);\n textWrap(CHAR);\n\n // Display the text.\n text('Have a wonderful day', 0, 10, 100);\n\n describe('The text \"Have a wonderful day\" written across two lines.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textSize(20);\n textWrap(CHAR);\n\n // Display the text.\n text('祝你有美好的一天', 0, 10, 100);\n\n describe('The text \"祝你有美好的一天\" written across two lines.');\n}\n
\nLoads a font and creates a p5.Font object.\nloadFont()
can load fonts in either .otf or .ttf format. Loaded fonts can\nbe used to style text on the canvas and in HTML elements.
The first parameter, path
, is the path to a font file.\nPaths to local files should be relative. For example,\n'/assets/inconsolata.otf'
. The Inconsolata font used in the following\nexamples can be downloaded for free\nhere.\nPaths to remote files should be URLs. For example,\n'https://example.com/inconsolata.otf'
. URLs may be blocked due to browser\nsecurity.
The second parameter, successCallback
, is optional. If a function is\npassed, it will be called once the font has loaded. The callback function\nmay use the new p5.Font object if needed.
The third parameter, failureCallback
, is also optional. If a function is\npassed, it will be called if the font fails to load. The callback function\nmay use the error\nEvent\nobject if needed.
Fonts can take time to load. Calling loadFont()
in\npreload() ensures fonts load before they're\nused in setup() or\ndraw().
path of the font to be loaded.
\n"],"type":[0,"String"]}],[0,{"name":[0,"successCallback"],"description":[0,"function called with the\n p5.Font object after it\n loads.
\n"],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"failureCallback"],"description":[0,"function called with the error\n Event\n object if the font fails to load.
\n"],"type":[0,"Function"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"p5.Font object."],"type":[0,"p5.Font"]}],"example":[1,[[0,"\n\n\nlet font;\n\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n fill('deeppink');\n textFont(font);\n textSize(36);\n text('p5*js', 10, 50);\n\n describe('The text \"p5*js\" written in pink on a white background.');\n}\n
\n\nfunction setup() {\n loadFont('/assets/inconsolata.otf', font => {\n fill('deeppink');\n textFont(font);\n textSize(36);\n text('p5*js', 10, 50);\n\n describe('The text \"p5*js\" written in pink on a white background.');\n });\n}\n
\n\nfunction setup() {\n loadFont('/assets/inconsolata.otf', success, failure);\n}\n\nfunction success(font) {\n fill('deeppink');\n textFont(font);\n textSize(36);\n text('p5*js', 10, 50);\n\n describe('The text \"p5*js\" written in pink on a white background.');\n}\n\nfunction failure(event) {\n console.error('Oops!', event);\n}\n
\n\nfunction preload() {\n loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n let p = createP('p5*js');\n p.style('color', 'deeppink');\n p.style('font-family', 'Inconsolata');\n p.style('font-size', '36px');\n p.position(10, 50);\n\n describe('The text \"p5*js\" written in pink on a white background.');\n}\n
\nDraws text to the canvas.
\nThe first parameter, str
, is the text to be drawn. The second and third\nparameters, x
and y
, set the coordinates of the text's bottom-left\ncorner. See textAlign() for other ways to\nalign text.
The fourth and fifth parameters, maxWidth
and maxHeight
, are optional.\nThey set the dimensions of the invisible rectangle containing the text. By\ndefault, they set its maximum width and height. See\nrectMode() for other ways to define the\nrectangular text box. Text will wrap to fit within the text box. Text\noutside of the box won't be drawn.
Text can be styled a few ways. Call the fill()\nfunction to set the text's fill color. Call\nstroke() and\nstrokeWeight() to set the text's outline.\nCall textSize() and\ntextFont() to set the text's size and font,\nrespectively.
\nNote: WEBGL
mode only supports fonts loaded with\nloadFont(). Calling\nstroke() has no effect in WEBGL
mode.
text to be displayed.
\n"],"type":[0,"String|Object|Array|Number|Boolean"]}],[0,{"name":[0,"x"],"description":[0,"x-coordinate of the text box.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"y-coordinate of the text box.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"maxWidth"],"description":[0,"maximum width of the text box. See\n rectMode() for\n other options.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"maxHeight"],"description":[0,"maximum height of the text box. See\n rectMode() for\n other options.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n background(200);\n text('hi', 50, 50);\n\n describe('The text \"hi\" written in black in the middle of a gray square.');\n}\n
\n\nfunction setup() {\n background('skyblue');\n textSize(100);\n text('🌈', 0, 100);\n\n describe('A rainbow in a blue sky.');\n}\n
\n\nfunction setup() {\n textSize(32);\n fill(255);\n stroke(0);\n strokeWeight(4);\n text('hi', 50, 50);\n\n describe('The text \"hi\" written in white with a black outline.');\n}\n
\n\nfunction setup() {\n background('black');\n textSize(22);\n fill('yellow');\n text('rainbows', 6, 20);\n fill('cornflowerblue');\n text('rainbows', 6, 45);\n fill('tomato');\n text('rainbows', 6, 70);\n fill('limegreen');\n text('rainbows', 6, 95);\n\n describe('The text \"rainbows\" written on several lines, each in a different color.');\n}\n
\n\nfunction setup() {\n background(200);\n let s = 'The quick brown fox jumps over the lazy dog.';\n text(s, 10, 10, 70, 80);\n\n describe('The sample text \"The quick brown fox...\" written in black across several lines.');\n}\n
\n\nfunction setup() {\n background(200);\n rectMode(CENTER);\n let s = 'The quick brown fox jumps over the lazy dog.';\n text(s, 50, 50, 70, 80);\n\n describe('The sample text \"The quick brown fox...\" written in black across several lines.');\n}\n
\n\nlet font;\n\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n textFont(font);\n textSize(32);\n textAlign(CENTER, CENTER);\n}\n\nfunction draw() {\n background(0);\n rotateY(frameCount / 30);\n text('p5*js', 0, 0);\n\n describe('The text \"p5*js\" written in white and spinning in 3D.');\n}\n
\nSets the font used by the text() function.
\nThe first parameter, font
, sets the font. textFont()
recognizes either\na p5.Font object or a string with the name of a\nsystem font. For example, 'Courier New'
.
The second parameter, size
, is optional. It sets the font size in pixels.\nThis has the same effect as calling textSize().
Note: WEBGL
mode only supports fonts loaded with\nloadFont().
font as a p5.Font object or a string.
\n"],"type":[0,"Object|String"]}],[0,{"name":[0,"size"],"description":[0,"font size in pixels.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"current font or p5 Object."],"type":[0,"Object"]}],"example":[1,[[0,"\n\nfunction setup() {\n background(200);\n textFont('Courier New');\n textSize(24);\n text('hi', 35, 55);\n\n describe('The text \"hi\" written in a black, monospace font on a gray background.');\n}\n
\n\nfunction setup() {\n background('black');\n fill('palegreen');\n textFont('Courier New', 10);\n text('You turn to the left and see a door. Do you enter?', 5, 5, 90, 90);\n text('>', 5, 70);\n\n describe('A text prompt from a game is written in a green, monospace font on a black background.');\n}\n
\n\nfunction setup() {\n background(200);\n textFont('Verdana');\n let currentFont = textFont();\n text(currentFont, 25, 50);\n\n describe('The text \"Verdana\" written in a black, sans-serif font on a gray background.');\n}\n
\n\nlet fontRegular;\nlet fontItalic;\nlet fontBold;\n\nfunction preload() {\n fontRegular = loadFont('/assets/Regular.otf');\n fontItalic = loadFont('/assets/Italic.ttf');\n fontBold = loadFont('/assets/Bold.ttf');\n}\n\nfunction setup() {\n background(200);\n textFont(fontRegular);\n text('I am Normal', 10, 30);\n textFont(fontItalic);\n text('I am Italic', 10, 50);\n textFont(fontBold);\n text('I am Bold', 10, 70);\n\n 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.');\n}\n
\nA class to describe fonts.
\n"],"line":[0,13],"params":[1,[[0,{"name":[0,"pInst"],"description":[0,"pointer to p5 instance.
\n"],"type":[0,"P5"],"optional":[0,true]}]]],"chainable":[0,false],"example":[1,[[0,"\n\nlet font;\n\nfunction preload() {\n // Creates a p5.Font object.\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Style the text.\n fill('deeppink');\n textFont(font);\n textSize(36);\n\n // Display the text.\n text('p5*js', 10, 50);\n\n describe('The text \"p5*js\" written in pink on a gray background.');\n}\n
\nReturns the bounding box for a string of text written using the font.
\nThe bounding box is the smallest rectangle that can contain a string of\ntext. font.textBounds()
returns an object with the bounding box's\nlocation and size. For example, calling font.textBounds('p5*js', 5, 20)
\nreturns an object in the format\n{ x: 5.7, y: 12.1 , w: 9.9, h: 28.6 }
. The x
and y
properties are\nalways the coordinates of the bounding box's top-left corner.
The first parameter, str
, is a string of text. The second and third\nparameters, x
and y
, are the text's position. By default, they set the\ncoordinates of the bounding box's bottom-left corner. See\ntextAlign() for more ways to align text.
The fourth parameter, fontSize
, is optional. It sets the font size used to\ndetermine the bounding box. By default, font.textBounds()
will use the\ncurrent textSize().
Returns an array of points outlining a string of text written using the\nfont.
\nEach point object in the array has three properties that describe the\npoint's location and orientation, called its path angle. For example,\n{ x: 10, y: 20, alpha: 450 }
.
The first parameter, str
, is a string of text. The second and third\nparameters, x
and y
, are the text's position. By default, they set the\ncoordinates of the bounding box's bottom-left corner. See\ntextAlign() for more ways to align text.
The fourth parameter, fontSize
, is optional. It sets the text's font\nsize. By default, font.textToPoints()
will use the current\ntextSize().
The fifth parameter, options
, is also optional. font.textToPoints()
\nexpects an object with the following properties:
sampleFactor
is the ratio of the text's path length to the number of\nsamples. It defaults to 0.1. Higher values produce more points along the\npath and are more precise.
simplifyThreshold
removes collinear points if it's set to a number other\nthan 0. The value represents the threshold angle to use when determining\nwhether two edges are collinear.
The font's underlying\nopentype.js\nfont object.
\n"],"path":[0,"p5.Font/font"]}]}],"isConstructor":[0,true],"path":[0,"p5/p5.Font"]}],"render":[0,null]}],"entries":[1,[[0,{"id":[0,"en/p5.Font/font.mdx"],"slug":[0,"en/p5font/font"],"body":[0,"\n\n# font\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"font"],"module":[0,"Typography"],"submodule":[0,"Loading & Displaying"],"file":[0,"src/typography/p5.Font.js"],"description":[0,"The font's underlying\nopentype.js\nfont object.
\n"],"line":[0,51],"itemtype":[0,"property"],"class":[0,"p5.Font"],"isConstructor":[0,false],"path":[0,"p5.Font/font"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Font/textBounds.mdx"],"slug":[0,"en/p5font/textbounds"],"body":[0,"\n\n# textBounds\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"textBounds()"],"module":[0,"Typography"],"submodule":[0,"Loading & Displaying"],"file":[0,"src/typography/p5.Font.js"],"description":[0,"Returns the bounding box for a string of text written using the font.
\nThe bounding box is the smallest rectangle that can contain a string of\ntext. font.textBounds()
returns an object with the bounding box's\nlocation and size. For example, calling font.textBounds('p5*js', 5, 20)
\nreturns an object in the format\n{ x: 5.7, y: 12.1 , w: 9.9, h: 28.6 }
. The x
and y
properties are\nalways the coordinates of the bounding box's top-left corner.
The first parameter, str
, is a string of text. The second and third\nparameters, x
and y
, are the text's position. By default, they set the\ncoordinates of the bounding box's bottom-left corner. See\ntextAlign() for more ways to align text.
The fourth parameter, fontSize
, is optional. It sets the font size used to\ndetermine the bounding box. By default, font.textBounds()
will use the\ncurrent textSize().
string of text.
\n"],"type":[0,"String"]}],[0,{"name":[0,"x"],"description":[0,"x-coordinate of the text.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"y-coordinate of the text.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"fontSize"],"description":[0,"font size. Defaults to the current\n textSize().
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Font"],"chainable":[0,false],"return":[0,{"description":[0,"object describing the bounding box with\n properties x, y, w, and h."],"type":[0,"Object"]}],"example":[1,[[0,"\n\nlet font;\n\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Display the bounding box.\n let bbox = font.textBounds('p5*js', 35, 53);\n rect(bbox.x, bbox.y, bbox.w, bbox.h);\n\n // Style the text.\n textFont(font);\n\n // Display the text.\n text('p5*js', 35, 53);\n\n describe('The text \"p5*js\" written in black inside a white rectangle.');\n}\n
\n\nlet font;\n\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textFont(font);\n textSize(15);\n textAlign(CENTER, CENTER);\n\n // Display the bounding box.\n let bbox = font.textBounds('p5*js', 50, 50);\n rect(bbox.x, bbox.y, bbox.w, bbox.h);\n\n // Display the text.\n text('p5*js', 50, 50);\n\n describe('The text \"p5*js\" written in black inside a white rectangle.');\n}\n
\n\nlet font;\n\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Display the bounding box.\n let bbox = font.textBounds('p5*js', 31, 53, 15);\n rect(bbox.x, bbox.y, bbox.w, bbox.h);\n\n // Style the text.\n textFont(font);\n textSize(15);\n\n // Display the text.\n text('p5*js', 31, 53);\n\n describe('The text \"p5*js\" written in black inside a white rectangle.');\n}\n
\nReturns an array of points outlining a string of text written using the\nfont.
\nEach point object in the array has three properties that describe the\npoint's location and orientation, called its path angle. For example,\n{ x: 10, y: 20, alpha: 450 }
.
The first parameter, str
, is a string of text. The second and third\nparameters, x
and y
, are the text's position. By default, they set the\ncoordinates of the bounding box's bottom-left corner. See\ntextAlign() for more ways to align text.
The fourth parameter, fontSize
, is optional. It sets the text's font\nsize. By default, font.textToPoints()
will use the current\ntextSize().
The fifth parameter, options
, is also optional. font.textToPoints()
\nexpects an object with the following properties:
sampleFactor
is the ratio of the text's path length to the number of\nsamples. It defaults to 0.1. Higher values produce more points along the\npath and are more precise.
simplifyThreshold
removes collinear points if it's set to a number other\nthan 0. The value represents the threshold angle to use when determining\nwhether two edges are collinear.
string of text.
\n"],"type":[0,"String"]}],[0,{"name":[0,"x"],"description":[0,"x-coordinate of the text.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"y-coordinate of the text.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"fontSize"],"description":[0,"font size. Defaults to the current\n textSize().
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"options"],"description":[0,"object with sampleFactor and simplifyThreshold\n properties.
\n"],"type":[0,"Object"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Font"],"chainable":[0,false],"return":[0,{"description":[0,"array of point objects, each with x, y, and alpha (path angle) properties."],"type":[0,"Array"]}],"example":[1,[[0,"\n\nlet font;\n\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the point array.\n let points = font.textToPoints('p5*js', 6, 60, 35, { sampleFactor: 0.5 });\n\n // Draw a dot at each point.\n for (let p of points) {\n point(p.x, p.y);\n }\n\n describe('A set of black dots outlining the text \"p5*js\" on a gray background.');\n}\n
\nCreates a new p5.Image object.
\ncreateImage()
uses the width
and height
parameters to set the new\np5.Image object's dimensions in pixels. The new\np5.Image can be modified by updating its\npixels array or by calling its\nget() and\nset() methods. The\nloadPixels() method must be called\nbefore reading or modifying pixel values. The\nupdatePixels() method must be called\nfor updates to take effect.
Note: The new p5.Image object is transparent by\ndefault.
\n"],"line":[0,15],"params":[1,[[0,{"name":[0,"width"],"description":[0,"width in pixels.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"height"],"description":[0,"height in pixels.
\n"],"type":[0,"Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.Image object."],"type":[0,"p5.Image"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the image's pixels into memory.\n img.loadPixels();\n\n // Set all the image's pixels to black.\n for (let x = 0; x < img.width; x += 1) {\n for (let y = 0; y < img.height; y += 1) {\n img.set(x, y, 0);\n }\n }\n\n // Update the image's pixel values.\n img.updatePixels();\n\n // Draw the image.\n image(img, 17, 17);\n\n describe('A black square drawn in the middle of a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the image's pixels into memory.\n img.loadPixels();\n\n // Create a color gradient.\n for (let x = 0; x < img.width; x += 1) {\n for (let y = 0; y < img.height; y += 1) {\n // Calculate the transparency.\n let a = map(x, 0, img.width, 0, 255);\n\n // Create a p5.Color object.\n let c = color(0, a);\n\n // Set the pixel's color.\n img.set(x, y, c);\n }\n }\n\n // Update the image's pixels.\n img.updatePixels();\n\n // Display the image.\n image(img, 17, 17);\n\n describe('A square with a horizontal color gradient that transitions from gray to black.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the pixels into memory.\n img.loadPixels();\n // Get the current pixel density.\n let d = pixelDensity();\n\n // Calculate the pixel that is halfway through the image's pixel array.\n let halfImage = 4 * (d * img.width) * (d * img.height / 2);\n\n // Set half of the image's pixels to black.\n for (let i = 0; i < halfImage; i += 4) {\n // Red.\n img.pixels[i] = 0;\n // Green.\n img.pixels[i + 1] = 0;\n // Blue.\n img.pixels[i + 2] = 0;\n // Alpha.\n img.pixels[i + 3] = 255;\n }\n\n // Update the image's pixels.\n img.updatePixels();\n\n // Display the image.\n image(img, 17, 17);\n\n describe('A black square drawn in the middle of a gray square.');\n}\n
\nSaves the current canvas as an image.
\nBy default, saveCanvas()
saves the canvas as a PNG image called\nuntitled.png
.
The first parameter, filename
, is optional. It's a string that sets the\nfile's name. If a file extension is included, as in\nsaveCanvas('drawing.png')
, then the image will be saved using that\nformat.
The second parameter, extension
, is also optional. It sets the files format.\nEither 'png'
, 'webp'
, or 'jpg'
can be used. For example, saveCanvas('drawing', 'jpg')
\nsaves the canvas to a file called drawing.jpg
.
Note: The browser will either save the file immediately or prompt the user\nwith a dialogue window.
\n"],"line":[0,153],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"selectedCanvas"],"description":[0,"reference to a\n specific HTML5 canvas element.
\n"],"type":[0,"p5.Framebuffer|p5.Element|HTMLCanvasElement"]}],[0,{"name":[0,"filename"],"description":[0,"file name. Defaults to 'untitled'.
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"extension"],"description":[0,"file extension, either 'png', 'webp', or 'jpg'. Defaults to 'png'.
\n"],"type":[0,"String"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"filename"],"description":[0,""],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"extension"],"description":[0,""],"type":[0,"String"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n background(255);\n\n // Save the canvas to 'untitled.png'.\n saveCanvas();\n\n describe('A white square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(255);\n\n // Save the canvas to 'myCanvas.jpg'.\n saveCanvas('myCanvas.jpg');\n\n describe('A white square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(255);\n\n // Save the canvas to 'myCanvas.jpg'.\n saveCanvas('myCanvas', 'jpg');\n\n describe('A white square.');\n}\n
\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n background(255);\n\n // Save the canvas to 'untitled.png'.\n saveCanvas(cnv);\n\n describe('A white square.');\n}\n
\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n background(255);\n\n // Save the canvas to 'myCanvas.jpg'.\n saveCanvas(cnv, 'myCanvas.jpg');\n\n describe('A white square.');\n}\n
\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n background(255);\n\n // Save the canvas to 'myCanvas.jpg'.\n saveCanvas(cnv, 'myCanvas', 'jpg');\n\n describe('A white square.');\n}\n
\nCaptures a sequence of frames from the canvas that can be saved as images.
\nsaveFrames()
creates an array of frame objects. Each frame is stored as\nan object with its file type, file name, and image data as a string. For\nexample, 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\nexample, setting the prefix to 'frame'
would generate the image files\nframe0.png
, frame1.png
, and so on.
The second parameter, extension
, sets the file type to either 'png'
or\n'jpg'
.
The third parameter, duration
, sets the duration to record in seconds.\nThe maximum duration is 15 seconds.
The fourth parameter, framerate
, sets the number of frames to record per\nsecond. The maximum frame rate value is 22. Limits are placed on duration
\nand framerate
to avoid using too much memory. Recording large canvases\ncan easily crash sketches or even web browsers.
The fifth parameter, callback
, is optional. If a function is passed,\nimage files won't be saved by default. The callback function can be used\nto process an array containing the data for each captured frame. The array\nof image data contains a sequence of objects with three properties for each\nframe: imageData
, filename
, and extension
.
Note: Frames are downloaded as individual image files by default.
\n"],"line":[0,561],"params":[1,[[0,{"name":[0,"filename"],"description":[0,"prefix of file name.
\n"],"type":[0,"String"]}],[0,{"name":[0,"extension"],"description":[0,"file extension, either 'jpg' or 'png'.
\n"],"type":[0,"String"]}],[0,{"name":[0,"duration"],"description":[0,"duration in seconds to record. This parameter will be constrained to be less or equal to 15.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"framerate"],"description":[0,"number of frames to save per second. This parameter will be constrained to be less or equal to 22.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"callback"],"description":[0,"callback function that will be executed\n to handle the image data. This function\n should accept an array as argument. The\n array will contain the specified number of\n frames of objects. Each object has three\n properties: imageData
, filename
, and extension
.
\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A square repeatedly changes color from blue to pink.');\n}\n\nfunction draw() {\n let r = frameCount % 255;\n let g = 50;\n let b = 100;\n background(r, g, b);\n}\n\n// Save the frames when the user presses the 's' key.\nfunction keyPressed() {\n if (key === 's') {\n saveFrames('frame', 'png', 1, 5);\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A square repeatedly changes color from blue to pink.');\n}\n\nfunction draw() {\n let r = frameCount % 255;\n let g = 50;\n let b = 100;\n background(r, g, b);\n}\n\n// Print 5 frames when the user presses the mouse.\nfunction mousePressed() {\n saveFrames('frame', 'png', 1, 5, printFrames);\n}\n\n// Prints an array of objects containing raw image data, filenames, and extensions.\nfunction printFrames(frames) {\n for (let frame of frames) {\n print(frame);\n }\n}\n
\nDraws an image to the canvas.
\nThe first parameter, img
, is the source image to be drawn. img
can be\nany of the following objects:
The second and third parameters, dx
and dy
, set the coordinates of the\ndestination image's top left corner. See\nimageMode() 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\nthe width and height to draw the destination image. By default, image()
\ndraws the full source image at its original size.
The sixth and seventh parameters, sx
and sy
, are also optional.\nThese coordinates define the top left corner of a subsection to draw from\nthe source image.
The eighth and ninth parameters, sw
and sh
, are also optional.\nThey define the width and height of a subsection to draw from the source\nimage. By default, image()
draws the full subsection that begins at\n(sx, sy)
and extends to the edges of the source image.
The ninth parameter, fit
, is also optional. It enables a subsection of\nthe source image to be drawn without affecting its aspect ratio. If\nCONTAIN
is passed, the full subsection will appear within the destination\nrectangle. If COVER
is passed, the subsection will completely cover the\ndestination rectangle. This may have the effect of zooming into the\nsubsection.
The tenth and eleventh paremeters, xAlign
and yAlign
, are also\noptional. They determine how to align the fitted subsection. xAlign
can\nbe set to either LEFT
, RIGHT
, or CENTER
. yAlign
can be set to\neither TOP
, BOTTOM
, or CENTER
. By default, both xAlign
and yAlign
\nare set to CENTER
.
image to display.
\n"],"type":[0,"p5.Image|p5.Element|p5.Texture|p5.Framebuffer|p5.FramebufferTexture"]}],[0,{"name":[0,"x"],"description":[0,"x-coordinate of the top-left corner of the image.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"y-coordinate of the top-left corner of the image.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"width"],"description":[0,"width to draw the image.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"height"],"description":[0,"height to draw the image.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"img"],"description":[0,""],"type":[0,"p5.Image|p5.Element|p5.Texture|p5.Framebuffer|p5.FramebufferTexture"]}],[0,{"name":[0,"dx"],"description":[0,"the x-coordinate of the destination\n rectangle in which to draw the source image
\n"],"type":[0,"Number"]}],[0,{"name":[0,"dy"],"description":[0,"the y-coordinate of the destination\n rectangle in which to draw the source image
\n"],"type":[0,"Number"]}],[0,{"name":[0,"dWidth"],"description":[0,"the width of the destination rectangle
\n"],"type":[0,"Number"]}],[0,{"name":[0,"dHeight"],"description":[0,"the height of the destination rectangle
\n"],"type":[0,"Number"]}],[0,{"name":[0,"sx"],"description":[0,"the x-coordinate of the subsection of the source\nimage to draw into the destination rectangle
\n"],"type":[0,"Number"]}],[0,{"name":[0,"sy"],"description":[0,"the y-coordinate of the subsection of the source\nimage to draw into the destination rectangle
\n"],"type":[0,"Number"]}],[0,{"name":[0,"sWidth"],"description":[0,"the width of the subsection of the\n source image to draw into the destination\n rectangle
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"sHeight"],"description":[0,"the height of the subsection of the\n source image to draw into the destination rectangle
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"fit"],"description":[0,"either CONTAIN or COVER
\n"],"type":[0,"Constant"],"optional":[0,true]}],[0,{"name":[0,"xAlign"],"description":[0,"either LEFT, RIGHT or CENTER default is CENTER
\n"],"type":[0,"Constant"],"optional":[0,true]}],[0,{"name":[0,"yAlign"],"description":[0,"either TOP, BOTTOM or CENTER default is CENTER
\n"],"type":[0,"Constant"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Draw the image.\n image(img, 0, 0);\n\n describe('An image of the underside of a white umbrella with a gridded ceiling above.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Draw the image.\n image(img, 10, 10);\n\n 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.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Draw the image 50x50.\n image(img, 0, 0, 50, 50);\n\n 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.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Draw the center of the image.\n image(img, 25, 25, 50, 50, 25, 25, 50, 50);\n\n describe('An image of a gridded ceiling drawn in the center of a dark gray square.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/moonwalk.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Draw the image and scale it to fit within the canvas.\n image(img, 0, 0, width, height, 0, 0, img.width, img.height, CONTAIN);\n\n describe('An image of an astronaut on the moon. The top and bottom borders of the image are dark gray.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n // Image is 50 x 50 pixels.\n img = loadImage('/assets/laDefense50.png');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Draw the image and scale it to cover the canvas.\n image(img, 0, 0, width, height, 0, 0, img.width, img.height, COVER);\n\n describe('A pixelated image of the underside of a white umbrella with a gridded ceiling above.');\n}\n
\nChanges the location from which images are drawn when\nimage() is called.
\nBy default, the first\ntwo parameters of image() are the x- and\ny-coordinates of the image's upper-left corner. The next parameters are\nits width and height. This is the same as calling imageMode(CORNER)
.
imageMode(CORNERS)
also uses the first two parameters of\nimage() as the x- and y-coordinates of the image's\ntop-left corner. The third and fourth parameters are the coordinates of its\nbottom-right corner.
imageMode(CENTER)
uses the first two parameters of\nimage() as the x- and y-coordinates of the image's\ncenter. The next parameters are its width and height.
either CORNER, CORNERS, or CENTER.
\n"],"type":[0,"Constant"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use CORNER mode.\n imageMode(CORNER);\n\n // Display the image.\n image(img, 10, 10, 50, 50);\n\n describe('A square image of a brick wall is drawn at the top left of a gray square.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use CORNERS mode.\n imageMode(CORNERS);\n\n // Display the image.\n image(img, 10, 10, 90, 40);\n\n describe('An image of a brick wall is drawn on a gray square. The image is squeezed into a small rectangular area.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use CENTER mode.\n imageMode(CENTER);\n\n // Display the image.\n image(img, 50, 50, 80, 80);\n\n describe('A square image of a brick wall is drawn on a gray square.');\n}\n
\nLoads an image to create a p5.Image object.
\nloadImage()
interprets the first parameter one of three ways. If the path\nto an image file is provided, loadImage()
will load it. Paths to local\nfiles should be relative, such as '/assets/thundercat.jpg'
. URLs such as\n'https://example.com/thundercat.jpg'
may be blocked due to browser\nsecurity. Raw image data can also be passed as a base64 encoded image in\nthe form 'data:image/png;base64,arandomsequenceofcharacters'
.
The second parameter is optional. If a function is passed, it will be\ncalled once the image has loaded. The callback function can optionally use\nthe new p5.Image object.
\nThe third parameter is also optional. If a function is passed, it will be\ncalled if the image fails to load. The callback function can optionally use\nthe event error.
\nImages can take time to load. Calling loadImage()
in\npreload() ensures images load before they're\nused in setup() or draw().
path of the image to be loaded or base64 encoded image.
\n"],"type":[0,"String"]}],[0,{"name":[0,"successCallback"],"description":[0,"function called with\n p5.Image once it\n loads.
\n"],"type":[0,"function(p5.Image)"],"optional":[0,true]}],[0,{"name":[0,"failureCallback"],"description":[0,"function called with event\n error if the image fails to load.
\n"],"type":[0,"Function(Event)"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"the p5.Image object."],"type":[0,"p5.Image"]}],"example":[1,[[0,"\n\nlet img;\n\n// Load the image and create a p5.Image object.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Draw the image.\n image(img, 0, 0);\n\n describe('Image of the underside of a white umbrella and a gridded ceiling.');\n}\n
\n\nfunction setup() {\n // Call handleImage() once the image loads.\n loadImage('/assets/laDefense.jpg', handleImage);\n\n describe('Image of the underside of a white umbrella and a gridded ceiling.');\n}\n\n// Display the image.\nfunction handleImage(img) {\n image(img, 0, 0);\n}\n
\n\nfunction setup() {\n // Call handleImage() once the image loads or\n // call handleError() if an error occurs.\n loadImage('/assets/laDefense.jpg', handleImage, handleError);\n}\n\n// Display the image.\nfunction handleImage(img) {\n image(img, 0, 0);\n\n describe('Image of the underside of a white umbrella and a gridded ceiling.');\n}\n\n// Log the error.\nfunction handleError(event) {\n console.error('Oops!', event);\n}\n
\nRemoves the current tint set by tint().
\nnoTint()
restores images to their original colors.
\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Left.\n // Tint with a CSS color string.\n tint('red');\n image(img, 0, 0);\n\n // Right.\n // Remove the tint.\n noTint();\n image(img, 50, 0);\n\n describe('Two images of an umbrella and a ceiling side-by-side. The image on the left has a red tint.');\n}\n
\nGenerates a gif from a sketch and saves it to a file.
\nsaveGif()
may be called in setup() or at any\npoint 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,\nsaveGif()
will use its properties to customize the gif. saveGif()
\nrecognizes the properties delay
, units
, silent
,\nnotificationDuration
, and notificationID
.
file name of gif.
\n"],"type":[0,"String"]}],[0,{"name":[0,"duration"],"description":[0,"duration in seconds to capture from the sketch.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"options"],"description":[0,"an object that can contain five more properties:\n delay
, a Number specifying how much time to wait before recording;\n units
, a String that can be either 'seconds' or 'frames'. By default it's 'seconds’;\n silent
, a Boolean that defines presence of progress notifications. By default it’s false
;\n notificationDuration
, a Number that defines how long in seconds the final notification\n will live. By default it's 0
, meaning the notification will never be removed;\n notificationID
, a String that specifies the id of the notification's DOM element. By default it’s 'progressBar’
.
\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A circle drawn in the middle of a gray square. The circle changes color from black to white, then repeats.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the circle.\n let c = frameCount % 255;\n fill(c);\n\n // Display the circle.\n circle(50, 50, 25);\n}\n\n// Save a 5-second gif when the user presses the 's' key.\nfunction keyPressed() {\n if (key === 's') {\n saveGif('mySketch', 5);\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A circle drawn in the middle of a gray square. The circle changes color from black to white, then repeats.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the circle.\n let c = frameCount % 255;\n fill(c);\n\n // Display the circle.\n circle(50, 50, 25);\n}\n\n// Save a 5-second gif when the user presses the 's' key.\n// Wait 1 second after the key press before recording.\nfunction keyPressed() {\n if (key === 's') {\n saveGif('mySketch', 5, { delay: 1 });\n }\n}\n
\nTints images using a color.
\nThe version of tint()
with one parameter interprets it one of four ways.\nIf the parameter is a number, it's interpreted as a grayscale value. If the\nparameter is a string, it's interpreted as a CSS color string. An array of\n[R, G, B, A]
values or a p5.Color object can\nalso be used to set the tint color.
The version of tint()
with two parameters uses the first one as a\ngrayscale value and the second as an alpha value. For example, calling\ntint(255, 128)
will make an image 50% transparent.
The version of tint()
with three parameters interprets them as RGB or\nHSB values, depending on the current\ncolorMode(). The optional fourth parameter\nsets the alpha value. For example, tint(255, 0, 0, 100)
will give images\na red tint and make them transparent.
red or hue value.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,"green or saturation value.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,"blue or brightness.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"alpha"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"value"],"description":[0,"CSS color string.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"gray"],"description":[0,"grayscale value.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"alpha"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"values"],"description":[0,"array containing the red, green, blue &\n alpha components of the color.
\n"],"type":[0,"Number[]"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"the tint color
\n"],"type":[0,"p5.Color"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Left image.\n image(img, 0, 0);\n\n // Right image.\n // Tint with a CSS color string.\n tint('red');\n image(img, 50, 0);\n\n describe('Two images of an umbrella and a ceiling side-by-side. The image on the right has a red tint.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Left image.\n image(img, 0, 0);\n\n // Right image.\n // Tint with RGB values.\n tint(255, 0, 0);\n image(img, 50, 0);\n\n describe('Two images of an umbrella and a ceiling side-by-side. The image on the right has a red tint.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Left.\n image(img, 0, 0);\n\n // Right.\n // Tint with RGBA values.\n tint(255, 0, 0, 100);\n image(img, 50, 0);\n\n describe('Two images of an umbrella and a ceiling side-by-side. The image on the right has a transparent red tint.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Left.\n image(img, 0, 0);\n\n // Right.\n // Tint with grayscale and alpha values.\n tint(255, 180);\n image(img, 50, 0);\n\n describe('Two images of an umbrella and a ceiling side-by-side. The image on the right is transparent.');\n}\n
\nCopies a region of pixels from one image to another.
\nThe first parameter, srcImage
, is the\np5.Image object to blend.
The next four parameters, sx
, sy
, sw
, and sh
determine the region\nto blend from the source image. (sx, sy)
is the top-left corner of the\nregion. sw
and sh
are the regions width and height.
The next four parameters, dx
, dy
, dw
, and dh
determine the region\nof the canvas to blend into. (dx, dy)
is the top-left corner of the\nregion. dw
and dh
are the regions width and height.
The tenth parameter, blendMode
, sets the effect used to blend the images'\ncolors. The options are BLEND
, DARKEST
, LIGHTEST
, DIFFERENCE
,\nMULTIPLY
, EXCLUSION
, SCREEN
, REPLACE
, OVERLAY
, HARD_LIGHT
,\nSOFT_LIGHT
, DODGE
, BURN
, ADD
, or NORMAL
source image.
\n"],"type":[0,"p5.Image"]}],[0,{"name":[0,"sx"],"description":[0,"x-coordinate of the source's upper-left corner.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"sy"],"description":[0,"y-coordinate of the source's upper-left corner.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"sw"],"description":[0,"source image width.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"sh"],"description":[0,"source image height.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"dx"],"description":[0,"x-coordinate of the destination's upper-left corner.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"dy"],"description":[0,"y-coordinate of the destination's upper-left corner.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"dw"],"description":[0,"destination image width.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"dh"],"description":[0,"destination image height.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"blendMode"],"description":[0,"the blend mode. either\n BLEND, DARKEST, LIGHTEST, DIFFERENCE,\n MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.
\n"],"type":[0,"Constant"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"sx"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"sy"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"sw"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"sh"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dx"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dy"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dw"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dh"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"blendMode"],"description":[0,""],"type":[0,"Constant"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nlet img0;\nlet img1;\n\n// Load the images.\nfunction preload() {\n img0 = loadImage('/assets/rockies.jpg');\n img1 = loadImage('/assets/bricks_third.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use the mountains as the background.\n background(img0);\n\n // Display the bricks.\n image(img1, 0, 0);\n\n // Display the bricks faded into the landscape.\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n\n describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears faded on the right of the image.');\n}\n
\n\nlet img0;\nlet img1;\n\n// Load the images.\nfunction preload() {\n img0 = loadImage('/assets/rockies.jpg');\n img1 = loadImage('/assets/bricks_third.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use the mountains as the background.\n background(img0);\n\n // Display the bricks.\n image(img1, 0, 0);\n\n // Display the bricks partially transparent.\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n\n describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears transparent on the right of the image.');\n}\n
\n\nlet img0;\nlet img1;\n\n// Load the images.\nfunction preload() {\n img0 = loadImage('/assets/rockies.jpg');\n img1 = loadImage('/assets/bricks_third.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use the mountains as the background.\n background(img0);\n\n // Display the bricks.\n image(img1, 0, 0);\n\n // Display the bricks washed out into the landscape.\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n\n 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.');\n}\n
\nCopies pixels from a source image to a region of the canvas.
\nThe first parameter, srcImage
, is the\np5.Image object to blend. The source image can be\nthe canvas itself or a\np5.Image object. copy()
will scale pixels from\nthe 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\nto copy from the source image. (sx, sy)
is the top-left corner of the\nregion. sw
and sh
are the region's width and height.
The next four parameters, dx
, dy
, dw
, and dh
determine the region\nof the canvas to copy into. (dx, dy)
is the top-left corner of the\nregion. dw
and dh
are the region's width and height.
source image.
\n"],"type":[0,"p5.Image|p5.Element"]}],[0,{"name":[0,"sx"],"description":[0,"x-coordinate of the source's upper-left corner.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"sy"],"description":[0,"y-coordinate of the source's upper-left corner.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"sw"],"description":[0,"source image width.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"sh"],"description":[0,"source image height.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"dx"],"description":[0,"x-coordinate of the destination's upper-left corner.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"dy"],"description":[0,"y-coordinate of the destination's upper-left corner.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"dw"],"description":[0,"destination image width.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"dh"],"description":[0,"destination image height.
\n"],"type":[0,"Integer"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"sx"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"sy"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"sw"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"sh"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dx"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dy"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dw"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dh"],"description":[0,""],"type":[0,"Integer"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use the mountains as the background.\n background(img);\n\n // Copy a region of pixels to another spot.\n copy(img, 7, 22, 10, 10, 35, 25, 50, 50);\n\n // Outline the copied region.\n stroke(255);\n noFill();\n square(7, 22, 10);\n\n 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.');\n}\n
\nApplies an image filter to the canvas.
\nThe preset options are:
\nINVERT
\nInverts the colors in the image. No parameter is used.
GRAY
\nConverts the image to grayscale. No parameter is used.
THRESHOLD
\nConverts the image to black and white. Pixels with a grayscale value\nabove a given threshold are converted to white. The rest are converted to\nblack. The threshold must be between 0.0 (black) and 1.0 (white). If no\nvalue is specified, 0.5 is used.
OPAQUE
\nSets the alpha channel to entirely opaque. No parameter is used.
POSTERIZE
\nLimits the number of colors in the image. Each color channel is limited to\nthe number of colors specified. Values between 2 and 255 are valid, but\nresults are most noticeable with lower values. The default value is 4.
BLUR
\nBlurs the image. The level of blurring is specified by a blur radius. Larger\nvalues increase the blur. The default value is 4. A gaussian blur is used\nin P2D
mode. A box blur is used in WEBGL
mode.
ERODE
\nReduces the light areas. No parameter is used.
DILATE
\nIncreases the light areas. No parameter is used.
filter()
uses WebGL in the background by default because it's faster.\nThis can be disabled in P2D
mode by adding a false
argument, as in\nfilter(BLUR, false)
. This may be useful to keep computation off the GPU\nor to work around a lack of WebGL support.
In WebgL mode, filter()
can also use custom shaders. See\ncreateFilterShader() for more\ninformation.
either THRESHOLD, GRAY, OPAQUE, INVERT,\n POSTERIZE, BLUR, ERODE, DILATE or BLUR.
\n"],"type":[0,"Constant"]}],[0,{"name":[0,"filterParam"],"description":[0,"parameter unique to each filter.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"useWebGL"],"description":[0,"flag to control whether to use fast\n WebGL filters (GPU) or original image\n filters (CPU); defaults to true
.
shader that's been loaded, with the\n frag shader using a tex0
uniform.
\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the INVERT filter.\n filter(INVERT);\n\n describe('A blue brick wall.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the GRAY filter.\n filter(GRAY);\n\n describe('A brick wall drawn in grayscale.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the THRESHOLD filter.\n filter(THRESHOLD);\n\n describe('A brick wall drawn in black and white.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the OPAQUE filter.\n filter(OPAQUE);\n\n describe('A red brick wall.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the POSTERIZE filter.\n filter(POSTERIZE, 3);\n\n describe('An image of a red brick wall drawn with limited color palette.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the BLUR filter.\n filter(BLUR, 3);\n\n describe('A blurry image of a red brick wall.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the DILATE filter.\n filter(DILATE);\n\n describe('A red brick wall with bright lines between each brick.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the ERODE filter.\n filter(ERODE);\n\n describe('A red brick wall with faint lines between each brick.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the BLUR filter.\n // Don't use WebGL.\n filter(BLUR, 3, false);\n\n describe('A blurry image of a red brick wall.');\n}\n
\nGets a pixel or a region of pixels from the canvas.
\nget()
is easy to use but it's not as fast as\npixels. Use pixels\nto 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\ncoordinates. It returns an array with the [R, G, B, A]
values of the\npixel at the given point.
The version of get()
with four parameters interprets them as coordinates\nand dimensions. It returns a subsection of the canvas as a\np5.Image object. The first two parameters are the\ncoordinates for the upper-left corner of the subsection. The last two\nparameters are the width and height of the subsection.
Use p5.Image.get() to work directly with\np5.Image objects.
\n"],"line":[0,820],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"x"],"description":[0,"x-coordinate of the pixel.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"y-coordinate of the pixel.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"w"],"description":[0,"width of the subsection to be returned.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"h"],"description":[0,"height of the subsection to be returned.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[]]}],[0,{"params":[1,[[0,{"name":[0,"x"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,""],"type":[0,"Number"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"subsection as a p5.Image object."],"type":[0,"p5.Image"]}],"example":[1,[[0,"\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Get the entire canvas.\n let c = get();\n\n // Display half the canvas.\n image(c, 50, 0);\n\n describe('Two identical mountain landscapes shown side-by-side.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Get the color of a pixel.\n let c = get(50, 90);\n\n // Style the square with the pixel's color.\n fill(c);\n noStroke();\n\n // Display the square.\n square(25, 25, 50);\n\n describe('A mountain landscape with an olive green square in its center.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Get a region of the image.\n let c = get(0, 0, 50, 50);\n\n // Display the region.\n image(c, 50, 50);\n\n describe('A mountain landscape drawn on top of another mountain landscape.');\n}\n
\nLoads the current value of each pixel on the canvas into the\npixels array.
\nloadPixels()
must be called before reading from or writing to\npixels.
\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0, 100, 100);\n\n // Get the pixel density.\n let d = pixelDensity();\n\n // Calculate the halfway index in the pixels array.\n let halfImage = 4 * (d * width) * (d * height / 2);\n\n // Load the pixels array.\n loadPixels();\n\n // Copy the top half of the canvas to the bottom.\n for (let i = 0; i < halfImage; i += 1) {\n pixels[i + halfImage] = pixels[i];\n }\n\n // Update the canvas.\n updatePixels();\n\n describe('Two identical images of mountain landscapes, one on top of the other.');\n}\n
\nAn array containing the color of each pixel on the canvas.
\nColors are stored as numbers representing red, green, blue, and alpha\n(RGBA) values. pixels
is a one-dimensional array for performance reasons.
Each pixel occupies four elements in the pixels
array, one for each RGBA\nvalue. For example, the pixel at coordinates (0, 0) stores its RGBA values\nat pixels[0]
, pixels[1]
, pixels[2]
, and pixels[3]
, respectively.\nThe next pixel at coordinates (1, 0) stores its RGBA values at pixels[4]
,\npixels[5]
, pixels[6]
, and pixels[7]
. And so on. The pixels
array\nfor a 100×100 canvas has 100 × 100 × 4 = 40,000 elements.
Some displays use several smaller pixels to set the color at a single\npoint. The pixelDensity() function returns\nthe pixel density of the canvas. High density displays often have a\npixelDensity() of 2. On such a display, the\npixels
array for a 100×100 canvas has 200 × 200 × 4 =\n160,000 elements.
Accessing the RGBA values for a point on the canvas requires a little math\nas shown below. The loadPixels() function\nmust be called before accessing the pixels
array. The\nupdatePixels() function must be called\nafter any changes are made.
\nfunction setup() {\n createCanvas(100, 100);\n\n // Load the pixels array.\n loadPixels();\n\n // Set the dot's coordinates.\n let x = 50;\n let y = 50;\n\n // Get the pixel density.\n let d = pixelDensity();\n\n // Set the pixel(s) at the center of the canvas black.\n for (let i = 0; i < d; i += 1) {\n for (let j = 0; j < d; j += 1) {\n let index = 4 * ((y * d + j) * width * d + (x * d + i));\n // Red.\n pixels[index] = 0;\n // Green.\n pixels[index + 1] = 0;\n // Blue.\n pixels[index + 2] = 0;\n // Alpha.\n pixels[index + 3] = 255;\n }\n }\n\n // Update the canvas.\n updatePixels();\n\n describe('A black dot in the middle of a gray rectangle.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Load the pixels array.\n loadPixels();\n\n // Get the pixel density.\n let d = pixelDensity();\n\n // Calculate the halfway index in the pixels array.\n let halfImage = 4 * (d * width) * (d * height / 2);\n\n // Make the top half of the canvas red.\n for (let i = 0; i < halfImage; i += 4) {\n // Red.\n pixels[i] = 255;\n // Green.\n pixels[i + 1] = 0;\n // Blue.\n pixels[i + 2] = 0;\n // Alpha.\n pixels[i + 3] = 255;\n }\n\n // Update the canvas.\n updatePixels();\n\n describe('A red rectangle drawn above a gray rectangle.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Color object.\n let pink = color(255, 102, 204);\n\n // Load the pixels array.\n loadPixels();\n\n // Get the pixel density.\n let d = pixelDensity();\n\n // Calculate the halfway index in the pixels array.\n let halfImage = 4 * (d * width) * (d * height / 2);\n\n // Make the top half of the canvas red.\n for (let i = 0; i < halfImage; i += 4) {\n pixels[i] = red(pink);\n pixels[i + 1] = green(pink);\n pixels[i + 2] = blue(pink);\n pixels[i + 3] = alpha(pink);\n }\n\n // Update the canvas.\n updatePixels();\n\n describe('A pink rectangle drawn above a gray rectangle.');\n}\n
\nSets the color of a pixel or draws an image to the canvas.
\nset()
is easy to use but it's not as fast as\npixels. Use pixels\nto set many pixel values.
set()
interprets the first two parameters as x- and y-coordinates. It\ninterprets the last parameter as a grayscale value, a [R, G, B, A]
pixel\narray, a p5.Color object, or a\np5.Image object. If an image is passed, the first\ntwo parameters set the coordinates for the image's upper-left corner,\nregardless of the current imageMode().
updatePixels() must be called after using\nset()
for changes to appear.
x-coordinate of the pixel.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"y-coordinate of the pixel.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"c"],"description":[0,"grayscale value | pixel array |\n p5.Color object | p5.Image to copy.
\n"],"type":[0,"Number|Number[]|Object"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Set four pixels to black.\n set(30, 20, 0);\n set(85, 20, 0);\n set(85, 75, 0);\n set(30, 75, 0);\n\n // Update the canvas.\n updatePixels();\n\n describe('Four black dots arranged in a square drawn on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let black = color(0);\n\n // Set four pixels to black.\n set(30, 20, black);\n set(85, 20, black);\n set(85, 75, black);\n set(30, 75, black);\n\n // Update the canvas.\n updatePixels();\n\n describe('Four black dots arranged in a square drawn on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(255);\n\n // Draw a horizontal color gradient.\n for (let x = 0; x < 100; x += 1) {\n for (let y = 0; y < 100; y += 1) {\n // Calculate the grayscale value.\n let c = map(x, 0, 100, 0, 255);\n\n // Set the pixel using the grayscale value.\n set(x, y, c);\n }\n }\n\n // Update the canvas.\n updatePixels();\n\n describe('A horiztonal color gradient from black to white.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use the image to set all pixels.\n set(0, 0, img);\n\n // Update the canvas.\n updatePixels();\n\n describe('An image of a mountain landscape.');\n}\n
\nUpdates the canvas with the RGBA values in the\npixels array.
\nupdatePixels()
only needs to be called after changing values in the\npixels array. Such changes can be made directly\nafter calling loadPixels() or by calling\nset().
x-coordinate of the upper-left corner of region\n to update.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"y"],"description":[0,"y-coordinate of the upper-left corner of region\n to update.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"w"],"description":[0,"width of region to update.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"h"],"description":[0,"height of region to update.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0, 100, 100);\n\n // Get the pixel density.\n let d = pixelDensity();\n\n // Calculate the halfway index in the pixels array.\n let halfImage = 4 * (d * width) * (d * height / 2);\n\n // Load the pixels array.\n loadPixels();\n\n // Copy the top half of the canvas to the bottom.\n for (let i = 0; i < halfImage; i += 1) {\n pixels[i + halfImage] = pixels[i];\n }\n\n // Update the canvas.\n updatePixels();\n\n describe('Two identical images of mountain landscapes, one on top of the other.');\n}\n
\nA class to describe an image.
\nImages are rectangular grids of pixels that can be displayed and modified.
\nExisting images can be loaded by calling\nloadImage(). Blank images can be created by\ncalling createImage(). p5.Image
objects\nhave methods for common tasks such as applying filters and modifying\npixel values.
\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('An image of a brick wall.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Apply the GRAY filter.\n img.filter(GRAY);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('A grayscale image of a brick wall.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the image's pixels.\n img.loadPixels();\n\n // Set the pixels to black.\n for (let x = 0; x < img.width; x += 1) {\n for (let y = 0; y < img.height; y += 1) {\n img.set(x, y, 0);\n }\n }\n\n // Update the image.\n img.updatePixels();\n\n // Display the image.\n image(img, 17, 17);\n\n describe('A black square drawn in the middle of a gray square.');\n}\n
\nGets or sets the pixel density for high pixel density displays.
\nBy default, the density will be set to 1.
\nCall this method with no arguments to get the default density, or pass\nin a number to set the density. If a non-positive number is provided,\nit defaults to 1.
\n"],"path":[0,"p5.Image/pixelDensity"]}],"loadPixels":[0,{"description":[0,"Loads the current value of each pixel in the image into the img.pixels
\narray.
img.loadPixels()
must be called before reading or modifying pixel\nvalues.
Updates the canvas with the RGBA values in the\nimg.pixels array.
\nimg.updatePixels()
only needs to be called after changing values in\nthe img.pixels array. Such changes can be\nmade directly after calling\nimg.loadPixels() or by calling\nimg.set().
The optional parameters x
, y
, width
, and height
define a\nsubsection of the image to update. Doing so can improve performance in\nsome cases.
If the image was loaded from a GIF, then calling img.updatePixels()
\nwill update the pixels in current frame.
Gets a pixel or a region of pixels from the image.
\nimg.get()
is easy to use but it's not as fast as\nimg.pixels. Use\nimg.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)
,\ninterprets them as coordinates. It returns an array with the\n[R, G, B, A]
values of the pixel at the given point.
The version of img.get()
with four parameters, as in\nimg,get(10, 20, 50, 90)
, interprets them as\ncoordinates and dimensions. The first two parameters are the coordinates\nof the upper-left corner of the subsection. The last two parameters are\nthe width and height of the subsection. It returns a subsection of the\ncanvas in a new p5.Image object.
Use img.get()
instead of get() to work directly\nwith images.
Sets the color of one or more pixels within an image.
\nimg.set()
is easy to use but it's not as fast as\nimg.pixels. Use\nimg.pixels to set many pixel values.
img.set()
interprets the first two parameters as x- and y-coordinates. It\ninterprets the last parameter as a grayscale value, a [R, G, B, A]
pixel\narray, a p5.Color object, or another\np5.Image object.
img.updatePixels() must be called\nafter using img.set()
for changes to appear.
Resizes the image to a given width and height.
\nThe image's original aspect ratio can be kept by passing 0 for either\nwidth
or height
. For example, calling img.resize(50, 0)
on an image\nthat was 500 × 300 pixels will resize it to 50 × 30 pixels.
Copies pixels from a source image to this image.
\nThe first parameter, srcImage
, is an optional\np5.Image object to copy. If a source image isn't\npassed, then img.copy()
can copy a region of this image to another\nregion.
The next four parameters, sx
, sy
, sw
, and sh
determine the region\nto copy from the source image. (sx, sy)
is the top-left corner of the\nregion. sw
and sh
are the region's width and height.
The next four parameters, dx
, dy
, dw
, and dh
determine the region\nof this image to copy into. (dx, dy)
is the top-left corner of the\nregion. dw
and dh
are the region's width and height.
Calling img.copy()
will scale pixels from the source region if it isn't\nthe same size as the destination region.
Masks part of the image with another.
\nimg.mask()
uses another p5.Image object's\nalpha channel as the alpha channel for this image. Masks are cumulative\nand can't be removed once applied. If the mask has a different\npixel density from this image, the mask will be scaled.
Applies an image filter to the image.
\nThe preset options are:
\nINVERT
\nInverts the colors in the image. No parameter is used.
GRAY
\nConverts the image to grayscale. No parameter is used.
THRESHOLD
\nConverts the image to black and white. Pixels with a grayscale value\nabove a given threshold are converted to white. The rest are converted to\nblack. The threshold must be between 0.0 (black) and 1.0 (white). If no\nvalue is specified, 0.5 is used.
OPAQUE
\nSets the alpha channel to be entirely opaque. No parameter is used.
POSTERIZE
\nLimits the number of colors in the image. Each color channel is limited to\nthe number of colors specified. Values between 2 and 255 are valid, but\nresults are most noticeable with lower values. The default value is 4.
BLUR
\nBlurs the image. The level of blurring is specified by a blur radius. Larger\nvalues increase the blur. The default value is 4. A gaussian blur is used\nin P2D
mode. A box blur is used in WEBGL
mode.
ERODE
\nReduces the light areas. No parameter is used.
DILATE
\nIncreases the light areas. No parameter is used.
Copies a region of pixels from another image into this one.
\nThe first parameter, srcImage
, is the\np5.Image object to blend.
The next four parameters, sx
, sy
, sw
, and sh
determine the region\nto blend from the source image. (sx, sy)
is the top-left corner of the\nregion. sw
and sh
are the regions width and height.
The next four parameters, dx
, dy
, dw
, and dh
determine the region\nof the canvas to blend into. (dx, dy)
is the top-left corner of the\nregion. dw
and dh
are the regions width and height.
The tenth parameter, blendMode
, sets the effect used to blend the images'\ncolors. The options are BLEND
, DARKEST
, LIGHTEST
, DIFFERENCE
,\nMULTIPLY
, EXCLUSION
, SCREEN
, REPLACE
, OVERLAY
, HARD_LIGHT
,\nSOFT_LIGHT
, DODGE
, BURN
, ADD
, or NORMAL
.
Saves the image to a file.
\nBy default, img.save()
saves the image as a PNG image called\nuntitled.png
.
The first parameter, filename
, is optional. It's a string that sets the\nfile's name. If a file extension is included, as in\nimg.save('drawing.png')
, then the image will be saved using that\nformat.
The second parameter, extension
, is also optional. It sets the files format.\nEither 'png'
or 'jpg'
can be used. For example, img.save('drawing', 'jpg')
\nsaves the canvas to a file called drawing.jpg
.
Note: The browser will either save the file immediately or prompt the user\nwith a dialogue window.
\nThe image will only be downloaded as an animated GIF if it was loaded\nfrom a GIF file. See saveGif() to create new\nGIFs.
\n"],"path":[0,"p5.Image/save"]}],"reset":[0,{"description":[0,"Restarts an animated GIF at its first frame.
\n"],"path":[0,"p5.Image/reset"]}],"getCurrentFrame":[0,{"description":[0,"Gets the index of the current frame in an animated GIF.
\n"],"path":[0,"p5.Image/getCurrentFrame"]}],"setFrame":[0,{"description":[0,"Sets the current frame in an animated GIF.
\n"],"path":[0,"p5.Image/setFrame"]}],"numFrames":[0,{"description":[0,"Returns the number of frames in an animated GIF.
\n"],"path":[0,"p5.Image/numFrames"]}],"play":[0,{"description":[0,"Plays an animated GIF that was paused with\nimg.pause().
\n"],"path":[0,"p5.Image/play"]}],"pause":[0,{"description":[0,"Pauses an animated GIF.
\nThe GIF can be resumed by calling\nimg.play().
\n"],"path":[0,"p5.Image/pause"]}],"delay":[0,{"description":[0,"Changes the delay between frames in an animated GIF.
\nThe first parameter, delay
, is the length of the delay in milliseconds.
The second parameter, index
, is optional. If provided, only the frame\nat index
will have its delay modified. All other frames will keep\ntheir default delay.
The image's width in pixels.
\n"],"path":[0,"p5.Image/width"]}],"height":[0,{"description":[0,"The image's height in pixels.
\n"],"path":[0,"p5.Image/height"]}],"pixels":[0,{"description":[0,"An array containing the color of each pixel in the image.
\nColors are stored as numbers representing red, green, blue, and alpha\n(RGBA) values. img.pixels
is a one-dimensional array for performance\nreasons.
Each pixel occupies four elements in the pixels array, one for each\nRGBA value. For example, the pixel at coordinates (0, 0) stores its\nRGBA values at img.pixels[0]
, img.pixels[1]
, img.pixels[2]
,\nand img.pixels[3]
, respectively. The next pixel at coordinates (1, 0)\nstores its RGBA values at img.pixels[4]
, img.pixels[5]
,\nimg.pixels[6]
, and img.pixels[7]
. And so on. The img.pixels
array\nfor a 100×100 p5.Image object has\n100 × 100 × 4 = 40,000 elements.
Accessing the RGBA values for a pixel in the image requires a little\nmath as shown in the examples below. The\nimg.loadPixels()\nmethod must be called before accessing the img.pixels
array. The\nimg.updatePixels() method must be\ncalled after any changes are made.
Copies a region of pixels from another image into this one.
\nThe first parameter, srcImage
, is the\np5.Image object to blend.
The next four parameters, sx
, sy
, sw
, and sh
determine the region\nto blend from the source image. (sx, sy)
is the top-left corner of the\nregion. sw
and sh
are the regions width and height.
The next four parameters, dx
, dy
, dw
, and dh
determine the region\nof the canvas to blend into. (dx, dy)
is the top-left corner of the\nregion. dw
and dh
are the regions width and height.
The tenth parameter, blendMode
, sets the effect used to blend the images'\ncolors. The options are BLEND
, DARKEST
, LIGHTEST
, DIFFERENCE
,\nMULTIPLY
, EXCLUSION
, SCREEN
, REPLACE
, OVERLAY
, HARD_LIGHT
,\nSOFT_LIGHT
, DODGE
, BURN
, ADD
, or NORMAL
.
source image
\n"],"type":[0,"p5.Image"]}],[0,{"name":[0,"sx"],"description":[0,"x-coordinate of the source's upper-left corner.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"sy"],"description":[0,"y-coordinate of the source's upper-left corner.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"sw"],"description":[0,"source image width.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"sh"],"description":[0,"source image height.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"dx"],"description":[0,"x-coordinate of the destination's upper-left corner.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"dy"],"description":[0,"y-coordinate of the destination's upper-left corner.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"dw"],"description":[0,"destination image width.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"dh"],"description":[0,"destination image height.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"blendMode"],"description":[0,"the blend mode. either\n BLEND, DARKEST, LIGHTEST, DIFFERENCE,\n MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.
\nAvailable blend modes are: normal | multiply | screen | overlay |\n darken | lighten | color-dodge | color-burn | hard-light |\n soft-light | difference | exclusion | hue | saturation |\n color | luminosity
\nhttp://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/
\n"],"type":[0,"Constant"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"sx"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"sy"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"sw"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"sh"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dx"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dy"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dw"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dh"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"blendMode"],"description":[0,""],"type":[0,"Constant"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Image"],"chainable":[0,false],"example":[1,[[0,"\n\nlet mountains;\nlet bricks;\n\n// Load the images.\nfunction preload() {\n mountains = loadImage('/assets/rockies.jpg');\n bricks = loadImage('/assets/bricks_third.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Blend the bricks image into the mountains.\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n\n // Display the mountains image.\n image(mountains, 0, 0);\n\n // Display the bricks image.\n image(bricks, 0, 0);\n\n describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears faded on the right of the image.');\n}\n
\n\nlet mountains;\nlet bricks;\n\n// Load the images.\nfunction preload() {\n mountains = loadImage('/assets/rockies.jpg');\n bricks = loadImage('/assets/bricks_third.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Blend the bricks image into the mountains.\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n\n // Display the mountains image.\n image(mountains, 0, 0);\n\n // Display the bricks image.\n image(bricks, 0, 0);\n\n describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears transparent on the right of the image.');\n}\n
\n\nlet mountains;\nlet bricks;\n\n// Load the images.\nfunction preload() {\n mountains = loadImage('/assets/rockies.jpg');\n bricks = loadImage('/assets/bricks_third.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Blend the bricks image into the mountains.\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n\n // Display the mountains image.\n image(mountains, 0, 0);\n\n // Display the bricks image.\n image(bricks, 0, 0);\n\n 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.');\n}\n
\nCopies pixels from a source image to this image.
\nThe first parameter, srcImage
, is an optional\np5.Image object to copy. If a source image isn't\npassed, then img.copy()
can copy a region of this image to another\nregion.
The next four parameters, sx
, sy
, sw
, and sh
determine the region\nto copy from the source image. (sx, sy)
is the top-left corner of the\nregion. sw
and sh
are the region's width and height.
The next four parameters, dx
, dy
, dw
, and dh
determine the region\nof this image to copy into. (dx, dy)
is the top-left corner of the\nregion. dw
and dh
are the region's width and height.
Calling img.copy()
will scale pixels from the source region if it isn't\nthe same size as the destination region.
source image.
\n"],"type":[0,"p5.Image|p5.Element"]}],[0,{"name":[0,"sx"],"description":[0,"x-coordinate of the source's upper-left corner.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"sy"],"description":[0,"y-coordinate of the source's upper-left corner.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"sw"],"description":[0,"source image width.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"sh"],"description":[0,"source image height.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"dx"],"description":[0,"x-coordinate of the destination's upper-left corner.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"dy"],"description":[0,"y-coordinate of the destination's upper-left corner.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"dw"],"description":[0,"destination image width.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"dh"],"description":[0,"destination image height.
\n"],"type":[0,"Integer"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"sx"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"sy"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"sw"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"sh"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dx"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dy"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dw"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dh"],"description":[0,""],"type":[0,"Integer"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Image"],"chainable":[0,false],"example":[1,[[0,"\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Copy one region of the image to another.\n img.copy(7, 22, 10, 10, 35, 25, 50, 50);\n\n // Display the image.\n image(img, 0, 0);\n\n // Outline the copied region.\n stroke(255);\n noFill();\n square(7, 22, 10);\n\n 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.');\n}\n
\n\nlet mountains;\nlet bricks;\n\n// Load the images.\nfunction preload() {\n mountains = loadImage('/assets/rockies.jpg');\n bricks = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Calculate the center of the bricks image.\n let x = bricks.width / 2;\n let y = bricks.height / 2;\n\n // Copy the bricks to the mountains image.\n mountains.copy(bricks, 0, 0, x, y, 0, 0, x, y);\n\n // Display the mountains image.\n image(mountains, 0, 0);\n\n describe('An image of a brick wall drawn at the top-left of an image of a mountain landscape.');\n}\n
\nChanges the delay between frames in an animated GIF.
\nThe first parameter, delay
, is the length of the delay in milliseconds.
The second parameter, index
, is optional. If provided, only the frame\nat index
will have its delay modified. All other frames will keep\ntheir default delay.
delay in milliseconds between switching frames.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"index"],"description":[0,"index of the frame that will have its delay modified.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Image"],"chainable":[0,false],"example":[1,[[0,"\n\nlet gifFast;\nlet gifSlow;\n\n// Load the images.\nfunction preload() {\n gifFast = loadImage('/assets/arnott-wallace-eye-loop-forever.gif');\n gifSlow = loadImage('/assets/arnott-wallace-eye-loop-forever.gif');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Resize the images.\n gifFast.resize(50, 50);\n gifSlow.resize(50, 50);\n\n // Set the delay lengths.\n gifFast.delay(10);\n gifSlow.delay(100);\n\n describe('Two animated eyes looking around. The eye on the left moves faster than the eye on the right.');\n}\n\nfunction draw() {\n // Display the images.\n image(gifFast, 0, 0);\n image(gifSlow, 50, 0);\n}\n
\n\nlet gif;\n\n// Load the image.\nfunction preload() {\n gif = loadImage('/assets/arnott-wallace-eye-loop-forever.gif');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Set the delay of frame 67.\n gif.delay(3000, 67);\n\n describe('An animated eye looking around. It pauses for three seconds while it looks down.');\n}\n\nfunction draw() {\n // Display the image.\n image(gif, 0, 0);\n}\n
\nApplies an image filter to the image.
\nThe preset options are:
\nINVERT
\nInverts the colors in the image. No parameter is used.
GRAY
\nConverts the image to grayscale. No parameter is used.
THRESHOLD
\nConverts the image to black and white. Pixels with a grayscale value\nabove a given threshold are converted to white. The rest are converted to\nblack. The threshold must be between 0.0 (black) and 1.0 (white). If no\nvalue is specified, 0.5 is used.
OPAQUE
\nSets the alpha channel to be entirely opaque. No parameter is used.
POSTERIZE
\nLimits the number of colors in the image. Each color channel is limited to\nthe number of colors specified. Values between 2 and 255 are valid, but\nresults are most noticeable with lower values. The default value is 4.
BLUR
\nBlurs the image. The level of blurring is specified by a blur radius. Larger\nvalues increase the blur. The default value is 4. A gaussian blur is used\nin P2D
mode. A box blur is used in WEBGL
mode.
ERODE
\nReduces the light areas. No parameter is used.
DILATE
\nIncreases the light areas. No parameter is used.
either THRESHOLD, GRAY, OPAQUE, INVERT,\n POSTERIZE, ERODE, DILATE or BLUR.
\n"],"type":[0,"Constant"]}],[0,{"name":[0,"filterParam"],"description":[0,"parameter unique to each filter.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Image"],"chainable":[0,false],"example":[1,[[0,"\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Apply the INVERT filter.\n img.filter(INVERT);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('A blue brick wall.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Apply the GRAY filter.\n img.filter(GRAY);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('A brick wall drawn in grayscale.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Apply the THRESHOLD filter.\n img.filter(THRESHOLD);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('A brick wall drawn in black and white.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Apply the OPAQUE filter.\n img.filter(OPAQUE);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('A red brick wall.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Apply the POSTERIZE filter.\n img.filter(POSTERIZE, 3);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('An image of a red brick wall drawn with a limited color palette.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Apply the BLUR filter.\n img.filter(BLUR, 3);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('A blurry image of a red brick wall.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Apply the DILATE filter.\n img.filter(DILATE);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('A red brick wall with bright lines between each brick.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Apply the ERODE filter.\n img.filter(ERODE);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('A red brick wall with faint lines between each brick.');\n}\n
\nGets a pixel or a region of pixels from the image.
\nimg.get()
is easy to use but it's not as fast as\nimg.pixels. Use\nimg.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)
,\ninterprets them as coordinates. It returns an array with the\n[R, G, B, A]
values of the pixel at the given point.
The version of img.get()
with four parameters, as in\nimg,get(10, 20, 50, 90)
, interprets them as\ncoordinates and dimensions. The first two parameters are the coordinates\nof the upper-left corner of the subsection. The last two parameters are\nthe width and height of the subsection. It returns a subsection of the\ncanvas in a new p5.Image object.
Use img.get()
instead of get() to work directly\nwith images.
x-coordinate of the pixel.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"y-coordinate of the pixel.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"w"],"description":[0,"width of the subsection to be returned.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"h"],"description":[0,"height of the subsection to be returned.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[]]}],[0,{"params":[1,[[0,{"name":[0,"x"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,""],"type":[0,"Number"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Image"],"chainable":[0,false],"return":[0,{"description":[0,"subsection as a p5.Image object."],"type":[0,"p5.Image"]}],"example":[1,[[0,"\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Display the image.\n image(img, 0, 0);\n\n // Copy the image.\n let img2 = get();\n\n // Display the copied image on the right.\n image(img2, 50, 0);\n\n describe('Two identical mountain landscapes shown side-by-side.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Get a pixel's color.\n let c = img.get(50, 90);\n\n // Style the square using the pixel's color.\n fill(c);\n noStroke();\n\n // Draw the square.\n square(25, 25, 50);\n\n describe('A mountain landscape with an olive green square in its center.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Copy half of the image.\n let img2 = img.get(0, 0, img.width / 2, img.height / 2);\n\n // Display half of the image.\n image(img2, 50, 50);\n\n describe('A mountain landscape drawn on top of another mountain landscape.');\n}\n
\nGets the index of the current frame in an animated GIF.
\n"],"line":[0,1716],"itemtype":[0,"method"],"class":[0,"p5.Image"],"chainable":[0,false],"return":[0,{"description":[0,"index of the GIF's current frame."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nlet gif;\n\n// Load the image.\nfunction preload() {\n gif = loadImage('/assets/arnott-wallace-eye-loop-forever.gif');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A cartoon eye repeatedly looks around, then outwards. A number displayed in the bottom-left corner increases from 0 to 124, then repeats.');\n}\n\nfunction draw() {\n // Get the index of the current GIF frame.\n let index = gif.getCurrentFrame();\n\n // Display the image.\n image(gif, 0, 0);\n\n // Display the current frame.\n text(index, 10, 90);\n}\n
\nThe image's height in pixels.
\n"],"line":[0,151],"itemtype":[0,"property"],"class":[0,"p5.Image"],"example":[1,[[0,"\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Calculate the center coordinates.\n let x = img.width / 2;\n let y = img.height / 2;\n\n // Draw a circle at the image's center.\n circle(x, y, 20);\n\n describe('An image of a mountain landscape with a white circle drawn in the middle.');\n}\n
\nLoads the current value of each pixel in the image into the img.pixels
\narray.
img.loadPixels()
must be called before reading or modifying pixel\nvalues.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the image's pixels.\n img.loadPixels();\n\n // Set the pixels to black.\n for (let x = 0; x < img.width; x += 1) {\n for (let y = 0; y < img.height; y += 1) {\n img.set(x, y, 0);\n }\n }\n\n // Update the image.\n img.updatePixels();\n\n // Display the image.\n image(img, 17, 17);\n\n describe('A black square drawn in the middle of a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the image's pixels.\n img.loadPixels();\n\n for (let i = 0; i < img.pixels.length; i += 4) {\n // Red.\n img.pixels[i] = 0;\n // Green.\n img.pixels[i + 1] = 0;\n // Blue.\n img.pixels[i + 2] = 0;\n // Alpha.\n img.pixels[i + 3] = 255;\n }\n\n // Update the image.\n img.updatePixels();\n\n // Display the image.\n image(img, 17, 17);\n\n describe('A black square drawn in the middle of a gray square.');\n}\n
\nMasks part of the image with another.
\nimg.mask()
uses another p5.Image object's\nalpha channel as the alpha channel for this image. Masks are cumulative\nand can't be removed once applied. If the mask has a different\npixel density from this image, the mask will be scaled.
source image.
\n"],"type":[0,"p5.Image"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Image"],"chainable":[0,false],"example":[1,[[0,"\n\nlet photo;\nlet maskImage;\n\n// Load the images.\nfunction preload() {\n photo = loadImage('/assets/rockies.jpg');\n maskImage = loadImage('/assets/mask2.png');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Apply the mask.\n photo.mask(maskImage);\n\n // Display the image.\n image(photo, 0, 0);\n\n describe('An image of a mountain landscape. The right side of the image has a faded patch of white.');\n}\n
\nReturns the number of frames in an animated GIF.
\n"],"line":[0,1818],"itemtype":[0,"method"],"class":[0,"p5.Image"],"chainable":[0,false],"return":[0,{"description":[0,"number of frames in the GIF."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nlet gif;\n\n// Load the image.\nfunction preload() {\n gif = loadImage('/assets/arnott-wallace-eye-loop-forever.gif');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A cartoon eye looks around. The text \"n / 125\" is shown at the bottom of the canvas.');\n}\n\nfunction draw() {\n // Display the image.\n image(gif, 0, 0);\n\n // Display the current state of playback.\n let total = gif.numFrames();\n let index = gif.getCurrentFrame();\n text(`${index} / ${total}`, 30, 90);\n}\n
\nPauses an animated GIF.
\nThe GIF can be resumed by calling\nimg.play().
\n"],"line":[0,1903],"itemtype":[0,"method"],"class":[0,"p5.Image"],"chainable":[0,false],"example":[1,[[0,"\n\nlet gif;\n\n// Load the image.\nfunction preload() {\n gif = loadImage('/assets/nancy-liang-wind-loop-forever.gif');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A drawing of a child with hair blowing in the wind. The animation freezes when clicked and resumes when released.');\n}\n\nfunction draw() {\n background(255);\n\n // Display the image.\n image(gif, 0, 0);\n}\n\n// Pause the GIF when the user presses the mouse.\nfunction mousePressed() {\n gif.pause();\n}\n\n// Play the GIF when the user presses the mouse.\nfunction mouseReleased() {\n gif.play();\n}\n
\nGets or sets the pixel density for high pixel density displays.
\nBy default, the density will be set to 1.
\nCall this method with no arguments to get the default density, or pass\nin a number to set the density. If a non-positive number is provided,\nit defaults to 1.
\n"],"line":[0,299],"params":[1,[[0,{"name":[0,"density"],"description":[0,"A scaling factor for the number of pixels per\nside
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Image"],"chainable":[0,false],"return":[0,{"description":[0,"The current density if called without arguments, or the instance for chaining if setting density."],"type":[0,"Number"]}],"isConstructor":[0,false],"path":[0,"p5.Image/pixelDensity"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Image/pixels.mdx"],"slug":[0,"en/p5image/pixels"],"body":[0,"\n\n# pixels\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"pixels"],"module":[0,"Image"],"submodule":[0,"Image"],"file":[0,"src/image/p5.Image.js"],"description":[0,"An array containing the color of each pixel in the image.
\nColors are stored as numbers representing red, green, blue, and alpha\n(RGBA) values. img.pixels
is a one-dimensional array for performance\nreasons.
Each pixel occupies four elements in the pixels array, one for each\nRGBA value. For example, the pixel at coordinates (0, 0) stores its\nRGBA values at img.pixels[0]
, img.pixels[1]
, img.pixels[2]
,\nand img.pixels[3]
, respectively. The next pixel at coordinates (1, 0)\nstores its RGBA values at img.pixels[4]
, img.pixels[5]
,\nimg.pixels[6]
, and img.pixels[7]
. And so on. The img.pixels
array\nfor a 100×100 p5.Image object has\n100 × 100 × 4 = 40,000 elements.
Accessing the RGBA values for a pixel in the image requires a little\nmath as shown in the examples below. The\nimg.loadPixels()\nmethod must be called before accessing the img.pixels
array. The\nimg.updatePixels() method must be\ncalled after any changes are made.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the image's pixels.\n img.loadPixels();\n\n for (let i = 0; i < img.pixels.length; i += 4) {\n // Red.\n img.pixels[i] = 0;\n // Green.\n img.pixels[i + 1] = 0;\n // Blue.\n img.pixels[i + 2] = 0;\n // Alpha.\n img.pixels[i + 3] = 255;\n }\n\n // Update the image.\n img.updatePixels();\n\n // Display the image.\n image(img, 17, 17);\n\n describe('A black square drawn in the middle of a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the image's pixels.\n img.loadPixels();\n\n // Set the pixels to red.\n for (let i = 0; i < img.pixels.length; i += 4) {\n // Red.\n img.pixels[i] = 255;\n // Green.\n img.pixels[i + 1] = 0;\n // Blue.\n img.pixels[i + 2] = 0;\n // Alpha.\n img.pixels[i + 3] = 255;\n }\n\n // Update the image.\n img.updatePixels();\n\n // Display the image.\n image(img, 17, 17);\n\n describe('A red square drawn in the middle of a gray square.');\n}\n
\nPlays an animated GIF that was paused with\nimg.pause().
\n"],"line":[0,1858],"itemtype":[0,"method"],"class":[0,"p5.Image"],"chainable":[0,false],"example":[1,[[0,"\n\nlet gif;\n\n// Load the image.\nfunction preload() {\n gif = loadImage('/assets/nancy-liang-wind-loop-forever.gif');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A drawing of a child with hair blowing in the wind. The animation freezes when clicked and resumes when released.');\n}\n\nfunction draw() {\n background(255);\n image(gif, 0, 0);\n}\n\n// Pause the GIF when the user presses the mouse.\nfunction mousePressed() {\n gif.pause();\n}\n\n// Play the GIF when the user releases the mouse.\nfunction mouseReleased() {\n gif.play();\n}\n
\nRestarts an animated GIF at its first frame.
\n"],"line":[0,1668],"itemtype":[0,"method"],"class":[0,"p5.Image"],"chainable":[0,false],"example":[1,[[0,"\n\nlet gif;\n\n// Load the image.\nfunction preload() {\n gif = loadImage('/assets/arnott-wallace-wink-loop-once.gif');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A cartoon face winks once and then freezes. Clicking resets the face and makes it wink again.');\n}\n\nfunction draw() {\n background(255);\n\n // Display the image.\n image(gif, 0, 0);\n}\n\n// Reset the GIF when the user presses the mouse.\nfunction mousePressed() {\n gif.reset();\n}\n
\nResizes the image to a given width and height.
\nThe image's original aspect ratio can be kept by passing 0 for either\nwidth
or height
. For example, calling img.resize(50, 0)
on an image\nthat was 500 × 300 pixels will resize it to 50 × 30 pixels.
resized image width.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"height"],"description":[0,"resized image height.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Image"],"chainable":[0,false],"example":[1,[[0,"\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Resize the image.\n img.resize(50, 100);\n\n // Display the resized image.\n image(img, 0, 0);\n\n describe('Two images of a mountain landscape. One copy of the image is squeezed horizontally.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Resize the image, keeping the aspect ratio.\n img.resize(0, 30);\n\n // Display the resized image.\n image(img, 0, 0);\n\n describe('Two images of a mountain landscape. The small copy of the image covers the top-left corner of the larger image.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Resize the image, keeping the aspect ratio.\n img.resize(60, 0);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('Two images of a mountain landscape. The small copy of the image covers the top-left corner of the larger image.');\n}\n
\nSaves the image to a file.
\nBy default, img.save()
saves the image as a PNG image called\nuntitled.png
.
The first parameter, filename
, is optional. It's a string that sets the\nfile's name. If a file extension is included, as in\nimg.save('drawing.png')
, then the image will be saved using that\nformat.
The second parameter, extension
, is also optional. It sets the files format.\nEither 'png'
or 'jpg'
can be used. For example, img.save('drawing', 'jpg')
\nsaves the canvas to a file called drawing.jpg
.
Note: The browser will either save the file immediately or prompt the user\nwith a dialogue window.
\nThe image will only be downloaded as an animated GIF if it was loaded\nfrom a GIF file. See saveGif() to create new\nGIFs.
\n"],"line":[0,1600],"params":[1,[[0,{"name":[0,"filename"],"description":[0,"filename. Defaults to 'untitled'.
\n"],"type":[0,"String"]}],[0,{"name":[0,"extension"],"description":[0,"file extension, either 'png' or 'jpg'.\n Defaults to 'png'.
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Image"],"chainable":[0,false],"example":[1,[[0,"\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('An image of a mountain landscape. The image is downloaded when the user presses the \"s\", \"j\", or \"p\" key.');\n}\n\n// Save the image with different options when the user presses a key.\nfunction keyPressed() {\n if (key === 's') {\n img.save();\n } else if (key === 'j') {\n img.save('rockies.jpg');\n } else if (key === 'p') {\n img.save('rockies', 'png');\n }\n}\n
\nSets the color of one or more pixels within an image.
\nimg.set()
is easy to use but it's not as fast as\nimg.pixels. Use\nimg.pixels to set many pixel values.
img.set()
interprets the first two parameters as x- and y-coordinates. It\ninterprets the last parameter as a grayscale value, a [R, G, B, A]
pixel\narray, a p5.Color object, or another\np5.Image object.
img.updatePixels() must be called\nafter using img.set()
for changes to appear.
x-coordinate of the pixel.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"y-coordinate of the pixel.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"a"],"description":[0,"grayscale value | pixel array |\n p5.Color object |\n p5.Image to copy.
\n"],"type":[0,"Number|Number[]|Object"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Image"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(100, 100);\n\n // Set four pixels to black.\n img.set(30, 20, 0);\n img.set(85, 20, 0);\n img.set(85, 75, 0);\n img.set(30, 75, 0);\n\n // Update the image.\n img.updatePixels();\n\n // Display the image.\n image(img, 0, 0);\n\n describe('Four black dots arranged in a square drawn on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(100, 100);\n\n // Create a p5.Color object.\n let black = color(0);\n\n // Set four pixels to black.\n img.set(30, 20, black);\n img.set(85, 20, black);\n img.set(85, 75, black);\n img.set(30, 75, black);\n\n // Update the image.\n img.updatePixels();\n\n // Display the image.\n image(img, 0, 0);\n\n describe('Four black dots arranged in a square drawn on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Draw a color gradient.\n for (let x = 0; x < img.width; x += 1) {\n for (let y = 0; y < img.height; y += 1) {\n let c = map(x, 0, img.width, 0, 255);\n img.set(x, y, c);\n }\n }\n\n // Update the image.\n img.updatePixels();\n\n // Display the image.\n image(img, 17, 17);\n\n describe('A square with a horiztonal color gradient from black to white drawn on a gray background.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Image object.\n let img2 = createImage(100, 100);\n\n // Set the blank image's pixels using the landscape.\n img2.set(0, 0, img);\n\n // Display the second image.\n image(img2, 0, 0);\n\n describe('An image of a mountain landscape.');\n}\n
\nSets the current frame in an animated GIF.
\n"],"line":[0,1758],"params":[1,[[0,{"name":[0,"index"],"description":[0,"index of the frame to display.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Image"],"chainable":[0,false],"example":[1,[[0,"\n\nlet gif;\nlet frameSlider;\n\n// Load the image.\nfunction preload() {\n gif = loadImage('/assets/arnott-wallace-eye-loop-forever.gif');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Get the index of the last frame.\n let maxFrame = gif.numFrames() - 1;\n\n // Create a slider to control which frame is drawn.\n frameSlider = createSlider(0, maxFrame);\n frameSlider.position(10, 80);\n frameSlider.size(80);\n\n describe('A cartoon eye looks around when a slider is moved.');\n}\n\nfunction draw() {\n // Get the slider's value.\n let index = frameSlider.value();\n\n // Set the GIF's frame.\n gif.setFrame(index);\n\n // Display the image.\n image(gif, 0, 0);\n}\n
\nUpdates the canvas with the RGBA values in the\nimg.pixels array.
\nimg.updatePixels()
only needs to be called after changing values in\nthe img.pixels array. Such changes can be\nmade directly after calling\nimg.loadPixels() or by calling\nimg.set().
The optional parameters x
, y
, width
, and height
define a\nsubsection of the image to update. Doing so can improve performance in\nsome cases.
If the image was loaded from a GIF, then calling img.updatePixels()
\nwill update the pixels in current frame.
x-coordinate of the upper-left corner\n of the subsection to update.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"y"],"description":[0,"y-coordinate of the upper-left corner\n of the subsection to update.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"w"],"description":[0,"width of the subsection to update.
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"h"],"description":[0,"height of the subsection to update.
\n"],"type":[0,"Integer"]}]]]}],[0,{"params":[1,[]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Image"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the image's pixels.\n img.loadPixels();\n\n // Set the pixels to black.\n for (let x = 0; x < img.width; x += 1) {\n for (let y = 0; y < img.height; y += 1) {\n img.set(x, y, 0);\n }\n }\n\n // Update the image.\n img.updatePixels();\n\n // Display the image.\n image(img, 17, 17);\n\n describe('A black square drawn in the middle of a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the image's pixels.\n img.loadPixels();\n\n // Set the pixels to black.\n for (let i = 0; i < img.pixels.length; i += 4) {\n // Red.\n img.pixels[i] = 0;\n // Green.\n img.pixels[i + 1] = 0;\n // Blue.\n img.pixels[i + 2] = 0;\n // Alpha.\n img.pixels[i + 3] = 255;\n }\n\n // Update the image.\n img.updatePixels();\n\n // Display the image.\n image(img, 17, 17);\n\n describe('A black square drawn in the middle of a gray square.');\n}\n
\nThe image's width in pixels.
\n"],"line":[0,114],"itemtype":[0,"property"],"class":[0,"p5.Image"],"example":[1,[[0,"\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Calculate the center coordinates.\n let x = img.width / 2;\n let y = img.height / 2;\n\n // Draw a circle at the image's center.\n circle(x, y, 20);\n\n describe('An image of a mountain landscape with a white circle drawn in the middle.');\n}\n
\nApplies a transformation matrix to the coordinate system.
\nTransformations such as\ntranslate(),\nrotate(), and\nscale()\nuse matrix-vector multiplication behind the scenes. A table of numbers,\ncalled a matrix, encodes each transformation. The values in the matrix\nthen multiply each point on the canvas, which is represented by a vector.
\napplyMatrix()
allows for many transformations to be applied at once. See\nWikipedia\nand MDN\nfor 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\nelements in the following transformation matrix:
\n\n\n
The numbers can be passed individually, as in\napplyMatrix(2, 0, 0, 0, 2, 0)
. They can also be passed in an array, as in\napplyMatrix([2, 0, 0, 0, 2, 0])
.
In 3D mode, the parameters a
, b
, c
, d
, e
, f
, g
, h
, i
,\nj
, k
, l
, m
, n
, o
, and p
correspond to elements in the\nfollowing transformation matrix:
The numbers can be passed individually, as in\napplyMatrix(2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1)
. They can\nalso be passed in an array, as in\napplyMatrix([2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1])
.
By default, transformations accumulate. The\npush() and pop() functions\ncan be used to isolate transformations within distinct drawing groups.
\nNote: Transformations are reset at the beginning of the draw loop. Calling\napplyMatrix()
inside the draw() function won't\ncause shapes to transform continuously.
an array containing the elements of the transformation matrix. Its length should be either 6 (2D) or 16 (3D).
\n"],"type":[0,"Array"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"a"],"description":[0,"an element of the transformation matrix.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"b"],"description":[0,"an element of the transformation matrix.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"c"],"description":[0,"an element of the transformation matrix.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"d"],"description":[0,"an element of the transformation matrix.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"e"],"description":[0,"an element of the transformation matrix.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"f"],"description":[0,"an element of the transformation matrix.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"a"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"b"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"c"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"d"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"e"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"f"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"g"],"description":[0,"an element of the transformation matrix.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"h"],"description":[0,"an element of the transformation matrix.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"i"],"description":[0,"an element of the transformation matrix.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"j"],"description":[0,"an element of the transformation matrix.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"k"],"description":[0,"an element of the transformation matrix.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"l"],"description":[0,"an element of the transformation matrix.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"m"],"description":[0,"an element of the transformation matrix.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"n"],"description":[0,"an element of the transformation matrix.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"o"],"description":[0,"an element of the transformation matrix.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"p"],"description":[0,"an element of the transformation matrix.
\n"],"type":[0,"Number"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n applyMatrix(1, 0, 0, 1, 50, 50);\n\n // Draw the circle at coordinates (0, 0).\n circle(0, 0, 40);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n let m = [1, 0, 0, 1, 50, 50];\n applyMatrix(m);\n\n // Draw the circle at coordinates (0, 0).\n circle(0, 0, 40);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\"A white rectangle on a gray background. The rectangle's long axis runs from top-left to bottom-right.\");\n}\n\nfunction draw() {\n background(200);\n\n // Rotate the coordinate system 1/8 turn.\n let angle = QUARTER_PI;\n let ca = cos(angle);\n let sa = sin(angle);\n applyMatrix(ca, sa, -sa, ca, 0, 0);\n\n // Draw a rectangle at coordinates (50, 0).\n rect(50, 0, 40, 20);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'Two white squares on a gray background. The larger square appears at the top-center. The smaller square appears at the top-left.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Draw a square at (30, 20).\n square(30, 20, 40);\n\n // Scale the coordinate system by a factor of 0.5.\n applyMatrix(0.5, 0, 0, 0.5, 0, 0);\n\n // Draw a square at (30, 20).\n // It appears at (15, 10) after scaling.\n square(30, 20, 40);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white quadrilateral on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the shear factor.\n let angle = QUARTER_PI;\n let shearFactor = 1 / tan(HALF_PI - angle);\n\n // Shear the coordinate system along the x-axis.\n applyMatrix(1, 0, shearFactor, 1, 0, 0);\n\n // Draw the square.\n square(0, 0, 50);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube rotates slowly against a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system a little more each frame.\n let angle = frameCount * 0.01;\n let ca = cos(angle);\n let sa = sin(angle);\n applyMatrix(ca, 0, sa, 0, 0, 1, 0, 0, -sa, 0, ca, 0, 0, 0, 0, 1);\n\n // Draw a box.\n box();\n}\n
\nClears all transformations applied to the coordinate system.
\n"],"line":[0,246],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'Two circles drawn on a gray background. A blue circle is at the top-left and a red circle is at the bottom-right.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Draw a blue circle at the coordinates (25, 25).\n fill('blue');\n circle(25, 25, 20);\n\n // Clear all transformations.\n // The origin is now at the top-left corner.\n resetMatrix();\n\n // Draw a red circle at the coordinates (25, 25).\n fill('red');\n circle(25, 25, 20);\n}\n
\nRotates the coordinate system.
\nBy default, the positive x-axis points to the right and the positive y-axis\npoints downward. The rotate()
function changes this orientation by\nrotating the coordinate system about the origin. Everything drawn after\nrotate()
is called will appear to be rotated.
The first parameter, angle
, is the amount to rotate. For example, calling\nrotate(1)
rotates the coordinate system clockwise 1 radian which is\nnearly 57˚. rotate()
interprets angle values using the current\nangleMode().
The second parameter, axis
, is optional. It's used to orient 3D rotations\nin WebGL mode. If a p5.Vector is passed, as in\nrotate(QUARTER_PI, myVector)
, then the coordinate system will rotate\nQUARTER_PI
radians about myVector
. If an array of vector components is\npassed, as in rotate(QUARTER_PI, [1, 0, 0])
, then the coordinate system\nwill rotate QUARTER_PI
radians about a vector with the components\n[1, 0, 0]
.
By default, transformations accumulate. For example, calling rotate(1)
\ntwice has the same effect as calling rotate(2)
once. The\npush() and pop() functions\ncan be used to isolate transformations within distinct drawing groups.
Note: Transformations are reset at the beginning of the draw loop. Calling\nrotate(1)
inside the draw() function won't cause\nshapes to spin.
angle of rotation in the current angleMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"axis"],"description":[0,"axis to rotate about in 3D.
\n"],"type":[0,"p5.Vector|Number[]"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n \"A white rectangle on a gray background. The rectangle's long axis runs from top-left to bottom-right.\"\n );\n}\n\nfunction draw() {\n background(200);\n\n // Rotate the coordinate system 1/8 turn.\n rotate(QUARTER_PI);\n\n // Draw a rectangle at coordinates (50, 0).\n rect(50, 0, 40, 20);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n \"A white rectangle on a gray background. The rectangle's long axis runs from top-left to bottom-right.\"\n );\n}\n\nfunction draw() {\n background(200);\n\n // Rotate the coordinate system 1/16 turn.\n rotate(QUARTER_PI / 2);\n\n // Rotate the coordinate system another 1/16 turn.\n rotate(QUARTER_PI / 2);\n\n // Draw a rectangle at coordinates (50, 0).\n rect(50, 0, 40, 20);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use degrees.\n angleMode(DEGREES);\n\n describe(\n \"A white rectangle on a gray background. The rectangle's long axis runs from top-left to bottom-right.\"\n );\n}\n\nfunction draw() {\n background(200);\n\n // Rotate the coordinate system 1/8 turn.\n rotate(45);\n\n // Draw a rectangle at coordinates (50, 0).\n rect(50, 0, 40, 20);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A white rectangle on a gray background. The rectangle rotates slowly about the top-left corner. It disappears and reappears periodically.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Rotate the coordinate system a little more each frame.\n let angle = frameCount * 0.01;\n rotate(angle);\n\n // Draw a rectangle at coordinates (50, 0).\n rect(50, 0, 40, 20);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\"A cube on a gray background. The cube's front face points to the top-right.\");\n}\n\nfunction draw() {\n background(200);\n\n // Rotate the coordinate system 1/8 turn about\n // the axis [1, 1, 0].\n let axis = createVector(1, 1, 0);\n rotate(QUARTER_PI, axis);\n\n // Draw a box.\n box();\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\"A cube on a gray background. The cube's front face points to the top-right.\");\n}\n\nfunction draw() {\n background(200);\n\n // Rotate the coordinate system 1/8 turn about\n // the axis [1, 1, 0].\n let axis = [1, 1, 0];\n rotate(QUARTER_PI, axis);\n\n // Draw a box.\n box();\n}\n
\nRotates the coordinate system about the x-axis in WebGL mode.
\nThe parameter, angle
, is the amount to rotate. For example, calling\nrotateX(1)
rotates the coordinate system about the x-axis by 1 radian.\nrotateX()
interprets angle values using the current\nangleMode().
By default, transformations accumulate. For example, calling rotateX(1)
\ntwice has the same effect as calling rotateX(2)
once. The\npush() and pop() functions\ncan be used to isolate transformations within distinct drawing groups.
Note: Transformations are reset at the beginning of the draw loop. Calling\nrotateX(1)
inside the draw() function won't cause\nshapes to spin.
angle of rotation in the current angleMode().
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system 1/8 turn.\n rotateX(QUARTER_PI);\n\n // Draw a box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system 1/16 turn.\n rotateX(QUARTER_PI / 2);\n\n // Rotate the coordinate system 1/16 turn.\n rotateX(QUARTER_PI / 2);\n\n // Draw a box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Use degrees.\n angleMode(DEGREES);\n\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system 1/8 turn.\n rotateX(45);\n\n // Draw a box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube rotates slowly against a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system a little more each frame.\n let angle = frameCount * 0.01;\n rotateX(angle);\n\n // Draw a box.\n box();\n}\n
\nRotates the coordinate system about the y-axis in WebGL mode.
\nThe parameter, angle
, is the amount to rotate. For example, calling\nrotateY(1)
rotates the coordinate system about the y-axis by 1 radian.\nrotateY()
interprets angle values using the current\nangleMode().
By default, transformations accumulate. For example, calling rotateY(1)
\ntwice has the same effect as calling rotateY(2)
once. The\npush() and pop() functions\ncan be used to isolate transformations within distinct drawing groups.
Note: Transformations are reset at the beginning of the draw loop. Calling\nrotateY(1)
inside the draw() function won't cause\nshapes to spin.
angle of rotation in the current angleMode().
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system 1/8 turn.\n rotateY(QUARTER_PI);\n\n // Draw a box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system 1/16 turn.\n rotateY(QUARTER_PI / 2);\n\n // Rotate the coordinate system 1/16 turn.\n rotateY(QUARTER_PI / 2);\n\n // Draw a box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Use degrees.\n angleMode(DEGREES);\n\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system 1/8 turn.\n rotateY(45);\n\n // Draw a box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube rotates slowly against a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system a little more each frame.\n let angle = frameCount * 0.01;\n rotateY(angle);\n\n // Draw a box.\n box();\n}\n
\nRotates the coordinate system about the z-axis in WebGL mode.
\nThe parameter, angle
, is the amount to rotate. For example, calling\nrotateZ(1)
rotates the coordinate system about the z-axis by 1 radian.\nrotateZ()
interprets angle values using the current\nangleMode().
By default, transformations accumulate. For example, calling rotateZ(1)
\ntwice has the same effect as calling rotateZ(2)
once. The\npush() and pop() functions\ncan be used to isolate transformations within distinct drawing groups.
Note: Transformations are reset at the beginning of the draw loop. Calling\nrotateZ(1)
inside the draw() function won't cause\nshapes to spin.
angle of rotation in the current angleMode().
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system 1/8 turn.\n rotateZ(QUARTER_PI);\n\n // Draw a box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system 1/16 turn.\n rotateZ(QUARTER_PI / 2);\n\n // Rotate the coordinate system 1/16 turn.\n rotateZ(QUARTER_PI / 2);\n\n // Draw a box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Use degrees.\n angleMode(DEGREES);\n\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system 1/8 turn.\n rotateZ(45);\n\n // Draw a box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube rotates slowly against a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system a little more each frame.\n let angle = frameCount * 0.01;\n rotateZ(angle);\n\n // Draw a box.\n box();\n}\n
\nScales the coordinate system.
\nBy default, shapes are drawn at their original scale. A rectangle that's 50\npixels wide appears to take up half the width of a 100 pixel-wide canvas.\nThe scale()
function can shrink or stretch the coordinate system so that\nshapes appear at different sizes. There are two ways to call scale()
with\nparameters that set the scale factor(s).
The first way to call scale()
uses numbers to set the amount of scaling.\nThe first parameter, s
, sets the amount to scale each axis. For example,\ncalling scale(2)
stretches the x-, y-, and z-axes by a factor of 2. The\nnext two parameters, y
and z
, are optional. They set the amount to\nscale the y- and z-axes. For example, calling scale(2, 0.5, 1)
stretches\nthe x-axis by a factor of 2, shrinks the y-axis by a factor of 0.5, and\nleaves the z-axis unchanged.
The second way to call scale()
uses a p5.Vector\nobject to set the scale factors. For example, calling scale(myVector)
\nuses the x-, y-, and z-components of myVector
to set the amount of\nscaling along the x-, y-, and z-axes. Doing so is the same as calling\nscale(myVector.x, myVector.y, myVector.z)
.
By default, transformations accumulate. For example, calling scale(1)
\ntwice has the same effect as calling scale(2)
once. The\npush() and pop() functions\ncan be used to isolate transformations within distinct drawing groups.
Note: Transformations are reset at the beginning of the draw loop. Calling\nscale(2)
inside the draw() function won't cause\nshapes to grow continuously.
amount to scale along the positive x-axis.
\n"],"type":[0,"Number|p5.Vector|Number[]"]}],[0,{"name":[0,"y"],"description":[0,"amount to scale along the positive y-axis. Defaults to s
.
amount to scale along the positive z-axis. Defaults to y
.
vector whose components should be used to scale.
\n"],"type":[0,"p5.Vector|Number[]"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'Two white squares on a gray background. The larger square appears at the top-center. The smaller square appears at the top-left.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Draw a square at (30, 20).\n square(30, 20, 40);\n\n // Scale the coordinate system by a factor of 0.5.\n scale(0.5);\n\n // Draw a square at (30, 20).\n // It appears at (15, 10) after scaling.\n square(30, 20, 40);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A rectangle and a square drawn in white on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw a square at (30, 20).\n square(30, 20, 40);\n\n // Scale the coordinate system by factors of\n // 0.5 along the x-axis and\n // 1.3 along the y-axis.\n scale(0.5, 1.3);\n\n // Draw a square at (30, 20).\n // It appears as a rectangle at (15, 26) after scaling.\n square(30, 20, 40);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A rectangle and a square drawn in white on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw a square at (30, 20).\n square(30, 20, 40);\n\n // Create a p5.Vector object.\n let v = createVector(0.5, 1.3);\n\n // Scale the coordinate system by factors of\n // 0.5 along the x-axis and\n // 1.3 along the y-axis.\n scale(v);\n\n // Draw a square at (30, 20).\n // It appears as a rectangle at (15, 26) after scaling.\n square(30, 20, 40);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'A red box and a blue box drawn on a gray background. The red box appears embedded in the blue box.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n lights();\n\n // Style the spheres.\n noStroke();\n\n // Draw the red sphere.\n fill('red');\n box();\n\n // Scale the coordinate system by factors of\n // 0.5 along the x-axis and\n // 1.3 along the y-axis and\n // 2 along the z-axis.\n scale(0.5, 1.3, 2);\n\n // Draw the blue sphere.\n fill('blue');\n box();\n}\n
\nShears the x-axis so that shapes appear skewed.
\nBy default, the x- and y-axes are perpendicular. The shearX()
function\ntransforms the coordinate system so that x-coordinates are translated while\ny-coordinates are fixed.
The first parameter, angle
, is the amount to shear. For example, calling\nshearX(1)
transforms all x-coordinates using the formula\nx = x + y * tan(angle)
. shearX()
interprets angle values using the\ncurrent angleMode().
By default, transformations accumulate. For example, calling\nshearX(1)
twice has the same effect as calling shearX(2)
once. The\npush() and\npop() functions can be used to isolate\ntransformations within distinct drawing groups.
Note: Transformations are reset at the beginning of the draw loop. Calling\nshearX(1)
inside the draw() function won't\ncause shapes to shear continuously.
angle to shear by in the current angleMode().
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white quadrilateral on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Shear the coordinate system along the x-axis.\n shearX(QUARTER_PI);\n\n // Draw the square.\n square(0, 0, 50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use degrees.\n angleMode(DEGREES);\n\n describe('A white quadrilateral on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Shear the coordinate system along the x-axis.\n shearX(45);\n\n // Draw the square.\n square(0, 0, 50);\n}\n
\nShears the y-axis so that shapes appear skewed.
\nBy default, the x- and y-axes are perpendicular. The shearY()
function\ntransforms the coordinate system so that y-coordinates are translated while\nx-coordinates are fixed.
The first parameter, angle
, is the amount to shear. For example, calling\nshearY(1)
transforms all y-coordinates using the formula\ny = y + x * tan(angle)
. shearY()
interprets angle values using the\ncurrent angleMode().
By default, transformations accumulate. For example, calling\nshearY(1)
twice has the same effect as calling shearY(2)
once. The\npush() and\npop() functions can be used to isolate\ntransformations within distinct drawing groups.
Note: Transformations are reset at the beginning of the draw loop. Calling\nshearY(1)
inside the draw() function won't\ncause shapes to shear continuously.
angle to shear by in the current angleMode().
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white quadrilateral on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Shear the coordinate system along the x-axis.\n shearY(QUARTER_PI);\n\n // Draw the square.\n square(0, 0, 50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use degrees.\n angleMode(DEGREES);\n\n describe('A white quadrilateral on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Shear the coordinate system along the x-axis.\n shearY(45);\n\n // Draw the square.\n square(0, 0, 50);\n}\n
\nTranslates the coordinate system.
\nBy default, the origin (0, 0)
is at the sketch's top-left corner in 2D\nmode and center in WebGL mode. The translate()
function shifts the origin\nto a different position. Everything drawn after translate()
is called\nwill appear to be shifted. There are two ways to call translate()
with\nparameters that set the origin's position.
The first way to call translate()
uses numbers to set the amount of\ntranslation. The first two parameters, x
and y
, set the amount to\ntranslate along the positive x- and y-axes. For example, calling\ntranslate(20, 30)
translates the origin 20 pixels along the x-axis and 30\npixels along the y-axis. The third parameter, z
, is optional. It sets the\namount to translate along the positive z-axis. For example, calling\ntranslate(20, 30, 40)
translates the origin 20 pixels along the x-axis,\n30 pixels along the y-axis, and 40 pixels along the z-axis.
The second way to call translate()
uses a\np5.Vector object to set the amount of\ntranslation. For example, calling translate(myVector)
uses the x-, y-,\nand z-components of myVector
to set the amount to translate along the x-,\ny-, and z-axes. Doing so is the same as calling\ntranslate(myVector.x, myVector.y, myVector.z)
.
By default, transformations accumulate. For example, calling\ntranslate(10, 0)
twice has the same effect as calling\ntranslate(20, 0)
once. The push() and\npop() functions can be used to isolate\ntransformations within distinct drawing groups.
Note: Transformations are reset at the beginning of the draw loop. Calling\ntranslate(10, 0)
inside the draw() function won't\ncause shapes to move continuously.
amount to translate along the positive x-axis.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"amount to translate along the positive y-axis.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,"amount to translate along the positive z-axis.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"vector"],"description":[0,"vector by which to translate.
\n"],"type":[0,"p5.Vector"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Draw a circle at coordinates (0, 0).\n circle(0, 0, 40);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'Two circles drawn on a gray background. The blue circle on the right overlaps the red circle at the center.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Draw the red circle.\n fill('red');\n circle(0, 0, 40);\n\n // Translate the origin to the right.\n translate(25, 0);\n\n // Draw the blue circle.\n fill('blue');\n circle(0, 0, 40);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle moves slowly from left to right on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the x-coordinate.\n let x = frameCount * 0.2;\n\n // Translate the origin.\n translate(x, 50);\n\n // Draw a circle at coordinates (0, 0).\n circle(0, 0, 40);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Create a p5.Vector object.\n let v = createVector(50, 50);\n\n // Translate the origin by the vector.\n translate(v);\n\n // Draw a circle at coordinates (0, 0).\n circle(0, 0, 40);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'Two spheres sitting side-by-side on gray background. The sphere at the center is red. The sphere on the right is blue.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Turn on the lights.\n lights();\n\n // Style the spheres.\n noStroke();\n\n // Draw the red sphere.\n fill('red');\n sphere(10);\n\n // Translate the origin to the right.\n translate(30, 0, 0);\n\n // Draw the blue sphere.\n fill('blue');\n sphere(10);\n}\n
\nChanges the cursor's appearance.
\nThe first parameter, type
, sets the type of cursor to display. The\nbuilt-in options are ARROW
, CROSS
, HAND
, MOVE
, TEXT
, and WAIT
.\ncursor()
also recognizes standard CSS cursor properties passed as\nstrings: 'help'
, 'wait'
, 'crosshair'
, 'not-allowed'
, 'zoom-in'
,\nand 'grab'
. If the path to an image is passed, as in\ncursor('/assets/target.png')
, then the image will be used as the cursor.\nImages 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\ncursor, x
and y
set the location pointed to within the image. They are\nboth 0 by default, so the cursor points to the image's top-left corner. x
\nand y
must be less than the image's width and height, respectively.
Built-in: either ARROW, CROSS, HAND, MOVE, TEXT, or WAIT.\n Native CSS properties: 'grab', 'progress', and so on.\n Path to cursor image.
\n"],"type":[0,"String|Constant"]}],[0,{"name":[0,"x"],"description":[0,"horizontal active spot of the cursor.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"y"],"description":[0,"vertical active spot of the cursor.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A gray square. The cursor appears as crosshairs.');\n}\n\nfunction draw() {\n background(200);\n\n // Set the cursor to crosshairs: +\n cursor(CROSS);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A gray square divided into quadrants. The cursor image changes when the mouse moves to each quadrant.');\n}\n\nfunction draw() {\n background(200);\n\n // Divide the canvas into quadrants.\n line(50, 0, 50, 100);\n line(0, 50, 100, 50);\n\n // Change cursor based on mouse position.\n if (mouseX < 50 && mouseY < 50) {\n cursor(CROSS);\n } else if (mouseX > 50 && mouseY < 50) {\n cursor('progress');\n } else if (mouseX > 50 && mouseY > 50) {\n cursor('https://avatars0.githubusercontent.com/u/1617169?s=16');\n } else {\n cursor('grab');\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('An image of three purple curves follows the mouse. The image shifts when the mouse is pressed.');\n}\n\nfunction draw() {\n background(200);\n\n // Change the cursor's active spot\n // when the mouse is pressed.\n if (mouseIsPressed === true) {\n cursor('https://avatars0.githubusercontent.com/u/1617169?s=16', 8, 8);\n } else {\n cursor('https://avatars0.githubusercontent.com/u/1617169?s=16');\n }\n}\n
\nA Number
variable that tracks the number of milliseconds it took to draw\nthe last frame.
deltaTime
contains the amount of time it took\ndraw() to execute during the previous frame. It's\nuseful for simulating physics.
\nlet x = 0;\nlet speed = 0.05;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Set the frameRate to 30.\n frameRate(30);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Use deltaTime to calculate\n // a change in position.\n let deltaX = speed * deltaTime;\n\n // Update the x variable.\n x += deltaX;\n\n // Reset x to 0 if it's\n // greater than 100.\n if (x > 100) {\n x = 0;\n }\n\n // Use x to set the circle's\n // position.\n circle(x, 50, 20);\n}\n
\nCreates a screen reader-accessible description of the canvas.
\nThe first parameter, text
, is the description of the canvas.
The second parameter, display
, is optional. It determines how the\ndescription is displayed. If LABEL
is passed, as in\ndescribe('A description.', LABEL)
, the description will be visible in\na div element next to the canvas. If FALLBACK
is passed, as in\ndescribe('A description.', FALLBACK)
, the description will only be\nvisible to screen readers. This is the default mode.
Read\nWriting accessible canvas descriptions\nto learn more about making sketches accessible.
\n"],"line":[0,18],"params":[1,[[0,{"name":[0,"text"],"description":[0,"description of the canvas.
\n"],"type":[0,"String"]}],[0,{"name":[0,"display"],"description":[0,"either LABEL or FALLBACK.
\n"],"type":[0,"Constant"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n background('pink');\n\n // Draw a heart.\n fill('red');\n noStroke();\n circle(67, 67, 20);\n circle(83, 67, 20);\n triangle(91, 73, 75, 95, 59, 73);\n\n // Add a general description of the canvas.\n describe('A pink square with a red heart in the bottom-right corner.');\n}\n
\n\nfunction setup() {\n background('pink');\n\n // Draw a heart.\n fill('red');\n noStroke();\n circle(67, 67, 20);\n circle(83, 67, 20);\n triangle(91, 73, 75, 95, 59, 73);\n\n // Add a general description of the canvas\n // and display it for debugging.\n describe('A pink square with a red heart in the bottom-right corner.', LABEL);\n}\n
\n\nfunction draw() {\n background(200);\n\n // The expression\n // frameCount % 100\n // causes x to increase from 0\n // to 99, then restart from 0.\n let x = frameCount % 100;\n\n // Draw the circle.\n fill(0, 255, 0);\n circle(x, 50, 40);\n\n // Add a general description of the canvas.\n describe(`A green circle at (${x}, 50) moves from left to right on a gray square.`);\n}\n
\n\nfunction draw() {\n background(200);\n\n // The expression\n // frameCount % 100\n // causes x to increase from 0\n // to 99, then restart from 0.\n let x = frameCount % 100;\n\n // Draw the circle.\n fill(0, 255, 0);\n circle(x, 50, 40);\n\n // Add a general description of the canvas\n // and display it for debugging.\n describe(`A green circle at (${x}, 50) moves from left to right on a gray square.`, LABEL);\n}\n
\nCreates a screen reader-accessible description of elements in the canvas.
\nElements are shapes or groups of shapes that create meaning together. For\nexample, a few overlapping circles could make an \"eye\" element.
\nThe 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\ndescription is displayed. If LABEL
is passed, as in\ndescribe('A description.', LABEL)
, the description will be visible in\na div element next to the canvas. Using LABEL
creates unhelpful\nduplicates for screen readers. Only use LABEL
during development. If\nFALLBACK
is passed, as in describe('A description.', FALLBACK)
, the\ndescription will only be visible to screen readers. This is the default\nmode.
Read\nWriting accessible canvas descriptions\nto learn more about making sketches accessible.
\n"],"line":[0,162],"params":[1,[[0,{"name":[0,"name"],"description":[0,"name of the element.
\n"],"type":[0,"String"]}],[0,{"name":[0,"text"],"description":[0,"description of the element.
\n"],"type":[0,"String"]}],[0,{"name":[0,"display"],"description":[0,"either LABEL or FALLBACK.
\n"],"type":[0,"Constant"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n background('pink');\n\n // Describe the first element\n // and draw it.\n describeElement('Circle', 'A yellow circle in the top-left corner.');\n noStroke();\n fill('yellow');\n circle(25, 25, 40);\n\n // Describe the second element\n // and draw it.\n describeElement('Heart', 'A red heart in the bottom-right corner.');\n fill('red');\n circle(66.6, 66.6, 20);\n circle(83.2, 66.6, 20);\n triangle(91.2, 72.6, 75, 95, 58.6, 72.6);\n\n // Add a general description of the canvas.\n describe('A red heart and yellow circle over a pink background.');\n}\n
\n\nfunction setup() {\n background('pink');\n\n // Describe the first element\n // and draw it. Display the\n // description for debugging.\n describeElement('Circle', 'A yellow circle in the top-left corner.', LABEL);\n noStroke();\n fill('yellow');\n circle(25, 25, 40);\n\n // Describe the second element\n // and draw it. Display the\n // description for debugging.\n describeElement('Heart', 'A red heart in the bottom-right corner.', LABEL);\n fill('red');\n circle(66.6, 66.6, 20);\n circle(83.2, 66.6, 20);\n triangle(91.2, 72.6, 75, 95, 58.6, 72.6);\n\n // Add a general description of the canvas.\n describe('A red heart and yellow circle over a pink background.');\n}\n
\nReturns the display's current pixel density.
\n"],"line":[0,1078],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"current pixel density of the display."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n // Set the pixel density to 1.\n pixelDensity(1);\n\n // Create a canvas and draw\n // a circle.\n createCanvas(100, 100);\n background(200);\n circle(50, 50, 70);\n\n describe('A fuzzy white circle drawn on a gray background. The circle becomes sharper when the mouse is pressed.');\n}\n\nfunction mousePressed() {\n // Get the current display density.\n let d = displayDensity();\n\n // Use the display density to set\n // the sketch's pixel density.\n pixelDensity(d);\n\n // Paint the background and\n // draw a circle.\n background(200);\n circle(50, 50, 70);\n}\n
\nA Number
variable that stores the height of the screen display.
displayHeight
is useful for running full-screen programs. Its value\ndepends on the current pixelDensity().
Note: The actual screen height can be computed as\ndisplayHeight * pixelDensity()
.
\nfunction setup() {\n // Set the canvas' width and height\n // using the display's dimensions.\n createCanvas(displayWidth, displayHeight);\n\n background(200);\n\n describe('A gray canvas that is the same size as the display.');\n}\n
\nA Number
variable that stores the width of the screen display.
displayWidth
is useful for running full-screen programs. Its value\ndepends on the current pixelDensity().
Note: The actual screen width can be computed as\ndisplayWidth * pixelDensity()
.
\nfunction setup() {\n // Set the canvas' width and height\n // using the display's dimensions.\n createCanvas(displayWidth, displayHeight);\n\n background(200);\n\n describe('A gray canvas that is the same size as the display.');\n}\n
\nA Boolean
variable that's true
if the browser is focused and false
if\nnot.
Note: The browser window can only receive input if it's focused.
\n"],"line":[0,174],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n// Open this example in two separate browser\n// windows placed side-by-side to demonstrate.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A square changes color from green to red when the browser window is out of focus.');\n}\n\nfunction draw() {\n // Change the background color\n // when the browser window\n // goes in/out of focus.\n if (focused === true) {\n background(0, 255, 0);\n } else {\n background(255, 0, 0);\n }\n}\n
\nA Number
variable that tracks the number of frames drawn since the sketch\nstarted.
frameCount
's value is 0 inside setup(). It\nincrements by 1 each time the code in draw()\nfinishes executing.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Display the value of\n // frameCount.\n textSize(30);\n textAlign(CENTER, CENTER);\n text(frameCount, 50, 50);\n\n describe('The number 0 written in black in the middle of a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Set the frameRate to 30.\n frameRate(30);\n\n textSize(30);\n textAlign(CENTER, CENTER);\n\n describe('A number written in black in the middle of a gray square. Its value increases rapidly.');\n}\n\nfunction draw() {\n background(200);\n\n // Display the value of\n // frameCount.\n text(frameCount, 50, 50);\n}\n
\nSets the number of frames to draw per second.
\nCalling frameRate()
with one numeric argument, as in frameRate(30)
,\nattempts to draw 30 frames per second (FPS). The target frame rate may not\nbe achieved depending on the sketch's processing needs. Most computers\ndefault to a frame rate of 60 FPS. Frame rates of 24 FPS and above are\nfast enough for smooth animations.
Calling frameRate()
without an argument returns the current frame rate.\nThe value returned is an approximation.
number of frames to draw per second.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Set the x variable based\n // on the current frameCount.\n let x = frameCount % 100;\n\n // If the mouse is pressed,\n // decrease the frame rate.\n if (mouseIsPressed === true) {\n frameRate(10);\n } else {\n frameRate(60);\n }\n\n // Use x to set the circle's\n // position.\n circle(x, 50, 20);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A number written in black on a gray background. The number decreases when the mouse is pressed.');\n}\n\nfunction draw() {\n background(200);\n\n // If the mouse is pressed, do lots\n // of math to slow down drawing.\n if (mouseIsPressed === true) {\n for (let i = 0; i < 1000000; i += 1) {\n random();\n }\n }\n\n // Get the current frame rate\n // and display it.\n let fps = frameRate();\n text(fps, 50, 50);\n}\n
\nToggles full-screen mode or returns the current mode.
\nCalling fullscreen(true)
makes the sketch full-screen. Calling\nfullscreen(false)
makes the sketch its original size.
Calling fullscreen()
without an argument returns true
if the sketch\nis in full-screen mode and false
if not.
Note: Due to browser restrictions, fullscreen()
can only be called with\nuser input such as a mouse press.
whether the sketch should be in fullscreen mode.
\n"],"type":[0,"Boolean"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"current fullscreen state."],"type":[0,"Boolean"]}],"example":[1,[[0,"\n\nfunction setup() {\n background(200);\n\n describe('A gray canvas that switches between default and full-screen display when clicked.');\n}\n\n// If the mouse is pressed,\n// toggle full-screen mode.\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n let fs = fullscreen();\n fullscreen(!fs);\n }\n}\n
\nReturns the target frame rate.
\nThe value is either the system frame rate or the last value passed to\nframeRate().
\n"],"line":[0,447],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"_targetFrameRate"],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('The number 20 written in black on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Set the frame rate to 20.\n frameRate(20);\n\n // Get the target frame rate and\n // display it.\n let fps = getTargetFrameRate();\n text(fps, 43, 54);\n}\n
\nReturns the sketch's current\nURL\nas a String
.
\nfunction setup() {\n background(200);\n\n // Get the sketch's URL\n // and display it.\n let url = getURL();\n textWrap(CHAR);\n text(url, 0, 40, 100);\n\n describe('The URL \"https://p5js.org/reference/p5/getURL\" written in black on a gray background.');\n}\n
\nReturns the current\nURL parameters\nin an Object
.
For example, calling getURLParams()
in a sketch hosted at the URL\nhttp://p5js.org?year=2014&month=May&day=15
returns\n{ year: 2014, month: 'May', day: 15 }
.
\n// Imagine this sketch is hosted at the following URL:\n// https://p5js.org?year=2014&month=May&day=15\n\nfunction setup() {\n background(200);\n\n // Get the sketch's URL\n // parameters and display\n // them.\n let params = getURLParams();\n text(params.day, 10, 20);\n text(params.month, 10, 40);\n text(params.year, 10, 60);\n\n describe('The text \"15\", \"May\", and \"2014\" written in black on separate lines.');\n}\n
\nReturns the current\nURL\npath as an Array
of String
s.
For example, consider a sketch hosted at the URL\nhttps://example.com/sketchbook
. Calling getURLPath()
returns\n['sketchbook']
. For a sketch hosted at the URL\nhttps://example.com/sketchbook/monday
, getURLPath()
returns\n['sketchbook', 'monday']
.
\nfunction setup() {\n background(200);\n\n // Get the sketch's URL path\n // and display the first\n // part.\n let path = getURLPath();\n text(path[0], 25, 54);\n\n describe('The word \"reference\" written in black on a gray background.');\n}\n
\nCreates a screen reader-accessible description of shapes on the canvas.
\ngridOutput()
adds a general description, table of shapes, and list of\nshapes to the web page. The general description includes the canvas size,\ncanvas color, and number of shapes. For example,\ngray 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\nis placed in a cell whose row and column correspond to the shape's location\non the canvas. The grid cells describe the color and type of shape at that\nlocation. For example, red circle
. These descriptions can be selected\nindividually to get more details. This is different from\ntextOutput(), which uses its table as a list.
A list of shapes follows the table. The list describes the color, type,\nlocation, and area of each shape. For example,\nred circle, location = middle, area = 3 %
.
The display
parameter is optional. It determines how the description is\ndisplayed. If LABEL
is passed, as in gridOutput(LABEL)
, the description\nwill be visible in a div element next to the canvas. Using LABEL
creates\nunhelpful duplicates for screen readers. Only use LABEL
during\ndevelopment. If FALLBACK
is passed, as in gridOutput(FALLBACK)
, the\ndescription will only be visible to screen readers. This is the default\nmode.
Read\nWriting accessible canvas descriptions\nto learn more about making sketches accessible.
\n"],"line":[0,144],"params":[1,[[0,{"name":[0,"display"],"description":[0,"either FALLBACK or LABEL.
\n"],"type":[0,"Constant"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n // Add the grid description.\n gridOutput();\n\n // Draw a couple of shapes.\n background(200);\n fill(255, 0, 0);\n circle(20, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle and a blue square on a gray background.');\n}\n
\n\nfunction setup() {\n // Add the grid description and\n // display it for debugging.\n gridOutput(LABEL);\n\n // Draw a couple of shapes.\n background(200);\n fill(255, 0, 0);\n circle(20, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle and a blue square on a gray background.');\n}\n
\n\nfunction draw() {\n // Add the grid description.\n gridOutput();\n\n // Draw a moving circle.\n background(200);\n let x = frameCount * 0.1;\n fill(255, 0, 0);\n circle(x, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle moves from left to right above a blue square.');\n}\n
\n\nfunction draw() {\n // Add the grid description and\n // display it for debugging.\n gridOutput(LABEL);\n\n // Draw a moving circle.\n background(200);\n let x = frameCount * 0.1;\n fill(255, 0, 0);\n circle(x, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle moves from left to right above a blue square.');\n}\n
\nA Number
variable that stores the height of the canvas in pixels.
height
's default value is 100. Calling\ncreateCanvas() or\nresizeCanvas() changes the value of\nheight
. Calling noCanvas() sets its value to\n0.
\nfunction setup() {\n background(200);\n\n // Display the canvas' height.\n text(height, 42, 54);\n\n describe('The number 100 written in black on a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 50);\n\n background(200);\n\n // Display the canvas' height.\n text(height, 42, 27);\n\n describe('The number 50 written in black on a gray rectangle.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Display the canvas' height.\n text(height, 42, 54);\n\n 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.');\n}\n\n// If the mouse is pressed, reisze\n// the canvas and display its new\n// height.\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n resizeCanvas(100, 50);\n background(200);\n text(height, 42, 27);\n }\n}\n
\nHides the cursor from view.
\n"],"line":[0,482],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n // Hide the cursor.\n noCursor();\n}\n\nfunction draw() {\n background(200);\n\n circle(mouseX, mouseY, 10);\n\n describe('A white circle on a gray background. The circle follows the mouse as it moves. The cursor is hidden.');\n}\n
\nSets the pixel density or returns the current density.
\nComputer displays are grids of little lights called pixels. A\ndisplay's pixel density describes how many pixels it packs into an\narea. Displays with smaller pixels have a higher pixel density and create\nsharper images.
\npixelDensity()
sets the pixel scaling for high pixel density displays.\nBy default, the pixel density is set to match the display's density.\nCalling pixelDensity(1)
turn this off.
Calling pixelDensity()
without an argument returns the current pixel\ndensity.
desired pixel density.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n // Set the pixel density to 1.\n pixelDensity(1);\n\n // Create a canvas and draw\n // a circle.\n createCanvas(100, 100);\n background(200);\n circle(50, 50, 70);\n\n describe('A fuzzy white circle on a gray canvas.');\n}\n
\n\nfunction setup() {\n // Set the pixel density to 3.\n pixelDensity(3);\n\n // Create a canvas, paint the\n // background, and draw a\n // circle.\n createCanvas(100, 100);\n background(200);\n circle(50, 50, 70);\n\n describe('A sharp white circle on a gray canvas.');\n}\n
\nDisplays text in the web browser's console.
\nprint()
is helpful for printing values while debugging. Each call to\nprint()
creates a new line of text.
Note: Call print('\\n')
to print a blank line. Calling print()
without\nan argument opens the browser's dialog for printing documents.
content to print to the console.
\n"],"type":[0,"Any"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n // Prints \"hello, world\" to the console.\n print('hello, world');\n}\n
\n\nfunction setup() {\n let name = 'ada';\n // Prints \"hello, ada\" to the console.\n print(`hello, ${name}`);\n}\n
\nCreates a screen reader-accessible description of shapes on the canvas.
\ntextOutput()
adds a general description, list of shapes, and\ntable of shapes to the web page. The general description includes the\ncanvas size, canvas color, and number of shapes. For example,\nYour 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\ncolor, location, and area of each shape. For example,\na red circle at middle covering 3% of the canvas
. Each shape can be\nselected to get more details.
textOutput()
uses its table of shapes as a list. The table describes the\nshape, color, location, coordinates and area. For example,\nred circle location = middle area = 3%
. This is different from\ngridOutput(), which uses its table as a grid.
The display
parameter is optional. It determines how the description is\ndisplayed. If LABEL
is passed, as in textOutput(LABEL)
, the description\nwill be visible in a div element next to the canvas. Using LABEL
creates\nunhelpful duplicates for screen readers. Only use LABEL
during\ndevelopment. If FALLBACK
is passed, as in textOutput(FALLBACK)
, the\ndescription will only be visible to screen readers. This is the default\nmode.
Read\nWriting accessible canvas descriptions\nto learn more about making sketches accessible.
\n"],"line":[0,10],"params":[1,[[0,{"name":[0,"display"],"description":[0,"either FALLBACK or LABEL.
\n"],"type":[0,"Constant"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n // Add the text description.\n textOutput();\n\n // Draw a couple of shapes.\n background(200);\n fill(255, 0, 0);\n circle(20, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle and a blue square on a gray background.');\n}\n
\n\nfunction setup() {\n // Add the text description and\n // display it for debugging.\n textOutput(LABEL);\n\n // Draw a couple of shapes.\n background(200);\n fill(255, 0, 0);\n circle(20, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle and a blue square on a gray background.');\n}\n
\n\nfunction draw() {\n // Add the text description.\n textOutput();\n\n // Draw a moving circle.\n background(200);\n let x = frameCount * 0.1;\n fill(255, 0, 0);\n circle(x, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle moves from left to right above a blue square.');\n}\n
\n\nfunction draw() {\n // Add the text description and\n // display it for debugging.\n textOutput(LABEL);\n\n // Draw a moving circle.\n background(200);\n let x = frameCount * 0.1;\n fill(255, 0, 0);\n circle(x, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle moves from left to right above a blue square.');\n}\n
\nA 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'
, orP2D
whose value is 'p2d'
. This is the default for 2D sketches.See setAttributes() for ways to set the\nWebGL version.
\n"],"line":[0,508],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n background(200);\n\n // Display the current WebGL version.\n text(webglVersion, 42, 54);\n\n describe('The text \"p2d\" written in black on a gray background.');\n}\n
\n\nlet font;\n\nfunction preload() {\n // Load a font to use.\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n // Create a canvas using WEBGL mode.\n createCanvas(100, 50, WEBGL);\n background(200);\n\n // Display the current WebGL version.\n fill(0);\n textFont(font);\n text(webglVersion, -15, 5);\n\n describe('The text \"webgl2\" written in black on a gray background.');\n}\n
\n\nlet font;\n\nfunction preload() {\n // Load a font to use.\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n // Create a canvas using WEBGL mode.\n createCanvas(100, 50, WEBGL);\n\n // Set WebGL to version 1.\n setAttributes({ version: 1 });\n\n background(200);\n\n // Display the current WebGL version.\n fill(0);\n textFont(font);\n text(webglVersion, -14, 5);\n\n describe('The text \"webgl\" written in black on a gray background.');\n}\n
\nA Number
variable that stores the width of the canvas in pixels.
width
's default value is 100. Calling\ncreateCanvas() or\nresizeCanvas() changes the value of\nwidth
. Calling noCanvas() sets its value to\n0.
\nfunction setup() {\n background(200);\n\n // Display the canvas' width.\n text(width, 42, 54);\n\n describe('The number 100 written in black on a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(50, 100);\n\n background(200);\n\n // Display the canvas' width.\n text(width, 21, 54);\n\n describe('The number 50 written in black on a gray rectangle.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Display the canvas' width.\n text(width, 42, 54);\n\n 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.');\n}\n\n// If the mouse is pressed, reisze\n// the canvas and display its new\n// width.\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n resizeCanvas(50, 100);\n background(200);\n text(width, 21, 54);\n }\n}\n
\nA Number
variable that stores the height of the browser's viewport.
The layout viewport\nis the area within the browser that's available for drawing.
\n"],"line":[0,680],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n // Set the canvas' width and height\n // using the browser's dimensions.\n createCanvas(windowWidth, windowHeight);\n\n background(200);\n\n describe('A gray canvas that takes up the entire browser window.');\n}\n
\nA function that's called when the browser window is resized.
\nCode placed in the body of windowResized()
will run when the\nbrowser window's size changes. It's a good place to call\nresizeCanvas() or make other\nadjustments to accommodate the new window size.
The event
parameter is optional. If added to the function declaration, it\ncan be used for debugging or other purposes.
optional resize Event.
\n"],"type":[0,"UIEvent"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(windowWidth, windowHeight);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw a circle at the center.\n circle(width / 2, height / 2, 50);\n}\n\n// Resize the canvas when the\n// browser's size changes.\nfunction windowResized() {\n resizeCanvas(windowWidth, windowHeight);\n}\n
\nA Number
variable that stores the width of the browser's viewport.
The layout viewport\nis the area within the browser that's available for drawing.
\n"],"line":[0,652],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n // Set the canvas' width and height\n // using the browser's dimensions.\n createCanvas(windowWidth, windowHeight);\n\n background(200);\n\n describe('A gray canvas that takes up the entire browser window.');\n}\n
\nSets the position and orientation of the current camera in a 3D sketch.
\ncamera()
allows objects to be viewed from different angles. It has nine\nparameters that are all optional.
The first three parameters, x
, y
, and z
, are the coordinates of the\ncamera’s position. For example, calling camera(0, 0, 0)
places the camera\nat the origin (0, 0, 0)
. By default, the camera is placed at\n(0, 0, 800)
.
The next three parameters, centerX
, centerY
, and centerZ
are the\ncoordinates of the point where the camera faces. For example, calling\ncamera(0, 0, 0, 10, 20, 30)
places the camera at the origin (0, 0, 0)
\nand points it at (10, 20, 30)
. By default, the camera points at the\norigin (0, 0, 0)
.
The last three parameters, upX
, upY
, and upZ
are the components of\nthe \"up\" vector. The \"up\" vector orients the camera’s y-axis. For example,\ncalling camera(0, 0, 0, 10, 20, 30, 0, -1, 0)
places the camera at the\norigin (0, 0, 0)
, points it at (10, 20, 30)
, and sets the \"up\" vector\nto (0, -1, 0)
which is like holding it upside-down. By default, the \"up\"\nvector is (0, 1, 0)
.
Note: camera()
can only be used in WebGL mode.
x-coordinate of the camera. Defaults to 0.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"y"],"description":[0,"y-coordinate of the camera. Defaults to 0.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"z"],"description":[0,"z-coordinate of the camera. Defaults to 800.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"centerX"],"description":[0,"x-coordinate of the point the camera faces. Defaults to 0.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"centerY"],"description":[0,"y-coordinate of the point the camera faces. Defaults to 0.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"centerZ"],"description":[0,"z-coordinate of the point the camera faces. Defaults to 0.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"upX"],"description":[0,"x-component of the camera’s \"up\" vector. Defaults to 0.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"upY"],"description":[0,"y-component of the camera’s \"up\" vector. Defaults to 1.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"upZ"],"description":[0,"z-component of the camera’s \"up\" vector. Defaults to 0.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Move the camera to the top-right.\n camera(200, -400, 800);\n\n // Draw the box.\n box();\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube apperas to sway left and right on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the camera's x-coordinate.\n let x = 400 * cos(frameCount * 0.01);\n\n // Orbit the camera around the box.\n camera(x, -400, 800);\n\n // Draw the box.\n box();\n}\n
\n\n// Adjust the range sliders to change the camera's position.\n\nlet xSlider;\nlet ySlider;\nlet zSlider;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create slider objects to set the camera's coordinates.\n xSlider = createSlider(-400, 400, 400);\n xSlider.position(0, 100);\n xSlider.size(100);\n ySlider = createSlider(-400, 400, -200);\n ySlider.position(0, 120);\n ySlider.size(100);\n zSlider = createSlider(0, 1600, 800);\n zSlider.position(0, 140);\n zSlider.size(100);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Get the camera's coordinates from the sliders.\n let x = xSlider.value();\n let y = ySlider.value();\n let z = zSlider.value();\n\n // Move the camera.\n camera(x, y, z);\n\n // Draw the box.\n box();\n}\n
\nCreates a new p5.Camera object and sets it\nas the current (active) camera.
\nThe new camera is initialized with a default position (0, 0, 800)
and a\ndefault perspective projection. Its properties can be controlled with\np5.Camera methods such as\nmyCamera.lookAt(0, 0, 0)
.
Note: Every 3D sketch starts with a default camera initialized.\nThis camera can be controlled with the functions\ncamera(),\nperspective(),\northo(), and\nfrustum() if it's the only camera in the scene.
\nNote: createCamera()
can only be used in WebGL mode.
\n// Double-click to toggle between cameras.\n\nlet cam1;\nlet cam2;\nlet usingCam1 = true;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create the first camera.\n // Keep its default settings.\n cam1 = createCamera();\n\n // Create the second camera.\n // Place it at the top-left.\n // Point it at the origin.\n cam2 = createCamera();\n cam2.setPosition(400, -400, 800);\n cam2.lookAt(0, 0, 0);\n\n // Set the current camera to cam1.\n setCamera(cam1);\n\n describe('A white cube on a gray background. The camera toggles between frontal and aerial views when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw the box.\n box();\n}\n\n// Toggle the current camera when the user double-clicks.\nfunction doubleClicked() {\n if (usingCam1 === true) {\n setCamera(cam2);\n usingCam1 = false;\n } else {\n setCamera(cam1);\n usingCam1 = true;\n }\n}\n
\nSets the frustum of the current camera in a 3D sketch.
\nIn a frustum projection, shapes that are further from the camera appear\nsmaller than shapes that are near the camera. This technique, called\nforeshortening, creates realistic 3D scenes.
\nfrustum()
changes the default camera’s perspective by changing its\nviewing frustum. The frustum is the volume of space that’s visible to the\ncamera. The frustum’s shape is a pyramid with its top cut off. The camera\nis placed where the top of the pyramid should be and points towards the\nbase of the pyramid. It views everything within the frustum.
The first four parameters, left
, right
, bottom
, and top
, set the\ncoordinates of the frustum’s sides, bottom, and top. For example, calling\nfrustum(-100, 100, 200, -200)
creates a frustum that’s 200 pixels wide\nand 400 pixels tall. By default, these coordinates are set based on the\nsketch’s width and height, as in\northo(-width / 20, width / 20, height / 20, -height / 20)
.
The last two parameters, near
and far
, set the distance of the\nfrustum’s near and far plane from the camera. For example, calling\northo(-100, 100, 200, -200, 50, 1000)
creates a frustum that’s 200 pixels\nwide, 400 pixels tall, starts 50 pixels from the camera, and ends 1,000\npixels from the camera. By default, near is set to 0.1 * 800
, which is\n1/10th the default distance between the camera and the origin. far
is set\nto 10 * 800
, which is 10 times the default distance between the camera\nand the origin.
Note: frustum()
can only be used in WebGL mode.
x-coordinate of the frustum’s left plane. Defaults to -width / 20
.
x-coordinate of the frustum’s right plane. Defaults to width / 20
.
y-coordinate of the frustum’s bottom plane. Defaults to height / 20
.
y-coordinate of the frustum’s top plane. Defaults to -height / 20
.
z-coordinate of the frustum’s near plane. Defaults to 0.1 * 800
.
z-coordinate of the frustum’s far plane. Defaults to 10 * 800
.
\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A row of white cubes on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Apply the default frustum projection.\n frustum();\n\n // Translate the origin toward the camera.\n translate(-10, 10, 600);\n\n // Rotate the coordinate system.\n rotateY(-0.1);\n rotateX(-0.1);\n\n // Draw the row of boxes.\n for (let i = 0; i < 6; i += 1) {\n translate(0, 0, -40);\n box(10);\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Adjust the frustum.\n // Center it.\n // Set its width and height to 20 pixels.\n // Place its near plane 300 pixels from the camera.\n // Place its far plane 350 pixels from the camera.\n frustum(-10, 10, -10, 10, 300, 350);\n\n // Translate the origin toward the camera.\n translate(-10, 10, 600);\n\n // Rotate the coordinate system.\n rotateY(-0.1);\n rotateX(-0.1);\n\n // Draw the row of boxes.\n for (let i = 0; i < 6; i += 1) {\n translate(0, 0, -40);\n box(10);\n }\n}\n
\nEnables or disables perspective for lines in 3D sketches.
\nIn WebGL mode, lines can be drawn with a thinner stroke when they’re\nfurther from the camera. Doing so gives them a more realistic appearance.
\nBy default, lines are drawn differently based on the type of perspective\nbeing used:
\nperspective()
and frustum()
simulate a realistic perspective. In\nthese modes, stroke weight is affected by the line’s distance from the\ncamera. Doing so results in a more natural appearance. perspective()
is\nthe default mode for 3D sketches.ortho()
doesn’t simulate a realistic perspective. In this mode, stroke\nweights are consistent regardless of the line’s distance from the camera.\nDoing 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\nway lines are drawn. If true
is passed, as in linePerspective(true)
,\nthen lines will appear thinner when they are further from the camera. If\nfalse
is passed, as in linePerspective(false)
, then lines will have\nconsistent stroke weights regardless of their distance from the camera. By\ndefault, linePerspective()
is enabled.
Calling linePerspective()
without passing an argument returns true
if\nit's enabled and false
if not.
Note: linePerspective()
can only be used in WebGL mode.
whether to enable line perspective.
\n"],"type":[0,"Boolean"]}]]]}],[0,{"params":[1,[]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// Double-click the canvas to toggle the line perspective.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'A white cube with black edges on a gray background. Its edges toggle between thick and thin when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin toward the camera.\n translate(-10, 10, 600);\n\n // Rotate the coordinate system.\n rotateY(-0.1);\n rotateX(-0.1);\n\n // Draw the row of boxes.\n for (let i = 0; i < 6; i += 1) {\n translate(0, 0, -40);\n box(10);\n }\n}\n\n// Toggle the line perspective when the user double-clicks.\nfunction doubleClicked() {\n let isEnabled = linePerspective();\n linePerspective(!isEnabled);\n}\n
\n\n// Double-click the canvas to toggle the line perspective.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'A row of cubes with black edges on a gray background. Their edges toggle between thick and thin when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Use an orthographic projection.\n ortho();\n\n // Translate the origin toward the camera.\n translate(-10, 10, 600);\n\n // Rotate the coordinate system.\n rotateY(-0.1);\n rotateX(-0.1);\n\n // Draw the row of boxes.\n for (let i = 0; i < 6; i += 1) {\n translate(0, 0, -40);\n box(10);\n }\n}\n\n// Toggle the line perspective when the user double-clicks.\nfunction doubleClicked() {\n let isEnabled = linePerspective();\n linePerspective(!isEnabled);\n}\n
\nSets an orthographic projection for the current camera in a 3D sketch.
\nIn an orthographic projection, shapes with the same size always appear the\nsame size, regardless of whether they are near or far from the camera.
\northo()
changes the camera’s perspective by changing its viewing frustum\nfrom a truncated pyramid to a rectangular prism. The camera is placed in\nfront of the frustum and views everything between the frustum’s near plane\nand its far plane. ortho()
has six optional parameters to define the\nfrustum.
The first four parameters, left
, right
, bottom
, and top
, set the\ncoordinates of the frustum’s sides, bottom, and top. For example, calling\northo(-100, 100, 200, -200)
creates a frustum that’s 200 pixels wide and\n400 pixels tall. By default, these coordinates are set based on the\nsketch’s width and height, as in\northo(-width / 2, width / 2, -height / 2, height / 2)
.
The last two parameters, near
and far
, set the distance of the\nfrustum’s near and far plane from the camera. For example, calling\northo(-100, 100, 200, 200, 50, 1000)
creates a frustum that’s 200 pixels\nwide, 400 pixels tall, starts 50 pixels from the camera, and ends 1,000\npixels from the camera. By default, near
and far
are set to 0 and\nmax(width, height) + 800
, respectively.
Note: ortho()
can only be used in WebGL mode.
x-coordinate of the frustum’s left plane. Defaults to -width / 2
.
x-coordinate of the frustum’s right plane. Defaults to width / 2
.
y-coordinate of the frustum’s bottom plane. Defaults to height / 2
.
y-coordinate of the frustum’s top plane. Defaults to -height / 2
.
z-coordinate of the frustum’s near plane. Defaults to 0.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"far"],"description":[0,"z-coordinate of the frustum’s far plane. Defaults to max(width, height) + 800
.
\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A row of tiny, white cubes on a gray background. All the cubes appear the same size.');\n}\n\nfunction draw() {\n background(200);\n\n // Apply an orthographic projection.\n ortho();\n\n // Translate the origin toward the camera.\n translate(-10, 10, 600);\n\n // Rotate the coordinate system.\n rotateY(-0.1);\n rotateX(-0.1);\n\n // Draw the row of boxes.\n for (let i = 0; i < 6; i += 1) {\n translate(0, 0, -40);\n box(10);\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Apply an orthographic projection.\n // Center the frustum.\n // Set its width and height to 20.\n // Place its near plane 300 pixels from the camera.\n // Place its far plane 350 pixels from the camera.\n ortho(-10, 10, -10, 10, 300, 350);\n\n // Translate the origin toward the camera.\n translate(-10, 10, 600);\n\n // Rotate the coordinate system.\n rotateY(-0.1);\n rotateX(-0.1);\n\n // Draw the row of boxes.\n for (let i = 0; i < 6; i += 1) {\n translate(0, 0, -40);\n box(10);\n }\n}\n
\nSets a perspective projection for the current camera in a 3D sketch.
\nIn a perspective projection, shapes that are further from the camera appear\nsmaller than shapes that are near the camera. This technique, called\nforeshortening, creates realistic 3D scenes. It’s applied by default in\nWebGL mode.
\nperspective()
changes the camera’s perspective by changing its viewing\nfrustum. The frustum is the volume of space that’s visible to the camera.\nIts shape is a pyramid with its top cut off. The camera is placed where\nthe top of the pyramid should be and views everything between the frustum’s\ntop (near) plane and its bottom (far) plane.
The first parameter, fovy
, is the camera’s vertical field of view. It’s\nan angle that describes how tall or narrow a view the camera has. For\nexample, calling perspective(0.5)
sets the camera’s vertical field of\nview to 0.5 radians. By default, fovy
is calculated based on the sketch’s\nheight and the camera’s default z-coordinate, which is 800. The formula for\nthe default fovy
is 2 * atan(height / 2 / 800)
.
The second parameter, aspect
, is the camera’s aspect ratio. It’s a number\nthat describes the ratio of the top plane’s width to its height. For\nexample, calling perspective(0.5, 1.5)
sets the camera’s field of view to\n0.5 radians and aspect ratio to 1.5, which would make shapes appear thinner\non a square canvas. By default, aspect is set to width / height
.
The third parameter, near
, is the distance from the camera to the near\nplane. For example, calling perspective(0.5, 1.5, 100)
sets the camera’s\nfield of view to 0.5 radians, its aspect ratio to 1.5, and places the near\nplane 100 pixels from the camera. Any shapes drawn less than 100 pixels\nfrom the camera won’t be visible. By default, near is set to 0.1 * 800
,\nwhich 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\nplane. For example, calling perspective(0.5, 1.5, 100, 10000)
sets the\ncamera’s field of view to 0.5 radians, its aspect ratio to 1.5, places the\nnear plane 100 pixels from the camera, and places the far plane 10,000\npixels from the camera. Any shapes drawn more than 10,000 pixels from the\ncamera won’t be visible. By default, far is set to 10 * 800
, which is 10\ntimes the default distance between the camera and the origin.
Note: perspective()
can only be used in WebGL mode.
camera frustum vertical field of view. Defaults to\n 2 * atan(height / 2 / 800)
.
camera frustum aspect ratio. Defaults to\n width / height
.
distance from the camera to the near clipping plane.\n Defaults to 0.1 * 800
.
distance from the camera to the far clipping plane.\n Defaults to 10 * 800
.
\n// Double-click to squeeze the box.\n\nlet isSqueezed = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white rectangular prism on a gray background. The box appears to become thinner when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Place the camera at the top-right.\n camera(400, -400, 800);\n\n if (isSqueezed === true) {\n // Set fovy to 0.2.\n // Set aspect to 1.5.\n perspective(0.2, 1.5);\n }\n\n // Draw the box.\n box();\n}\n\n// Change the camera's perspective when the user double-clicks.\nfunction doubleClicked() {\n isSqueezed = true;\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white rectangular prism on a gray background. The prism moves away from the camera until it disappears.');\n}\n\nfunction draw() {\n background(200);\n\n // Place the camera at the top-right.\n camera(400, -400, 800);\n\n // Set fovy to 0.2.\n // Set aspect to 1.5.\n // Set near to 600.\n // Set far to 1200.\n perspective(0.2, 1.5, 600, 1200);\n\n // Move the origin away from the camera.\n let x = -frameCount;\n let y = frameCount;\n let z = -2 * frameCount;\n translate(x, y, z);\n\n // Draw the box.\n box();\n}\n
\nSets the current (active) camera of a 3D sketch.
\nsetCamera()
allows for switching between multiple cameras created with\ncreateCamera().
Note: setCamera()
can only be used in WebGL mode.
camera that should be made active.
\n"],"type":[0,"p5.Camera"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// Double-click to toggle between cameras.\n\nlet cam1;\nlet cam2;\nlet usingCam1 = true;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create the first camera.\n // Keep its default settings.\n cam1 = createCamera();\n\n // Create the second camera.\n // Place it at the top-left.\n // Point it at the origin.\n cam2 = createCamera();\n cam2.setPosition(400, -400, 800);\n cam2.lookAt(0, 0, 0);\n\n // Set the current camera to cam1.\n setCamera(cam1);\n\n describe('A white cube on a gray background. The camera toggles between frontal and aerial views when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw the box.\n box();\n}\n\n// Toggle the current camera when the user double-clicks.\nfunction doubleClicked() {\n if (usingCam1 === true) {\n setCamera(cam2);\n usingCam1 = false;\n } else {\n setCamera(cam1);\n usingCam1 = true;\n }\n}\n
\nAdds a grid and an axes icon to clarify orientation in 3D sketches.
\ndebugMode()
adds a grid that shows where the “ground” is in a sketch. By\ndefault, the grid will run through the origin (0, 0, 0)
of the sketch\nalong the XZ plane. debugMode()
also adds an axes icon that points along\nthe positive x-, y-, and z-axes. Calling debugMode()
displays the grid\nand axes icon with their default size and position.
There are four ways to call debugMode()
with optional parameters to\ncustomize the debugging environment.
The first way to call debugMode()
has one parameter, mode
. If the\nsystem constant GRID
is passed, as in debugMode(GRID)
, then the grid\nwill be displayed and the axes icon will be hidden. If the constant AXES
\nis passed, as in debugMode(AXES)
, then the axes icon will be displayed\nand the grid will be hidden.
The second way to call debugMode()
has six parameters. The first\nparameter, mode
, selects either GRID
or AXES
to be displayed. The\nnext five parameters, gridSize
, gridDivisions
, xOff
, yOff
, and\nzOff
are optional. They’re numbers that set the appearance of the grid\n(gridSize
and gridDivisions
) and the placement of the axes icon\n(xOff
, yOff
, and zOff
). For example, calling\ndebugMode(20, 5, 10, 10, 10)
sets the gridSize
to 20 pixels, the number\nof gridDivisions
to 5, and offsets the axes icon by 10 pixels along the\nx-, y-, and z-axes.
The third way to call debugMode()
has five parameters. The first\nparameter, mode
, selects either GRID
or AXES
to be displayed. The\nnext four parameters, axesSize
, xOff
, yOff
, and zOff
are optional.\nThey’re numbers that set the appearance of the size of the axes icon\n(axesSize
) and its placement (xOff
, yOff
, and zOff
).
The fourth way to call debugMode()
has nine optional parameters. The\nfirst five parameters, gridSize
, gridDivisions
, gridXOff
, gridYOff
,\nand gridZOff
are numbers that set the appearance of the grid. For\nexample, calling debugMode(100, 5, 0, 0, 0)
sets the gridSize
to 100,\nthe number of gridDivisions
to 5, and sets all the offsets to 0 so that\nthe grid is centered at the origin. The next four parameters, axesSize
,\nxOff
, yOff
, and zOff
are numbers that set the appearance of the size\nof the axes icon (axesSize
) and its placement (axesXOff
, axesYOff
,\nand axesZOff
). For example, calling\ndebugMode(100, 5, 0, 0, 0, 50, 10, 10, 10)
sets the gridSize
to 100,\nthe number of gridDivisions
to 5, and sets all the offsets to 0 so that\nthe grid is centered at the origin. It then sets the axesSize
to 50 and\noffsets the icon 10 pixels along each axis.
either GRID or AXES
\n"],"type":[0,"Constant"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"mode"],"description":[0,""],"type":[0,"Constant"]}],[0,{"name":[0,"gridSize"],"description":[0,"side length of the grid.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"gridDivisions"],"description":[0,"number of divisions in the grid.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"xOff"],"description":[0,"offset from origin along the x-axis.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"yOff"],"description":[0,"offset from origin along the y-axis.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"zOff"],"description":[0,"offset from origin along the z-axis.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"mode"],"description":[0,""],"type":[0,"Constant"]}],[0,{"name":[0,"axesSize"],"description":[0,"length of axes icon markers.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"xOff"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"yOff"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"zOff"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"gridSize"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"gridDivisions"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"gridXOff"],"description":[0,"grid offset from the origin along the x-axis.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"gridYOff"],"description":[0,"grid offset from the origin along the y-axis.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"gridZOff"],"description":[0,"grid offset from the origin along the z-axis.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"axesSize"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"axesXOff"],"description":[0,"axes icon offset from the origin along the x-axis.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"axesYOff"],"description":[0,"axes icon offset from the origin along the y-axis.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"axesZOff"],"description":[0,"axes icon offset from the origin along the z-axis.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Enable debug mode.\n debugMode();\n\n describe('A multicolor box on a gray background. A grid and axes icon are displayed near the box.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Style the box.\n normalMaterial();\n\n // Draw the box.\n box(20, 40);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Enable debug mode.\n // Only display the axes icon.\n debugMode(AXES);\n\n describe('A multicolor box on a gray background. A grid and axes icon are displayed near the box.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Style the box.\n normalMaterial();\n\n // Draw the box.\n box(20, 40);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Enable debug mode.\n // Only display the grid and customize it:\n // - size: 50\n // - divisions: 10\n // - offsets: 0, 20, 0\n debugMode(GRID, 50, 10, 0, 20, 0);\n\n describe('A multicolor box on a gray background. A grid is displayed below the box.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Style the box.\n normalMaterial();\n\n // Draw the box.\n box(20, 40);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Enable debug mode.\n // Display the grid and axes icon and customize them:\n // Grid\n // ----\n // - size: 50\n // - divisions: 10\n // - offsets: 0, 20, 0\n // Axes\n // ----\n // - size: 50\n // - offsets: 0, 0, 0\n debugMode(50, 10, 0, 20, 0, 50, 0, 0, 0);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Style the box.\n normalMaterial();\n\n // Draw the box.\n box(20, 40);\n}\n
\nTurns off debugMode() in a 3D sketch.
\n"],"line":[0,725],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Enable debug mode.\n debugMode();\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Style the box.\n normalMaterial();\n\n // Draw the box. box(20, 40);\n}\n\n// Disable debug mode when the user double-clicks.\nfunction doubleClicked() {\n noDebugMode();\n}\n
\nAllows the user to orbit around a 3D sketch using a mouse, trackpad, or\ntouchscreen.
\n3D sketches are viewed through an imaginary camera. Calling\norbitControl()
within the draw() function allows\nthe user to change the camera’s position:
function draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rest of sketch.\n}\n
\nLeft-clicking and dragging or swipe motion will rotate the camera position\nabout the center of the sketch. Right-clicking and dragging or multi-swipe\nwill pan the camera position without rotation. Using the mouse wheel\n(scrolling) or pinch in/out will move the camera further or closer from the\ncenter of the sketch.
\nThe first three parameters, sensitivityX
, sensitivityY
, and\nsensitivityZ
, are optional. They’re numbers that set the sketch’s\nsensitivity to movement along each axis. For example, calling\norbitControl(1, 2, -1)
keeps movement along the x-axis at its default\nvalue, makes the sketch twice as sensitive to movement along the y-axis,\nand reverses motion along the z-axis. By default, all sensitivity values\nare 1.
The fourth parameter, options
, is also optional. It’s an object that\nchanges the behavior of orbiting. For example, calling\norbitControl(1, 1, 1, options)
keeps the default sensitivity values while\nchanging the behaviors set with options
. The object can have the\nfollowing properties:
let options = {\n // Setting this to false makes mobile interactions smoother by\n // preventing accidental interactions with the page while orbiting.\n // By default, it's true.\n disableTouchActions: true,\n\n // Setting this to true makes the camera always rotate in the\n // direction the mouse/touch is moving.\n // By default, it's false.\n freeRotation: false\n};\n\norbitControl(1, 1, 1, options);\n
\n"],"line":[0,11],"params":[1,[[0,{"name":[0,"sensitivityX"],"description":[0,"sensitivity to movement along the x-axis. Defaults to 1.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"sensitivityY"],"description":[0,"sensitivity to movement along the y-axis. Defaults to 1.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"sensitivityZ"],"description":[0,"sensitivity to movement along the z-axis. Defaults to 1.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"options"],"description":[0,"object with two optional properties, disableTouchActions
\n and freeRotation
. Both are Boolean
s. disableTouchActions
\n defaults to true
and freeRotation
defaults to false
.
\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A multicolor box on a gray background. The camera angle changes when the user interacts using a mouse, trackpad, or touchscreen.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Style the box.\n normalMaterial();\n\n // Draw the box.\n box(30, 50);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A multicolor box on a gray background. The camera angle changes when the user interacts using a mouse, trackpad, or touchscreen.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n // Make the interactions 3X sensitive.\n orbitControl(3, 3, 3);\n\n // Style the box.\n normalMaterial();\n\n // Draw the box.\n box(30, 50);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A multicolor box on a gray background. The camera angle changes when the user interacts using a mouse, trackpad, or touchscreen.');\n}\n\nfunction draw() {\n background(200);\n\n // Create an options object.\n let options = {\n disableTouchActions: false,\n freeRotation: true\n };\n\n // Enable orbiting with the mouse.\n // Prevent accidental touch actions on touchscreen devices\n // and enable free rotation.\n orbitControl(1, 1, 1, options);\n\n // Style the box.\n normalMaterial();\n\n // Draw the box.\n box(30, 50);\n}\n
\nCreates a light that shines from all directions.
\nAmbient light does not come from one direction. Instead, 3D shapes are\nlit evenly from all sides. Ambient lights are almost always used in\ncombination with other types of lights.
\nThere are three ways to call ambientLight()
with optional parameters to\nset the light’s color.
The first way to call ambientLight()
has two parameters, gray
and\nalpha
. alpha
is optional. Grayscale and alpha values between 0 and 255\ncan be passed to set the ambient light’s color, as in ambientLight(50)
or\nambientLight(50, 30)
.
The second way to call ambientLight()
has one parameter, color. A\np5.Color object, an array of color values, or a\nCSS color string, as in ambientLight('magenta')
, can be passed to set the\nambient light’s color.
The third way to call ambientLight()
has four parameters, v1
, v2
,\nv3
, and alpha
. alpha
is optional. RGBA, HSBA, or HSLA values can be\npassed to set the ambient light’s colors, as in ambientLight(255, 0, 0)
\nor ambientLight(255, 0, 0, 30)
. Color values will be interpreted using\nthe current colorMode().
red or hue value in the current\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,"green or saturation value in the current\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,"blue, brightness, or lightness value in the current\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"alpha"],"description":[0,"alpha (transparency) value in the current\n colorMode().
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"gray"],"description":[0,"grayscale value between 0 and 255.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"alpha"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"value"],"description":[0,"color as a CSS string.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"values"],"description":[0,"color as an array of RGBA, HSBA, or HSLA\n values.
\n"],"type":[0,"Number[]"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"color as a p5.Color object.
\n"],"type":[0,"p5.Color"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click the canvas to turn on the light.\n\nlet isLit = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A sphere drawn against a gray background. The sphere appears to change color when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Control the light.\n if (isLit === true) {\n // Use a grayscale value of 80.\n ambientLight(80);\n }\n\n // Draw the sphere.\n sphere(30);\n}\n\n// Turn on the ambient light when the user double-clicks.\nfunction doubleClicked() {\n isLit = true;\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A faded magenta sphere drawn against a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n // Use a p5.Color object.\n let c = color('orchid');\n ambientLight(c);\n\n // Draw the sphere.\n sphere();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A faded magenta sphere drawn against a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n // Use a CSS color string.\n ambientLight('#DA70D6');\n\n // Draw the sphere.\n sphere(30);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A faded magenta sphere drawn against a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n // Use RGB values\n ambientLight(218, 112, 214);\n\n // Draw the sphere.\n sphere(30);\n}\n
\nCreates a light that shines in one direction.
\nDirectional lights don’t shine from a specific point. They’re like a sun\nthat shines from somewhere offscreen. The light’s direction is set using\nthree (x, y, z)
values between -1 and 1. For example, setting a light’s\ndirection as (1, 0, 0)
will light p5.Geometry\nobjects from the left since the light faces directly to the right. A\nmaximum of 5 directional lights can be active at once.
There are four ways to call directionalLight()
with parameters to set the\nlight’s color and direction.
The first way to call directionalLight()
has six parameters. The first\nthree parameters, v1
, v2
, and v3
, set the light’s color using the\ncurrent colorMode(). The last three\nparameters, x
, y
, and z
, set the light’s direction. For example,\ndirectionalLight(255, 0, 0, 1, 0, 0)
creates a red (255, 0, 0)
light\nthat shines to the right (1, 0, 0)
.
The second way to call directionalLight()
has four parameters. The first\nthree parameters, v1
, v2
, and v3
, set the light’s color using the\ncurrent colorMode(). The last parameter,\ndirection
sets the light’s direction using a\np5.Geometry object. For example,\ndirectionalLight(255, 0, 0, lightDir)
creates a red (255, 0, 0)
light\nthat shines in the direction the lightDir
vector points.
The third way to call directionalLight()
has four parameters. The first\nparameter, color
, sets the light’s color using a\np5.Color object or an array of color values. The\nlast three parameters, x
, y
, and z
, set the light’s direction. For\nexample, directionalLight(myColor, 1, 0, 0)
creates a light that shines\nto the right (1, 0, 0)
with the color value of myColor
.
The fourth way to call directionalLight()
has two parameters. The first\nparameter, color
, sets the light’s color using a\np5.Color object or an array of color values. The\nsecond parameter, direction
, sets the light’s direction using a\np5.Color object. For example,\ndirectionalLight(myColor, lightDir)
creates a light that shines in the\ndirection the lightDir
vector points with the color value of myColor
.
red or hue value in the current\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,"green or saturation value in the current\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,"blue, brightness, or lightness value in the current\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"x"],"description":[0,"x-component of the light's direction between -1 and 1.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"y-component of the light's direction between -1 and 1.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,"z-component of the light's direction between -1 and 1.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"direction"],"description":[0,"direction of the light as a\n p5.Vector object.
\n"],"type":[0,"p5.Vector"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"color as a p5.Color object,\n an array of color values, or as a CSS string.
\n"],"type":[0,"p5.Color|Number[]|String"]}],[0,{"name":[0,"x"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,""],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,""],"type":[0,"p5.Color|Number[]|String"]}],[0,{"name":[0,"direction"],"description":[0,""],"type":[0,"p5.Vector"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click to turn on the directional light.\n\nlet isLit = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A sphere drawn on a gray background. A red light starts shining from above when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Control the light.\n if (isLit === true) {\n // Add a red directional light from above.\n // Use RGB values and XYZ directions.\n directionalLight(255, 0, 0, 0, 1, 0);\n }\n\n // Style the sphere.\n noStroke();\n\n // Draw the sphere.\n sphere(30);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A sphere drawn on a gray background. The top of the sphere appears bright red. The color gets darker toward the bottom.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Add a red directional light from above.\n // Use a p5.Color object and XYZ directions.\n let c = color(255, 0, 0);\n directionalLight(c, 0, 1, 0);\n\n // Style the sphere.\n noStroke();\n\n // Draw the sphere.\n sphere(30);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A sphere drawn on a gray background. The top of the sphere appears bright red. The color gets darker toward the bottom.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Add a red directional light from above.\n // Use a p5.Color object and a p5.Vector object.\n let c = color(255, 0, 0);\n let lightDir = createVector(0, 1, 0);\n directionalLight(c, lightDir);\n\n // Style the sphere.\n noStroke();\n\n // Draw the sphere.\n sphere(30);\n}\n
\nCreates an ambient light from an image.
\nimageLight()
simulates a light shining from all directions. The effect is\nlike placing the sketch at the center of a giant sphere that uses the image\nas its texture. The image's diffuse light will be affected by\nfill() and the specular reflections will be\naffected by specularMaterial() and\nshininess().
The parameter, img
, is the p5.Image object to\nuse as the light source.
image to use as the light source.
\n"],"type":[0,"p5.image"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n\nlet img;\n\n// Load an image and create a p5.Image object.\nfunction preload() {\n img = loadImage('/assets/outdoor_spheremap.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A sphere floating above a landscape. The surface of the sphere reflects the landscape.');\n}\n\nfunction draw() {\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Draw the image as a panorama (360˚ background).\n panorama(img);\n\n // Add a soft ambient light.\n ambientLight(50);\n\n // Add light from the image.\n imageLight(img);\n\n // Style the sphere.\n specularMaterial(20);\n shininess(100);\n noStroke();\n\n // Draw the sphere.\n sphere(30);\n}\n
\nSets the falloff rate for pointLight()\nand spotLight().
\nA light’s falloff describes the intensity of its beam at a distance. For\nexample, a lantern has a slow falloff, a flashlight has a medium falloff,\nand a laser pointer has a sharp falloff.
\nlightFalloff()
has three parameters, constant
, linear
, and\nquadratic
. They’re numbers used to calculate falloff at a distance, d
,\nas follows:
falloff = 1 / (constant + d * linear + (d * d) * quadratic)
Note: constant
, linear
, and quadratic
should always be set to values\ngreater than 0.
constant value for calculating falloff.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"linear"],"description":[0,"linear value for calculating falloff.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"quadratic"],"description":[0,"quadratic value for calculating falloff.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click to change the falloff rate.\n\nlet useFalloff = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A sphere drawn against a gray background. The intensity of the light changes when the user double-clicks.');\n}\n\nfunction draw() {\n background(50);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Set the light falloff.\n if (useFalloff === true) {\n lightFalloff(2, 0, 0);\n }\n\n // Add a white point light from the front.\n pointLight(255, 255, 255, 0, 0, 100);\n\n // Style the sphere.\n noStroke();\n\n // Draw the sphere.\n sphere(30);\n}\n\n// Change the falloff value when the user double-clicks.\nfunction doubleClicked() {\n useFalloff = true;\n}\n
\nPlaces an ambient and directional light in the scene.\nThe lights are set to ambientLight(128, 128, 128) and\ndirectionalLight(128, 128, 128, 0, 0, -1).
\nNote: lights need to be called (whether directly or indirectly)\nwithin draw() to remain persistent in a looping program.\nPlacing them in setup() will cause them to only have an effect\nthe first time through the loop.
\n"],"line":[0,1077],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click to turn on the lights.\n\nlet isLit = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white box drawn against a gray background. The quality of the light changes when the user double-clicks.');\n}\n\nfunction draw() {\n background(50);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Control the lights.\n if (isLit === true) {\n lights();\n }\n\n // Draw the box.\n box();\n}\n\n// Turn on the lights when the user double-clicks.\nfunction doubleClicked() {\n isLit = true;\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white box drawn against a gray background.');\n}\n\nfunction draw() {\n background(50);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n ambientLight(128, 128, 128);\n directionalLight(128, 128, 128, 0, 0, -1);\n\n // Draw the box.\n box();\n}\n
\nRemoves all lights from the sketch.
\nCalling noLights()
removes any lights created with\nlights(),\nambientLight(),\ndirectionalLight(),\npointLight(), or\nspotLight(). These functions may be called\nafter noLights()
to create a new lighting scheme.
\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('Two spheres drawn against a gray background. The top sphere is white and the bottom sphere is red.');\n}\n\nfunction draw() {\n background(50);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n lights();\n\n // Style the spheres.\n noStroke();\n\n // Draw the top sphere.\n push();\n translate(0, -25, 0);\n sphere(20);\n pop();\n\n // Turn off the lights.\n noLights();\n\n // Add a red directional light that points into the screen.\n directionalLight(255, 0, 0, 0, 0, -1);\n\n // Draw the bottom sphere.\n push();\n translate(0, 25, 0);\n sphere(20);\n pop();\n}\n
\nCreates an immersive 3D background.
\npanorama()
transforms images containing 360˚ content, such as maps or\nHDRIs, into immersive 3D backgrounds that surround a sketch. Exploring the\nspace requires changing the camera's perspective with functions such as\norbitControl() or\ncamera().
360˚ image to use as the background.
\n"],"type":[0,"p5.Image"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n\nlet img;\n\n// Load an image and create a p5.Image object.\nfunction preload() {\n img = loadImage('/assets/outdoor_spheremap.jpg');\n}\n\nfunction setup() {\n createCanvas(100 ,100 ,WEBGL);\n\n 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.');\n}\n\nfunction draw() {\n // Add the panorama.\n panorama(img);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Use the image as a light source.\n imageLight(img);\n\n // Style the sphere.\n noStroke();\n specularMaterial(50);\n shininess(200);\n metalness(100);\n\n // Draw the sphere.\n sphere(30);\n}\n
\nCreates a light that shines from a point in all directions.
\nPoint lights are like light bulbs that shine in all directions. They can be\nplaced at different positions to achieve different lighting effects. A\nmaximum of 5 point lights can be active at once.
\nThere are four ways to call pointLight()
with parameters to set the\nlight’s color and position.
The first way to call pointLight()
has six parameters. The first three\nparameters, v1
, v2
, and v3
, set the light’s color using the current\ncolorMode(). The last three parameters, x
,\ny
, and z
, set the light’s position. For example,\npointLight(255, 0, 0, 50, 0, 0)
creates a red (255, 0, 0)
light that\nshines from the coordinates (50, 0, 0)
.
The second way to call pointLight()
has four parameters. The first three\nparameters, v1
, v2
, and v3
, set the light’s color using the current\ncolorMode(). The last parameter, position sets\nthe light’s position using a p5.Vector object.\nFor example, pointLight(255, 0, 0, lightPos)
creates a red (255, 0, 0)
\nlight that shines from the position set by the lightPos
vector.
The third way to call pointLight()
has four parameters. The first\nparameter, color
, sets the light’s color using a\np5.Color object or an array of color values. The\nlast three parameters, x
, y
, and z
, set the light’s position. For\nexample, directionalLight(myColor, 50, 0, 0)
creates a light that shines\nfrom the coordinates (50, 0, 0)
with the color value of myColor
.
The fourth way to call pointLight()
has two parameters. The first\nparameter, color
, sets the light’s color using a\np5.Color object or an array of color values. The\nsecond parameter, position
, sets the light’s position using a\np5.Vector object. For example,\ndirectionalLight(myColor, lightPos)
creates a light that shines from the\nposition set by the lightPos
vector with the color value of myColor
.
red or hue value in the current\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,"green or saturation value in the current\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,"blue, brightness, or lightness value in the current\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"x"],"description":[0,"x-coordinate of the light.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"y-coordinate of the light.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,"z-coordinate of the light.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"position"],"description":[0,"position of the light as a\n p5.Vector object.
\n"],"type":[0,"p5.Vector"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"color as a p5.Color object,\n an array of color values, or a CSS string.
\n"],"type":[0,"p5.Color|Number[]|String"]}],[0,{"name":[0,"x"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,""],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,""],"type":[0,"p5.Color|Number[]|String"]}],[0,{"name":[0,"position"],"description":[0,""],"type":[0,"p5.Vector"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click to turn on the point light.\n\nlet isLit = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A sphere drawn on a gray background. A red light starts shining from above when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Control the light.\n if (isLit === true) {\n // Add a red point light from above.\n // Use RGB values and XYZ coordinates.\n pointLight(255, 0, 0, 0, -150, 0);\n }\n\n // Style the sphere.\n noStroke();\n\n // Draw the sphere.\n sphere(30);\n}\n\n// Turn on the point light when the user double-clicks.\nfunction doubleClicked() {\n isLit = true;\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A sphere drawn on a gray background. The top of the sphere appears bright red. The color gets darker toward the bottom.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Add a red point light from above.\n // Use a p5.Color object and XYZ directions.\n let c = color(255, 0, 0);\n pointLight(c, 0, -150, 0);\n\n // Style the sphere.\n noStroke();\n\n // Draw the sphere.\n sphere(30);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A sphere drawn on a gray background. The top of the sphere appears bright red. The color gets darker toward the bottom.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Add a red point light from above.\n // Use a p5.Color object and a p5.Vector object.\n let c = color(255, 0, 0);\n let lightPos = createVector(0, -150, 0);\n pointLight(c, lightPos);\n\n // Style the sphere.\n noStroke();\n\n // Draw the sphere.\n sphere(30);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Add a red point light that points to the center of the scene.\n // Use a p5.Color object and a p5.Vector object.\n let c = color(255, 0, 0);\n let lightPos = createVector(0, 0, 65);\n pointLight(c, lightPos);\n\n // Style the spheres.\n noStroke();\n\n // Draw a sphere up and to the left.\n push();\n translate(-25, -25, 25);\n sphere(10);\n pop();\n\n // Draw a box up and to the right.\n push();\n translate(25, -25, 25);\n sphere(10);\n pop();\n\n // Draw a sphere down and to the left.\n push();\n translate(-25, 25, 25);\n sphere(10);\n pop();\n\n // Draw a box down and to the right.\n push();\n translate(25, 25, 25);\n sphere(10);\n pop();\n}\n
\nSets the specular color for lights.
\nspecularColor()
affects lights that bounce off a surface in a preferred\ndirection. These lights include\ndirectionalLight(),\npointLight(), and\nspotLight(). The function helps to create\nhighlights on p5.Geometry objects that are\nstyled with specularMaterial(). If a\ngeometry does not use\nspecularMaterial(), then\nspecularColor()
will have no effect.
Note: specularColor()
doesn’t affect lights that bounce in all\ndirections, including ambientLight() and\nimageLight().
There are three ways to call specularColor()
with optional parameters to\nset the specular highlight color.
The first way to call specularColor()
has two optional parameters, gray
\nand alpha
. Grayscale and alpha values between 0 and 255, as in\nspecularColor(50)
or specularColor(50, 80)
, can be passed to set the\nspecular highlight color.
The second way to call specularColor()
has one optional parameter,\ncolor
. A p5.Color object, an array of color\nvalues, or a CSS color string can be passed to set the specular highlight\ncolor.
The third way to call specularColor()
has four optional parameters, v1
,\nv2
, v3
, and alpha
. RGBA, HSBA, or HSLA values, as in\nspecularColor(255, 0, 0, 80)
, can be passed to set the specular highlight\ncolor. Color values will be interpreted using the current\ncolorMode().
red or hue value in the current\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,"green or saturation value in the current\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,"blue, brightness, or lightness value in the current\n colorMode().
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"gray"],"description":[0,"grayscale value between 0 and 255.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"value"],"description":[0,"color as a CSS string.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"values"],"description":[0,"color as an array of RGBA, HSBA, or HSLA\n values.
\n"],"type":[0,"Number[]"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"color as a p5.Color object.
\n"],"type":[0,"p5.Color"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white sphere drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // No specular color.\n // Draw the sphere.\n sphere(30);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click the canvas to add a point light.\n\nlet isLit = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A sphere drawn on a gray background. A spotlight starts shining when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Style the sphere.\n noStroke();\n specularColor(100);\n specularMaterial(255, 255, 255);\n\n // Control the light.\n if (isLit === true) {\n // Add a white point light from the top-right.\n pointLight(255, 255, 255, 30, -20, 40);\n }\n\n // Draw the sphere.\n sphere(30);\n}\n\n// Turn on the point light when the user double-clicks.\nfunction doubleClicked() {\n isLit = true;\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A black sphere drawn on a gray background. An area on the surface of the sphere is highlighted in blue.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Add a specular highlight.\n // Use a p5.Color object.\n let c = color('dodgerblue');\n specularColor(c);\n\n // Add a white point light from the top-right.\n pointLight(255, 255, 255, 30, -20, 40);\n\n // Style the sphere.\n noStroke();\n\n // Add a white specular material.\n specularMaterial(255, 255, 255);\n\n // Draw the sphere.\n sphere(30);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A black sphere drawn on a gray background. An area on the surface of the sphere is highlighted in blue.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Add a specular highlight.\n // Use a CSS color string.\n specularColor('#1E90FF');\n\n // Add a white point light from the top-right.\n pointLight(255, 255, 255, 30, -20, 40);\n\n // Style the sphere.\n noStroke();\n\n // Add a white specular material.\n specularMaterial(255, 255, 255);\n\n // Draw the sphere.\n sphere(30);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A black sphere drawn on a gray background. An area on the surface of the sphere is highlighted in blue.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Add a specular highlight.\n // Use RGB values.\n specularColor(30, 144, 255);\n\n // Add a white point light from the top-right.\n pointLight(255, 255, 255, 30, -20, 40);\n\n // Style the sphere.\n noStroke();\n\n // Add a white specular material.\n specularMaterial(255, 255, 255);\n\n // Draw the sphere.\n sphere(30);\n}\n
\nCreates a light that shines from a point in one direction.
\nSpot lights are like flashlights that shine in one direction creating a\ncone of light. The shape of the cone can be controlled using the angle and\nconcentration parameters. A maximum of 5 spot lights can be active at once.
\nThere are eight ways to call spotLight()
with parameters to set the\nlight’s color, position, direction. For example,\nspotLight(255, 0, 0, 0, 0, 0, 1, 0, 0)
creates a red (255, 0, 0)
light\nat 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.\nFor example, spotLight(255, 0, 0, 0, 0, 0, 1, 0, 0, PI / 16)
creates a\nred (255, 0, 0)
light at the origin (0, 0, 0)
that points to the right\n(1, 0, 0)
with an angle of PI / 16
radians. By default, angle
is\nPI / 3
radians.
The concentration
parameter is also optional. It focuses the light\ntowards the center of the light cone. For example,\nspotLight(255, 0, 0, 0, 0, 0, 1, 0, 0, PI / 16, 50)
creates a red\n(255, 0, 0)
light at the origin (0, 0, 0)
that points to the right\n(1, 0, 0)
with an angle of PI / 16
radians at concentration of 50. By\ndefault, concentration
is 100.
red or hue value in the current\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,"green or saturation value in the current\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,"blue, brightness, or lightness value in the current\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"x"],"description":[0,"x-coordinate of the light.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"y-coordinate of the light.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,"z-coordinate of the light.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"rx"],"description":[0,"x-component of light direction between -1 and 1.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"ry"],"description":[0,"y-component of light direction between -1 and 1.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"rz"],"description":[0,"z-component of light direction between -1 and 1.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"angle"],"description":[0,"angle of the light cone. Defaults to PI / 3
.
concentration of the light. Defaults to 100.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"color as a p5.Color object,\n an array of color values, or a CSS string.
\n"],"type":[0,"p5.Color|Number[]|String"]}],[0,{"name":[0,"position"],"description":[0,"position of the light as a p5.Vector object.
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"direction"],"description":[0,"direction of light as a p5.Vector object.
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"angle"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"concentration"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"position"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"direction"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"angle"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"concentration"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,""],"type":[0,"p5.Color|Number[]|String"]}],[0,{"name":[0,"x"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"direction"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"angle"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"concentration"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,""],"type":[0,"p5.Color|Number[]|String"]}],[0,{"name":[0,"position"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"rx"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"ry"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"rz"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"angle"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"concentration"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"x"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"direction"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"angle"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"concentration"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"position"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"rx"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"ry"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"rz"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"angle"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"concentration"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,""],"type":[0,"p5.Color|Number[]|String"]}],[0,{"name":[0,"x"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"rx"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"ry"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"rz"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"angle"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"concentration"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click to adjust the spotlight.\n\nlet isLit = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white sphere drawn on a gray background. A red spotlight starts shining when the user double-clicks.');\n}\n\nfunction draw() {\n background(50);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n lights();\n\n // Control the spotlight.\n if (isLit === true) {\n // Add a red spot light that shines into the screen.\n // Set its angle to PI / 32 radians.\n spotLight(255, 0, 0, 0, 0, 100, 0, 0, -1, PI / 32);\n }\n\n // Draw the sphere.\n sphere(30);\n}\n\n// Turn on the spotlight when the user double-clicks.\nfunction doubleClicked() {\n isLit = true;\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click to adjust the spotlight.\n\nlet isLit = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white sphere drawn on a gray background. A red spotlight starts shining when the user double-clicks.');\n}\n\nfunction draw() {\n background(50);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n lights();\n\n // Control the spotlight.\n if (isLit === true) {\n // Add a red spot light that shines into the screen.\n // Set its angle to PI / 3 radians (default).\n // Set its concentration to 1000.\n let c = color(255, 0, 0);\n let position = createVector(0, 0, 100);\n let direction = createVector(0, 0, -1);\n spotLight(c, position, direction, PI / 3, 1000);\n }\n\n // Draw the sphere.\n sphere(30);\n}\n\n// Turn on the spotlight when the user double-clicks.\nfunction doubleClicked() {\n isLit = true;\n}\n
\nSets the ambient color of shapes’ surface material.
\nThe ambientMaterial()
color sets the components of the\nambientLight() color that shapes will\nreflect. For example, calling ambientMaterial(255, 255, 0)
would cause a\nshape to reflect red and green light, but not blue light.
ambientMaterial()
can be called three ways with different parameters to\nset the material’s color.
The first way to call ambientMaterial()
has one parameter, gray
.\nGrayscale values between 0 and 255, as in ambientMaterial(50)
, can be\npassed to set the material’s color. Higher grayscale values make shapes\nappear brighter.
The second way to call ambientMaterial()
has one parameter, color
. A\np5.Color object, an array of color values, or a\nCSS color string, as in ambientMaterial('magenta')
, can be passed to set\nthe material’s color.
The third way to call ambientMaterial()
has three parameters, v1
, v2
,\nand v3
. RGB, HSB, or HSL values, as in ambientMaterial(255, 0, 0)
, can\nbe passed to set the material’s colors. Color values will be interpreted\nusing the current colorMode().
Note: ambientMaterial()
can only be used in WebGL mode.
red or hue value in the current\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,"green or saturation value in the\n current colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,"blue, brightness, or lightness value in the\n current colorMode().
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"gray"],"description":[0,"grayscale value between 0 (black) and 255 (white).
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"color as a p5.Color object,\n an array of color values, or a CSS string.
\n"],"type":[0,"p5.Color|Number[]|String"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A magenta cube drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on a magenta ambient light.\n ambientLight(255, 0, 255);\n\n // Draw the box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A purple cube drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on a magenta ambient light.\n ambientLight(255, 0, 255);\n\n // Add a dark gray ambient material.\n ambientMaterial(150);\n\n // Draw the box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A red cube drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on a magenta ambient light.\n ambientLight(255, 0, 255);\n\n // Add a yellow ambient material using RGB values.\n ambientMaterial(255, 255, 0);\n\n // Draw the box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A red cube drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on a magenta ambient light.\n ambientLight(255, 0, 255);\n\n // Add a yellow ambient material using a p5.Color object.\n let c = color(255, 255, 0);\n ambientMaterial(c);\n\n // Draw the box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A red cube drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on a magenta ambient light.\n ambientLight(255, 0, 255);\n\n // Add a yellow ambient material using a color string.\n ambientMaterial('yellow');\n\n // Draw the box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A yellow cube drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on a white ambient light.\n ambientLight(255, 255, 255);\n\n // Add a yellow ambient material using a color string.\n ambientMaterial('yellow');\n\n // Draw the box.\n box();\n}\n
\nGet the shader used when no lights or materials are applied.
\nYou can call baseColorShader().modify()
\nand change any of the following hooks:
Hook | \nDescription | \n
---|---|
void beforeVertex | \nCalled at the start of the vertex shader. | \n
vec3 getLocalPosition | \nUpdate the position of vertices before transforms are applied. It takes in vec3 position and must return a modified version. | \n
vec3 getWorldPosition | \nUpdate the position of vertices after transforms are applied. It takes in vec3 position and pust return a modified version. | \n
vec3 getLocalNormal | \nUpdate the normal before transforms are applied. It takes in vec3 normal and must return a modified version. | \n
vec3 getWorldNormal | \nUpdate the normal after transforms are applied. It takes in vec3 normal and must return a modified version. | \n
vec2 getUV | \nUpdate the texture coordinates. It takes in vec2 uv and must return a modified version. | \n
vec4 getVertexColor | \nUpdate the color of each vertex. It takes in a vec4 color and must return a modified version. | \n
void afterVertex | \nCalled at the end of the vertex shader. | \n
void beforeFragment | \nCalled at the start of the fragment shader. | \n
vec4 getFinalColor | \nUpdate the final color after mixing. It takes in a vec4 color and must return a modified version. | \n
void afterFragment | \nCalled at the end of the fragment shader. | \n
Most of the time, you will need to write your hooks in GLSL ES version 300. If you\nare using WebGL 1 instead of 2, write your hooks in GLSL ES 100 instead.
\nCall baseColorShader().inspectHooks()
to see all the possible hooks and\ntheir default implementations.
\nlet myShader;\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseColorShader().modify({\n uniforms: {\n 'float time': () => millis()\n },\n 'vec3 getWorldPosition': `(vec3 pos) {\n pos.y += 20. * sin(time * 0.001 + pos.x * 0.05);\n return pos;\n }`\n });\n}\n\nfunction draw() {\n background(255);\n shader(myShader);\n noStroke();\n fill('red');\n circle(0, 0, 50);\n}\n
\nGet the default shader used with lights, materials,\nand textures.
\nYou can call baseMaterialShader().modify()
\nand change any of the following hooks:
Hook | Description |
---|---|
\n\n
| \n\n Called at the start of the vertex shader. \n |
\n\n
| \n\n Update the position of vertices before transforms are applied. It takes in |
\n\n
| \n\n Update the position of vertices after transforms are applied. It takes in |
\n\n
| \n\n Update the normal before transforms are applied. It takes in |
\n\n
| \n\n Update the normal after transforms are applied. It takes in |
\n\n
| \n\n Update the texture coordinates. It takes in |
\n\n
| \n\n Update the color of each vertex. It takes in a |
\n\n
| \n\n Called at the end of the vertex shader. \n |
\n\n
| \n\n Called at the start of the fragment shader. \n |
\n\n
| \n\n Update the per-pixel inputs of the material. It takes in an
|
\n\n
| \n\n Take in a
|
\n\n
| \n\n Update the final color after mixing. It takes in a |
\n\n
| \n\n Called at the end of the fragment shader. \n |
Most of the time, you will need to write your hooks in GLSL ES version 300. If you\nare using WebGL 1 instead of 2, write your hooks in GLSL ES 100 instead.
\nCall baseMaterialShader().inspectHooks()
to see all the possible hooks and\ntheir default implementations.
\nlet myShader;\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseMaterialShader().modify({\n uniforms: {\n 'float time': () => millis()\n },\n 'vec3 getWorldPosition': `(vec3 pos) {\n pos.y += 20.0 * sin(time * 0.001 + pos.x * 0.05);\n return pos;\n }`\n });\n}\n\nfunction draw() {\n background(255);\n shader(myShader);\n lights();\n noStroke();\n fill('red');\n sphere(50);\n}\n
\n\nlet myShader;\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseMaterialShader().modify({\n declarations: 'vec3 myNormal;',\n 'Inputs getPixelInputs': `(Inputs inputs) {\n myNormal = inputs.normal;\n return inputs;\n }`,\n 'vec4 getFinalColor': `(vec4 color) {\n return mix(\n vec4(1.0, 1.0, 1.0, 1.0),\n color,\n abs(dot(myNormal, vec3(0.0, 0.0, 1.0)))\n );\n }`\n });\n}\n\nfunction draw() {\n background(255);\n rotateY(millis() * 0.001);\n shader(myShader);\n lights();\n noStroke();\n fill('red');\n torus(30);\n}\n
\n\nlet myShader;\nlet environment;\n\nfunction preload() {\n environment = loadImage('/assets/outdoor_spheremap.jpg');\n}\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseMaterialShader().modify({\n 'Inputs getPixelInputs': `(Inputs inputs) {\n float factor =\n sin(\n inputs.texCoord.x * ${TWO_PI} +\n inputs.texCoord.y * ${TWO_PI}\n ) * 0.4 + 0.5;\n inputs.shininess = mix(1., 100., factor);\n inputs.metalness = factor;\n return inputs;\n }`\n });\n}\n\nfunction draw() {\n panorama(environment);\n ambientLight(100);\n imageLight(environment);\n rotateY(millis() * 0.001);\n shader(myShader);\n noStroke();\n fill(255);\n specularMaterial(150);\n sphere(50);\n}\n
\n\nlet myShader;\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseMaterialShader().modify({\n 'Inputs getPixelInputs': `(Inputs inputs) {\n vec3 newNormal = inputs.normal;\n // Simple bump mapping: adjust the normal based on position\n newNormal.x += 0.2 * sin(\n sin(\n inputs.texCoord.y * ${TWO_PI} * 10.0 +\n inputs.texCoord.x * ${TWO_PI} * 25.0\n )\n );\n newNormal.y += 0.2 * sin(\n sin(\n inputs.texCoord.x * ${TWO_PI} * 10.0 +\n inputs.texCoord.y * ${TWO_PI} * 25.0\n )\n );\n inputs.normal = normalize(newNormal);\n return inputs;\n }`\n });\n}\n\nfunction draw() {\n background(255);\n shader(myShader);\n ambientLight(150);\n pointLight(\n 255, 255, 255,\n 100*cos(frameCount*0.04), -50, 100*sin(frameCount*0.04)\n );\n noStroke();\n fill('red');\n shininess(200);\n specularMaterial(255);\n sphere(50);\n}\n
\nGet the shader used by normalMaterial()
.
You can call baseNormalShader().modify()
\nand change any of the following hooks:
Hook | \nDescription | \n
---|---|
void beforeVertex | \nCalled at the start of the vertex shader. | \n
vec3 getLocalPosition | \nUpdate the position of vertices before transforms are applied. It takes in vec3 position and must return a modified version. | \n
vec3 getWorldPosition | \nUpdate the position of vertices after transforms are applied. It takes in vec3 position and pust return a modified version. | \n
vec3 getLocalNormal | \nUpdate the normal before transforms are applied. It takes in vec3 normal and must return a modified version. | \n
vec3 getWorldNormal | \nUpdate the normal after transforms are applied. It takes in vec3 normal and must return a modified version. | \n
vec2 getUV | \nUpdate the texture coordinates. It takes in vec2 uv and must return a modified version. | \n
vec4 getVertexColor | \nUpdate the color of each vertex. It takes in a vec4 color and must return a modified version. | \n
void afterVertex | \nCalled at the end of the vertex shader. | \n
void beforeFragment | \nCalled at the start of the fragment shader. | \n
vec4 getFinalColor | \nUpdate the final color after mixing. It takes in a vec4 color and must return a modified version. | \n
void afterFragment | \nCalled at the end of the fragment shader. | \n
Most of the time, you will need to write your hooks in GLSL ES version 300. If you\nare using WebGL 1 instead of 2, write your hooks in GLSL ES 100 instead.
\nCall baseNormalShader().inspectHooks()
to see all the possible hooks and\ntheir default implementations.
\nlet myShader;\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseNormalShader().modify({\n uniforms: {\n 'float time': () => millis()\n },\n 'vec3 getWorldPosition': `(vec3 pos) {\n pos.y += 20. * sin(time * 0.001 + pos.x * 0.05);\n return pos;\n }`\n });\n}\n\nfunction draw() {\n background(255);\n shader(myShader);\n noStroke();\n sphere(50);\n}\n
\n\nlet myShader;\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseNormalShader().modify({\n 'vec3 getWorldNormal': '(vec3 normal) { return abs(normal); }',\n 'vec4 getFinalColor': `(vec4 color) {\n // Map the r, g, and b values of the old normal to new colors\n // instead of just red, green, and blue:\n vec3 newColor =\n color.r * vec3(89.0, 240.0, 232.0) / 255.0 +\n color.g * vec3(240.0, 237.0, 89.0) / 255.0 +\n color.b * vec3(205.0, 55.0, 222.0) / 255.0;\n newColor = newColor / (color.r + color.g + color.b);\n return vec4(newColor, 1.0) * color.a;\n }`\n });\n}\n\nfunction draw() {\n background(255);\n shader(myShader);\n noStroke();\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.015);\n box(100);\n}\n
\nGet the shader used when drawing the strokes of shapes.
\nYou can call baseStrokeShader().modify()
\nand change any of the following hooks:
Hook | Description |
---|---|
\n\n
| \n\n Called at the start of the vertex shader. \n |
\n\n
| \n\n Update the position of vertices before transforms are applied. It takes in |
\n\n
| \n\n Update the position of vertices after transforms are applied. It takes in |
\n\n
| \n\n Update the stroke weight. It takes in |
\n\n
| \n\n Update the center of the line. It takes in |
\n\n
| \n\n Update the position of each vertex on the edge of the line. It takes in |
\n\n
| \n\n Update the color of each vertex. It takes in a |
\n\n
| \n\n Called at the end of the vertex shader. \n |
\n\n
| \n\n Called at the start of the fragment shader. \n |
\n\n
| \n\n Update the inputs to the shader. It takes in a struct
|
\n\n
| \n\n 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 |
\n\n
| \n\n Update the final color after mixing. It takes in a |
\n\n
| \n\n Called at the end of the fragment shader. \n |
Most of the time, you will need to write your hooks in GLSL ES version 300. If you\nare using WebGL 1 instead of 2, write your hooks in GLSL ES 100 instead.
\nCall baseStrokeShader().inspectHooks()
to see all the possible hooks and\ntheir default implementations.
\nlet myShader;\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseStrokeShader().modify({\n 'Inputs getPixelInputs': `(Inputs inputs) {\n float opacity = 1.0 - smoothstep(\n 0.0,\n 15.0,\n length(inputs.position - inputs.center)\n );\n inputs.color *= opacity;\n return inputs;\n }`\n });\n}\n\nfunction draw() {\n background(255);\n shader(myShader);\n strokeWeight(30);\n line(\n -width/3,\n sin(millis()*0.001) * height/4,\n width/3,\n sin(millis()*0.001 + 1) * height/4\n );\n}\n
\n\nlet myShader;\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseStrokeShader().modify({\n uniforms: {\n 'float time': () => millis()\n },\n declarations: 'vec3 myPosition;',\n 'vec3 getWorldPosition': `(vec3 pos) {\n myPosition = pos;\n return pos;\n }`,\n 'float getStrokeWeight': `(float w) {\n // Add a somewhat random offset to the weight\n // that varies based on position and time\n float scale = 0.8 + 0.2*sin(10.0 * sin(\n floor(time/250.) +\n myPosition.x*0.01 +\n myPosition.y*0.01\n ));\n return w * scale;\n }`\n });\n}\n\nfunction draw() {\n background(255);\n shader(myShader);\n myShader.setUniform('time', millis());\n strokeWeight(10);\n beginShape();\n for (let i = 0; i <= 50; i++) {\n let r = map(i, 0, 50, 0, width/3);\n let x = r*cos(i*0.2);\n let y = r*sin(i*0.2);\n vertex(x, y);\n }\n endShape();\n}\n
\n\nlet myShader;\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseStrokeShader().modify({\n 'float random': `(vec2 p) {\n vec3 p3 = fract(vec3(p.xyx) * .1031);\n p3 += dot(p3, p3.yzx + 33.33);\n return fract((p3.x + p3.y) * p3.z);\n }`,\n 'Inputs getPixelInputs': `(Inputs inputs) {\n // Replace alpha in the color with dithering by\n // randomly setting pixel colors to 0 based on opacity\n float a = inputs.color.a;\n inputs.color.a = 1.0;\n inputs.color *= random(inputs.position.xy) > a ? 0.0 : 1.0;\n return inputs;\n }`\n });\n}\n\nfunction draw() {\n background(255);\n shader(myShader);\n strokeWeight(10);\n beginShape();\n for (let i = 0; i <= 50; i++) {\n stroke(\n 0,\n 255\n * map(i, 0, 20, 0, 1, true)\n * map(i, 30, 50, 1, 0, true)\n );\n vertex(\n map(i, 0, 50, -1, 1) * width/3,\n 50 * sin(i/10 + frameCount/100)\n );\n }\n endShape();\n}\n
\nCreates a p5.Shader object to be used with the\nfilter() function.
\ncreateFilterShader()
works like\ncreateShader() but has a default vertex\nshader included. createFilterShader()
is intended to be used along with\nfilter() for filtering the contents of a canvas.\nA filter shader will be applied to the whole canvas instead of just\np5.Geometry objects.
The parameter, fragSrc
, sets the fragment shader. It’s a string that\ncontains the fragment shader program written in\nGLSL.
The p5.Shader object that's created has some\nuniforms that can be set:
\nsampler2D 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\nvarying vec2 vTexCoord
, a coordinate with values between 0 and 1.\nvTexCoord
describes where on the canvas the pixel will be drawn.
For more info about filters and shaders, see Adam Ferriss' repo of shader examples\nor the Introduction to Shaders tutorial.
\n"],"line":[0,540],"params":[1,[[0,{"name":[0,"fragSrc"],"description":[0,"source code for the fragment shader.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new shader object created from the fragment shader."],"type":[0,"p5.Shader"]}],"example":[1,[[0,"\n\nfunction setup() {\n let fragSrc = `precision highp float;\n void main() {\n gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0);\n }`;\n\n createCanvas(100, 100, WEBGL);\n let s = createFilterShader(fragSrc);\n filter(s);\n describe('a yellow canvas');\n}\n
\n\nlet img, s;\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\nfunction setup() {\n let fragSrc = `precision highp float;\n\n // x,y coordinates, given from the vertex shader\n varying vec2 vTexCoord;\n\n // the canvas contents, given from filter()\n uniform sampler2D tex0;\n // other useful information from the canvas\n uniform vec2 texelSize;\n uniform vec2 canvasSize;\n // a custom variable from this sketch\n uniform float darkness;\n\n void main() {\n // get the color at current pixel\n vec4 color = texture2D(tex0, vTexCoord);\n // set the output color\n color.b = 1.0;\n color *= darkness;\n gl_FragColor = vec4(color.rgb, 1.0);\n }`;\n\n createCanvas(100, 100, WEBGL);\n s = createFilterShader(fragSrc);\n}\nfunction draw() {\n image(img, -50, -50);\n s.setUniform('darkness', 0.5);\n filter(s);\n describe('a image of bricks tinted dark blue');\n}\n
\nCreates a new p5.Shader object.
\nShaders are programs that run on the graphics processing unit (GPU). They\ncan process many pixels at the same time, making them fast for many\ngraphics tasks. They’re written in a language called\nGLSL\nand run along with the rest of the code in a sketch.
\nOnce the p5.Shader object is created, it can be\nused with the shader() function, as in\nshader(myShader)
. A shader program consists of two parts, a vertex shader\nand a fragment shader. The vertex shader affects where 3D geometry is drawn\non the screen and the fragment shader affects color.
The first parameter, vertSrc
, sets the vertex shader. It’s a string that\ncontains the vertex shader program written in GLSL.
The second parameter, fragSrc
, sets the fragment shader. It’s a string\nthat contains the fragment shader program written in GLSL.
A shader can optionally describe hooks, which are functions in GLSL that\nusers may choose to provide to customize the behavior of the shader using the\nmodify()
method of p5.Shader
. These are added by\ndescribing the hooks in a third parameter, options
, and referencing the hooks in\nyour vertSrc
or fragSrc
. Hooks for the vertex or fragment shader are described under\nthe vertex
and fragment
keys of options
. Each one is an object. where each key is\nthe type and name of a hook function, and each value is a string with the\nparameter list and default implementation of the hook. For example, to let users\noptionally run code at the start of the vertex shader, the options object could\ninclude:
{\n vertex: {\n 'void beforeVertex': '() {}'\n }\n}\n
\nThen, in your vertex shader source, you can run a hook by calling a function\nwith the same name prefixed by HOOK_
. If you want to check if the default\nhook has been replaced, maybe to avoid extra overhead, you can check if the\nsame name prefixed by AUGMENTED_HOOK_
has been defined:
void main() {\n // In most cases, just calling the hook is fine:\n HOOK_beforeVertex();\n\n // Alternatively, for more efficiency:\n #ifdef AUGMENTED_HOOK_beforeVertex\n HOOK_beforeVertex();\n #endif\n\n // Add the rest of your shader code here!\n}\n
\nNote: Only filter shaders can be used in 2D mode. All shaders can be used\nin WebGL mode.
\n"],"line":[0,173],"params":[1,[[0,{"name":[0,"vertSrc"],"description":[0,"source code for the vertex shader.
\n"],"type":[0,"String"]}],[0,{"name":[0,"fragSrc"],"description":[0,"source code for the fragment shader.
\n"],"type":[0,"String"]}],[0,{"name":[0,"options"],"description":[0,"An optional object describing how this shader can\nbe augmented with hooks. It can include:
\nvertex
: An object describing the available vertex shader hooks.fragment
: An object describing the available frament shader hooks.\n// Note: A \"uniform\" is a global variable within a shader program.\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision highp float;\n\nvoid main() {\n // Set each pixel's RGBA value to yellow.\n gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0);\n}\n`;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Shader object.\n let shaderProgram = createShader(vertSrc, fragSrc);\n\n // Compile and apply the p5.Shader object.\n shader(shaderProgram);\n\n // Style the drawing surface.\n noStroke();\n\n // Add a plane as a drawing surface.\n plane(100, 100);\n\n describe('A yellow square.');\n}\n
\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision highp float;\nuniform vec2 p;\nuniform float r;\nconst int numIterations = 500;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vec2 c = p + gl_FragCoord.xy * r;\n vec2 z = c;\n float n = 0.0;\n\n for (int i = numIterations; i > 0; i--) {\n if (z.x * z.x + z.y * z.y > 4.0) {\n n = float(i) / float(numIterations);\n break;\n }\n z = vec2(z.x * z.x - z.y * z.y, 2.0 * z.x * z.y) + c;\n }\n\n gl_FragColor = vec4(\n 0.5 - cos(n * 17.0) / 2.0,\n 0.5 - cos(n * 13.0) / 2.0,\n 0.5 - cos(n * 23.0) / 2.0,\n 1.0\n );\n}\n`;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Shader object.\n let mandelbrot = createShader(vertSrc, fragSrc);\n\n // Compile and apply the p5.Shader object.\n shader(mandelbrot);\n\n // Set the shader uniform p to an array.\n // p is the center point of the Mandelbrot image.\n mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]);\n\n // Set the shader uniform r to 0.005.\n // r is the size of the image in Mandelbrot-space.\n mandelbrot.setUniform('r', 0.005);\n\n // Style the drawing surface.\n noStroke();\n\n // Add a plane as a drawing surface.\n plane(100, 100);\n\n describe('A black fractal image on a magenta background.');\n}\n
\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision highp float;\nuniform vec2 p;\nuniform float r;\nconst int numIterations = 500;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vec2 c = p + gl_FragCoord.xy * r;\n vec2 z = c;\n float n = 0.0;\n\n for (int i = numIterations; i > 0; i--) {\n if (z.x * z.x + z.y * z.y > 4.0) {\n n = float(i) / float(numIterations);\n break;\n }\n\n z = vec2(z.x * z.x - z.y * z.y, 2.0 * z.x * z.y) + c;\n }\n\n gl_FragColor = vec4(\n 0.5 - cos(n * 17.0) / 2.0,\n 0.5 - cos(n * 13.0) / 2.0,\n 0.5 - cos(n * 23.0) / 2.0,\n 1.0\n );\n}\n`;\n\nlet mandelbrot;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Shader object.\n mandelbrot = createShader(vertSrc, fragSrc);\n\n // Apply the p5.Shader object.\n shader(mandelbrot);\n\n // Set the shader uniform p to an array.\n // p is the center point of the Mandelbrot image.\n mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]);\n\n describe('A fractal image zooms in and out of focus.');\n}\n\nfunction draw() {\n // Set the shader uniform r to a value that oscillates\n // between 0 and 0.005.\n // r is the size of the image in Mandelbrot-space.\n let radius = 0.005 * (sin(frameCount * 0.01) + 1);\n mandelbrot.setUniform('r', radius);\n\n // Style the drawing surface.\n noStroke();\n\n // Add a plane as a drawing surface.\n plane(100, 100);\n}\n
\n\n// A shader with hooks.\nlet myShader;\n\n// A shader with modified hooks.\nlet modifiedShader;\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\n\nvoid main() {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n`;\n\n// Create a fragment shader that uses a hook.\nlet fragSrc = `\nprecision highp float;\nvoid main() {\n // Let users override the color\n gl_FragColor = HOOK_getColor(vec4(1., 0., 0., 1.));\n}\n`;\n\nfunction setup() {\n createCanvas(50, 50, WEBGL);\n\n // Create a shader with hooks\n myShader = createShader(vertSrc, fragSrc, {\n fragment: {\n 'vec4 getColor': '(vec4 color) { return color; }'\n }\n });\n\n // Make a version of the shader with a hook overridden\n modifiedShader = myShader.modify({\n 'vec4 getColor': `(vec4 color) {\n return vec4(0., 0., 1., 1.);\n }`\n });\n}\n\nfunction draw() {\n noStroke();\n\n push();\n shader(myShader);\n translate(-width/3, 0);\n sphere(10);\n pop();\n\n push();\n shader(modifiedShader);\n translate(width/3, 0);\n sphere(10);\n pop();\n}\n
\nSets the emissive color of shapes’ surface material.
\nThe emissiveMaterial()
color sets a color shapes display at full\nstrength, regardless of lighting. This can give the appearance that a shape\nis glowing. However, emissive materials don’t actually emit light that\ncan affect surrounding objects.
emissiveMaterial()
can be called three ways with different parameters to\nset the material’s color.
The first way to call emissiveMaterial()
has one parameter, gray
.\nGrayscale values between 0 and 255, as in emissiveMaterial(50)
, can be\npassed to set the material’s color. Higher grayscale values make shapes\nappear brighter.
The second way to call emissiveMaterial()
has one parameter, color
. A\np5.Color object, an array of color values, or a\nCSS color string, as in emissiveMaterial('magenta')
, can be passed to set\nthe material’s color.
The third way to call emissiveMaterial()
has four parameters, v1
, v2
,\nv3
, and alpha
. alpha
is optional. RGBA, HSBA, or HSLA values can be\npassed to set the material’s colors, as in emissiveMaterial(255, 0, 0)
or\nemissiveMaterial(255, 0, 0, 30)
. Color values will be interpreted using\nthe current colorMode().
Note: emissiveMaterial()
can only be used in WebGL mode.
red or hue value in the current\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,"green or saturation value in the\n current colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,"blue, brightness, or lightness value in the\n current colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"alpha"],"description":[0,"alpha value in the current\n colorMode().
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"gray"],"description":[0,"grayscale value between 0 (black) and 255 (white).
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"color as a p5.Color object,\n an array of color values, or a CSS string.
\n"],"type":[0,"p5.Color|Number[]|String"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A red cube drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on a white ambient light.\n ambientLight(255, 255, 255);\n\n // Add a red emissive material using RGB values.\n emissiveMaterial(255, 0, 0);\n\n // Draw the box.\n box();\n}\n
\nLoads vertex and fragment shaders to create a\np5.Shader object.
\nShaders are programs that run on the graphics processing unit (GPU). They\ncan process many pixels at the same time, making them fast for many\ngraphics tasks. They’re written in a language called\nGLSL\nand run along with the rest of the code in a sketch.
\nOnce the p5.Shader object is created, it can be\nused with the shader() function, as in\nshader(myShader)
. A shader program consists of two files, a vertex shader\nand a fragment shader. The vertex shader affects where 3D geometry is drawn\non the screen and the fragment shader affects color.
loadShader()
loads the vertex and fragment shaders from their .vert
and\n.frag
files. For example, calling\nloadShader('/assets/shader.vert', '/assets/shader.frag')
loads both\nrequired shaders and returns a p5.Shader object.
The third parameter, successCallback
, is optional. If a function is\npassed, it will be called once the shader has loaded. The callback function\ncan use the new p5.Shader object as its\nparameter.
The fourth parameter, failureCallback
, is also optional. If a function is\npassed, it will be called if the shader fails to load. The callback\nfunction can use the event error as its parameter.
Shaders can take time to load. Calling loadShader()
in\npreload() ensures shaders load before they're\nused in setup() or draw().
Note: Shaders can only be used in WebGL mode.
\n"],"line":[0,12],"params":[1,[[0,{"name":[0,"vertFilename"],"description":[0,"path of the vertex shader to be loaded.
\n"],"type":[0,"String"]}],[0,{"name":[0,"fragFilename"],"description":[0,"path of the fragment shader to be loaded.
\n"],"type":[0,"String"]}],[0,{"name":[0,"successCallback"],"description":[0,"function to call once the shader is loaded. Can be passed the\n p5.Shader object.
\n"],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"failureCallback"],"description":[0,"function to call if the shader fails to load. Can be passed an\n Error
event object.
\n// Note: A \"uniform\" is a global variable within a shader program.\n\nlet mandelbrot;\n\n// Load the shader and create a p5.Shader object.\nfunction preload() {\n mandelbrot = loadShader('/assets/shader.vert', '/assets/shader.frag');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Compile and apply the p5.Shader object.\n shader(mandelbrot);\n\n // Set the shader uniform p to an array.\n mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]);\n\n // Set the shader uniform r to the value 1.5.\n mandelbrot.setUniform('r', 1.5);\n\n // Add a quad as a display surface for the shader.\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n\n describe('A black fractal image on a magenta background.');\n}\n
\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\nlet mandelbrot;\n\n// Load the shader and create a p5.Shader object.\nfunction preload() {\n mandelbrot = loadShader('/assets/shader.vert', '/assets/shader.frag');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Use the p5.Shader object.\n shader(mandelbrot);\n\n // Set the shader uniform p to an array.\n mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]);\n\n describe('A fractal image zooms in and out of focus.');\n}\n\nfunction draw() {\n // Set the shader uniform r to a value that oscillates between 0 and 2.\n mandelbrot.setUniform('r', sin(frameCount * 0.01) + 1);\n\n // Add a quad as a display surface for the shader.\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n
\nSets the amount of \"metalness\" of a\nspecularMaterial().
\nmetalness()
can make materials appear more metallic. It affects the way\nmaterials reflect light sources including\naffects the way materials reflect light sources including\ndirectionalLight(),\npointLight(),\nspotLight(), and\nimageLight().
The parameter, metallic
, is a number that sets the amount of metalness.\nmetallic
must be greater than 1, which is its default value. Higher\nvalues, such as metalness(100)
, make specular materials appear more\nmetallic.
amount of metalness.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Turn on an ambient light.\n ambientLight(200);\n\n // Get the mouse's coordinates.\n let mx = mouseX - 50;\n let my = mouseY - 50;\n\n // Turn on a white point light that follows the mouse.\n pointLight(255, 255, 255, mx, my, 50);\n\n // Style the spheres.\n noStroke();\n fill(30, 30, 255);\n specularMaterial(255);\n shininess(20);\n\n // Draw the left sphere with low metalness.\n translate(-25, 0, 0);\n metalness(1);\n sphere(20);\n\n // Draw the right sphere with high metalness.\n translate(50, 0, 0);\n metalness(50);\n sphere(20);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nlet img;\n\nfunction preload() {\n img = loadImage('/assets/outdoor_spheremap.jpg');\n}\n\nfunction setup() {\n createCanvas(100 ,100 ,WEBGL);\n\n describe(\n 'Two spheres floating above a landscape. The surface of the spheres reflect the landscape. The right sphere is more reflective than the left sphere.'\n );\n}\n\nfunction draw() {\n // Add the panorama.\n panorama(img);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Use the image as a light source.\n imageLight(img);\n\n // Style the spheres.\n noStroke();\n specularMaterial(50);\n shininess(200);\n\n // Draw the left sphere with low metalness.\n translate(-25, 0, 0);\n metalness(1);\n sphere(20);\n\n // Draw the right sphere with high metalness.\n translate(50, 0, 0);\n metalness(50);\n sphere(20);\n}\n
\nSets the current material as a normal material.
\nA normal material sets surfaces facing the x-axis to red, those facing the\ny-axis to green, and those facing the z-axis to blue. Normal material isn't\naffected by light. It’s often used as a placeholder material when debugging.
\nNote: normalMaterial()
can only be used in WebGL mode.
\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A multicolor torus drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Style the torus.\n normalMaterial();\n\n // Draw the torus.\n torus(30);\n}\n
\nRestores the default shaders.
\nresetShader()
deactivates any shaders previously applied by\nshader().
Note: Shaders can only be used in WebGL mode.
\n"],"line":[0,1628],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nuniform mat4 uProjectionMatrix;\nuniform mat4 uModelViewMatrix;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 position = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * position;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision mediump float;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vec2 uv = vTexCoord;\n vec3 color = vec3(uv.x, uv.y, min(uv.x + uv.y, 1.0));\n gl_FragColor = vec4(color, 1.0);\n}\n`;\n\nlet myShader;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Shader object.\n myShader = createShader(vertSrc, fragSrc);\n\n describe(\n 'Two rotating cubes on a gray background. The left one has a blue-purple gradient on each face. The right one is red.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Draw a box using the p5.Shader.\n // shader() sets the active shader to myShader.\n shader(myShader);\n push();\n translate(-25, 0, 0);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(width / 4);\n pop();\n\n // Draw a box using the default fill shader.\n // resetShader() restores the default fill shader.\n resetShader();\n fill(255, 0, 0);\n push();\n translate(25, 0, 0);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(width / 4);\n pop();\n}\n
\nSets the p5.Shader object to apply while drawing.
\nShaders are programs that run on the graphics processing unit (GPU). They\ncan process many pixels or vertices at the same time, making them fast for\nmany graphics tasks. They’re written in a language called\nGLSL\nand run along with the rest of the code in a sketch.\np5.Shader objects can be created using the\ncreateShader() and\nloadShader() functions.
\nThe parameter, s
, is the p5.Shader object to\napply. For example, calling shader(myShader)
applies myShader
to\nprocess each pixel on the canvas. The shader will be used for:
sampler2D
.aNormal
, or if it has any of the following uniforms: uUseLighting
, uAmbientLightCount
, uDirectionalLightCount
, uPointLightCount
, uAmbientColor
, uDirectionalDiffuseColors
, uDirectionalSpecularColors
, uPointLightLocation
, uPointLightDiffuseColors
, uPointLightSpecularColors
, uLightingDirection
, or uSpecular
.uStrokeWeight
.The source code from a p5.Shader object's\nfragment and vertex shaders will be compiled the first time it's passed to\nshader()
. See\nMDN\nfor more information about compiling shaders.
Calling resetShader() restores a sketch’s\ndefault shaders.
\nNote: Shaders can only be used in WebGL mode.
\n"],"line":[0,682],"params":[1,[[0,{"name":[0,"s"],"description":[0,"p5.Shader object\n to apply.
\n"],"type":[0,"p5.Shader"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision highp float;\n\nvoid main() {\n // Set each pixel's RGBA value to yellow.\n gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0);\n}\n`;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Shader object.\n let shaderProgram = createShader(vertSrc, fragSrc);\n\n // Apply the p5.Shader object.\n shader(shaderProgram);\n\n // Style the drawing surface.\n noStroke();\n\n // Add a plane as a drawing surface.\n plane(100, 100);\n\n describe('A yellow square.');\n}\n
\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\nlet mandelbrot;\n\n// Load the shader and create a p5.Shader object.\nfunction preload() {\n mandelbrot = loadShader('/assets/shader.vert', '/assets/shader.frag');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Use the p5.Shader object.\n shader(mandelbrot);\n\n // Set the shader uniform p to an array.\n mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]);\n\n describe('A fractal image zooms in and out of focus.');\n}\n\nfunction draw() {\n // Set the shader uniform r to a value that oscillates between 0 and 2.\n mandelbrot.setUniform('r', sin(frameCount * 0.01) + 1);\n\n // Add a quad as a display surface for the shader.\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n
\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\nlet redGreen;\nlet orangeBlue;\nlet showRedGreen = false;\n\n// Load the shader and create two separate p5.Shader objects.\nfunction preload() {\n redGreen = loadShader('/assets/shader.vert', '/assets/shader-gradient.frag');\n orangeBlue = loadShader('/assets/shader.vert', '/assets/shader-gradient.frag');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Initialize the redGreen shader.\n shader(redGreen);\n\n // Set the redGreen shader's center and background color.\n redGreen.setUniform('colorCenter', [1.0, 0.0, 0.0]);\n redGreen.setUniform('colorBackground', [0.0, 1.0, 0.0]);\n\n // Initialize the orangeBlue shader.\n shader(orangeBlue);\n\n // Set the orangeBlue shader's center and background color.\n orangeBlue.setUniform('colorCenter', [1.0, 0.5, 0.0]);\n orangeBlue.setUniform('colorBackground', [0.226, 0.0, 0.615]);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n // Update the offset values for each shader.\n // Move orangeBlue vertically.\n // Move redGreen horizontally.\n orangeBlue.setUniform('offset', [0, sin(frameCount * 0.01) + 1]);\n redGreen.setUniform('offset', [sin(frameCount * 0.01), 1]);\n\n if (showRedGreen === true) {\n shader(redGreen);\n } else {\n shader(orangeBlue);\n }\n\n // Style the drawing surface.\n noStroke();\n\n // Add a quad as a drawing surface.\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n\n// Toggle between shaders when the user double-clicks.\nfunction doubleClicked() {\n showRedGreen = !showRedGreen;\n}\n
\nSets the amount of gloss (\"shininess\") of a\nspecularMaterial().
\nShiny materials focus reflected light more than dull materials.\nshininess()
affects the way materials reflect light sources including\ndirectionalLight(),\npointLight(),\nand spotLight().
The parameter, shine
, is a number that sets the amount of shininess.\nshine
must be greater than 1, which is its default value.
amount of shine.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Turn on a red ambient light.\n ambientLight(255, 0, 0);\n\n // Get the mouse's coordinates.\n let mx = mouseX - 50;\n let my = mouseY - 50;\n\n // Turn on a white point light that follows the mouse.\n pointLight(255, 255, 255, mx, my, 50);\n\n // Style the sphere.\n noStroke();\n\n // Add a specular material with a grayscale value.\n specularMaterial(255);\n\n // Draw the left sphere with low shininess.\n translate(-25, 0, 0);\n shininess(10);\n sphere(20);\n\n // Draw the right sphere with high shininess.\n translate(50, 0, 0);\n shininess(100);\n sphere(20);\n}\n
\nSets the specular color of shapes’ surface material.
\nThe specularMaterial()
color sets the components of light color that\nglossy coats on shapes will reflect. For example, calling\nspecularMaterial(255, 255, 0)
would cause a shape to reflect red and\ngreen light, but not blue light.
Unlike ambientMaterial(),\nspecularMaterial()
will reflect the full color of light sources including\ndirectionalLight(),\npointLight(),\nand spotLight(). This is what gives it shapes\ntheir \"shiny\" appearance. The material’s shininess can be controlled by the\nshininess() function.
specularMaterial()
can be called three ways with different parameters to\nset the material’s color.
The first way to call specularMaterial()
has one parameter, gray
.\nGrayscale values between 0 and 255, as in specularMaterial(50)
, can be\npassed to set the material’s color. Higher grayscale values make shapes\nappear brighter.
The second way to call specularMaterial()
has one parameter, color
. A\np5.Color> object, an array of color values, or a CSS\ncolor string, as in specularMaterial('magenta')
, can be passed to set the\nmaterial’s color.
The third way to call specularMaterial()
has four parameters, v1
, v2
,\nv3
, and alpha
. alpha
is optional. RGBA, HSBA, or HSLA values can be\npassed to set the material’s colors, as in specularMaterial(255, 0, 0)
or\nspecularMaterial(255, 0, 0, 30)
. Color values will be interpreted using\nthe current colorMode().
grayscale value between 0 (black) and 255 (white).
\n"],"type":[0,"Number"]}],[0,{"name":[0,"alpha"],"description":[0,"alpha value in the current current\n colorMode().
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,"red or hue value in\n the current colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,"green or saturation value\n in the current colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,"blue, brightness, or lightness value\n in the current colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"alpha"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"color as a p5.Color object,\n an array of color values, or a CSS string.
\n"],"type":[0,"p5.Color|Number[]|String"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click the canvas to apply a specular material.\n\nlet isGlossy = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A red torus drawn on a gray background. It becomes glossy when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on a white point light at the top-right.\n pointLight(255, 255, 255, 30, -40, 30);\n\n // Add a glossy coat if the user has double-clicked.\n if (isGlossy === true) {\n specularMaterial(255);\n shininess(50);\n }\n\n // Style the torus.\n noStroke();\n fill(255, 0, 0);\n\n // Draw the torus.\n torus(30);\n}\n\n// Make the torus glossy when the user double-clicks.\nfunction doubleClicked() {\n isGlossy = true;\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click the canvas to apply a specular material.\n\nlet isGlossy = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'A red torus drawn on a gray background. It becomes glossy and reflects green light when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on a white point light at the top-right.\n pointLight(255, 255, 255, 30, -40, 30);\n\n // Add a glossy green coat if the user has double-clicked.\n if (isGlossy === true) {\n specularMaterial(0, 255, 0);\n shininess(50);\n }\n\n // Style the torus.\n noStroke();\n fill(255, 0, 0);\n\n // Draw the torus.\n torus(30);\n}\n\n// Make the torus glossy when the user double-clicks.\nfunction doubleClicked() {\n isGlossy = true;\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click the canvas to apply a specular material.\n\nlet isGlossy = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'A red torus drawn on a gray background. It becomes glossy and reflects green light when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on a white point light at the top-right.\n pointLight(255, 255, 255, 30, -40, 30);\n\n // Add a glossy green coat if the user has double-clicked.\n if (isGlossy === true) {\n // Create a p5.Color object.\n let c = color('green');\n specularMaterial(c);\n shininess(50);\n }\n\n // Style the torus.\n noStroke();\n fill(255, 0, 0);\n\n // Draw the torus.\n torus(30);\n}\n\n// Make the torus glossy when the user double-clicks.\nfunction doubleClicked() {\n isGlossy = true;\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click the canvas to apply a specular material.\n\nlet isGlossy = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'A red torus drawn on a gray background. It becomes glossy and reflects green light when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on a white point light at the top-right.\n pointLight(255, 255, 255, 30, -40, 30);\n\n // Add a glossy green coat if the user has double-clicked.\n if (isGlossy === true) {\n specularMaterial('#00FF00');\n shininess(50);\n }\n\n // Style the torus.\n noStroke();\n fill(255, 0, 0);\n\n // Draw the torus.\n torus(30);\n}\n\n// Make the torus glossy when the user double-clicks.\nfunction doubleClicked() {\n isGlossy = true;\n}\n
\nSets the texture that will be used on shapes.
\nA texture is like a skin that wraps around a shape. texture()
works with\nbuilt-in shapes, such as square() and\nsphere(), and custom shapes created with\nfunctions such as buildGeometry(). To\ntexture a geometry created with beginShape(),\nuv coordinates must be passed to each\nvertex() call.
The parameter, tex
, is the texture to apply. texture()
can use a range\nof sources including images, videos, and offscreen renderers such as\np5.Graphics and\np5.Framebuffer objects.
To texture a geometry created with beginShape(),\nyou will need to specify uv coordinates in vertex().
\nNote: texture()
can only be used in WebGL mode.
media to use as the texture.
\n"],"type":[0,"p5.Image|p5.MediaElement|p5.Graphics|p5.Texture|p5.Framebuffer|p5.FramebufferTexture"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nlet img;\n\n// Load an image and create a p5.Image object.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A spinning cube with an image of a ceiling on each face.');\n}\n\nfunction draw() {\n background(0);\n\n // Rotate around the x-, y-, and z-axes.\n rotateZ(frameCount * 0.01);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n\n // Apply the image as a texture.\n texture(img);\n\n // Draw the box.\n box(50);\n}\n
\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Graphics object.\n pg = createGraphics(100, 100);\n\n // Draw a circle to the p5.Graphics object.\n pg.background(200);\n pg.circle(50, 50, 30);\n\n describe('A spinning cube with circle at the center of each face.');\n}\n\nfunction draw() {\n background(0);\n\n // Rotate around the x-, y-, and z-axes.\n rotateZ(frameCount * 0.01);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n\n // Apply the p5.Graphics object as a texture.\n texture(pg);\n\n // Draw the box.\n box(50);\n}\n
\n\nlet vid;\n\n// Load a video and create a p5.MediaElement object.\nfunction preload() {\n vid = createVideo('/assets/fingers.mov');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Hide the video.\n vid.hide();\n\n // Set the video to loop.\n vid.loop();\n\n describe('A rectangle with video as texture');\n}\n\nfunction draw() {\n background(0);\n\n // Rotate around the y-axis.\n rotateY(frameCount * 0.01);\n\n // Apply the video as a texture.\n texture(vid);\n\n // Draw the rectangle.\n rect(-40, -40, 80, 80);\n}\n
\n\nlet vid;\n\n// Load a video and create a p5.MediaElement object.\nfunction preload() {\n vid = createVideo('/assets/fingers.mov');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Hide the video.\n vid.hide();\n\n // Set the video to loop.\n vid.loop();\n\n describe('A rectangle with video as texture');\n}\n\nfunction draw() {\n background(0);\n\n // Rotate around the y-axis.\n rotateY(frameCount * 0.01);\n\n // Set the texture mode.\n textureMode(NORMAL);\n\n // Apply the video as a texture.\n texture(vid);\n\n // Draw a custom shape using uv coordinates.\n beginShape();\n vertex(-40, -40, 0, 0);\n vertex(40, -40, 1, 0);\n vertex(40, 40, 1, 1);\n vertex(-40, 40, 0, 1);\n endShape();\n}\n
\nChanges the coordinate system used for textures when they’re applied to\ncustom shapes.
\nIn order for texture() to work, a shape needs a\nway to map the points on its surface to the pixels in an image. Built-in\nshapes such as rect() and\nbox() already have these texture mappings based on\ntheir vertices. Custom shapes created with\nvertex() require texture mappings to be passed as\nuv coordinates.
\nEach call to vertex() must include 5 arguments,\nas in vertex(x, y, z, u, v)
, to map the vertex at coordinates (x, y, z)
\nto the pixel at coordinates (u, v)
within an image. For example, the\ncorners of a rectangular image are mapped to the corners of a rectangle by default:
\n// Apply the image as a texture.\ntexture(img);\n\n// Draw the rectangle.\nrect(0, 0, 30, 50);\n
\nIf the image in the code snippet above has dimensions of 300 x 500 pixels,\nthe same result could be achieved as follows:
\n\n// Apply the image as a texture.\ntexture(img);\n\n// Draw the rectangle.\nbeginShape();
\n// Top-left.\n// u: 0, v: 0\nvertex(0, 0, 0, 0, 0);
\n// Top-right.\n// u: 300, v: 0\nvertex(30, 0, 0, 300, 0);
\n// Bottom-right.\n// u: 300, v: 500\nvertex(30, 50, 0, 300, 500);
\n// Bottom-left.\n// u: 0, v: 500\nvertex(0, 50, 0, 0, 500);
\nendShape();\n
\ntextureMode()
changes the coordinate system for uv coordinates.
The parameter, mode
, accepts two possible constants. If NORMAL
is\npassed, as in textureMode(NORMAL)
, then the texture’s uv coordinates can\nbe provided in the range 0 to 1 instead of the image’s dimensions. This can\nbe helpful for using the same code for multiple images of different sizes.\nFor example, the code snippet above could be rewritten as follows:
\n// Set the texture mode to use normalized coordinates.\ntextureMode(NORMAL);\n\n// Apply the image as a texture.\ntexture(img);
\n// Draw the rectangle.\nbeginShape();
\n// Top-left.\n// u: 0, v: 0\nvertex(0, 0, 0, 0, 0);
\n// Top-right.\n// u: 1, v: 0\nvertex(30, 0, 0, 1, 0);
\n// Bottom-right.\n// u: 1, v: 1\nvertex(30, 50, 0, 1, 1);
\n// Bottom-left.\n// u: 0, v: 1\nvertex(0, 50, 0, 0, 1);
\nendShape();\n
\nBy default, mode
is IMAGE
, which scales uv coordinates to the\ndimensions of the image. Calling textureMode(IMAGE)
applies the default.
Note: textureMode()
can only be used in WebGL mode.
either IMAGE or NORMAL.
\n"],"type":[0,"Constant"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nlet img;\n\n// Load an image and create a p5.Image object.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('An image of a ceiling against a black background.');\n}\n\nfunction draw() {\n background(0);\n\n // Apply the image as a texture.\n texture(img);\n\n // Draw the custom shape.\n // Use the image's width and height as uv coordinates.\n beginShape();\n vertex(-30, -30, 0, 0);\n vertex(30, -30, img.width, 0);\n vertex(30, 30, img.width, img.height);\n vertex(-30, 30, 0, img.height);\n endShape();\n}\n
\n\nlet img;\n\n// Load an image and create a p5.Image object.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('An image of a ceiling against a black background.');\n}\n\nfunction draw() {\n background(0);\n\n // Set the texture mode.\n textureMode(NORMAL);\n\n // Apply the image as a texture.\n texture(img);\n\n // Draw the custom shape.\n // Use normalized uv coordinates.\n beginShape();\n vertex(-30, -30, 0, 0);\n vertex(30, -30, 1, 0);\n vertex(30, 30, 1, 1);\n vertex(-30, 30, 0, 1);\n endShape();\n}\n
\nChanges the way textures behave when a shape’s uv coordinates go beyond the\ntexture.
\nIn order for texture() to work, a shape needs a\nway to map the points on its surface to the pixels in an image. Built-in\nshapes such as rect() and\nbox() already have these texture mappings based on\ntheir vertices. Custom shapes created with\nvertex() require texture mappings to be passed as\nuv coordinates.
\nEach call to vertex() must include 5 arguments,\nas in vertex(x, y, z, u, v)
, to map the vertex at coordinates (x, y, z)
\nto the pixel at coordinates (u, v)
within an image. For example, the\ncorners of a rectangular image are mapped to the corners of a rectangle by default:
// Apply the image as a texture.\ntexture(img);\n\n// Draw the rectangle.\nrect(0, 0, 30, 50);\n
\nIf the image in the code snippet above has dimensions of 300 x 500 pixels,\nthe same result could be achieved as follows:
\n// Apply the image as a texture.\ntexture(img);\n\n// Draw the rectangle.\nbeginShape();\n\n// Top-left.\n// u: 0, v: 0\nvertex(0, 0, 0, 0, 0);\n\n// Top-right.\n// u: 300, v: 0\nvertex(30, 0, 0, 300, 0);\n\n// Bottom-right.\n// u: 300, v: 500\nvertex(30, 50, 0, 300, 500);\n\n// Bottom-left.\n// u: 0, v: 500\nvertex(0, 50, 0, 0, 500);\n\nendShape();\n
\ntextureWrap()
controls how textures behave when their uv's go beyond the\ntexture. Doing so can produce interesting visual effects such as tiling.\nFor example, the custom shape above could have u-coordinates are greater\nthan the image’s width:
// Apply the image as a texture.\ntexture(img);\n\n// Draw the rectangle.\nbeginShape();\nvertex(0, 0, 0, 0, 0);\n\n// Top-right.\n// u: 600\nvertex(30, 0, 0, 600, 0);\n\n// Bottom-right.\n// u: 600\nvertex(30, 50, 0, 600, 500);\n\nvertex(0, 50, 0, 0, 500);\nendShape();\n
\nThe u-coordinates of 600 are greater than the texture image’s width of 300.\nThis creates interesting possibilities.
\nThe first parameter, wrapX
, accepts three possible constants. If CLAMP
\nis passed, as in textureWrap(CLAMP)
, the pixels at the edge of the\ntexture will extend to the shape’s edges. If REPEAT
is passed, as in\ntextureWrap(REPEAT)
, the texture will tile repeatedly until reaching the\nshape’s edges. If MIRROR
is passed, as in textureWrap(MIRROR)
, the\ntexture will tile repeatedly until reaching the shape’s edges, flipping\nits orientation between tiles. By default, textures CLAMP
.
The second parameter, wrapY
, is optional. It accepts the same three\nconstants, CLAMP
, REPEAT
, and MIRROR
. If one of these constants is\npassed, as in textureWRAP(MIRROR, REPEAT)
, then the texture will MIRROR
\nhorizontally and REPEAT
vertically. By default, wrapY
will be set to\nthe same value as wrapX
.
Note: textureWrap()
can only be used in WebGL mode.
either CLAMP, REPEAT, or MIRROR
\n"],"type":[0,"Constant"]}],[0,{"name":[0,"wrapY"],"description":[0,"either CLAMP, REPEAT, or MIRROR
\n"],"type":[0,"Constant"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nlet img;\n\nfunction preload() {\n img = loadImage('/assets/rockies128.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(0);\n\n // Set the texture mode.\n textureMode(NORMAL);\n\n // Set the texture wrapping.\n // Note: CLAMP is the default mode.\n textureWrap(CLAMP);\n\n // Apply the image as a texture.\n texture(img);\n\n // Style the shape.\n noStroke();\n\n // Draw the shape.\n // Use uv coordinates > 1.\n beginShape();\n vertex(-30, -30, 0, 0, 0);\n vertex(30, -30, 0, 2, 0);\n vertex(30, 30, 0, 2, 2);\n vertex(-30, 30, 0, 0, 2);\n endShape();\n}\n
\n\nlet img;\n\nfunction preload() {\n img = loadImage('/assets/rockies128.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('Four identical images of a landscape arranged in a grid.');\n}\n\nfunction draw() {\n background(0);\n\n // Set the texture mode.\n textureMode(NORMAL);\n\n // Set the texture wrapping.\n textureWrap(REPEAT);\n\n // Apply the image as a texture.\n texture(img);\n\n // Style the shape.\n noStroke();\n\n // Draw the shape.\n // Use uv coordinates > 1.\n beginShape();\n vertex(-30, -30, 0, 0, 0);\n vertex(30, -30, 0, 2, 0);\n vertex(30, 30, 0, 2, 2);\n vertex(-30, 30, 0, 0, 2);\n endShape();\n}\n
\n\nlet img;\n\nfunction preload() {\n img = loadImage('/assets/rockies128.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'Four identical images of a landscape arranged in a grid. The images are reflected horizontally and vertically, creating a kaleidoscope effect.'\n );\n}\n\nfunction draw() {\n background(0);\n\n // Set the texture mode.\n textureMode(NORMAL);\n\n // Set the texture wrapping.\n textureWrap(MIRROR);\n\n // Apply the image as a texture.\n texture(img);\n\n // Style the shape.\n noStroke();\n\n // Draw the shape.\n // Use uv coordinates > 1.\n beginShape();\n vertex(-30, -30, 0, 0, 0);\n vertex(30, -30, 0, 2, 0);\n vertex(30, 30, 0, 2, 2);\n vertex(-30, 30, 0, 0, 2);\n endShape();\n}\n
\n\nlet img;\n\nfunction preload() {\n img = loadImage('/assets/rockies128.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'Four identical images of a landscape arranged in a grid. The top row and bottom row are reflections of each other.'\n );\n}\n\nfunction draw() {\n background(0);\n\n // Set the texture mode.\n textureMode(NORMAL);\n\n // Set the texture wrapping.\n textureWrap(REPEAT, MIRROR);\n\n // Apply the image as a texture.\n texture(img);\n\n // Style the shape.\n noStroke();\n\n // Draw the shape.\n // Use uv coordinates > 1.\n beginShape();\n vertex(-30, -30, 0, 0, 0);\n vertex(30, -30, 0, 2, 0);\n vertex(30, 30, 0, 2, 2);\n vertex(-30, 30, 0, 0, 2);\n endShape();\n}\n
\nA class to describe a camera for viewing a 3D sketch.
\nEach p5.Camera
object represents a camera that views a section of 3D\nspace. It stores information about the camera’s position, orientation, and\nprojection.
In WebGL mode, the default camera is a p5.Camera
object that can be\ncontrolled with the camera(),\nperspective(),\northo(), and\nfrustum() functions. Additional cameras can be\ncreated with createCamera() and activated\nwith setCamera().
Note: p5.Camera
’s methods operate in two coordinate systems:
myCamera.setPosition()
places the camera in 3D space using\n\"world\" coordinates.myCamera.move()
moves the camera along its own axes.instance of WebGL renderer
\n"],"type":[0,"RendererGL"]}]]],"chainable":[0,false],"example":[1,[[0,"\n\nlet cam;\nlet delta = 0.001;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Camera object.\n cam = createCamera();\n\n // Place the camera at the top-center.\n cam.setPosition(0, -400, 800);\n\n // Point the camera at the origin.\n cam.lookAt(0, 0, 0);\n\n describe(\n 'A white cube on a gray background. The cube goes in and out of view as the camera pans left and right.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Turn the camera left and right, called \"panning\".\n cam.pan(delta);\n\n // Switch directions every 120 frames.\n if (frameCount % 120 === 0) {\n delta *= -1;\n }\n\n // Draw the box.\n box();\n}\n
\n\n// Double-click to toggle between cameras.\n\nlet cam1;\nlet cam2;\nlet isDefaultCamera = true;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create the first camera.\n // Keep its default settings.\n cam1 = createCamera();\n\n // Create the second camera.\n // Place it at the top-left.\n // Point it at the origin.\n cam2 = createCamera();\n cam2.setPosition(400, -400, 800);\n cam2.lookAt(0, 0, 0);\n\n // Set the current camera to cam1.\n setCamera(cam1);\n\n describe(\n 'A white cube on a gray background. The camera toggles between frontal and aerial views when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Draw the box.\n box();\n}\n\n// Toggle the current camera when the user double-clicks.\nfunction doubleClicked() {\n if (isDefaultCamera === true) {\n setCamera(cam2);\n isDefaultCamera = false;\n } else {\n setCamera(cam1);\n isDefaultCamera = true;\n }\n}\n
\nSets a perspective projection for the camera.
\nIn a perspective projection, shapes that are further from the camera appear\nsmaller than shapes that are near the camera. This technique, called\nforeshortening, creates realistic 3D scenes. It’s applied by default in new\np5.Camera
objects.
myCamera.perspective()
changes the camera’s perspective by changing its\nviewing frustum. The frustum is the volume of space that’s visible to the\ncamera. The frustum’s shape is a pyramid with its top cut off. The camera\nis placed where the top of the pyramid should be and points towards the\nbase of the pyramid. It views everything within the frustum.
The first parameter, fovy
, is the camera’s vertical field of view. It’s\nan angle that describes how tall or narrow a view the camera has. For\nexample, calling myCamera.perspective(0.5)
sets the camera’s vertical\nfield of view to 0.5 radians. By default, fovy
is calculated based on the\nsketch’s height and the camera’s default z-coordinate, which is 800. The\nformula for the default fovy
is 2 * atan(height / 2 / 800)
.
The second parameter, aspect
, is the camera’s aspect ratio. It’s a number\nthat describes the ratio of the top plane’s width to its height. For\nexample, calling myCamera.perspective(0.5, 1.5)
sets the camera’s field\nof view to 0.5 radians and aspect ratio to 1.5, which would make shapes\nappear thinner on a square canvas. By default, aspect
is set to\nwidth / height
.
The third parameter, near
, is the distance from the camera to the near\nplane. For example, calling myCamera.perspective(0.5, 1.5, 100)
sets the\ncamera’s field of view to 0.5 radians, its aspect ratio to 1.5, and places\nthe near plane 100 pixels from the camera. Any shapes drawn less than 100\npixels from the camera won’t be visible. By default, near
is set to\n0.1 * 800
, which is 1/10th the default distance between the camera and\nthe origin.
The fourth parameter, far
, is the distance from the camera to the far\nplane. For example, calling myCamera.perspective(0.5, 1.5, 100, 10000)
\nsets the camera’s field of view to 0.5 radians, its aspect ratio to 1.5,\nplaces the near plane 100 pixels from the camera, and places the far plane\n10,000 pixels from the camera. Any shapes drawn more than 10,000 pixels\nfrom the camera won’t be visible. By default, far
is set to 10 * 800
,\nwhich is 10 times the default distance between the camera and the origin.
Sets an orthographic projection for the camera.
\nIn an orthographic projection, shapes with the same size always appear the\nsame size, regardless of whether they are near or far from the camera.
\nmyCamera.ortho()
changes the camera’s perspective by changing its viewing\nfrustum from a truncated pyramid to a rectangular prism. The frustum is the\nvolume of space that’s visible to the camera. The camera is placed in front\nof the frustum and views everything within the frustum. myCamera.ortho()
\nhas six optional parameters to define the viewing frustum.
The first four parameters, left
, right
, bottom
, and top
, set the\ncoordinates of the frustum’s sides, bottom, and top. For example, calling\nmyCamera.ortho(-100, 100, 200, -200)
creates a frustum that’s 200 pixels\nwide and 400 pixels tall. By default, these dimensions are set based on\nthe sketch’s width and height, as in\nmyCamera.ortho(-width / 2, width / 2, -height / 2, height / 2)
.
The last two parameters, near
and far
, set the distance of the\nfrustum’s near and far plane from the camera. For example, calling\nmyCamera.ortho(-100, 100, 200, -200, 50, 1000)
creates a frustum that’s\n200 pixels wide, 400 pixels tall, starts 50 pixels from the camera, and\nends 1,000 pixels from the camera. By default, near
and far
are set to\n0 and max(width, height) + 800
, respectively.
Sets the camera's frustum.
\nIn a frustum projection, shapes that are further from the camera appear\nsmaller than shapes that are near the camera. This technique, called\nforeshortening, creates realistic 3D scenes.
\nmyCamera.frustum()
changes the camera’s perspective by changing its\nviewing frustum. The frustum is the volume of space that’s visible to the\ncamera. The frustum’s shape is a pyramid with its top cut off. The camera\nis placed where the top of the pyramid should be and points towards the\nbase of the pyramid. It views everything within the frustum.
The first four parameters, left
, right
, bottom
, and top
, set the\ncoordinates of the frustum’s sides, bottom, and top. For example, calling\nmyCamera.frustum(-100, 100, 200, -200)
creates a frustum that’s 200\npixels wide and 400 pixels tall. By default, these coordinates are set\nbased on the sketch’s width and height, as in\nmyCamera.frustum(-width / 20, width / 20, height / 20, -height / 20)
.
The last two parameters, near
and far
, set the distance of the\nfrustum’s near and far plane from the camera. For example, calling\nmyCamera.frustum(-100, 100, 200, -200, 50, 1000)
creates a frustum that’s\n200 pixels wide, 400 pixels tall, starts 50 pixels from the camera, and ends\n1,000 pixels from the camera. By default, near is set to 0.1 * 800
, which\nis 1/10th the default distance between the camera and the origin. far
is\nset to 10 * 800
, which is 10 times the default distance between the\ncamera and the origin.
Rotates the camera in a clockwise/counter-clockwise direction.
\nRolling rotates the camera without changing its orientation. The rotation\nhappens in the camera’s \"local\" space.
\nThe parameter, angle
, is the angle the camera should rotate. Passing a\npositive angle, as in myCamera.roll(0.001)
, rotates the camera in counter-clockwise direction.\nPassing a negative angle, as in myCamera.roll(-0.001)
, rotates the\ncamera in clockwise direction.
Note: Angles are interpreted based on the current\nangleMode().
\n"],"path":[0,"p5.Camera/roll"]}],"pan":[0,{"description":[0,"Rotates the camera left and right.
\nPanning rotates the camera without changing its position. The rotation\nhappens in the camera’s \"local\" space.
\nThe parameter, angle
, is the angle the camera should rotate. Passing a\npositive angle, as in myCamera.pan(0.001)
, rotates the camera to the\nright. Passing a negative angle, as in myCamera.pan(-0.001)
, rotates the\ncamera to the left.
Note: Angles are interpreted based on the current\nangleMode().
\n"],"path":[0,"p5.Camera/pan"]}],"tilt":[0,{"description":[0,"Rotates the camera up and down.
\nTilting rotates the camera without changing its position. The rotation\nhappens in the camera’s \"local\" space.
\nThe parameter, angle
, is the angle the camera should rotate. Passing a\npositive angle, as in myCamera.tilt(0.001)
, rotates the camera down.\nPassing a negative angle, as in myCamera.tilt(-0.001)
, rotates the camera\nup.
Note: Angles are interpreted based on the current\nangleMode().
\n"],"path":[0,"p5.Camera/tilt"]}],"lookAt":[0,{"description":[0,"Points the camera at a location.
\nmyCamera.lookAt()
changes the camera’s orientation without changing its\nposition.
The parameters, x
, y
, and z
, are the coordinates in \"world\" space\nwhere the camera should point. For example, calling\nmyCamera.lookAt(10, 20, 30)
points the camera at the coordinates\n(10, 20, 30)
.
Sets the position and orientation of the camera.
\nmyCamera.camera()
allows objects to be viewed from different angles. It\nhas nine parameters that are all optional.
The first three parameters, x
, y
, and z
, are the coordinates of the\ncamera’s position in \"world\" space. For example, calling\nmyCamera.camera(0, 0, 0)
places the camera at the origin (0, 0, 0)
. By\ndefault, the camera is placed at (0, 0, 800)
.
The next three parameters, centerX
, centerY
, and centerZ
are the\ncoordinates of the point where the camera faces in \"world\" space. For\nexample, calling myCamera.camera(0, 0, 0, 10, 20, 30)
places the camera\nat the origin (0, 0, 0)
and points it at (10, 20, 30)
. By default, the\ncamera points at the origin (0, 0, 0)
.
The last three parameters, upX
, upY
, and upZ
are the components of\nthe \"up\" vector in \"local\" space. The \"up\" vector orients the camera’s\ny-axis. For example, calling\nmyCamera.camera(0, 0, 0, 10, 20, 30, 0, -1, 0)
places the camera at the\norigin (0, 0, 0)
, points it at (10, 20, 30)
, and sets the \"up\" vector\nto (0, -1, 0)
which is like holding it upside-down. By default, the \"up\"\nvector is (0, 1, 0)
.
Moves the camera along its \"local\" axes without changing its orientation.
\nThe parameters, x
, y
, and z
, are the distances the camera should\nmove. For example, calling myCamera.move(10, 20, 30)
moves the camera 10\npixels to the right, 20 pixels down, and 30 pixels backward in its \"local\"\nspace.
Sets the camera’s position in \"world\" space without changing its\norientation.
\nThe parameters, x
, y
, and z
, are the coordinates where the camera\nshould be placed. For example, calling myCamera.setPosition(10, 20, 30)
\nplaces the camera at coordinates (10, 20, 30)
in \"world\" space.
Sets the camera’s position, orientation, and projection by copying another\ncamera.
\nThe parameter, cam
, is the p5.Camera
object to copy. For example, calling\ncam2.set(cam1)
will set cam2
using cam1
’s configuration.
Sets the camera’s position and orientation to values that are in-between\nthose of two other cameras.
\nmyCamera.slerp()
uses spherical linear interpolation to calculate a\nposition and orientation that’s in-between two other cameras. Doing so is\nhelpful for transitioning smoothly between two perspectives.
The first two parameters, cam0
and cam1
, are the p5.Camera
objects\nthat should be used to set the current camera.
The third parameter, amt
, is the amount to interpolate between cam0
and\ncam1
. 0.0 keeps the camera’s position and orientation equal to cam0
’s,\n0.5 sets them halfway between cam0
’s and cam1
’s , and 1.0 sets the\nposition and orientation equal to cam1
’s.
For example, calling myCamera.slerp(cam0, cam1, 0.1)
sets cam’s position\nand orientation very close to cam0
’s. Calling\nmyCamera.slerp(cam0, cam1, 0.9)
sets cam’s position and orientation very\nclose to cam1
’s.
Note: All of the cameras must use the same projection.
\n"],"path":[0,"p5.Camera/slerp"]}]}],"properties":[0,{"eyeX":[0,{"description":[0,"The camera’s x-coordinate.
\nBy default, the camera’s x-coordinate is set to 0 in \"world\" space.
\n"],"path":[0,"p5.Camera/eyeX"]}],"eyeY":[0,{"description":[0,"The camera’s y-coordinate.
\nBy default, the camera’s y-coordinate is set to 0 in \"world\" space.
\n"],"path":[0,"p5.Camera/eyeY"]}],"eyeZ":[0,{"description":[0,"The camera’s z-coordinate.
\nBy default, the camera’s z-coordinate is set to 800 in \"world\" space.
\n"],"path":[0,"p5.Camera/eyeZ"]}],"centerX":[0,{"description":[0,"The x-coordinate of the place where the camera looks.
\nBy default, the camera looks at the origin (0, 0, 0)
in \"world\" space, so\nmyCamera.centerX
is 0.
The y-coordinate of the place where the camera looks.
\nBy default, the camera looks at the origin (0, 0, 0)
in \"world\" space, so\nmyCamera.centerY
is 0.
The y-coordinate of the place where the camera looks.
\nBy default, the camera looks at the origin (0, 0, 0)
in \"world\" space, so\nmyCamera.centerZ
is 0.
The x-component of the camera's \"up\" vector.
\nThe camera's \"up\" vector orients its y-axis. By default, the \"up\" vector is\n(0, 1, 0)
, so its x-component is 0 in \"local\" space.
The y-component of the camera's \"up\" vector.
\nThe camera's \"up\" vector orients its y-axis. By default, the \"up\" vector is\n(0, 1, 0)
, so its y-component is 1 in \"local\" space.
The z-component of the camera's \"up\" vector.
\nThe camera's \"up\" vector orients its y-axis. By default, the \"up\" vector is\n(0, 1, 0)
, so its z-component is 0 in \"local\" space.
Sets the position and orientation of the camera.
\nmyCamera.camera()
allows objects to be viewed from different angles. It\nhas nine parameters that are all optional.
The first three parameters, x
, y
, and z
, are the coordinates of the\ncamera’s position in \"world\" space. For example, calling\nmyCamera.camera(0, 0, 0)
places the camera at the origin (0, 0, 0)
. By\ndefault, the camera is placed at (0, 0, 800)
.
The next three parameters, centerX
, centerY
, and centerZ
are the\ncoordinates of the point where the camera faces in \"world\" space. For\nexample, calling myCamera.camera(0, 0, 0, 10, 20, 30)
places the camera\nat the origin (0, 0, 0)
and points it at (10, 20, 30)
. By default, the\ncamera points at the origin (0, 0, 0)
.
The last three parameters, upX
, upY
, and upZ
are the components of\nthe \"up\" vector in \"local\" space. The \"up\" vector orients the camera’s\ny-axis. For example, calling\nmyCamera.camera(0, 0, 0, 10, 20, 30, 0, -1, 0)
places the camera at the\norigin (0, 0, 0)
, points it at (10, 20, 30)
, and sets the \"up\" vector\nto (0, -1, 0)
which is like holding it upside-down. By default, the \"up\"\nvector is (0, 1, 0)
.
x-coordinate of the camera. Defaults to 0.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"y"],"description":[0,"y-coordinate of the camera. Defaults to 0.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"z"],"description":[0,"z-coordinate of the camera. Defaults to 800.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"centerX"],"description":[0,"x-coordinate of the point the camera faces. Defaults to 0.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"centerY"],"description":[0,"y-coordinate of the point the camera faces. Defaults to 0.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"centerZ"],"description":[0,"z-coordinate of the point the camera faces. Defaults to 0.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"upX"],"description":[0,"x-component of the camera’s \"up\" vector. Defaults to 0.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"upY"],"description":[0,"x-component of the camera’s \"up\" vector. Defaults to 1.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"upZ"],"description":[0,"z-component of the camera’s \"up\" vector. Defaults to 0.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Camera"],"chainable":[0,false],"example":[1,[[0,"\n\n// Double-click to toggle between cameras.\n\nlet cam1;\nlet cam2;\nlet isDefaultCamera = true;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create the first camera.\n // Keep its default settings.\n cam1 = createCamera();\n\n // Create the second camera.\n cam2 = createCamera();\n\n // Place it at the top-right: (1200, -600, 100)\n // Point it at the row of boxes: (-10, -10, 400)\n // Set its \"up\" vector to the default: (0, 1, 0)\n cam2.camera(1200, -600, 100, -10, -10, 400, 0, 1, 0);\n\n // Set the current camera to cam1.\n setCamera(cam1);\n\n describe(\n 'A row of white cubes against a gray background. The camera toggles between a frontal and an aerial view when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin toward the camera.\n translate(-10, 10, 500);\n\n // Rotate the coordinate system.\n rotateY(-0.1);\n rotateX(-0.1);\n\n // Draw the row of boxes.\n for (let i = 0; i < 6; i += 1) {\n translate(0, 0, -30);\n box(10);\n }\n}\n\n// Toggle the current camera when the user double-clicks.\nfunction doubleClicked() {\n if (isDefaultCamera === true) {\n setCamera(cam2);\n isDefaultCamera = false;\n } else {\n setCamera(cam1);\n isDefaultCamera = true;\n }\n}\n
\n\n// Double-click to toggle between cameras.\n\nlet cam1;\nlet cam2;\nlet isDefaultCamera = true;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create the first camera.\n // Keep its default settings.\n cam1 = createCamera();\n\n // Create the second camera.\n cam2 = createCamera();\n\n // Place it at the right: (1200, 0, 100)\n // Point it at the row of boxes: (-10, -10, 400)\n // Set its \"up\" vector to the default: (0, 1, 0)\n cam2.camera(1200, 0, 100, -10, -10, 400, 0, 1, 0);\n\n // Set the current camera to cam1.\n setCamera(cam1);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Update cam2's position.\n let x = 1200 * cos(frameCount * 0.01);\n let y = -600 * sin(frameCount * 0.01);\n cam2.camera(x, y, 100, -10, -10, 400, 0, 1, 0);\n\n // Translate the origin toward the camera.\n translate(-10, 10, 500);\n\n // Rotate the coordinate system.\n rotateY(-0.1);\n rotateX(-0.1);\n\n // Draw the row of boxes.\n for (let i = 0; i < 6; i += 1) {\n translate(0, 0, -30);\n box(10);\n }\n}\n\n// Toggle the current camera when the user double-clicks.\nfunction doubleClicked() {\n if (isDefaultCamera === true) {\n setCamera(cam2);\n isDefaultCamera = false;\n } else {\n setCamera(cam1);\n isDefaultCamera = true;\n }\n}\n
\nThe x-coordinate of the place where the camera looks.
\nBy default, the camera looks at the origin (0, 0, 0)
in \"world\" space, so\nmyCamera.centerX
is 0.
\nlet cam;\nlet font;\n\n// Load a font and create a p5.Font object.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Camera object.\n cam = createCamera();\n\n // Place the camera at the top-center.\n cam.setPosition(0, -400, 800);\n\n // Point the camera at (10, 20, -30).\n cam.lookAt(10, 20, -30);\n\n describe(\n 'A white cube on a gray background. The text \"centerX: 10\" is written in black beneath it.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the box.\n fill(255);\n\n // Draw the box.\n box();\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Display the value of centerX, rounded to the nearest integer.\n text(`centerX: ${round(cam.centerX)}`, 0, 55);\n}\n
\n\nlet cam;\nlet font;\n\n// Load a font and create a p5.Font object.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Camera object.\n cam = createCamera();\n\n // Place the camera at the top-right.\n cam.setPosition(100, -400, 800);\n\n // Point the camera at (10, 20, -30).\n cam.lookAt(10, 20, -30);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the box.\n fill(255);\n\n // Draw the box.\n box();\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Calculate the new x-coordinate.\n let x = 25 * sin(frameCount * 0.01) + 10;\n\n // Point the camera.\n cam.lookAt(x, 20, -30);\n\n // Display the value of centerX, rounded to the nearest integer.\n text(`centerX: ${round(cam.centerX)}`, 0, 55);\n}\n
\nThe y-coordinate of the place where the camera looks.
\nBy default, the camera looks at the origin (0, 0, 0)
in \"world\" space, so\nmyCamera.centerY
is 0.
\nlet cam;\nlet font;\n\n// Load a font and create a p5.Font object.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Camera object.\n cam = createCamera();\n\n // Place the camera at the top-center.\n cam.setPosition(0, -400, 800);\n\n // Point the camera at (10, 20, -30).\n cam.lookAt(10, 20, -30);\n\n describe(\n 'A white cube on a gray background. The text \"centerY: 20\" is written in black beneath it.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the box.\n fill(255);\n\n // Draw the box.\n box();\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Display the value of centerY, rounded to the nearest integer.\n text(`centerY: ${round(cam.centerY)}`, 0, 55);\n}\n
\n\nlet cam;\nlet font;\n\n// Load a font and create a p5.Font object.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Camera object.\n cam = createCamera();\n\n // Place the camera at the top-right.\n cam.setPosition(100, -400, 800);\n\n // Point the camera at (10, 20, -30).\n cam.lookAt(10, 20, -30);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the box.\n fill(255);\n\n // Draw the box.\n box();\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Calculate the new y-coordinate.\n let y = 25 * sin(frameCount * 0.01) + 20;\n\n // Point the camera.\n cam.lookAt(10, y, -30);\n\n // Display the value of centerY, rounded to the nearest integer.\n text(`centerY: ${round(cam.centerY)}`, 0, 55);\n}\n
\nThe y-coordinate of the place where the camera looks.
\nBy default, the camera looks at the origin (0, 0, 0)
in \"world\" space, so\nmyCamera.centerZ
is 0.
\nlet cam;\nlet font;\n\n// Load a font and create a p5.Font object.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Camera object.\n cam = createCamera();\n\n // Place the camera at the top-center.\n cam.setPosition(0, -400, 800);\n\n // Point the camera at (10, 20, -30).\n cam.lookAt(10, 20, -30);\n\n describe(\n 'A white cube on a gray background. The text \"centerZ: -30\" is written in black beneath it.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the box.\n fill(255);\n\n // Draw the box.\n box();\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Display the value of centerZ, rounded to the nearest integer.\n text(`centerZ: ${round(cam.centerZ)}`, 0, 55);\n}\n
\n\nlet cam;\nlet font;\n\n// Load a font and create a p5.Font object.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Camera object.\n cam = createCamera();\n\n // Place the camera at the top-right.\n cam.setPosition(100, -400, 800);\n\n // Point the camera at (10, 20, -30).\n cam.lookAt(10, 20, -30);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the box.\n fill(255);\n\n // Draw the box.\n box();\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Calculate the new z-coordinate.\n let z = 25 * sin(frameCount * 0.01) - 30;\n\n // Point the camera.\n cam.lookAt(10, 20, z);\n\n // Display the value of centerZ, rounded to the nearest integer.\n text(`centerZ: ${round(cam.centerZ)}`, 0, 55);\n}\n
\nThe camera’s x-coordinate.
\nBy default, the camera’s x-coordinate is set to 0 in \"world\" space.
\n"],"line":[0,851],"itemtype":[0,"property"],"class":[0,"p5.Camera"],"example":[1,[[0,"\n\nlet cam;\nlet font;\n\n// Load a font and create a p5.Font object.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Camera object.\n cam = createCamera();\n\n // Place the camera at the top-center.\n cam.setPosition(0, -400, 800);\n\n // Point the camera at the origin.\n cam.lookAt(0, 0, 0);\n\n describe(\n 'A white cube on a gray background. The text \"eyeX: 0\" is written in black beneath it.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the box.\n fill(255);\n\n // Draw the box.\n box();\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Display the value of eyeX, rounded to the nearest integer.\n text(`eyeX: ${round(cam.eyeX)}`, 0, 55);\n}\n
\n\nlet cam;\nlet font;\n\n// Load a font and create a p5.Font object.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Camera object.\n cam = createCamera();\n\n // Place the camera at the top-center.\n cam.setPosition(0, -400, 800);\n\n // Point the camera at the origin.\n cam.lookAt(0, 0, 0);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the box.\n fill(255);\n\n // Draw the box.\n box();\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Calculate the new x-coordinate.\n let x = 25 * sin(frameCount * 0.01);\n\n // Set the camera's position.\n cam.setPosition(x, -400, 800);\n\n // Display the value of eyeX, rounded to the nearest integer.\n text(`eyeX: ${round(cam.eyeX)}`, 0, 55);\n}\n
\nThe camera’s y-coordinate.
\nBy default, the camera’s y-coordinate is set to 0 in \"world\" space.
\n"],"line":[0,963],"itemtype":[0,"property"],"class":[0,"p5.Camera"],"example":[1,[[0,"\n\nlet cam;\nlet font;\n\n// Load a font and create a p5.Font object.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Camera object.\n cam = createCamera();\n\n // Place the camera at the top-center.\n cam.setPosition(0, -400, 800);\n\n // Point the camera at the origin.\n cam.lookAt(0, 0, 0);\n\n describe(\n 'A white cube on a gray background. The text \"eyeY: -400\" is written in black beneath it.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the box.\n fill(255);\n\n // Draw the box.\n box();\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Display the value of eyeY, rounded to the nearest integer.\n text(`eyeX: ${round(cam.eyeY)}`, 0, 55);\n}\n
\n\nlet cam;\nlet font;\n\n// Load a font and create a p5.Font object.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Camera object.\n cam = createCamera();\n\n // Place the camera at the top-center.\n cam.setPosition(0, -400, 800);\n\n // Point the camera at the origin.\n cam.lookAt(0, 0, 0);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the box.\n fill(255);\n\n // Draw the box.\n box();\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Calculate the new y-coordinate.\n let y = 25 * sin(frameCount * 0.01) - 400;\n\n // Set the camera's position.\n cam.setPosition(0, y, 800);\n\n // Display the value of eyeY, rounded to the nearest integer.\n text(`eyeY: ${round(cam.eyeY)}`, 0, 55);\n}\n
\nThe camera’s z-coordinate.
\nBy default, the camera’s z-coordinate is set to 800 in \"world\" space.
\n"],"line":[0,1075],"itemtype":[0,"property"],"class":[0,"p5.Camera"],"example":[1,[[0,"\n\nlet cam;\nlet font;\n\n// Load a font and create a p5.Font object.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Camera object.\n cam = createCamera();\n\n // Place the camera at the top-center.\n cam.setPosition(0, -400, 800);\n\n // Point the camera at the origin.\n cam.lookAt(0, 0, 0);\n\n describe(\n 'A white cube on a gray background. The text \"eyeZ: 800\" is written in black beneath it.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the box.\n fill(255);\n\n // Draw the box.\n box();\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Display the value of eyeZ, rounded to the nearest integer.\n text(`eyeZ: ${round(cam.eyeZ)}`, 0, 55);\n}\n
\n\nlet cam;\nlet font;\n\n// Load a font and create a p5.Font object.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Camera object.\n cam = createCamera();\n\n // Place the camera at the top-center.\n cam.setPosition(0, -400, 800);\n\n // Point the camera at the origin.\n cam.lookAt(0, 0, 0);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the box.\n fill(255);\n\n // Draw the box.\n box();\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Calculate the new z-coordinate.\n let z = 100 * sin(frameCount * 0.01) + 800;\n\n // Set the camera's position.\n cam.setPosition(0, -400, z);\n\n // Display the value of eyeZ, rounded to the nearest integer.\n text(`eyeZ: ${round(cam.eyeZ)}`, 0, 55);\n}\n
\nSets the camera's frustum.
\nIn a frustum projection, shapes that are further from the camera appear\nsmaller than shapes that are near the camera. This technique, called\nforeshortening, creates realistic 3D scenes.
\nmyCamera.frustum()
changes the camera’s perspective by changing its\nviewing frustum. The frustum is the volume of space that’s visible to the\ncamera. The frustum’s shape is a pyramid with its top cut off. The camera\nis placed where the top of the pyramid should be and points towards the\nbase of the pyramid. It views everything within the frustum.
The first four parameters, left
, right
, bottom
, and top
, set the\ncoordinates of the frustum’s sides, bottom, and top. For example, calling\nmyCamera.frustum(-100, 100, 200, -200)
creates a frustum that’s 200\npixels wide and 400 pixels tall. By default, these coordinates are set\nbased on the sketch’s width and height, as in\nmyCamera.frustum(-width / 20, width / 20, height / 20, -height / 20)
.
The last two parameters, near
and far
, set the distance of the\nfrustum’s near and far plane from the camera. For example, calling\nmyCamera.frustum(-100, 100, 200, -200, 50, 1000)
creates a frustum that’s\n200 pixels wide, 400 pixels tall, starts 50 pixels from the camera, and ends\n1,000 pixels from the camera. By default, near is set to 0.1 * 800
, which\nis 1/10th the default distance between the camera and the origin. far
is\nset to 10 * 800
, which is 10 times the default distance between the\ncamera and the origin.
x-coordinate of the frustum’s left plane. Defaults to -width / 20
.
x-coordinate of the frustum’s right plane. Defaults to width / 20
.
y-coordinate of the frustum’s bottom plane. Defaults to height / 20
.
y-coordinate of the frustum’s top plane. Defaults to -height / 20
.
z-coordinate of the frustum’s near plane. Defaults to 0.1 * 800
.
z-coordinate of the frustum’s far plane. Defaults to 10 * 800
.
\n// Double-click to toggle between cameras.\n\nlet cam1;\nlet cam2;\nlet isDefaultCamera = true;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create the first camera.\n // Keep its default settings.\n cam1 = createCamera();\n\n // Create the second camera.\n cam2 = createCamera();\n\n // Adjust the frustum.\n // Center it.\n // Set its width and height to 20 pixels.\n // Place its near plane 300 pixels from the camera.\n // Place its far plane 350 pixels from the camera.\n cam2.frustum(-10, 10, -10, 10, 300, 350);\n\n // Set the current camera to cam1.\n setCamera(cam1);\n\n describe(\n 'A row of white cubes against a gray background. The camera zooms in on one cube when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin toward the camera.\n translate(-10, 10, 600);\n\n // Rotate the coordinate system.\n rotateY(-0.1);\n rotateX(-0.1);\n\n // Draw the row of boxes.\n for (let i = 0; i < 6; i += 1) {\n translate(0, 0, -40);\n box(10);\n }\n}\n\n// Toggle the current camera when the user double-clicks.\nfunction doubleClicked() {\n if (isDefaultCamera === true) {\n setCamera(cam2);\n isDefaultCamera = false;\n } else {\n setCamera(cam1);\n isDefaultCamera = true;\n }\n}\n
\nPoints the camera at a location.
\nmyCamera.lookAt()
changes the camera’s orientation without changing its\nposition.
The parameters, x
, y
, and z
, are the coordinates in \"world\" space\nwhere the camera should point. For example, calling\nmyCamera.lookAt(10, 20, 30)
points the camera at the coordinates\n(10, 20, 30)
.
x-coordinate of the position where the camera should look in \"world\" space.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"y-coordinate of the position where the camera should look in \"world\" space.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,"z-coordinate of the position where the camera should look in \"world\" space.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Camera"],"chainable":[0,false],"example":[1,[[0,"\n\n// Double-click to look at a different cube.\n\nlet cam;\nlet isLookingLeft = true;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Camera object.\n cam = createCamera();\n\n // Place the camera at the top-center.\n cam.setPosition(0, -400, 800);\n\n // Point the camera at the origin.\n cam.lookAt(-30, 0, 0);\n\n describe(\n 'A red cube and a blue cube on a gray background. The camera switches focus between the cubes when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Draw the box on the left.\n push();\n // Translate the origin to the left.\n translate(-30, 0, 0);\n // Style the box.\n fill(255, 0, 0);\n // Draw the box.\n box(20);\n pop();\n\n // Draw the box on the right.\n push();\n // Translate the origin to the right.\n translate(30, 0, 0);\n // Style the box.\n fill(0, 0, 255);\n // Draw the box.\n box(20);\n pop();\n}\n\n// Change the camera's focus when the user double-clicks.\nfunction doubleClicked() {\n if (isLookingLeft === true) {\n cam.lookAt(30, 0, 0);\n isLookingLeft = false;\n } else {\n cam.lookAt(-30, 0, 0);\n isLookingLeft = true;\n }\n}\n
\nMoves the camera along its \"local\" axes without changing its orientation.
\nThe parameters, x
, y
, and z
, are the distances the camera should\nmove. For example, calling myCamera.move(10, 20, 30)
moves the camera 10\npixels to the right, 20 pixels down, and 30 pixels backward in its \"local\"\nspace.
distance to move along the camera’s \"local\" x-axis.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"distance to move along the camera’s \"local\" y-axis.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,"distance to move along the camera’s \"local\" z-axis.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Camera"],"chainable":[0,false],"example":[1,[[0,"\n\n// Click the canvas to begin detecting key presses.\n\nlet cam;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create the first camera.\n // Keep its default settings.\n cam = createCamera();\n\n // Place the camera at the top-right.\n cam.setPosition(400, -400, 800);\n\n // Point it at the origin.\n cam.lookAt(0, 0, 0);\n\n describe(\n 'A white cube drawn against a gray background. The cube appears to move when the user presses certain keys.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Move the camera along its \"local\" axes\n // when the user presses certain keys.\n if (keyIsPressed === true) {\n\n // Move horizontally.\n if (keyCode === LEFT_ARROW) {\n cam.move(-1, 0, 0);\n }\n if (keyCode === RIGHT_ARROW) {\n cam.move(1, 0, 0);\n }\n\n // Move vertically.\n if (keyCode === UP_ARROW) {\n cam.move(0, -1, 0);\n }\n if (keyCode === DOWN_ARROW) {\n cam.move(0, 1, 0);\n }\n\n // Move in/out of the screen.\n if (key === 'i') {\n cam.move(0, 0, -1);\n }\n if (key === 'o') {\n cam.move(0, 0, 1);\n }\n }\n\n // Draw the box.\n box();\n}\n
\nSets an orthographic projection for the camera.
\nIn an orthographic projection, shapes with the same size always appear the\nsame size, regardless of whether they are near or far from the camera.
\nmyCamera.ortho()
changes the camera’s perspective by changing its viewing\nfrustum from a truncated pyramid to a rectangular prism. The frustum is the\nvolume of space that’s visible to the camera. The camera is placed in front\nof the frustum and views everything within the frustum. myCamera.ortho()
\nhas six optional parameters to define the viewing frustum.
The first four parameters, left
, right
, bottom
, and top
, set the\ncoordinates of the frustum’s sides, bottom, and top. For example, calling\nmyCamera.ortho(-100, 100, 200, -200)
creates a frustum that’s 200 pixels\nwide and 400 pixels tall. By default, these dimensions are set based on\nthe sketch’s width and height, as in\nmyCamera.ortho(-width / 2, width / 2, -height / 2, height / 2)
.
The last two parameters, near
and far
, set the distance of the\nfrustum’s near and far plane from the camera. For example, calling\nmyCamera.ortho(-100, 100, 200, -200, 50, 1000)
creates a frustum that’s\n200 pixels wide, 400 pixels tall, starts 50 pixels from the camera, and\nends 1,000 pixels from the camera. By default, near
and far
are set to\n0 and max(width, height) + 800
, respectively.
x-coordinate of the frustum’s left plane. Defaults to -width / 2
.
x-coordinate of the frustum’s right plane. Defaults to width / 2
.
y-coordinate of the frustum’s bottom plane. Defaults to height / 2
.
y-coordinate of the frustum’s top plane. Defaults to -height / 2
.
z-coordinate of the frustum’s near plane. Defaults to 0.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"far"],"description":[0,"z-coordinate of the frustum’s far plane. Defaults to max(width, height) + 800
.
\n// Double-click to toggle between cameras.\n\nlet cam1;\nlet cam2;\nlet isDefaultCamera = true;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create the first camera.\n // Keep its default settings.\n cam1 = createCamera();\n\n // Create the second camera.\n cam2 = createCamera();\n\n // Apply an orthographic projection.\n cam2.ortho();\n\n // Set the current camera to cam1.\n setCamera(cam1);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin toward the camera.\n translate(-10, 10, 500);\n\n // Rotate the coordinate system.\n rotateY(-0.1);\n rotateX(-0.1);\n\n // Draw the row of boxes.\n for (let i = 0; i < 6; i += 1) {\n translate(0, 0, -40);\n box(10);\n }\n}\n\n// Toggle the current camera when the user double-clicks.\nfunction doubleClicked() {\n if (isDefaultCamera === true) {\n setCamera(cam2);\n isDefaultCamera = false;\n } else {\n setCamera(cam1);\n isDefaultCamera = true;\n }\n}\n
\n\n// Double-click to toggle between cameras.\n\nlet cam1;\nlet cam2;\nlet isDefaultCamera = true;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create the first camera.\n // Keep its default settings.\n cam1 = createCamera();\n\n // Create the second camera.\n cam2 = createCamera();\n\n // Apply an orthographic projection.\n cam2.ortho();\n\n // Set the current camera to cam1.\n setCamera(cam1);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin toward the camera.\n translate(-10, 10, 500);\n\n // Rotate the coordinate system.\n rotateY(-0.1);\n rotateX(-0.1);\n\n // Draw the row of boxes.\n for (let i = 0; i < 6; i += 1) {\n push();\n // Calculate the box's coordinates.\n let x = 10 * sin(frameCount * 0.02 + i * 0.6);\n let z = -40 * i;\n // Translate the origin.\n translate(x, 0, z);\n // Draw the box.\n box(10);\n pop();\n }\n}\n\n// Toggle the current camera when the user double-clicks.\nfunction doubleClicked() {\n if (isDefaultCamera === true) {\n setCamera(cam2);\n isDefaultCamera = false;\n } else {\n setCamera(cam1);\n isDefaultCamera = true;\n }\n}\n
\nRotates the camera left and right.
\nPanning rotates the camera without changing its position. The rotation\nhappens in the camera’s \"local\" space.
\nThe parameter, angle
, is the angle the camera should rotate. Passing a\npositive angle, as in myCamera.pan(0.001)
, rotates the camera to the\nright. Passing a negative angle, as in myCamera.pan(-0.001)
, rotates the\ncamera to the left.
Note: Angles are interpreted based on the current\nangleMode().
\n"],"line":[0,2542],"params":[1,[[0,{"name":[0,"angle"],"description":[0,"amount to rotate in the current\n angleMode().
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Camera"],"chainable":[0,false],"example":[1,[[0,"\n\nlet cam;\nlet delta = 0.001;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Camera object.\n cam = createCamera();\n\n // Place the camera at the top-center.\n cam.setPosition(0, -400, 800);\n\n // Point the camera at the origin.\n cam.lookAt(0, 0, 0);\n\n describe(\n 'A white cube on a gray background. The cube goes in and out of view as the camera pans left and right.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Pan with the camera.\n cam.pan(delta);\n\n // Switch directions every 120 frames.\n if (frameCount % 120 === 0) {\n delta *= -1;\n }\n\n // Draw the box.\n box();\n}\n
\nSets a perspective projection for the camera.
\nIn a perspective projection, shapes that are further from the camera appear\nsmaller than shapes that are near the camera. This technique, called\nforeshortening, creates realistic 3D scenes. It’s applied by default in new\np5.Camera
objects.
myCamera.perspective()
changes the camera’s perspective by changing its\nviewing frustum. The frustum is the volume of space that’s visible to the\ncamera. The frustum’s shape is a pyramid with its top cut off. The camera\nis placed where the top of the pyramid should be and points towards the\nbase of the pyramid. It views everything within the frustum.
The first parameter, fovy
, is the camera’s vertical field of view. It’s\nan angle that describes how tall or narrow a view the camera has. For\nexample, calling myCamera.perspective(0.5)
sets the camera’s vertical\nfield of view to 0.5 radians. By default, fovy
is calculated based on the\nsketch’s height and the camera’s default z-coordinate, which is 800. The\nformula for the default fovy
is 2 * atan(height / 2 / 800)
.
The second parameter, aspect
, is the camera’s aspect ratio. It’s a number\nthat describes the ratio of the top plane’s width to its height. For\nexample, calling myCamera.perspective(0.5, 1.5)
sets the camera’s field\nof view to 0.5 radians and aspect ratio to 1.5, which would make shapes\nappear thinner on a square canvas. By default, aspect
is set to\nwidth / height
.
The third parameter, near
, is the distance from the camera to the near\nplane. For example, calling myCamera.perspective(0.5, 1.5, 100)
sets the\ncamera’s field of view to 0.5 radians, its aspect ratio to 1.5, and places\nthe near plane 100 pixels from the camera. Any shapes drawn less than 100\npixels from the camera won’t be visible. By default, near
is set to\n0.1 * 800
, which is 1/10th the default distance between the camera and\nthe origin.
The fourth parameter, far
, is the distance from the camera to the far\nplane. For example, calling myCamera.perspective(0.5, 1.5, 100, 10000)
\nsets the camera’s field of view to 0.5 radians, its aspect ratio to 1.5,\nplaces the near plane 100 pixels from the camera, and places the far plane\n10,000 pixels from the camera. Any shapes drawn more than 10,000 pixels\nfrom the camera won’t be visible. By default, far
is set to 10 * 800
,\nwhich is 10 times the default distance between the camera and the origin.
camera frustum vertical field of view. Defaults to\n 2 * atan(height / 2 / 800)
.
camera frustum aspect ratio. Defaults to\n width / height
.
distance from the camera to the near clipping plane.\n Defaults to 0.1 * 800
.
distance from the camera to the far clipping plane.\n Defaults to 10 * 800
.
\n// Double-click to toggle between cameras.\n\nlet cam1;\nlet cam2;\nlet isDefaultCamera = true;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create the first camera.\n // Keep its default settings.\n cam1 = createCamera();\n\n // Create the second camera.\n cam2 = createCamera();\n\n // Place it at the top-right.\n cam2.camera(400, -400, 800);\n\n // Set its fovy to 0.2.\n // Set its aspect to 1.5.\n // Set its near to 600.\n // Set its far to 1200.\n cam2.perspective(0.2, 1.5, 600, 1200);\n\n // Set the current camera to cam1.\n setCamera(cam1);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw the box.\n box();\n}\n\n// Toggle the current camera when the user double-clicks.\nfunction doubleClicked() {\n if (isDefaultCamera === true) {\n setCamera(cam2);\n isDefaultCamera = false;\n } else {\n setCamera(cam1);\n isDefaultCamera = true;\n }\n}\n
\n\n// Double-click to toggle between cameras.\n\nlet cam1;\nlet cam2;\nlet isDefaultCamera = true;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create the first camera.\n // Keep its default settings.\n cam1 = createCamera();\n\n // Create the second camera.\n cam2 = createCamera();\n\n // Place it at the top-right.\n cam2.camera(400, -400, 800);\n\n // Set its fovy to 0.2.\n // Set its aspect to 1.5.\n // Set its near to 600.\n // Set its far to 1200.\n cam2.perspective(0.2, 1.5, 600, 1200);\n\n // Set the current camera to cam1.\n setCamera(cam1);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin left and right.\n let x = 100 * sin(frameCount * 0.01);\n translate(x, 0, 0);\n\n // Draw the box.\n box();\n}\n\n// Toggle the current camera when the user double-clicks.\nfunction doubleClicked() {\n if (isDefaultCamera === true) {\n setCamera(cam2);\n isDefaultCamera = false;\n } else {\n setCamera(cam1);\n isDefaultCamera = true;\n }\n}\n
\nRotates the camera in a clockwise/counter-clockwise direction.
\nRolling rotates the camera without changing its orientation. The rotation\nhappens in the camera’s \"local\" space.
\nThe parameter, angle
, is the angle the camera should rotate. Passing a\npositive angle, as in myCamera.roll(0.001)
, rotates the camera in counter-clockwise direction.\nPassing a negative angle, as in myCamera.roll(-0.001)
, rotates the\ncamera in clockwise direction.
Note: Angles are interpreted based on the current\nangleMode().
\n"],"line":[0,2464],"params":[1,[[0,{"name":[0,"angle"],"description":[0,"amount to rotate camera in current\nangleMode units.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Camera"],"chainable":[0,false],"example":[1,[[0,"\n\nlet cam;\nlet delta = 0.01;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n // Create a p5.Camera object.\n cam = createCamera();\n}\n\nfunction draw() {\n background(200);\n\n // Roll camera according to angle 'delta'\n cam.roll(delta);\n\n translate(0, 0, 0);\n box(20);\n translate(0, 25, 0);\n box(20);\n translate(0, 26, 0);\n box(20);\n translate(0, 27, 0);\n box(20);\n translate(0, 28, 0);\n box(20);\n translate(0,29, 0);\n box(20);\n translate(0, 30, 0);\n box(20);\n}\n
\nSets the camera’s position, orientation, and projection by copying another\ncamera.
\nThe parameter, cam
, is the p5.Camera
object to copy. For example, calling\ncam2.set(cam1)
will set cam2
using cam1
’s configuration.
camera to copy.
\n"],"type":[0,"p5.Camera"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Camera"],"chainable":[0,false],"example":[1,[[0,"\n\n// Double-click to \"reset\" the camera zoom.\n\nlet cam1;\nlet cam2;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create the first camera.\n cam1 = createCamera();\n\n // Place the camera at the top-right.\n cam1.setPosition(400, -400, 800);\n\n // Point it at the origin.\n cam1.lookAt(0, 0, 0);\n\n // Create the second camera.\n cam2 = createCamera();\n\n // Copy cam1's configuration.\n cam2.set(cam1);\n\n describe(\n 'A white cube drawn against a gray background. The camera slowly moves forward. The camera resets when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Update cam2's position.\n cam2.move(0, 0, -1);\n\n // Draw the box.\n box();\n}\n\n// \"Reset\" the camera when the user double-clicks.\nfunction doubleClicked() {\n cam2.set(cam1);\n}"]]],"isConstructor":[0,false],"path":[0,"p5.Camera/set"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Camera/setPosition.mdx"],"slug":[0,"en/p5camera/setposition"],"body":[0,"\n\n# setPosition\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"setPosition()"],"module":[0,"3D"],"submodule":[0,"Camera"],"file":[0,"src/webgl/p5.Camera.js"],"description":[0,"Sets the camera’s position in \"world\" space without changing its\norientation.
\nThe parameters, x
, y
, and z
, are the coordinates where the camera\nshould be placed. For example, calling myCamera.setPosition(10, 20, 30)
\nplaces the camera at coordinates (10, 20, 30)
in \"world\" space.
\n"],"line":[0,3090],"params":[1,[[0,{"name":[0,"x"],"description":[0,"x-coordinate in \"world\" space.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"y-coordinate in \"world\" space.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,"z-coordinate in \"world\" space.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Camera"],"chainable":[0,false],"example":[1,[[0,"\n\n\n// Double-click to toggle between cameras.\n\nlet cam1;\nlet cam2;\nlet isDefaultCamera = true;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create the first camera.\n // Keep its default settings.\n cam1 = createCamera();\n\n // Create the second camera.\n cam2 = createCamera();\n\n // Place it closer to the origin.\n cam2.setPosition(0, 0, 600);\n\n // Set the current camera to cam1.\n setCamera(cam1);\n\n describe(\n 'A row of white cubes against a gray background. The camera toggles the amount of zoom when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin toward the camera.\n translate(-10, 10, 500);\n\n // Rotate the coordinate system.\n rotateY(-0.1);\n rotateX(-0.1);\n\n // Draw the row of boxes.\n for (let i = 0; i < 6; i += 1) {\n translate(0, 0, -30);\n box(10);\n }\n}\n\n// Toggle the current camera when the user double-clicks.\nfunction doubleClicked() {\n if (isDefaultCamera === true) {\n setCamera(cam2);\n isDefaultCamera = false;\n } else {\n setCamera(cam1);\n isDefaultCamera = true;\n }\n}\n
\n\n\n\n\n// Double-click to toggle between cameras.\n\nlet cam1;\nlet cam2;\nlet isDefaultCamera = true;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create the first camera.\n // Keep its default settings.\n cam1 = createCamera();\n\n // Create the second camera.\n cam2 = createCamera();\n\n // Place it closer to the origin.\n cam2.setPosition(0, 0, 600);\n\n // Set the current camera to cam1.\n setCamera(cam1);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Update cam2's z-coordinate.\n let z = 100 * sin(frameCount * 0.01) + 700;\n cam2.setPosition(0, 0, z);\n\n // Translate the origin toward the camera.\n translate(-10, 10, 500);\n\n // Rotate the coordinate system.\n rotateY(-0.1);\n rotateX(-0.1);\n\n // Draw the row of boxes.\n for (let i = 0; i < 6; i += 1) {\n translate(0, 0, -30);\n box(10);\n }\n}\n\n// Toggle the current camera when the user double-clicks.\nfunction doubleClicked() {\n if (isDefaultCamera === true) {\n setCamera(cam2);\n isDefaultCamera = false;\n } else {\n setCamera(cam1);\n isDefaultCamera = true;\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Camera/setPosition"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Camera/slerp.mdx"],"slug":[0,"en/p5camera/slerp"],"body":[0,"\n\n# slerp\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"slerp()"],"module":[0,"3D"],"submodule":[0,"Camera"],"file":[0,"src/webgl/p5.Camera.js"],"description":[0,"Sets the camera’s position and orientation to values that are in-between\nthose of two other cameras.
\nmyCamera.slerp()
uses spherical linear interpolation to calculate a\nposition and orientation that’s in-between two other cameras. Doing so is\nhelpful for transitioning smoothly between two perspectives.
\nThe first two parameters, cam0
and cam1
, are the p5.Camera
objects\nthat should be used to set the current camera.
\nThe third parameter, amt
, is the amount to interpolate between cam0
and\ncam1
. 0.0 keeps the camera’s position and orientation equal to cam0
’s,\n0.5 sets them halfway between cam0
’s and cam1
’s , and 1.0 sets the\nposition and orientation equal to cam1
’s.
\nFor example, calling myCamera.slerp(cam0, cam1, 0.1)
sets cam’s position\nand orientation very close to cam0
’s. Calling\nmyCamera.slerp(cam0, cam1, 0.9)
sets cam’s position and orientation very\nclose to cam1
’s.
\nNote: All of the cameras must use the same projection.
\n"],"line":[0,3321],"params":[1,[[0,{"name":[0,"cam0"],"description":[0,"first camera.
\n"],"type":[0,"p5.Camera"]}],[0,{"name":[0,"cam1"],"description":[0,"second camera.
\n"],"type":[0,"p5.Camera"]}],[0,{"name":[0,"amt"],"description":[0,"amount of interpolation between 0.0 (cam0
) and 1.0 (cam1
).
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Camera"],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet cam;\nlet cam0;\nlet cam1;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create the main camera.\n // Keep its default settings.\n cam = createCamera();\n\n // Create the first camera.\n // Keep its default settings.\n cam0 = createCamera();\n\n // Create the second camera.\n cam1 = createCamera();\n\n // Place it at the top-right.\n cam1.setPosition(400, -400, 800);\n\n // Point it at the origin.\n cam1.lookAt(0, 0, 0);\n\n // Set the current camera to cam.\n setCamera(cam);\n\n describe('A white cube drawn against a gray background. The camera slowly oscillates between a frontal view and an aerial view.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the amount to interpolate between cam0 and cam1.\n let amt = 0.5 * sin(frameCount * 0.01) + 0.5;\n\n // Update the main camera's position and orientation.\n cam.slerp(cam0, cam1, amt);\n\n box();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Camera/slerp"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Camera/tilt.mdx"],"slug":[0,"en/p5camera/tilt"],"body":[0,"\n\n# tilt\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"tilt()"],"module":[0,"3D"],"submodule":[0,"Camera"],"file":[0,"src/webgl/p5.Camera.js"],"description":[0,"Rotates the camera up and down.
\nTilting rotates the camera without changing its position. The rotation\nhappens in the camera’s \"local\" space.
\nThe parameter, angle
, is the angle the camera should rotate. Passing a\npositive angle, as in myCamera.tilt(0.001)
, rotates the camera down.\nPassing a negative angle, as in myCamera.tilt(-0.001)
, rotates the camera\nup.
\nNote: Angles are interpreted based on the current\nangleMode().
\n"],"line":[0,2605],"params":[1,[[0,{"name":[0,"angle"],"description":[0,"amount to rotate in the current\n angleMode().
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Camera"],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet cam;\nlet delta = 0.001;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Camera object.\n cam = createCamera();\n\n // Place the camera at the top-center.\n cam.setPosition(0, -400, 800);\n\n // Point the camera at the origin.\n cam.lookAt(0, 0, 0);\n\n describe(\n 'A white cube on a gray background. The cube goes in and out of view as the camera tilts up and down.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Pan with the camera.\n cam.tilt(delta);\n\n // Switch directions every 120 frames.\n if (frameCount % 120 === 0) {\n delta *= -1;\n }\n\n // Draw the box.\n box();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Camera/tilt"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Camera/upX.mdx"],"slug":[0,"en/p5camera/upx"],"body":[0,"\n\n# upX\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"upX"],"module":[0,"3D"],"submodule":[0,"Camera"],"file":[0,"src/webgl/p5.Camera.js"],"description":[0,"The x-component of the camera's \"up\" vector.
\nThe camera's \"up\" vector orients its y-axis. By default, the \"up\" vector is\n(0, 1, 0)
, so its x-component is 0 in \"local\" space.
\n"],"line":[0,1526],"itemtype":[0,"property"],"class":[0,"p5.Camera"],"example":[1,[[0,"\n\n\nlet cam;\nlet font;\n\n// Load a font and create a p5.Font object.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Camera object.\n cam = createCamera();\n\n // Place the camera at the top-right: (100, -400, 800)\n // Point it at the origin: (0, 0, 0)\n // Set its \"up\" vector: (0, 1, 0).\n cam.camera(100, -400, 800, 0, 0, 0, 0, 1, 0);\n\n describe(\n 'A white cube on a gray background. The text \"upX: 0\" is written in black beneath it.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the box.\n fill(255);\n\n // Draw the box.\n box();\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Display the value of upX, rounded to the nearest tenth.\n text(`upX: ${round(cam.upX, 1)}`, 0, 55);\n}\n
\n\n\n\n\nlet cam;\nlet font;\n\n// Load a font and create a p5.Font object.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Camera object.\n cam = createCamera();\n\n // Place the camera at the top-right: (100, -400, 800)\n // Point it at the origin: (0, 0, 0)\n // Set its \"up\" vector: (0, 1, 0).\n cam.camera(100, -400, 800, 0, 0, 0, 0, 1, 0);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the box.\n fill(255);\n\n // Draw the box.\n box();\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Calculate the x-component.\n let x = sin(frameCount * 0.01);\n\n // Update the camera's \"up\" vector.\n cam.camera(100, -400, 800, 0, 0, 0, x, 1, 0);\n\n // Display the value of upX, rounded to the nearest tenth.\n text(`upX: ${round(cam.upX, 1)}`, 0, 55);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Camera/upX"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Camera/upY.mdx"],"slug":[0,"en/p5camera/upy"],"body":[0,"\n\n# upY\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"upY"],"module":[0,"3D"],"submodule":[0,"Camera"],"file":[0,"src/webgl/p5.Camera.js"],"description":[0,"The y-component of the camera's \"up\" vector.
\nThe camera's \"up\" vector orients its y-axis. By default, the \"up\" vector is\n(0, 1, 0)
, so its y-component is 1 in \"local\" space.
\n"],"line":[0,1637],"itemtype":[0,"property"],"class":[0,"p5.Camera"],"example":[1,[[0,"\n\n\nlet cam;\nlet font;\n\n// Load a font and create a p5.Font object.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Camera object.\n cam = createCamera();\n\n // Place the camera at the top-right: (100, -400, 800)\n // Point it at the origin: (0, 0, 0)\n // Set its \"up\" vector: (0, 1, 0).\n cam.camera(100, -400, 800, 0, 0, 0, 0, 1, 0);\n\n describe(\n 'A white cube on a gray background. The text \"upY: 1\" is written in black beneath it.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the box.\n fill(255);\n\n // Draw the box.\n box();\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Display the value of upY, rounded to the nearest tenth.\n text(`upY: ${round(cam.upY, 1)}`, 0, 55);\n}\n
\n\n\n\n\nlet cam;\nlet font;\n\n// Load a font and create a p5.Font object.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Camera object.\n cam = createCamera();\n\n // Place the camera at the top-right: (100, -400, 800)\n // Point it at the origin: (0, 0, 0)\n // Set its \"up\" vector: (0, 1, 0).\n cam.camera(100, -400, 800, 0, 0, 0, 0, 1, 0);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the box.\n fill(255);\n\n // Draw the box.\n box();\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Calculate the y-component.\n let y = sin(frameCount * 0.01);\n\n // Update the camera's \"up\" vector.\n cam.camera(100, -400, 800, 0, 0, 0, 0, y, 0);\n\n // Display the value of upY, rounded to the nearest tenth.\n text(`upY: ${round(cam.upY, 1)}`, 0, 55);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Camera/upY"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Camera/upZ.mdx"],"slug":[0,"en/p5camera/upz"],"body":[0,"\n\n# upZ\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"upZ"],"module":[0,"3D"],"submodule":[0,"Camera"],"file":[0,"src/webgl/p5.Camera.js"],"description":[0,"The z-component of the camera's \"up\" vector.
\nThe camera's \"up\" vector orients its y-axis. By default, the \"up\" vector is\n(0, 1, 0)
, so its z-component is 0 in \"local\" space.
\n"],"line":[0,1748],"itemtype":[0,"property"],"class":[0,"p5.Camera"],"example":[1,[[0,"\n\n\nlet cam;\nlet font;\n\n// Load a font and create a p5.Font object.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Camera object.\n cam = createCamera();\n\n // Place the camera at the top-right: (100, -400, 800)\n // Point it at the origin: (0, 0, 0)\n // Set its \"up\" vector: (0, 1, 0).\n cam.camera(100, -400, 800, 0, 0, 0, 0, 1, 0);\n\n describe(\n 'A white cube on a gray background. The text \"upZ: 0\" is written in black beneath it.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the box.\n fill(255);\n\n // Draw the box.\n box();\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Display the value of upZ, rounded to the nearest tenth.\n text(`upZ: ${round(cam.upZ, 1)}`, 0, 55);\n}\n
\n\n\n\n\nlet cam;\nlet font;\n\n// Load a font and create a p5.Font object.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Camera object.\n cam = createCamera();\n\n // Place the camera at the top-right: (100, -400, 800)\n // Point it at the origin: (0, 0, 0)\n // Set its \"up\" vector: (0, 1, 0).\n cam.camera(100, -400, 800, 0, 0, 0, 0, 1, 0);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the box.\n fill(255);\n\n // Draw the box.\n box();\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Calculate the z-component.\n let z = sin(frameCount * 0.01);\n\n // Update the camera's \"up\" vector.\n cam.camera(100, -400, 800, 0, 0, 0, 0, 1, z);\n\n // Display the value of upZ, rounded to the nearest tenth.\n text(`upZ: ${round(cam.upZ, 1)}`, 0, 55);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Camera/upZ"]}],"render":[0,null]}]]]}],[0,{"name":[0,"p5.Shader"],"entry":[0,{"id":[0,"en/p5/p5.Shader.mdx"],"slug":[0,"en/p5/p5shader"],"body":[0,"\n\n# p5.Shader\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"p5.Shader"],"module":[0,"3D"],"submodule":[0,"Material"],"file":[0,"src/webgl/p5.Shader.js"],"description":[0,"A class to describe a shader program.
\nEach p5.Shader
object contains a shader program that runs on the graphics\nprocessing unit (GPU). Shaders can process many pixels or vertices at the\nsame time, making them fast for many graphics tasks. They’re written in a\nlanguage called\nGLSL\nand run along with the rest of the code in a sketch.
\nA shader program consists of two files, a vertex shader and a fragment\nshader. The vertex shader affects where 3D geometry is drawn on the screen\nand the fragment shader affects color. Once the p5.Shader
object is\ncreated, it can be used with the shader()\nfunction, as in shader(myShader)
.
\nA shader can optionally describe hooks, which are functions in GLSL that\nusers may choose to provide to customize the behavior of the shader. For the\nvertex or the fragment shader, users can pass in an object where each key is\nthe type and name of a hook function, and each value is a string with the\nparameter list and default implementation of the hook. For example, to let users\noptionally run code at the start of the vertex shader, the options object could\ninclude:
\n{\n vertex: {\n 'void beforeVertex': '() {}'\n }\n}\n
\nThen, in your vertex shader source, you can run a hook by calling a function\nwith the same name prefixed by HOOK_
:
\nvoid main() {\n HOOK_beforeVertex();\n // Add the rest of your shader code here!\n}\n
\nNote: createShader(),\ncreateFilterShader(), and\nloadShader() are the recommended ways to\ncreate an instance of this class.
\n"],"line":[0,11],"params":[1,[[0,{"name":[0,"renderer"],"description":[0,"WebGL context for this shader.
\n"],"type":[0,"p5.RendererGL"]}],[0,{"name":[0,"vertSrc"],"description":[0,"source code for the vertex shader program.
\n"],"type":[0,"String"]}],[0,{"name":[0,"fragSrc"],"description":[0,"source code for the fragment shader program.
\n"],"type":[0,"String"]}],[0,{"name":[0,"options"],"description":[0,"An optional object describing how this shader can\nbe augmented with hooks. It can include:
\n\nvertex
: An object describing the available vertex shader hooks. \nfragment
: An object describing the available frament shader hooks. \n
\n"],"type":[0,"Object"],"optional":[0,true]}]]],"chainable":[0,false],"example":[1,[[0,"\n\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision highp float;\n\nvoid main() {\n // Set each pixel's RGBA value to yellow.\n gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0);\n}\n`;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Shader object.\n let myShader = createShader(vertSrc, fragSrc);\n\n // Apply the p5.Shader object.\n shader(myShader);\n\n // Style the drawing surface.\n noStroke();\n\n // Add a plane as a drawing surface.\n plane(100, 100);\n\n describe('A yellow square.');\n}\n
\n\n\n\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\nlet mandelbrot;\n\n// Load the shader and create a p5.Shader object.\nfunction preload() {\n mandelbrot = loadShader('/assets/shader.vert', '/assets/shader.frag');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Use the p5.Shader object.\n shader(mandelbrot);\n\n // Set the shader uniform p to an array.\n mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]);\n\n describe('A fractal image zooms in and out of focus.');\n}\n\nfunction draw() {\n // Set the shader uniform r to a value that oscillates between 0 and 2.\n mandelbrot.setUniform('r', sin(frameCount * 0.01) + 1);\n\n // Add a quad as a display surface for the shader.\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n
\n"]]],"methods":[0,{"inspectHooks":[0,{"description":[0,"Logs the hooks available in this shader, and their current implementation.
\nEach shader may let you override bits of its behavior. Each bit is called\na hook. A hook is either for the vertex shader, if it affects the\nposition of vertices, or in the fragment shader, if it affects the pixel\ncolor. This method logs those values to the console, letting you know what\nyou are able to use in a call to\nmodify()
.
\nFor example, this shader will produce the following output:
\nmyShader = baseMaterialShader().modify({\n declarations: 'uniform float time;',\n 'vec3 getWorldPosition': `(vec3 pos) {\n pos.y += 20. * sin(time * 0.001 + pos.x * 0.05);\n return pos;\n }`\n});\nmyShader.inspectHooks();\n
\n==== Vertex shader hooks: ====\nvoid beforeVertex() {}\nvec3 getLocalPosition(vec3 position) { return position; }\n[MODIFIED] vec3 getWorldPosition(vec3 pos) {\n pos.y += 20. * sin(time * 0.001 + pos.x * 0.05);\n return pos;\n }\nvec3 getLocalNormal(vec3 normal) { return normal; }\nvec3 getWorldNormal(vec3 normal) { return normal; }\nvec2 getUV(vec2 uv) { return uv; }\nvec4 getVertexColor(vec4 color) { return color; }\nvoid afterVertex() {}\n\n==== Fragment shader hooks: ====\nvoid beforeFragment() {}\nInputs getPixelInputs(Inputs inputs) { return inputs; }\nvec4 combineColors(ColorComponents components) {\n vec4 color = vec4(0.);\n color.rgb += components.diffuse * components.baseColor;\n color.rgb += components.ambient * components.ambientColor;\n color.rgb += components.specular * components.specularColor;\n color.rgb += components.emissive;\n color.a = components.opacity;\n return color;\n }\nvec4 getFinalColor(vec4 color) { return color; }\nvoid afterFragment() {}\n
\n"],"path":[0,"p5.Shader/inspectHooks"]}],"modify":[0,{"description":[0,"Returns a new shader, based on the original, but with custom snippets\nof shader code replacing default behaviour.
\nEach shader may let you override bits of its behavior. Each bit is called\na hook. A hook is either for the vertex shader, if it affects the\nposition of vertices, or in the fragment shader, if it affects the pixel\ncolor. You can inspect the different hooks available by calling\nyourShader.inspectHooks()
. You can\nalso read the reference for the default material, normal material, color, line, and point shaders to\nsee what hooks they have available.
\nmodify()
takes one parameter, hooks
, an object with the hooks you want\nto override. Each key of the hooks
object is the name\nof a hook, and the value is a string with the GLSL code for your hook.
\nIf you supply functions that aren't existing hooks, they will get added at the start of\nthe shader as helper functions so that you can use them in your hooks.
\nTo add new uniforms to your shader, you can pass in a uniforms
object containing\nthe type and name of the uniform as the key, and a default value or function returning\na default value as its value. These will be automatically set when the shader is set\nwith shader(yourShader)
.
\nYou can also add a declarations
key, where the value is a GLSL string declaring\ncustom uniform variables, globals, and functions shared\nbetween hooks. To add declarations just in a vertex or fragment shader, add\nvertexDeclarations
and fragmentDeclarations
keys.
\n"],"path":[0,"p5.Shader/modify"]}],"copyToContext":[0,{"description":[0,"Copies the shader from one drawing context to another.
\nEach p5.Shader
object must be compiled by calling\nshader() before it can run. Compilation happens\nin a drawing context which is usually the main canvas or an instance of\np5.Graphics. A shader can only be used in the\ncontext where it was compiled. The copyToContext()
method compiles the\nshader again and copies it to another drawing context where it can be\nreused.
\nThe parameter, context
, is the drawing context where the shader will be\nused. The shader can be copied to an instance of\np5.Graphics, as in\nmyShader.copyToContext(pg)
. The shader can also be copied from a\np5.Graphics object to the main canvas using\nthe window
variable, as in myShader.copyToContext(window)
.
\nNote: A p5.Shader object created with\ncreateShader(),\ncreateFilterShader(), or\nloadShader()\ncan be used directly with a p5.Framebuffer\nobject created with\ncreateFramebuffer(). Both objects\nhave the same context as the main canvas.
\n"],"path":[0,"p5.Shader/copyToContext"]}],"setUniform":[0,{"description":[0,"Sets the shader’s uniform (global) variables.
\nShader programs run on the computer’s graphics processing unit (GPU).\nThey live in part of the computer’s memory that’s completely separate\nfrom the sketch that runs them. Uniforms are global variables within a\nshader program. They provide a way to pass values from a sketch running\non the CPU to a shader program running on the GPU.
\nThe first parameter, uniformName
, is a string with the uniform’s name.\nFor the shader above, uniformName
would be 'r'
.
\nThe second parameter, data
, is the value that should be used to set the\nuniform. For example, calling myShader.setUniform('r', 0.5)
would set\nthe r
uniform in the shader above to 0.5
. data should match the\nuniform’s type. Numbers, strings, booleans, arrays, and many types of\nimages can all be passed to a shader with setUniform()
.
\n"],"path":[0,"p5.Shader/setUniform"]}]}],"isConstructor":[0,true],"path":[0,"p5/p5.Shader"]}],"render":[0,null]}],"entries":[1,[[0,{"id":[0,"en/p5.Shader/copyToContext.mdx"],"slug":[0,"en/p5shader/copytocontext"],"body":[0,"\n\n# copyToContext\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"copyToContext()"],"module":[0,"3D"],"submodule":[0,"Material"],"file":[0,"src/webgl/p5.Shader.js"],"description":[0,"Copies the shader from one drawing context to another.
\nEach p5.Shader
object must be compiled by calling\nshader() before it can run. Compilation happens\nin a drawing context which is usually the main canvas or an instance of\np5.Graphics. A shader can only be used in the\ncontext where it was compiled. The copyToContext()
method compiles the\nshader again and copies it to another drawing context where it can be\nreused.
\nThe parameter, context
, is the drawing context where the shader will be\nused. The shader can be copied to an instance of\np5.Graphics, as in\nmyShader.copyToContext(pg)
. The shader can also be copied from a\np5.Graphics object to the main canvas using\nthe window
variable, as in myShader.copyToContext(window)
.
\nNote: A p5.Shader object created with\ncreateShader(),\ncreateFilterShader(), or\nloadShader()\ncan be used directly with a p5.Framebuffer\nobject created with\ncreateFramebuffer(). Both objects\nhave the same context as the main canvas.
\n"],"line":[0,574],"params":[1,[[0,{"name":[0,"context"],"description":[0,"WebGL context for the copied shader.
\n"],"type":[0,"p5|p5.Graphics"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Shader"],"chainable":[0,false],"return":[0,{"description":[0,"new shader compiled for the target context."],"type":[0,"p5.Shader"]}],"example":[1,[[0,"\n\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision mediump float;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vec2 uv = vTexCoord;\n vec3 color = vec3(uv.x, uv.y, min(uv.x + uv.y, 1.0));\n gl_FragColor = vec4(color, 1.0);\\\n}\n`;\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n // Create a p5.Shader object.\n let original = createShader(vertSrc, fragSrc);\n\n // Compile the p5.Shader object.\n shader(original);\n\n // Create a p5.Graphics object.\n pg = createGraphics(50, 50, WEBGL);\n\n // Copy the original shader to the p5.Graphics object.\n let copied = original.copyToContext(pg);\n\n // Apply the copied shader to the p5.Graphics object.\n pg.shader(copied);\n\n // Style the display surface.\n pg.noStroke();\n\n // Add a display surface for the shader.\n pg.plane(50, 50);\n\n describe('A square with purple-blue gradient on its surface drawn against a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw the p5.Graphics object to the main canvas.\n image(pg, -25, -25);\n}\n
\n\n\n\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision mediump float;\n\nvarying vec2 vTexCoord;\n\nvoid main() {\n vec2 uv = vTexCoord;\n vec3 color = vec3(uv.x, uv.y, min(uv.x + uv.y, 1.0));\n gl_FragColor = vec4(color, 1.0);\n}\n`;\n\nlet copied;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Graphics object.\n let pg = createGraphics(25, 25, WEBGL);\n\n // Create a p5.Shader object.\n let original = pg.createShader(vertSrc, fragSrc);\n\n // Compile the p5.Shader object.\n pg.shader(original);\n\n // Copy the original shader to the main canvas.\n copied = original.copyToContext(window);\n\n // Apply the copied shader to the main canvas.\n shader(copied);\n\n describe('A rotating cube with a purple-blue gradient on its surface drawn against a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Rotate around the x-, y-, and z-axes.\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n rotateZ(frameCount * 0.01);\n\n // Draw the box.\n box(50);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Shader/copyToContext"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Shader/inspectHooks.mdx"],"slug":[0,"en/p5shader/inspecthooks"],"body":[0,"\n\n# inspectHooks\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"inspectHooks()"],"module":[0,"3D"],"submodule":[0,"Material"],"file":[0,"src/webgl/p5.Shader.js"],"description":[0,"Logs the hooks available in this shader, and their current implementation.
\nEach shader may let you override bits of its behavior. Each bit is called\na hook. A hook is either for the vertex shader, if it affects the\nposition of vertices, or in the fragment shader, if it affects the pixel\ncolor. This method logs those values to the console, letting you know what\nyou are able to use in a call to\nmodify()
.
\nFor example, this shader will produce the following output:
\nmyShader = baseMaterialShader().modify({\n declarations: 'uniform float time;',\n 'vec3 getWorldPosition': `(vec3 pos) {\n pos.y += 20. * sin(time * 0.001 + pos.x * 0.05);\n return pos;\n }`\n});\nmyShader.inspectHooks();\n
\n==== Vertex shader hooks: ====\nvoid beforeVertex() {}\nvec3 getLocalPosition(vec3 position) { return position; }\n[MODIFIED] vec3 getWorldPosition(vec3 pos) {\n pos.y += 20. * sin(time * 0.001 + pos.x * 0.05);\n return pos;\n }\nvec3 getLocalNormal(vec3 normal) { return normal; }\nvec3 getWorldNormal(vec3 normal) { return normal; }\nvec2 getUV(vec2 uv) { return uv; }\nvec4 getVertexColor(vec4 color) { return color; }\nvoid afterVertex() {}\n\n==== Fragment shader hooks: ====\nvoid beforeFragment() {}\nInputs getPixelInputs(Inputs inputs) { return inputs; }\nvec4 combineColors(ColorComponents components) {\n vec4 color = vec4(0.);\n color.rgb += components.diffuse * components.baseColor;\n color.rgb += components.ambient * components.ambientColor;\n color.rgb += components.specular * components.specularColor;\n color.rgb += components.emissive;\n color.a = components.opacity;\n return color;\n }\nvec4 getFinalColor(vec4 color) { return color; }\nvoid afterFragment() {}\n
\n"],"line":[0,259],"itemtype":[0,"method"],"class":[0,"p5.Shader"],"chainable":[0,false],"beta":[0,true],"isConstructor":[0,false],"path":[0,"p5.Shader/inspectHooks"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Shader/modify.mdx"],"slug":[0,"en/p5shader/modify"],"body":[0,"\n\n# modify\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"modify()"],"module":[0,"3D"],"submodule":[0,"Material"],"file":[0,"src/webgl/p5.Shader.js"],"description":[0,"Returns a new shader, based on the original, but with custom snippets\nof shader code replacing default behaviour.
\nEach shader may let you override bits of its behavior. Each bit is called\na hook. A hook is either for the vertex shader, if it affects the\nposition of vertices, or in the fragment shader, if it affects the pixel\ncolor. You can inspect the different hooks available by calling\nyourShader.inspectHooks()
. You can\nalso read the reference for the default material, normal material, color, line, and point shaders to\nsee what hooks they have available.
\nmodify()
takes one parameter, hooks
, an object with the hooks you want\nto override. Each key of the hooks
object is the name\nof a hook, and the value is a string with the GLSL code for your hook.
\nIf you supply functions that aren't existing hooks, they will get added at the start of\nthe shader as helper functions so that you can use them in your hooks.
\nTo add new uniforms to your shader, you can pass in a uniforms
object containing\nthe type and name of the uniform as the key, and a default value or function returning\na default value as its value. These will be automatically set when the shader is set\nwith shader(yourShader)
.
\nYou can also add a declarations
key, where the value is a GLSL string declaring\ncustom uniform variables, globals, and functions shared\nbetween hooks. To add declarations just in a vertex or fragment shader, add\nvertexDeclarations
and fragmentDeclarations
keys.
\n"],"line":[0,340],"params":[1,[[0,{"name":[0,"hooks"],"description":[0,"The hooks in the shader to replace.
\n"],"type":[0,"Object"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Shader"],"chainable":[0,false],"beta":[0,true],"return":[0,{"description":[0,""],"type":[0,"p5.Shader"]}],"example":[1,[[0,"\n\n\nlet myShader;\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseMaterialShader().modify({\n uniforms: {\n 'float time': () => millis()\n },\n 'vec3 getWorldPosition': `(vec3 pos) {\n pos.y += 20. * sin(time * 0.001 + pos.x * 0.05);\n return pos;\n }`\n });\n}\n\nfunction draw() {\n background(255);\n shader(myShader);\n lights();\n noStroke();\n fill('red');\n sphere(50);\n}\n
\n"],[0,"\n\n\nlet myShader;\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseMaterialShader().modify({\n // Manually specifying a uniform\n declarations: 'uniform float time;',\n 'vec3 getWorldPosition': `(vec3 pos) {\n pos.y += 20. * sin(time * 0.001 + pos.x * 0.05);\n return pos;\n }`\n });\n}\n\nfunction draw() {\n background(255);\n shader(myShader);\n myShader.setUniform('time', millis());\n lights();\n noStroke();\n fill('red');\n sphere(50);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Shader/modify"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Shader/setUniform.mdx"],"slug":[0,"en/p5shader/setuniform"],"body":[0,"\n\n# setUniform\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"setUniform()"],"module":[0,"3D"],"submodule":[0,"Material"],"file":[0,"src/webgl/p5.Shader.js"],"description":[0,"Sets the shader’s uniform (global) variables.
\nShader programs run on the computer’s graphics processing unit (GPU).\nThey live in part of the computer’s memory that’s completely separate\nfrom the sketch that runs them. Uniforms are global variables within a\nshader program. They provide a way to pass values from a sketch running\non the CPU to a shader program running on the GPU.
\nThe first parameter, uniformName
, is a string with the uniform’s name.\nFor the shader above, uniformName
would be 'r'
.
\nThe second parameter, data
, is the value that should be used to set the\nuniform. For example, calling myShader.setUniform('r', 0.5)
would set\nthe r
uniform in the shader above to 0.5
. data should match the\nuniform’s type. Numbers, strings, booleans, arrays, and many types of\nimages can all be passed to a shader with setUniform()
.
\n"],"line":[0,990],"params":[1,[[0,{"name":[0,"uniformName"],"description":[0,"name of the uniform. Must match the name\n used in the vertex and fragment shaders.
\n"],"type":[0,"String"]}],[0,{"name":[0,"data"],"description":[0,"value to assign to the uniform. Must match the uniform’s data type.
\n"],"type":[0,"Boolean|Number|Number[]|p5.Image|p5.Graphics|p5.MediaElement|p5.Texture"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Shader"],"chainable":[0,true],"example":[1,[[0,"\n\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision mediump float;\n\nuniform float r;\n\nvoid main() {\n gl_FragColor = vec4(r, 1.0, 1.0, 1.0);\n}\n`;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Shader object.\n let myShader = createShader(vertSrc, fragSrc);\n\n // Apply the p5.Shader object.\n shader(myShader);\n\n // Set the r uniform to 0.5.\n myShader.setUniform('r', 0.5);\n\n // Style the drawing surface.\n noStroke();\n\n // Add a plane as a drawing surface for the shader.\n plane(100, 100);\n\n describe('A cyan square.');\n}\n
\n\n\n\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision mediump float;\n\nuniform float r;\n\nvoid main() {\n gl_FragColor = vec4(r, 1.0, 1.0, 1.0);\n}\n`;\n\nlet myShader;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Shader object.\n myShader = createShader(vertSrc, fragSrc);\n\n // Compile and apply the p5.Shader object.\n shader(myShader);\n\n describe('A square oscillates color between cyan and white.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the drawing surface.\n noStroke();\n\n // Update the r uniform.\n let nextR = 0.5 * (sin(frameCount * 0.01) + 1);\n myShader.setUniform('r', nextR);\n\n // Add a plane as a drawing surface.\n plane(100, 100);\n}\n
\n\n\n\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision highp float;\nuniform vec2 p;\nuniform float r;\nconst int numIterations = 500;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vec2 c = p + gl_FragCoord.xy * r;\n vec2 z = c;\n float n = 0.0;\n\n for (int i = numIterations; i > 0; i--) {\n if (z.x * z.x + z.y * z.y > 4.0) {\n n = float(i) / float(numIterations);\n break;\n }\n\n z = vec2(z.x * z.x - z.y * z.y, 2.0 * z.x * z.y) + c;\n }\n\n gl_FragColor = vec4(\n 0.5 - cos(n * 17.0) / 2.0,\n 0.5 - cos(n * 13.0) / 2.0,\n 0.5 - cos(n * 23.0) / 2.0,\n 1.0\n );\n}\n`;\n\nlet mandelbrot;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Shader object.\n mandelbrot = createShader(vertSrc, fragSrc);\n\n // Compile and apply the p5.Shader object.\n shader(mandelbrot);\n\n // Set the shader uniform p to an array.\n // p is the center point of the Mandelbrot image.\n mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]);\n\n describe('A fractal image zooms in and out of focus.');\n}\n\nfunction draw() {\n // Set the shader uniform r to a value that oscillates\n // between 0 and 0.005.\n // r is the size of the image in Mandelbrot-space.\n let radius = 0.005 * (sin(frameCount * 0.01) + 1);\n mandelbrot.setUniform('r', radius);\n\n // Style the drawing surface.\n noStroke();\n\n // Add a plane as a drawing surface.\n plane(100, 100);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Shader/setUniform"]}],"render":[0,null]}]]]}]]]}],[0,{"name":[0,"Rendering"],"subcats":[1,[[0,{"name":[0],"entry":[0],"entries":[1,[]]}],[0,{"name":[0],"entry":[0],"entries":[1,[[0,{"id":[0,"en/p5/blendMode.mdx"],"slug":[0,"en/p5/blendmode"],"body":[0,"\n\n# blendMode\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"blendMode()"],"module":[0,"Rendering"],"submodule":[0,"Rendering"],"file":[0,"src/core/rendering.js"],"description":[0,"Sets the way colors blend when added to the canvas.
\nBy default, drawing with a solid color paints over the current pixel values\non the canvas. blendMode()
offers many options for blending colors.
\nShapes, images, and text can be used as sources for drawing to the canvas.\nA source pixel changes the color of the canvas pixel where it's drawn. The\nfinal color results from blending the source pixel's color with the canvas\npixel's color. RGB color values from the source and canvas pixels are\ncompared, added, subtracted, multiplied, and divided to create different\neffects. Red values with red values, greens with greens, and blues with\nblues.
\nThe parameter, mode
, sets the blend mode. For example, calling\nblendMode(ADD)
sets the blend mode to ADD
. The following blend modes\nare available in both 2D and WebGL mode:
\n\nBLEND
: color values from the source overwrite the canvas. This is the default mode. \nADD
: color values from the source are added to values from the canvas. \nDARKEST
: keeps the darkest color value. \nLIGHTEST
: keeps the lightest color value. \nEXCLUSION
: similar to DIFFERENCE
but with less contrast. \nMULTIPLY
: color values from the source are multiplied with values from the canvas. The result is always darker. \nSCREEN
: all color values are inverted, then multiplied, then inverted again. The result is always lighter. (Opposite of MULTIPLY
) \nREPLACE
: the last source drawn completely replaces the rest of the canvas. \nREMOVE
: overlapping pixels are removed by making them completely transparent. \n
\nThe following blend modes are only available in 2D mode:
\n\nDIFFERENCE
: color values from the source are subtracted from the values from the canvas. If the difference is a negative number, it's made positive. \nOVERLAY
: combines MULTIPLY
and SCREEN
. Dark values in the canvas get darker and light values get lighter. \nHARD_LIGHT
: combines MULTIPLY
and SCREEN
. Dark values in the source get darker and light values get lighter. \nSOFT_LIGHT
: a softer version of HARD_LIGHT
. \nDODGE
: lightens light tones and increases contrast. Divides the canvas color values by the inverted color values from the source. \nBURN
: darkens dark tones and increases contrast. Divides the source color values by the inverted color values from the canvas, then inverts the result. \n
\nThe following blend modes are only available in WebGL mode:
\n\nSUBTRACT
: 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. \n
\n"],"line":[0,720],"params":[1,[[0,{"name":[0,"mode"],"description":[0,"blend mode to set.\n either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY,\n EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD, REMOVE or SUBTRACT
\n"],"type":[0,"Constant"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Use the default blend mode.\n blendMode(BLEND);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('A Sky Blue line and a Deep Rose line form an X on a gray background.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(HARD_LIGHT);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n 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.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(ADD);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('An icy blue line and a light lavender line form an X on a gray background. The area where they overlap is white.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(DARKEST);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('A steel blue line and a cranberry line form an X on a gray background. The area where they overlap is deep purple.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(BURN);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('A cobalt blue line and a burgundy line form an X on a gray background. The area where they overlap is black.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(LIGHTEST);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n 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.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(EXCLUSION);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n 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.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(MULTIPLY);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('A slate blue line and a plum line form an X on a gray background. The area where they overlap is dark Indigo.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(SCREEN);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n 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.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(REPLACE);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('A diagonal deep rose line.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(REMOVE);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('The silhouette of an X is missing from a gray background.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(DIFFERENCE);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n 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.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(OVERLAY);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('A cornflower blue line and a light rose line form an X on a gray background. The area where they overlap is violet.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(SOFT_LIGHT);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('A pale sky line and a rose blush line form an X on a gray background. The area where they overlap is lavender.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(DODGE);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('An aqua blue line and a light pink line form an X on a gray background. The area where they overlap is white.');\n}\n
\n\n\n\n\nfunction setup() {\n // Create a canvas with WEBGL mode.\n createCanvas(100, 100, WEBGL);\n\n // Set the background color.\n background(180);\n\n // Set the blend mode to SUBTRACT.\n blendMode(SUBTRACT);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the blue line.\n stroke('#1a85ff');\n line(-25, -25, 25, 25);\n\n // Draw the red line.\n stroke('#d41159');\n line(25, -25, -25, 25);\n\n describe('A burnt orange and a sea green line form an X on a gray background. The area where they overlap is forest green.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/blendMode"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/clearDepth.mdx"],"slug":[0,"en/p5/cleardepth"],"body":[0,"\n\n# clearDepth\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"clearDepth()"],"module":[0,"Rendering"],"submodule":[0,"Rendering"],"file":[0,"src/core/rendering.js"],"description":[0,"Clears the depth buffer in WebGL mode.
\nclearDepth()
clears information about how far objects are from the camera\nin 3D space. This information is stored in an object called the\ndepth buffer. Clearing the depth buffer ensures new objects aren't drawn\nbehind old ones. Doing so can be useful for feedback effects in which the\nprevious frame serves as the background for the current frame.
\nThe parameter, depth
, is optional. If a number is passed, as in\nclearDepth(0.5)
, it determines the range of objects to clear from the\ndepth buffer. 0 doesn't clear any depth information, 0.5 clears depth\ninformation halfway between the near and far clipping planes, and 1 clears\ndepth information all the way to the far clipping plane. By default,\ndepth
is 1.
\nNote: clearDepth()
can only be used in WebGL mode.
\n"],"line":[0,635],"params":[1,[[0,{"name":[0,"depth"],"description":[0,"amount of the depth buffer to clear between 0\n (none) and 1 (far clipping plane). Defaults to 1.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet previous;\nlet current;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create the p5.Framebuffer objects.\n previous = createFramebuffer({ format: FLOAT });\n current = createFramebuffer({ format: FLOAT });\n\n describe(\n 'A multicolor box drifts from side to side on a white background. It leaves a trail that fades over time.'\n );\n}\n\nfunction draw() {\n // Swap the previous p5.Framebuffer and the\n // current one so it can be used as a texture.\n [previous, current] = [current, previous];\n\n // Start drawing to the current p5.Framebuffer.\n current.begin();\n\n // Paint the background.\n background(255);\n\n // Draw the previous p5.Framebuffer.\n // Clear the depth buffer so the previous\n // frame doesn't block the current one.\n push();\n tint(255, 250);\n image(previous, -50, -50);\n clearDepth();\n pop();\n\n // Draw the box on top of the previous frame.\n push();\n let x = 25 * sin(frameCount * 0.01);\n let y = 25 * sin(frameCount * 0.02);\n translate(x, y, 0);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n normalMaterial();\n box(12);\n pop();\n\n // Stop drawing to the current p5.Framebuffer.\n current.end();\n\n // Display the current p5.Framebuffer.\n image(current, -50, -50);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/clearDepth"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/createCanvas.mdx"],"slug":[0,"en/p5/createcanvas"],"body":[0,"\n\n# createCanvas\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createCanvas()"],"module":[0,"Rendering"],"submodule":[0,"Rendering"],"file":[0,"src/core/rendering.js"],"description":[0,"Creates a canvas element on the web page.
\ncreateCanvas()
creates the main drawing canvas for a sketch. It should\nonly be called once at the beginning of setup().\nCalling createCanvas()
more than once causes unpredictable behavior.
\nThe first two parameters, width
and height
, are optional. They set the\ndimensions of the canvas and the values of the\nwidth and height system\nvariables. For example, calling createCanvas(900, 500)
creates a canvas\nthat's 900×500 pixels. By default, width
and height
are both 100.
\nThe third parameter is also optional. If either of the constants P2D
or\nWEBGL
is passed, as in createCanvas(900, 500, WEBGL)
, then it will set\nthe sketch's rendering mode. If an existing\nHTMLCanvasElement\nis passed, as in createCanvas(900, 500, myCanvas)
, then it will be used\nby the sketch.
\nThe fourth parameter is also optional. If an existing\nHTMLCanvasElement\nis passed, as in createCanvas(900, 500, WEBGL, myCanvas)
, then it will be\nused by the sketch.
\nNote: In WebGL mode, the canvas will use a WebGL2 context if it's supported\nby the browser. Check the webglVersion\nsystem variable to check what version is being used, or call\nsetAttributes({ version: 1 })
to create a WebGL1 context.
\n"],"line":[0,15],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"width"],"description":[0,"width of the canvas. Defaults to 100.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"height"],"description":[0,"height of the canvas. Defaults to 100.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"renderer"],"description":[0,"either P2D or WEBGL. Defaults to P2D
.
\n"],"type":[0,"Constant"],"optional":[0,true]}],[0,{"name":[0,"canvas"],"description":[0,"existing canvas element that should be used for the sketch.
\n"],"type":[0,"HTMLCanvasElement"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"width"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"height"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"canvas"],"description":[0,""],"type":[0,"HTMLCanvasElement"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new `p5.Renderer` that holds the canvas."],"type":[0,"p5.Renderer"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Draw a diagonal line.\n line(0, 0, width, height);\n\n describe('A diagonal line drawn from top-left to bottom-right on a gray background.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 50);\n\n background(180);\n\n // Draw a diagonal line.\n line(0, 0, width, height);\n\n describe('A diagonal line drawn from top-left to bottom-right on a gray background.');\n}\n
\n\n\n\n\n// Use WebGL mode.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(180);\n\n // Draw a diagonal line.\n line(-width / 2, -height / 2, width / 2, height / 2);\n\n describe('A diagonal line drawn from top-left to bottom-right on a gray background.');\n}\n
\n\n\n\n\nfunction setup() {\n // Create a p5.Render object.\n let cnv = createCanvas(50, 50);\n\n // Position the canvas.\n cnv.position(10, 20);\n\n background(180);\n\n // Draw a diagonal line.\n line(0, 0, width, height);\n\n describe('A diagonal line drawn from top-left to bottom-right on a gray background.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/createCanvas"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/createFramebuffer.mdx"],"slug":[0,"en/p5/createframebuffer"],"body":[0,"\n\n# createFramebuffer\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createFramebuffer()"],"module":[0,"Rendering"],"submodule":[0,"Rendering"],"file":[0,"src/core/rendering.js"],"description":[0,"Creates and a new p5.Framebuffer object.
\np5.Framebuffer objects are separate drawing\nsurfaces that can be used as textures in WebGL mode. They're similar to\np5.Graphics objects and generally run much\nfaster when used as textures.
\nThe parameter, options
, is optional. An object can be passed to configure\nthe p5.Framebuffer object. The available\nproperties are:
\n\nformat
: data format of the texture, either UNSIGNED_BYTE
, FLOAT
, or HALF_FLOAT
. Default is UNSIGNED_BYTE
. \nchannels
: whether to store RGB
or RGBA
color channels. Default is to match the main canvas which is RGBA
. \ndepth
: whether to include a depth buffer. Default is true
. \ndepthFormat
: data format of depth information, either UNSIGNED_INT
or FLOAT
. Default is FLOAT
. \nstencil
: 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
. \nantialias
: 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). \nwidth
: width of the p5.Framebuffer object. Default is to always match the main canvas width. \nheight
: height of the p5.Framebuffer object. Default is to always match the main canvas height. \ndensity
: pixel density of the p5.Framebuffer object. Default is to always match the main canvas pixel density. \ntextureFiltering
: 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
. \n
\nIf the width
, height
, or density
attributes are set, they won't automatically match the main canvas and must be changed manually.
\nNote: createFramebuffer()
can only be used in WebGL mode.
\n"],"line":[0,495],"params":[1,[[0,{"name":[0,"options"],"description":[0,"configuration options.
\n"],"type":[0,"Object"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new framebuffer."],"type":[0,"p5.Framebuffer"]}],"example":[1,[[0,"\n\n\nlet myBuffer;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Framebuffer object.\n myBuffer = createFramebuffer();\n\n describe('A grid of white toruses rotating against a dark gray background.');\n}\n\nfunction draw() {\n background(50);\n\n // Start drawing to the p5.Framebuffer object.\n myBuffer.begin();\n\n // Clear the drawing surface.\n clear();\n\n // Turn on the lights.\n lights();\n\n // Rotate the coordinate system.\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n\n // Style the torus.\n noStroke();\n\n // Draw the torus.\n torus(20);\n\n // Stop drawing to the p5.Framebuffer object.\n myBuffer.end();\n\n // Iterate from left to right.\n for (let x = -50; x < 50; x += 25) {\n // Iterate from top to bottom.\n for (let y = -50; y < 50; y += 25) {\n // Draw the p5.Framebuffer object to the canvas.\n image(myBuffer, x, y, 25, 25);\n }\n }\n}\n
\n\n\n\n\nlet myBuffer;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create an options object.\n let options = { width: 25, height: 25 };\n\n // Create a p5.Framebuffer object.\n // Use options for configuration.\n myBuffer = createFramebuffer(options);\n\n describe('A grid of white toruses rotating against a dark gray background.');\n}\n\nfunction draw() {\n background(50);\n\n // Start drawing to the p5.Framebuffer object.\n myBuffer.begin();\n\n // Clear the drawing surface.\n clear();\n\n // Turn on the lights.\n lights();\n\n // Rotate the coordinate system.\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n\n // Style the torus.\n noStroke();\n\n // Draw the torus.\n torus(5, 2.5);\n\n // Stop drawing to the p5.Framebuffer object.\n myBuffer.end();\n\n // Iterate from left to right.\n for (let x = -50; x < 50; x += 25) {\n // Iterate from top to bottom.\n for (let y = -50; y < 50; y += 25) {\n // Draw the p5.Framebuffer object to the canvas.\n image(myBuffer, x, y);\n }\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/createFramebuffer"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/createGraphics.mdx"],"slug":[0,"en/p5/creategraphics"],"body":[0,"\n\n# createGraphics\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createGraphics()"],"module":[0,"Rendering"],"submodule":[0,"Rendering"],"file":[0,"src/core/rendering.js"],"description":[0,"Creates a p5.Graphics object.
\ncreateGraphics()
creates an offscreen drawing canvas (graphics buffer)\nand returns it as a p5.Graphics object. Drawing\nto a separate graphics buffer can be helpful for performance and for\norganizing code.
\nThe first two parameters, width
and height
, are optional. They set the\ndimensions of the p5.Graphics object. For\nexample, calling createGraphics(900, 500)
creates a graphics buffer\nthat's 900×500 pixels.
\nThe third parameter is also optional. If either of the constants P2D
or\nWEBGL
is passed, as in createGraphics(900, 500, WEBGL)
, then it will set\nthe p5.Graphics object's rendering mode. If an\nexisting\nHTMLCanvasElement\nis passed, as in createGraphics(900, 500, myCanvas)
, then it will be used\nby the graphics buffer.
\nThe fourth parameter is also optional. If an existing\nHTMLCanvasElement\nis passed, as in createGraphics(900, 500, WEBGL, myCanvas)
, then it will be\nused by the graphics buffer.
\nNote: In WebGL mode, the p5.Graphics object\nwill use a WebGL2 context if it's supported by the browser. Check the\nwebglVersion system variable to check what\nversion is being used, or call setAttributes({ version: 1 })
to create a\nWebGL1 context.
\n"],"line":[0,370],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"width"],"description":[0,"width of the graphics buffer.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"height"],"description":[0,"height of the graphics buffer.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"renderer"],"description":[0,"either P2D or WEBGL. Defaults to P2D.
\n"],"type":[0,"Constant"],"optional":[0,true]}],[0,{"name":[0,"canvas"],"description":[0,"existing canvas element that should be\n used for the graphics buffer..
\n"],"type":[0,"HTMLCanvasElement"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"width"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"height"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"canvas"],"description":[0,""],"type":[0,"HTMLCanvasElement"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new graphics buffer."],"type":[0,"p5.Graphics"]}],"example":[1,[[0,"\n\n\n// Double-click to draw the contents of the graphics buffer.\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Create the p5.Graphics object.\n pg = createGraphics(50, 50);\n\n // Draw to the graphics buffer.\n pg.background(100);\n pg.circle(pg.width / 2, pg.height / 2, 20);\n\n describe('A gray square. A smaller, darker square with a white circle at its center appears when the user double-clicks.');\n}\n\n// Display the graphics buffer when the user double-clicks.\nfunction doubleClicked() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n image(pg, 25, 25);\n }\n}\n
\n\n\n\n\n// Double-click to draw the contents of the graphics buffer.\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Create the p5.Graphics object in WebGL mode.\n pg = createGraphics(50, 50, WEBGL);\n\n // Draw to the graphics buffer.\n pg.background(100);\n pg.lights();\n pg.noStroke();\n pg.rotateX(QUARTER_PI);\n pg.rotateY(QUARTER_PI);\n pg.torus(15, 5);\n\n describe('A gray square. A smaller, darker square with a white torus at its center appears when the user double-clicks.');\n}\n\n// Display the graphics buffer when the user double-clicks.\nfunction doubleClicked() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n image(pg, 25, 25);\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/createGraphics"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/drawingContext.mdx"],"slug":[0,"en/p5/drawingcontext"],"body":[0,"\n\n# drawingContext\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"drawingContext"],"module":[0,"Rendering"],"submodule":[0,"Rendering"],"file":[0,"src/core/rendering.js"],"description":[0,"A system variable that provides direct access to the sketch's\n
element.
\nThe
element provides many specialized features that aren't\nincluded in the p5.js library. The drawingContext
system variable\nprovides access to these features by exposing the sketch's\nCanvasRenderingContext2D\nobject.
\n"],"line":[0,1198],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Style the circle using shadows.\n drawingContext.shadowOffsetX = 5;\n drawingContext.shadowOffsetY = -5;\n drawingContext.shadowBlur = 10;\n drawingContext.shadowColor = 'black';\n\n // Draw the circle.\n circle(50, 50, 40);\n\n describe(\"A white circle on a gray background. The circle's edges are shadowy.\");\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background('skyblue');\n\n // Style the circle using a color gradient.\n let myGradient = drawingContext.createRadialGradient(50, 50, 3, 50, 50, 40);\n myGradient.addColorStop(0, 'yellow');\n myGradient.addColorStop(0.6, 'orangered');\n myGradient.addColorStop(1, 'yellow');\n drawingContext.fillStyle = myGradient;\n drawingContext.strokeStyle = 'rgba(0, 0, 0, 0)';\n\n // Draw the circle.\n circle(50, 50, 40);\n\n describe('A fiery sun drawn on a light blue background.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/drawingContext"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/noCanvas.mdx"],"slug":[0,"en/p5/nocanvas"],"body":[0,"\n\n# noCanvas\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"noCanvas()"],"module":[0,"Rendering"],"submodule":[0,"Rendering"],"file":[0,"src/core/rendering.js"],"description":[0,"Removes the default canvas.
\nBy default, a 100×100 pixels canvas is created without needing to call\ncreateCanvas(). noCanvas()
removes the\ndefault canvas for sketches that don't need it.
\n"],"line":[0,346],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\nfunction setup() {\n noCanvas();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/noCanvas"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/resizeCanvas.mdx"],"slug":[0,"en/p5/resizecanvas"],"body":[0,"\n\n# resizeCanvas\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"resizeCanvas()"],"module":[0,"Rendering"],"submodule":[0,"Rendering"],"file":[0,"src/core/rendering.js"],"description":[0,"Resizes the canvas to a given width and height.
\nresizeCanvas()
immediately clears the canvas and calls\nredraw(). It's common to call resizeCanvas()
\nwithin the body of windowResized() like\nso:
\nfunction windowResized() {\n resizeCanvas(windowWidth, windowHeight);\n}\n
\nThe first two parameters, width
and height
, set the dimensions of the\ncanvas. They also the values of the width and\nheight system variables. For example, calling\nresizeCanvas(300, 500)
resizes the canvas to 300×500 pixels, then sets\nwidth to 300 and\nheight 500.
\nThe third parameter, noRedraw
, is optional. If true
is passed, as in\nresizeCanvas(300, 500, true)
, then the canvas will be canvas to 300×500\npixels but the redraw() function won't be called\nimmediately. By default, redraw() is called\nimmediately when resizeCanvas()
finishes executing.
\n"],"line":[0,221],"params":[1,[[0,{"name":[0,"width"],"description":[0,"width of the canvas.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"height"],"description":[0,"height of the canvas.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"noRedraw"],"description":[0,"whether to delay calling\n redraw(). Defaults\n to false
.
\n"],"type":[0,"Boolean"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\n// Double-click to resize the canvas.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A white circle drawn on a gray background. The canvas shrinks by half the first time the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(180);\n\n // Draw a circle at the center of the canvas.\n circle(width / 2, height / 2, 20);\n}\n\n// Resize the canvas when the user double-clicks.\nfunction doubleClicked() {\n resizeCanvas(50, 50);\n}\n
\n\n\n\n\n// Resize the web browser to change the canvas size.\n\nfunction setup() {\n createCanvas(windowWidth, windowHeight);\n\n describe('A white circle drawn on a gray background.');\n}\n\nfunction draw() {\n background(180);\n\n // Draw a circle at the center of the canvas.\n circle(width / 2, height / 2, 20);\n}\n\n// Always resize the canvas to fill the browser window.\nfunction windowResized() {\n resizeCanvas(windowWidth, windowHeight);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/resizeCanvas"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/setAttributes.mdx"],"slug":[0,"en/p5/setattributes"],"body":[0,"\n\n# setAttributes\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"setAttributes()"],"module":[0,"Rendering"],"submodule":[0,"Rendering"],"file":[0,"src/webgl/p5.RendererGL.js"],"description":[0,"Set attributes for the WebGL Drawing context.\nThis is a way of adjusting how the WebGL\nrenderer works to fine-tune the display and performance.
\nNote that this will reinitialize the drawing context\nif called after the WebGL canvas is made.
\nIf an object is passed as the parameter, all attributes\nnot declared in the object will be set to defaults.
\nThe available attributes are:\n
\nalpha - indicates if the canvas contains an alpha buffer\ndefault is true
\ndepth - indicates whether the drawing buffer has a depth buffer\nof at least 16 bits - default is true
\nstencil - indicates whether the drawing buffer has a stencil buffer\nof at least 8 bits
\nantialias - indicates whether or not to perform anti-aliasing\ndefault is false (true in Safari)
\npremultipliedAlpha - indicates that the page compositor will assume\nthe drawing buffer contains colors with pre-multiplied alpha\ndefault is true
\npreserveDrawingBuffer - if true the buffers will not be cleared and\nand will preserve their values until cleared or overwritten by author\n(note that p5 clears automatically on draw loop)\ndefault is true
\nperPixelLighting - if true, per-pixel lighting will be used in the\nlighting shader otherwise per-vertex lighting is used.\ndefault is true.
\nversion - either 1 or 2, to specify which WebGL version to ask for. By\ndefault, WebGL 2 will be requested. If WebGL2 is not available, it will\nfall back to WebGL 1. You can check what version is used with by looking at\nthe global webglVersion
property.
\n"],"line":[0,118],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"key"],"description":[0,"Name of attribute
\n"],"type":[0,"String"]}],[0,{"name":[0,"value"],"description":[0,"New value of named attribute
\n"],"type":[0,"Boolean"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"obj"],"description":[0,"object with key-value pairs
\n"],"type":[0,"Object"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(255);\n push();\n rotateZ(frameCount * 0.02);\n rotateX(frameCount * 0.02);\n rotateY(frameCount * 0.02);\n fill(0, 0, 0);\n box(50);\n pop();\n}\n
\n\n
\nNow with the antialias attribute set to true.\n
\n\n\nfunction setup() {\n setAttributes('antialias', true);\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(255);\n push();\n rotateZ(frameCount * 0.02);\n rotateX(frameCount * 0.02);\n rotateY(frameCount * 0.02);\n fill(0, 0, 0);\n box(50);\n pop();\n}\n
\n\n\n\n\n// press the mouse button to disable perPixelLighting\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noStroke();\n fill(255);\n}\n\nlet lights = [\n { c: '#f00', t: 1.12, p: 1.91, r: 0.2 },\n { c: '#0f0', t: 1.21, p: 1.31, r: 0.2 },\n { c: '#00f', t: 1.37, p: 1.57, r: 0.2 },\n { c: '#ff0', t: 1.12, p: 1.91, r: 0.7 },\n { c: '#0ff', t: 1.21, p: 1.31, r: 0.7 },\n { c: '#f0f', t: 1.37, p: 1.57, r: 0.7 }\n];\n\nfunction draw() {\n let t = millis() / 1000 + 1000;\n background(0);\n directionalLight(color('#222'), 1, 1, 1);\n\n for (let i = 0; i < lights.length; i++) {\n let light = lights[i];\n pointLight(\n color(light.c),\n p5.Vector.fromAngles(t * light.t, t * light.p, width * light.r)\n );\n }\n\n specularMaterial(255);\n sphere(width * 0.1);\n\n rotateX(t * 0.77);\n rotateY(t * 0.83);\n rotateZ(t * 0.91);\n torus(width * 0.3, width * 0.07, 24, 10);\n}\n\nfunction mousePressed() {\n setAttributes('perPixelLighting', false);\n noStroke();\n fill(255);\n}\nfunction mouseReleased() {\n setAttributes('perPixelLighting', true);\n noStroke();\n fill(255);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/setAttributes"]}],"render":[0,null]}]]]}],[0,{"name":[0,"p5.Framebuffer"],"entry":[0,{"id":[0,"en/p5/p5.Framebuffer.mdx"],"slug":[0,"en/p5/p5framebuffer"],"body":[0,"\n\n# p5.Framebuffer\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"p5.Framebuffer"],"module":[0,"Rendering"],"file":[0,"src/webgl/p5.Framebuffer.js"],"description":[0,"A class to describe a high-performance drawing surface for textures.
\nEach p5.Framebuffer
object provides a dedicated drawing surface called\na framebuffer. They're similar to\np5.Graphics objects but can run much faster.\nPerformance is improved because the framebuffer shares the same WebGL\ncontext as the canvas used to create it.
\np5.Framebuffer
objects have all the drawing features of the main\ncanvas. Drawing instructions meant for the framebuffer must be placed\nbetween calls to\nmyBuffer.begin() and\nmyBuffer.end(). The resulting image\ncan be applied as a texture by passing the p5.Framebuffer
object to the\ntexture() function, as in texture(myBuffer)
.\nIt can also be displayed on the main canvas by passing it to the\nimage() function, as in image(myBuffer, 0, 0)
.
\nNote: createFramebuffer() is the\nrecommended way to create an instance of this class.
\n"],"line":[0,76],"params":[1,[[0,{"name":[0,"target"],"description":[0,"sketch instance or\n p5.Graphics\n object.
\n"],"type":[0,"p5.Graphics|p5"]}],[0,{"name":[0,"settings"],"description":[0,"configuration options.
\n"],"type":[0,"Object"],"optional":[0,true]}]]],"chainable":[0,false],"methods":[0,{"resize":[0,{"description":[0,"Resizes the framebuffer to a given width and height.
\nThe parameters, width
and height
, set the dimensions of the\nframebuffer. For example, calling myBuffer.resize(300, 500)
resizes\nthe framebuffer to 300×500 pixels, then sets myBuffer.width
to 300\nand myBuffer.height
500.
\n"],"path":[0,"p5.Framebuffer/resize"]}],"pixelDensity":[0,{"description":[0,"Sets the framebuffer's pixel density or returns its current density.
\nComputer displays are grids of little lights called pixels. A display's\npixel density describes how many pixels it packs into an area. Displays\nwith smaller pixels have a higher pixel density and create sharper\nimages.
\nThe parameter, density
, is optional. If a number is passed, as in\nmyBuffer.pixelDensity(1)
, it sets the framebuffer's pixel density. By\ndefault, the framebuffer's pixel density will match that of the canvas\nwhere it was created. All canvases default to match the display's pixel\ndensity.
\nCalling myBuffer.pixelDensity()
without an argument returns its current\npixel density.
\n"],"path":[0,"p5.Framebuffer/pixelDensity"]}],"autoSized":[0,{"description":[0,"Toggles the framebuffer's autosizing mode or returns the current mode.
\nBy default, the framebuffer automatically resizes to match the canvas\nthat created it. Calling myBuffer.autoSized(false)
disables this\nbehavior and calling myBuffer.autoSized(true)
re-enables it.
\nCalling myBuffer.autoSized()
without an argument returns true
if\nthe framebuffer automatically resizes and false
if not.
\n"],"path":[0,"p5.Framebuffer/autoSized"]}],"createCamera":[0,{"description":[0,"Creates a new\np5.Camera object to use with the framebuffer.
\nThe new camera is initialized with a default position (0, 0, 800)
and a\ndefault perspective projection. Its properties can be controlled with\np5.Camera methods such as myCamera.lookAt(0, 0, 0)
.
\nFramebuffer cameras should be created between calls to\nmyBuffer.begin() and\nmyBuffer.end() like so:
\nlet myCamera;\n\nmyBuffer.begin();\n\n// Create the camera for the framebuffer.\nmyCamera = myBuffer.createCamera();\n\nmyBuffer.end();\n
\nCalling setCamera() updates the\nframebuffer's projection using the camera.\nresetMatrix() must also be called for the\nview to change properly:
\nmyBuffer.begin();\n\n// Set the camera for the framebuffer.\nsetCamera(myCamera);\n\n// Reset all transformations.\nresetMatrix();\n\n// Draw stuff...\n\nmyBuffer.end();\n
\n"],"path":[0,"p5.Framebuffer/createCamera"]}],"remove":[0,{"description":[0,"Deletes the framebuffer from GPU memory.
\nCalling myBuffer.remove()
frees the GPU memory used by the framebuffer.\nThe framebuffer also uses a bit of memory on the CPU which can be freed\nlike so:
\n// Delete the framebuffer from GPU memory.\nmyBuffer.remove();\n\n// Delete the framebuffer from CPU memory.\nmyBuffer = undefined;\n
\nNote: All variables that reference the framebuffer must be assigned\nthe value undefined
to delete the framebuffer from CPU memory. If any\nvariable still refers to the framebuffer, then it won't be garbage\ncollected.
\n"],"path":[0,"p5.Framebuffer/remove"]}],"begin":[0,{"description":[0,"Begins drawing shapes to the framebuffer.
\nmyBuffer.begin()
and myBuffer.end()\nallow shapes to be drawn to the framebuffer. myBuffer.begin()
begins\ndrawing to the framebuffer and\nmyBuffer.end() stops drawing to the\nframebuffer. Changes won't be visible until the framebuffer is displayed\nas an image or texture.
\n"],"path":[0,"p5.Framebuffer/begin"]}],"end":[0,{"description":[0,"Stops drawing shapes to the framebuffer.
\nmyBuffer.begin() and myBuffer.end()
\nallow shapes to be drawn to the framebuffer.\nmyBuffer.begin() begins drawing to\nthe framebuffer and myBuffer.end()
stops drawing to the framebuffer.\nChanges won't be visible until the framebuffer is displayed as an image\nor texture.
\n"],"path":[0,"p5.Framebuffer/end"]}],"draw":[0,{"description":[0,"Draws to the framebuffer by calling a function that contains drawing\ninstructions.
\nThe parameter, callback
, is a function with the drawing instructions\nfor the framebuffer. For example, calling myBuffer.draw(myFunction)
\nwill call a function named myFunction()
to draw to the framebuffer.\nDoing so has the same effect as the following:
\nmyBuffer.begin();\nmyFunction();\nmyBuffer.end();\n
\n"],"path":[0,"p5.Framebuffer/draw"]}],"loadPixels":[0,{"description":[0,"Loads the current value of each pixel in the framebuffer into its\npixels array.
\nmyBuffer.loadPixels()
must be called before reading from or writing to\nmyBuffer.pixels.
\n"],"path":[0,"p5.Framebuffer/loadPixels"]}],"get":[0,{"description":[0,"Gets a pixel or a region of pixels from the framebuffer.
\nmyBuffer.get()
is easy to use but it's not as fast as\nmyBuffer.pixels. Use\nmyBuffer.pixels to read many pixel\nvalues.
\nThe version of myBuffer.get()
with no parameters returns the entire\nframebuffer as a a p5.Image object.
\nThe version of myBuffer.get()
with two parameters interprets them as\ncoordinates. It returns an array with the [R, G, B, A]
values of the\npixel at the given point.
\nThe version of myBuffer.get()
with four parameters interprets them as\ncoordinates and dimensions. It returns a subsection of the framebuffer as\na p5.Image object. The first two parameters are\nthe coordinates for the upper-left corner of the subsection. The last two\nparameters are the width and height of the subsection.
\n"],"path":[0,"p5.Framebuffer/get"]}],"updatePixels":[0,{"description":[0,"Updates the framebuffer with the RGBA values in the\npixels array.
\nmyBuffer.updatePixels()
only needs to be called after changing values\nin the myBuffer.pixels array. Such\nchanges can be made directly after calling\nmyBuffer.loadPixels().
\n"],"path":[0,"p5.Framebuffer/updatePixels"]}]}],"properties":[0,{"pixels":[0,{"description":[0,"An array containing the color of each pixel in the framebuffer.
\nmyBuffer.loadPixels() must be\ncalled before accessing the myBuffer.pixels
array.\nmyBuffer.updatePixels()\nmust be called after any changes are made.
\nNote: Updating pixels via this property is slower than drawing to the\nframebuffer directly. Consider using a\np5.Shader object instead of looping over\nmyBuffer.pixels
.
\n"],"path":[0,"p5.Framebuffer/pixels"]}],"color":[0,{"description":[0,"An object that stores the framebuffer's color data.
\nEach framebuffer uses a\nWebGLTexture\nobject internally to store its color data. The myBuffer.color
property\nmakes it possible to pass this data directly to other functions. For\nexample, calling texture(myBuffer.color)
or\nmyShader.setUniform('colorTexture', myBuffer.color)
may be helpful for\nadvanced use cases.
\nNote: By default, a framebuffer's y-coordinates are flipped compared to\nimages and videos. It's easy to flip a framebuffer's y-coordinates as\nneeded when applying it as a texture. For example, calling\nplane(myBuffer.width, -myBuffer.height)
will flip the framebuffer.
\n"],"path":[0,"p5.Framebuffer/color"]}],"depth":[0,{"description":[0,"An object that stores the framebuffer's depth data.
\nEach framebuffer uses a\nWebGLTexture\nobject internally to store its depth data. The myBuffer.depth
property\nmakes it possible to pass this data directly to other functions. For\nexample, calling texture(myBuffer.depth)
or\nmyShader.setUniform('depthTexture', myBuffer.depth)
may be helpful for\nadvanced use cases.
\nNote: By default, a framebuffer's y-coordinates are flipped compared to\nimages and videos. It's easy to flip a framebuffer's y-coordinates as\nneeded when applying it as a texture. For example, calling\nplane(myBuffer.width, -myBuffer.height)
will flip the framebuffer.
\n"],"path":[0,"p5.Framebuffer/depth"]}]}],"isConstructor":[0,true],"path":[0,"p5/p5.Framebuffer"]}],"render":[0,null]}],"entries":[1,[[0,{"id":[0,"en/p5.Framebuffer/autoSized.mdx"],"slug":[0,"en/p5framebuffer/autosized"],"body":[0,"\n\n# autoSized\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"autoSized()"],"module":[0,"Rendering"],"submodule":[0,""],"file":[0,"src/webgl/p5.Framebuffer.js"],"description":[0,"Toggles the framebuffer's autosizing mode or returns the current mode.
\nBy default, the framebuffer automatically resizes to match the canvas\nthat created it. Calling myBuffer.autoSized(false)
disables this\nbehavior and calling myBuffer.autoSized(true)
re-enables it.
\nCalling myBuffer.autoSized()
without an argument returns true
if\nthe framebuffer automatically resizes and false
if not.
\n"],"line":[0,402],"params":[1,[[0,{"name":[0,"autoSized"],"description":[0,"whether to automatically resize the framebuffer to match the canvas.
\n"],"type":[0,"Boolean"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Framebuffer"],"chainable":[0,false],"return":[0,{"description":[0,"current autosize setting."],"type":[0,"Boolean"]}],"example":[1,[[0,"\n\n\n// Double-click to toggle the autosizing mode.\n\nlet myBuffer;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Framebuffer object.\n myBuffer = createFramebuffer();\n\n describe('A multicolor sphere on a gray background. The image resizes when the user moves the mouse.');\n}\n\nfunction draw() {\n background(50);\n\n // Draw to the p5.Framebuffer object.\n myBuffer.begin();\n background(200);\n normalMaterial();\n sphere(width / 4);\n myBuffer.end();\n\n // Display the p5.Framebuffer object.\n image(myBuffer, -width / 2, -height / 2);\n}\n\n// Resize the canvas when the user moves the mouse.\nfunction mouseMoved() {\n let w = constrain(mouseX, 0, 100);\n let h = constrain(mouseY, 0, 100);\n resizeCanvas(w, h);\n}\n\n// Toggle autoSizing when the user double-clicks.\n// Note: opened an issue to fix(?) this.\nfunction doubleClicked() {\n let isAuto = myBuffer.autoSized();\n myBuffer.autoSized(!isAuto);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Framebuffer/autoSized"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Framebuffer/begin.mdx"],"slug":[0,"en/p5framebuffer/begin"],"body":[0,"\n\n# begin\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"begin()"],"module":[0,"Rendering"],"submodule":[0,""],"file":[0,"src/webgl/p5.Framebuffer.js"],"description":[0,"Begins drawing shapes to the framebuffer.
\nmyBuffer.begin()
and myBuffer.end()\nallow shapes to be drawn to the framebuffer. myBuffer.begin()
begins\ndrawing to the framebuffer and\nmyBuffer.end() stops drawing to the\nframebuffer. Changes won't be visible until the framebuffer is displayed\nas an image or texture.
\n"],"line":[0,1118],"itemtype":[0,"method"],"class":[0,"p5.Framebuffer"],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet myBuffer;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Framebuffer object.\n myBuffer = createFramebuffer();\n\n describe('An empty gray canvas. The canvas gets darker and a rotating, multicolor torus appears while the user presses and holds the mouse.');\n}\n\nfunction draw() {\n background(200);\n\n // Start drawing to the p5.Framebuffer object.\n myBuffer.begin();\n\n background(50);\n rotateY(frameCount * 0.01);\n normalMaterial();\n torus(30);\n\n // Stop drawing to the p5.Framebuffer object.\n myBuffer.end();\n\n // Display the p5.Framebuffer object while\n // the user presses the mouse.\n if (mouseIsPressed === true) {\n image(myBuffer, -50, -50);\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Framebuffer/begin"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Framebuffer/color.mdx"],"slug":[0,"en/p5framebuffer/color"],"body":[0,"\n\n# color\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"color"],"module":[0,"Rendering"],"submodule":[0,""],"file":[0,"src/webgl/p5.Framebuffer.js"],"description":[0,"An object that stores the framebuffer's color data.
\nEach framebuffer uses a\nWebGLTexture\nobject internally to store its color data. The myBuffer.color
property\nmakes it possible to pass this data directly to other functions. For\nexample, calling texture(myBuffer.color)
or\nmyShader.setUniform('colorTexture', myBuffer.color)
may be helpful for\nadvanced use cases.
\nNote: By default, a framebuffer's y-coordinates are flipped compared to\nimages and videos. It's easy to flip a framebuffer's y-coordinates as\nneeded when applying it as a texture. For example, calling\nplane(myBuffer.width, -myBuffer.height)
will flip the framebuffer.
\n"],"line":[0,1701],"itemtype":[0,"property"],"class":[0,"p5.Framebuffer"],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n // Create a p5.Framebuffer object.\n let myBuffer = createFramebuffer();\n\n // Start drawing to the p5.Framebuffer object.\n myBuffer.begin();\n\n triangle(-25, 25, 0, -25, 25, 25);\n\n // Stop drawing to the p5.Framebuffer object.\n myBuffer.end();\n\n // Use the p5.Framebuffer object's WebGLTexture.\n texture(myBuffer.color);\n\n // Style the plane.\n noStroke();\n\n // Draw the plane.\n plane(myBuffer.width, myBuffer.height);\n\n describe('A white triangle on a gray background.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Framebuffer/color"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Framebuffer/createCamera.mdx"],"slug":[0,"en/p5framebuffer/createcamera"],"body":[0,"\n\n# createCamera\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createCamera()"],"module":[0,"Rendering"],"submodule":[0,""],"file":[0,"src/webgl/p5.Framebuffer.js"],"description":[0,"Creates a new\np5.Camera object to use with the framebuffer.
\nThe new camera is initialized with a default position (0, 0, 800)
and a\ndefault perspective projection. Its properties can be controlled with\np5.Camera methods such as myCamera.lookAt(0, 0, 0)
.
\nFramebuffer cameras should be created between calls to\nmyBuffer.begin() and\nmyBuffer.end() like so:
\nlet myCamera;\n\nmyBuffer.begin();\n\n// Create the camera for the framebuffer.\nmyCamera = myBuffer.createCamera();\n\nmyBuffer.end();\n
\nCalling setCamera() updates the\nframebuffer's projection using the camera.\nresetMatrix() must also be called for the\nview to change properly:
\nmyBuffer.begin();\n\n// Set the camera for the framebuffer.\nsetCamera(myCamera);\n\n// Reset all transformations.\nresetMatrix();\n\n// Draw stuff...\n\nmyBuffer.end();\n
\n"],"line":[0,892],"itemtype":[0,"method"],"class":[0,"p5.Framebuffer"],"chainable":[0,false],"return":[0,{"description":[0,"new camera."],"type":[0,"p5.Camera"]}],"example":[1,[[0,"\n\n\n// Double-click to toggle between cameras.\n\nlet myBuffer;\nlet cam1;\nlet cam2;\nlet usingCam1 = true;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Framebuffer object.\n myBuffer = createFramebuffer();\n\n // Create the cameras between begin() and end().\n myBuffer.begin();\n\n // Create the first camera.\n // Keep its default settings.\n cam1 = myBuffer.createCamera();\n\n // Create the second camera.\n // Place it at the top-left.\n // Point it at the origin.\n cam2 = myBuffer.createCamera();\n cam2.setPosition(400, -400, 800);\n cam2.lookAt(0, 0, 0);\n\n myBuffer.end();\n\n describe(\n 'A white cube on a gray background. The camera toggles between frontal and aerial views when the user double-clicks.'\n );\n}\n\nfunction draw() {\n // Draw to the p5.Framebuffer object.\n myBuffer.begin();\n background(200);\n\n // Set the camera.\n if (usingCam1 === true) {\n setCamera(cam1);\n } else {\n setCamera(cam2);\n }\n\n // Reset all transformations.\n resetMatrix();\n\n // Draw the box.\n box();\n\n myBuffer.end();\n\n // Display the p5.Framebuffer object.\n image(myBuffer, -50, -50);\n}\n\n// Toggle the current camera when the user double-clicks.\nfunction doubleClicked() {\n if (usingCam1 === true) {\n usingCam1 = false;\n } else {\n usingCam1 = true;\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Framebuffer/createCamera"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Framebuffer/depth.mdx"],"slug":[0,"en/p5framebuffer/depth"],"body":[0,"\n\n# depth\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"depth"],"module":[0,"Rendering"],"submodule":[0,""],"file":[0,"src/webgl/p5.Framebuffer.js"],"description":[0,"An object that stores the framebuffer's depth data.
\nEach framebuffer uses a\nWebGLTexture\nobject internally to store its depth data. The myBuffer.depth
property\nmakes it possible to pass this data directly to other functions. For\nexample, calling texture(myBuffer.depth)
or\nmyShader.setUniform('depthTexture', myBuffer.depth)
may be helpful for\nadvanced use cases.
\nNote: By default, a framebuffer's y-coordinates are flipped compared to\nimages and videos. It's easy to flip a framebuffer's y-coordinates as\nneeded when applying it as a texture. For example, calling\nplane(myBuffer.width, -myBuffer.height)
will flip the framebuffer.
\n"],"line":[0,1754],"itemtype":[0,"property"],"class":[0,"p5.Framebuffer"],"example":[1,[[0,"\n\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * viewModelPosition;\n vTexCoord = aTexCoord;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D depth;\n\nvoid main() {\n // Get the pixel's depth value.\n float depthVal = texture2D(depth, vTexCoord).r;\n\n // Set the pixel's color based on its depth.\n gl_FragColor = mix(\n vec4(0., 0., 0., 1.),\n vec4(1., 0., 1., 1.),\n depthVal);\n}\n`;\n\nlet myBuffer;\nlet myShader;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Framebuffer object.\n myBuffer = createFramebuffer();\n\n // Create a p5.Shader object.\n myShader = createShader(vertSrc, fragSrc);\n\n // Compile and apply the shader.\n shader(myShader);\n\n describe('The shadow of a box rotates slowly against a magenta background.');\n}\n\nfunction draw() {\n // Draw to the p5.Framebuffer object.\n myBuffer.begin();\n background(255);\n rotateX(frameCount * 0.01);\n box(20, 20, 80);\n myBuffer.end();\n\n // Set the shader's depth uniform using\n // the framebuffer's depth texture.\n myShader.setUniform('depth', myBuffer.depth);\n\n // Style the plane.\n noStroke();\n\n // Draw the plane.\n plane(myBuffer.width, myBuffer.height);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Framebuffer/depth"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Framebuffer/draw.mdx"],"slug":[0,"en/p5framebuffer/draw"],"body":[0,"\n\n# draw\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"draw()"],"module":[0,"Rendering"],"submodule":[0,""],"file":[0,"src/webgl/p5.Framebuffer.js"],"description":[0,"Draws to the framebuffer by calling a function that contains drawing\ninstructions.
\nThe parameter, callback
, is a function with the drawing instructions\nfor the framebuffer. For example, calling myBuffer.draw(myFunction)
\nwill call a function named myFunction()
to draw to the framebuffer.\nDoing so has the same effect as the following:
\nmyBuffer.begin();\nmyFunction();\nmyBuffer.end();\n
\n"],"line":[0,1323],"params":[1,[[0,{"name":[0,"callback"],"description":[0,"function that draws to the framebuffer.
\n"],"type":[0,"Function"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Framebuffer"],"chainable":[0,false],"example":[1,[[0,"\n\n\n// Click the canvas to display the framebuffer.\n\nlet myBuffer;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Framebuffer object.\n myBuffer = createFramebuffer();\n\n describe('An empty gray canvas. The canvas gets darker and a rotating, multicolor torus appears while the user presses and holds the mouse.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw to the p5.Framebuffer object.\n myBuffer.draw(bagel);\n\n // Display the p5.Framebuffer object while\n // the user presses the mouse.\n if (mouseIsPressed === true) {\n image(myBuffer, -50, -50);\n }\n}\n\n// Draw a rotating, multicolor torus.\nfunction bagel() {\n background(50);\n rotateY(frameCount * 0.01);\n normalMaterial();\n torus(30);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Framebuffer/draw"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Framebuffer/end.mdx"],"slug":[0,"en/p5framebuffer/end"],"body":[0,"\n\n# end\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"end()"],"module":[0,"Rendering"],"submodule":[0,""],"file":[0,"src/webgl/p5.Framebuffer.js"],"description":[0,"Stops drawing shapes to the framebuffer.
\nmyBuffer.begin() and myBuffer.end()
\nallow shapes to be drawn to the framebuffer.\nmyBuffer.begin() begins drawing to\nthe framebuffer and myBuffer.end()
stops drawing to the framebuffer.\nChanges won't be visible until the framebuffer is displayed as an image\nor texture.
\n"],"line":[0,1254],"itemtype":[0,"method"],"class":[0,"p5.Framebuffer"],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet myBuffer;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Framebuffer object.\n myBuffer = createFramebuffer();\n\n describe('An empty gray canvas. The canvas gets darker and a rotating, multicolor torus appears while the user presses and holds the mouse.');\n}\n\nfunction draw() {\n background(200);\n\n // Start drawing to the p5.Framebuffer object.\n myBuffer.begin();\n\n background(50);\n rotateY(frameCount * 0.01);\n normalMaterial();\n torus(30);\n\n // Stop drawing to the p5.Framebuffer object.\n myBuffer.end();\n\n // Display the p5.Framebuffer object while\n // the user presses the mouse.\n if (mouseIsPressed === true) {\n image(myBuffer, -50, -50);\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Framebuffer/end"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Framebuffer/get.mdx"],"slug":[0,"en/p5framebuffer/get"],"body":[0,"\n\n# get\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"get()"],"module":[0,"Rendering"],"submodule":[0,""],"file":[0,"src/webgl/p5.Framebuffer.js"],"description":[0,"Gets a pixel or a region of pixels from the framebuffer.
\nmyBuffer.get()
is easy to use but it's not as fast as\nmyBuffer.pixels. Use\nmyBuffer.pixels to read many pixel\nvalues.
\nThe version of myBuffer.get()
with no parameters returns the entire\nframebuffer as a a p5.Image object.
\nThe version of myBuffer.get()
with two parameters interprets them as\ncoordinates. It returns an array with the [R, G, B, A]
values of the\npixel at the given point.
\nThe version of myBuffer.get()
with four parameters interprets them as\ncoordinates and dimensions. It returns a subsection of the framebuffer as\na p5.Image object. The first two parameters are\nthe coordinates for the upper-left corner of the subsection. The last two\nparameters are the width and height of the subsection.
\n"],"line":[0,1455],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"x"],"description":[0,"x-coordinate of the pixel. Defaults to 0.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"y-coordinate of the pixel. Defaults to 0.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"w"],"description":[0,"width of the subsection to be returned.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"h"],"description":[0,"height of the subsection to be returned.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[]]}],[0,{"params":[1,[[0,{"name":[0,"x"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,""],"type":[0,"Number"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Framebuffer"],"chainable":[0,false],"return":[0,{"description":[0,"subsection as a p5.Image object."],"type":[0,"p5.Image"]}],"isConstructor":[0,false],"path":[0,"p5.Framebuffer/get"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Framebuffer/loadPixels.mdx"],"slug":[0,"en/p5framebuffer/loadpixels"],"body":[0,"\n\n# loadPixels\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"loadPixels()"],"module":[0,"Rendering"],"submodule":[0,""],"file":[0,"src/webgl/p5.Framebuffer.js"],"description":[0,"Loads the current value of each pixel in the framebuffer into its\npixels array.
\nmyBuffer.loadPixels()
must be called before reading from or writing to\nmyBuffer.pixels.
\n"],"line":[0,1386],"itemtype":[0,"method"],"class":[0,"p5.Framebuffer"],"chainable":[0,false],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n // Create a p5.Framebuffer object.\n let myBuffer = createFramebuffer();\n\n // Load the pixels array.\n myBuffer.loadPixels();\n\n // Get the number of pixels in the\n // top half of the framebuffer.\n let numPixels = myBuffer.pixels.length / 2;\n\n // Set the framebuffer's top half to pink.\n for (let i = 0; i < numPixels; i += 4) {\n myBuffer.pixels[i] = 255;\n myBuffer.pixels[i + 1] = 102;\n myBuffer.pixels[i + 2] = 204;\n myBuffer.pixels[i + 3] = 255;\n }\n\n // Update the pixels array.\n myBuffer.updatePixels();\n\n // Draw the p5.Framebuffer object to the canvas.\n image(myBuffer, -50, -50);\n\n describe('A pink rectangle above a gray rectangle.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Framebuffer/loadPixels"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Framebuffer/pixelDensity.mdx"],"slug":[0,"en/p5framebuffer/pixeldensity"],"body":[0,"\n\n# pixelDensity\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"pixelDensity()"],"module":[0,"Rendering"],"submodule":[0,""],"file":[0,"src/webgl/p5.Framebuffer.js"],"description":[0,"Sets the framebuffer's pixel density or returns its current density.
\nComputer displays are grids of little lights called pixels. A display's\npixel density describes how many pixels it packs into an area. Displays\nwith smaller pixels have a higher pixel density and create sharper\nimages.
\nThe parameter, density
, is optional. If a number is passed, as in\nmyBuffer.pixelDensity(1)
, it sets the framebuffer's pixel density. By\ndefault, the framebuffer's pixel density will match that of the canvas\nwhere it was created. All canvases default to match the display's pixel\ndensity.
\nCalling myBuffer.pixelDensity()
without an argument returns its current\npixel density.
\n"],"line":[0,297],"params":[1,[[0,{"name":[0,"density"],"description":[0,"pixel density to set.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Framebuffer"],"chainable":[0,false],"return":[0,{"description":[0,"current pixel density."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nlet myBuffer;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Framebuffer object.\n myBuffer = createFramebuffer();\n\n describe(\"A white circle on a gray canvas. The circle's edge become fuzzy while the user presses and holds the mouse.\");\n}\n\nfunction draw() {\n // Draw to the p5.Framebuffer object.\n myBuffer.begin();\n background(200);\n circle(0, 0, 40);\n myBuffer.end();\n\n // Display the p5.Framebuffer object.\n image(myBuffer, -50, -50);\n}\n\n// Decrease the pixel density when the user\n// presses the mouse.\nfunction mousePressed() {\n myBuffer.pixelDensity(1);\n}\n\n// Increase the pixel density when the user\n// releases the mouse.\nfunction mouseReleased() {\n myBuffer.pixelDensity(2);\n}\n
\n\n\n\n\nlet myBuffer;\nlet myFont;\n\n// Load a font and create a p5.Font object.\nfunction preload() {\n myFont = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n // Create a p5.Framebuffer object.\n myBuffer = createFramebuffer();\n\n // Get the p5.Framebuffer object's pixel density.\n let d = myBuffer.pixelDensity();\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont(myFont);\n textSize(16);\n fill(0);\n\n // Display the pixel density.\n text(`Density: ${d}`, 0, 0);\n\n describe(`The text \"Density: ${d}\" written in black on a gray background.`);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Framebuffer/pixelDensity"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Framebuffer/pixels.mdx"],"slug":[0,"en/p5framebuffer/pixels"],"body":[0,"\n\n# pixels\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"pixels"],"module":[0,"Rendering"],"submodule":[0,""],"file":[0,"src/webgl/p5.Framebuffer.js"],"description":[0,"An array containing the color of each pixel in the framebuffer.
\nmyBuffer.loadPixels() must be\ncalled before accessing the myBuffer.pixels
array.\nmyBuffer.updatePixels()\nmust be called after any changes are made.
\nNote: Updating pixels via this property is slower than drawing to the\nframebuffer directly. Consider using a\np5.Shader object instead of looping over\nmyBuffer.pixels
.
\n"],"line":[0,111],"itemtype":[0,"property"],"class":[0,"p5.Framebuffer"],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n // Create a p5.Framebuffer object.\n let myBuffer = createFramebuffer();\n\n // Load the pixels array.\n myBuffer.loadPixels();\n\n // Get the number of pixels in the\n // top half of the framebuffer.\n let numPixels = myBuffer.pixels.length / 2;\n\n // Set the framebuffer's top half to pink.\n for (let i = 0; i < numPixels; i += 4) {\n myBuffer.pixels[i] = 255;\n myBuffer.pixels[i + 1] = 102;\n myBuffer.pixels[i + 2] = 204;\n myBuffer.pixels[i + 3] = 255;\n }\n\n // Update the pixels array.\n myBuffer.updatePixels();\n\n // Draw the p5.Framebuffer object to the canvas.\n image(myBuffer, -50, -50);\n\n describe('A pink rectangle above a gray rectangle.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Framebuffer/pixels"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Framebuffer/remove.mdx"],"slug":[0,"en/p5framebuffer/remove"],"body":[0,"\n\n# remove\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"remove()"],"module":[0,"Rendering"],"submodule":[0,""],"file":[0,"src/webgl/p5.Framebuffer.js"],"description":[0,"Deletes the framebuffer from GPU memory.
\nCalling myBuffer.remove()
frees the GPU memory used by the framebuffer.\nThe framebuffer also uses a bit of memory on the CPU which can be freed\nlike so:
\n// Delete the framebuffer from GPU memory.\nmyBuffer.remove();\n\n// Delete the framebuffer from CPU memory.\nmyBuffer = undefined;\n
\nNote: All variables that reference the framebuffer must be assigned\nthe value undefined
to delete the framebuffer from CPU memory. If any\nvariable still refers to the framebuffer, then it won't be garbage\ncollected.
\n"],"line":[0,1031],"itemtype":[0,"method"],"class":[0,"p5.Framebuffer"],"chainable":[0,false],"example":[1,[[0,"\n\n\n// Double-click to remove the p5.Framebuffer object.\n\nlet myBuffer;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create an options object.\n let options = { width: 60, height: 60 };\n\n // Create a p5.Framebuffer object and\n // configure it using options.\n myBuffer = createFramebuffer(options);\n\n describe('A white circle at the center of a dark gray square disappears when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Display the p5.Framebuffer object if\n // it's available.\n if (myBuffer) {\n // Draw to the p5.Framebuffer object.\n myBuffer.begin();\n background(100);\n circle(0, 0, 20);\n myBuffer.end();\n\n image(myBuffer, -30, -30);\n }\n}\n\n// Remove the p5.Framebuffer object when the\n// the user double-clicks.\nfunction doubleClicked() {\n // Delete the framebuffer from GPU memory.\n myBuffer.remove();\n\n // Delete the framebuffer from CPU memory.\n myBuffer = undefined;\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Framebuffer/remove"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Framebuffer/resize.mdx"],"slug":[0,"en/p5framebuffer/resize"],"body":[0,"\n\n# resize\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"resize()"],"module":[0,"Rendering"],"submodule":[0,""],"file":[0,"src/webgl/p5.Framebuffer.js"],"description":[0,"Resizes the framebuffer to a given width and height.
\nThe parameters, width
and height
, set the dimensions of the\nframebuffer. For example, calling myBuffer.resize(300, 500)
resizes\nthe framebuffer to 300×500 pixels, then sets myBuffer.width
to 300\nand myBuffer.height
500.
\n"],"line":[0,238],"params":[1,[[0,{"name":[0,"width"],"description":[0,"width of the framebuffer.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"height"],"description":[0,"height of the framebuffer.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Framebuffer"],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet myBuffer;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Framebuffer object.\n myBuffer = createFramebuffer();\n\n describe('A multicolor sphere on a white surface. The image grows larger or smaller when the user moves the mouse, revealing a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw to the p5.Framebuffer object.\n myBuffer.begin();\n background(255);\n normalMaterial();\n sphere(20);\n myBuffer.end();\n\n // Display the p5.Framebuffer object.\n image(myBuffer, -50, -50);\n}\n\n// Resize the p5.Framebuffer object when the\n// user moves the mouse.\nfunction mouseMoved() {\n myBuffer.resize(mouseX, mouseY);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Framebuffer/resize"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Framebuffer/updatePixels.mdx"],"slug":[0,"en/p5framebuffer/updatepixels"],"body":[0,"\n\n# updatePixels\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"updatePixels()"],"module":[0,"Rendering"],"submodule":[0,""],"file":[0,"src/webgl/p5.Framebuffer.js"],"description":[0,"Updates the framebuffer with the RGBA values in the\npixels array.
\nmyBuffer.updatePixels()
only needs to be called after changing values\nin the myBuffer.pixels array. Such\nchanges can be made directly after calling\nmyBuffer.loadPixels().
\n"],"line":[0,1581],"itemtype":[0,"method"],"class":[0,"p5.Framebuffer"],"chainable":[0,false],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n // Create a p5.Framebuffer object.\n let myBuffer = createFramebuffer();\n\n // Load the pixels array.\n myBuffer.loadPixels();\n\n // Get the number of pixels in the\n // top half of the framebuffer.\n let numPixels = myBuffer.pixels.length / 2;\n\n // Set the framebuffer's top half to pink.\n for (let i = 0; i < numPixels; i += 4) {\n myBuffer.pixels[i] = 255;\n myBuffer.pixels[i + 1] = 102;\n myBuffer.pixels[i + 2] = 204;\n myBuffer.pixels[i + 3] = 255;\n }\n\n // Update the pixels array.\n myBuffer.updatePixels();\n\n // Draw the p5.Framebuffer object to the canvas.\n image(myBuffer, -50, -50);\n\n describe('A pink rectangle above a gray rectangle.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Framebuffer/updatePixels"]}],"render":[0,null]}]]]}],[0,{"name":[0,"p5.Graphics"],"entry":[0,{"id":[0,"en/p5/p5.Graphics.mdx"],"slug":[0,"en/p5/p5graphics"],"body":[0,"\n\n# p5.Graphics\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"p5.Graphics"],"module":[0,"Rendering"],"submodule":[0,"Rendering"],"file":[0,"src/core/p5.Graphics.js"],"description":[0,"A class to describe a drawing surface that's separate from the main canvas.
\nEach p5.Graphics
object provides a dedicated drawing surface called a\ngraphics buffer. Graphics buffers are helpful when drawing should happen\noffscreen. For example, separate scenes can be drawn offscreen and\ndisplayed only when needed.
\np5.Graphics
objects have nearly all the drawing features of the main\ncanvas. For example, calling the method myGraphics.circle(50, 50, 20)
\ndraws to the graphics buffer. The resulting image can be displayed on the\nmain canvas by passing the p5.Graphics
object to the\nimage() function, as in image(myGraphics, 0, 0)
.
\nNote: createGraphics() is the recommended\nway to create an instance of this class.
\n"],"line":[0,10],"params":[1,[[0,{"name":[0,"width"],"description":[0,"width of the graphics buffer in pixels.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"height"],"description":[0,"height of the graphics buffer in pixels.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"renderer"],"description":[0,"renderer to use, either P2D or WEBGL.
\n"],"type":[0,"Constant"]}],[0,{"name":[0,"pInst"],"description":[0,"sketch instance.
\n"],"type":[0,"P5"],"optional":[0,true]}],[0,{"name":[0,"canvas"],"description":[0,"existing <canvas>
element to use.
\n"],"type":[0,"HTMLCanvasElement"],"optional":[0,true]}]]],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Graphics object.\n pg = createGraphics(50, 50);\n\n // Draw to the p5.Graphics object.\n pg.background(100);\n pg.circle(25, 25, 20);\n\n describe('A dark gray square with a white circle at its center drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Display the p5.Graphics object.\n image(pg, 25, 25);\n}\n
\n\n\n\n\n// Click the canvas to display the graphics buffer.\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Graphics object.\n pg = createGraphics(50, 50);\n\n describe('A square appears on a gray background when the user presses the mouse. The square cycles between white and black.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the background color.\n let bg = frameCount % 255;\n\n // Draw to the p5.Graphics object.\n pg.background(bg);\n\n // Display the p5.Graphics object while\n // the user presses the mouse.\n if (mouseIsPressed === true) {\n image(pg, 25, 25);\n }\n}\n
\n"]]],"methods":[0,{"reset":[0,{"description":[0,"Resets the graphics buffer's transformations and lighting.
\nBy default, the main canvas resets certain transformation and lighting\nvalues each time draw() executes. p5.Graphics
\nobjects must reset these values manually by calling myGraphics.reset()
.
\n"],"path":[0,"p5.Graphics/reset"]}],"remove":[0,{"description":[0,"Removes the graphics buffer from the web page.
\nCalling myGraphics.remove()
removes the graphics buffer's\n
element from the web page. The graphics buffer also uses\na bit of memory on the CPU that can be freed like so:
\n// Remove the graphics buffer from the web page.\nmyGraphics.remove();\n\n// Delete the graphics buffer from CPU memory.\nmyGraphics = undefined;\n
\nNote: All variables that reference the graphics buffer must be assigned\nthe value undefined
to delete the graphics buffer from CPU memory. If any\nvariable still refers to the graphics buffer, then it won't be garbage\ncollected.
\n"],"path":[0,"p5.Graphics/remove"]}],"createFramebuffer":[0,{"description":[0,"Creates a new p5.Framebuffer object with\nthe same WebGL context as the graphics buffer.
\np5.Framebuffer objects are separate drawing\nsurfaces that can be used as textures in WebGL mode. They're similar to\np5.Graphics objects and generally run much\nfaster when used as textures. Creating a\np5.Framebuffer object in the same context\nas the graphics buffer makes this speedup possible.
\nThe parameter, options
, is optional. An object can be passed to configure\nthe p5.Framebuffer object. The available\nproperties are:
\n\nformat
: data format of the texture, either UNSIGNED_BYTE
, FLOAT
, or HALF_FLOAT
. Default is UNSIGNED_BYTE
. \nchannels
: whether to store RGB
or RGBA
color channels. Default is to match the graphics buffer which is RGBA
. \ndepth
: whether to include a depth buffer. Default is true
. \ndepthFormat
: data format of depth information, either UNSIGNED_INT
or FLOAT
. Default is FLOAT
. \nstencil
: 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
. \nantialias
: 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). \nwidth
: width of the p5.Framebuffer object. Default is to always match the graphics buffer width. \nheight
: height of the p5.Framebuffer object. Default is to always match the graphics buffer height. \ndensity
: pixel density of the p5.Framebuffer object. Default is to always match the graphics buffer pixel density. \ntextureFiltering
: 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
. \n
\nIf the width
, height
, or density
attributes are set, they won't\nautomatically match the graphics buffer and must be changed manually.
\n"],"path":[0,"p5.Graphics/createFramebuffer"]}]}],"isConstructor":[0,true],"path":[0,"p5/p5.Graphics"]}],"render":[0,null]}],"entries":[1,[[0,{"id":[0,"en/p5.Graphics/createFramebuffer.mdx"],"slug":[0,"en/p5graphics/createframebuffer"],"body":[0,"\n\n# createFramebuffer\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createFramebuffer()"],"module":[0,"Rendering"],"submodule":[0,"Rendering"],"file":[0,"src/core/p5.Graphics.js"],"description":[0,"Creates a new p5.Framebuffer object with\nthe same WebGL context as the graphics buffer.
\np5.Framebuffer objects are separate drawing\nsurfaces that can be used as textures in WebGL mode. They're similar to\np5.Graphics objects and generally run much\nfaster when used as textures. Creating a\np5.Framebuffer object in the same context\nas the graphics buffer makes this speedup possible.
\nThe parameter, options
, is optional. An object can be passed to configure\nthe p5.Framebuffer object. The available\nproperties are:
\n\nformat
: data format of the texture, either UNSIGNED_BYTE
, FLOAT
, or HALF_FLOAT
. Default is UNSIGNED_BYTE
. \nchannels
: whether to store RGB
or RGBA
color channels. Default is to match the graphics buffer which is RGBA
. \ndepth
: whether to include a depth buffer. Default is true
. \ndepthFormat
: data format of depth information, either UNSIGNED_INT
or FLOAT
. Default is FLOAT
. \nstencil
: 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
. \nantialias
: 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). \nwidth
: width of the p5.Framebuffer object. Default is to always match the graphics buffer width. \nheight
: height of the p5.Framebuffer object. Default is to always match the graphics buffer height. \ndensity
: pixel density of the p5.Framebuffer object. Default is to always match the graphics buffer pixel density. \ntextureFiltering
: 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
. \n
\nIf the width
, height
, or density
attributes are set, they won't\nautomatically match the graphics buffer and must be changed manually.
\n"],"line":[0,400],"params":[1,[[0,{"name":[0,"options"],"description":[0,"configuration options.
\n"],"type":[0,"Object"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Graphics"],"chainable":[0,false],"return":[0,{"description":[0,"new framebuffer."],"type":[0,"p5.Framebuffer"]}],"example":[1,[[0,"\n\n\n// Click and hold a mouse button to change shapes.\n\nlet pg;\nlet torusLayer;\nlet boxLayer;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Graphics object using WebGL mode.\n pg = createGraphics(100, 100, WEBGL);\n\n // Create the p5.Framebuffer objects.\n torusLayer = pg.createFramebuffer();\n boxLayer = pg.createFramebuffer();\n\n describe('A grid of white toruses rotating against a dark gray background. The shapes become boxes while the user holds a mouse button.');\n}\n\nfunction draw() {\n // Update and draw the layers offscreen.\n drawTorus();\n drawBox();\n\n // Choose the layer to display.\n let layer;\n if (mouseIsPressed === true) {\n layer = boxLayer;\n } else {\n layer = torusLayer;\n }\n\n // Draw to the p5.Graphics object.\n pg.background(50);\n\n // Iterate from left to right.\n for (let x = -50; x < 50; x += 25) {\n // Iterate from top to bottom.\n for (let y = -50; y < 50; y += 25) {\n // Draw the layer to the p5.Graphics object\n pg.image(layer, x, y, 25, 25);\n }\n }\n\n // Display the p5.Graphics object.\n image(pg, 0, 0);\n}\n\n// Update and draw the torus layer offscreen.\nfunction drawTorus() {\n // Start drawing to the torus p5.Framebuffer.\n torusLayer.begin();\n\n // Clear the drawing surface.\n pg.clear();\n\n // Turn on the lights.\n pg.lights();\n\n // Rotate the coordinate system.\n pg.rotateX(frameCount * 0.01);\n pg.rotateY(frameCount * 0.01);\n\n // Style the torus.\n pg.noStroke();\n\n // Draw the torus.\n pg.torus(20);\n\n // Start drawing to the torus p5.Framebuffer.\n torusLayer.end();\n}\n\n// Update and draw the box layer offscreen.\nfunction drawBox() {\n // Start drawing to the box p5.Framebuffer.\n boxLayer.begin();\n\n // Clear the drawing surface.\n pg.clear();\n\n // Turn on the lights.\n pg.lights();\n\n // Rotate the coordinate system.\n pg.rotateX(frameCount * 0.01);\n pg.rotateY(frameCount * 0.01);\n\n // Style the box.\n pg.noStroke();\n\n // Draw the box.\n pg.box(30);\n\n // Start drawing to the box p5.Framebuffer.\n boxLayer.end();\n}\n
\n\n\n\n\n// Click and hold a mouse button to change shapes.\n\nlet pg;\nlet torusLayer;\nlet boxLayer;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create an options object.\n let options = { width: 25, height: 25 };\n\n // Create a p5.Graphics object using WebGL mode.\n pg = createGraphics(100, 100, WEBGL);\n\n // Create the p5.Framebuffer objects.\n // Use options for configuration.\n torusLayer = pg.createFramebuffer(options);\n boxLayer = pg.createFramebuffer(options);\n\n describe('A grid of white toruses rotating against a dark gray background. The shapes become boxes while the user holds a mouse button.');\n}\n\nfunction draw() {\n // Update and draw the layers offscreen.\n drawTorus();\n drawBox();\n\n // Choose the layer to display.\n let layer;\n if (mouseIsPressed === true) {\n layer = boxLayer;\n } else {\n layer = torusLayer;\n }\n\n // Draw to the p5.Graphics object.\n pg.background(50);\n\n // Iterate from left to right.\n for (let x = -50; x < 50; x += 25) {\n // Iterate from top to bottom.\n for (let y = -50; y < 50; y += 25) {\n // Draw the layer to the p5.Graphics object\n pg.image(layer, x, y);\n }\n }\n\n // Display the p5.Graphics object.\n image(pg, 0, 0);\n}\n\n// Update and draw the torus layer offscreen.\nfunction drawTorus() {\n // Start drawing to the torus p5.Framebuffer.\n torusLayer.begin();\n\n // Clear the drawing surface.\n pg.clear();\n\n // Turn on the lights.\n pg.lights();\n\n // Rotate the coordinate system.\n pg.rotateX(frameCount * 0.01);\n pg.rotateY(frameCount * 0.01);\n\n // Style the torus.\n pg.noStroke();\n\n // Draw the torus.\n pg.torus(5, 2.5);\n\n // Start drawing to the torus p5.Framebuffer.\n torusLayer.end();\n}\n\n// Update and draw the box layer offscreen.\nfunction drawBox() {\n // Start drawing to the box p5.Framebuffer.\n boxLayer.begin();\n\n // Clear the drawing surface.\n pg.clear();\n\n // Turn on the lights.\n pg.lights();\n\n // Rotate the coordinate system.\n pg.rotateX(frameCount * 0.01);\n pg.rotateY(frameCount * 0.01);\n\n // Style the box.\n pg.noStroke();\n\n // Draw the box.\n pg.box(7.5);\n\n // Start drawing to the box p5.Framebuffer.\n boxLayer.end();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Graphics/createFramebuffer"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Graphics/remove.mdx"],"slug":[0,"en/p5graphics/remove"],"body":[0,"\n\n# remove\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"remove()"],"module":[0,"Rendering"],"submodule":[0,"Rendering"],"file":[0,"src/core/p5.Graphics.js"],"description":[0,"Removes the graphics buffer from the web page.
\nCalling myGraphics.remove()
removes the graphics buffer's\n
element from the web page. The graphics buffer also uses\na bit of memory on the CPU that can be freed like so:
\n// Remove the graphics buffer from the web page.\nmyGraphics.remove();\n\n// Delete the graphics buffer from CPU memory.\nmyGraphics = undefined;\n
\nNote: All variables that reference the graphics buffer must be assigned\nthe value undefined
to delete the graphics buffer from CPU memory. If any\nvariable still refers to the graphics buffer, then it won't be garbage\ncollected.
\n"],"line":[0,320],"itemtype":[0,"method"],"class":[0,"p5.Graphics"],"chainable":[0,false],"example":[1,[[0,"\n\n\n// Double-click to remove the p5.Graphics object.\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Graphics object.\n pg = createGraphics(60, 60);\n\n // Draw to the p5.Graphics object.\n pg.background(100);\n pg.circle(30, 30, 20);\n\n describe('A white circle at the center of a dark gray square disappears when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Display the p5.Graphics object if\n // it's available.\n if (pg) {\n image(pg, 20, 20);\n }\n}\n\n// Remove the p5.Graphics object when the\n// the user double-clicks.\nfunction doubleClicked() {\n // Remove the p5.Graphics object from the web page.\n pg.remove();\n pg = undefined;\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Graphics/remove"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Graphics/reset.mdx"],"slug":[0,"en/p5graphics/reset"],"body":[0,"\n\n# reset\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"reset()"],"module":[0,"Rendering"],"submodule":[0,"Rendering"],"file":[0,"src/core/p5.Graphics.js"],"description":[0,"Resets the graphics buffer's transformations and lighting.
\nBy default, the main canvas resets certain transformation and lighting\nvalues each time draw() executes. p5.Graphics
\nobjects must reset these values manually by calling myGraphics.reset()
.
\n"],"line":[0,153],"itemtype":[0,"method"],"class":[0,"p5.Graphics"],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Graphics object.\n pg = createGraphics(60, 60);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Translate the p5.Graphics object's coordinate system.\n // The translation accumulates; the white circle moves.\n pg.translate(0, 0.1);\n\n // Draw to the p5.Graphics object.\n pg.background(100);\n pg.circle(30, 0, 10);\n\n // Display the p5.Graphics object.\n image(pg, 20, 20);\n\n // Translate the main canvas' coordinate system.\n // The translation doesn't accumulate; the dark\n // square is always in the same place.\n translate(0, 0.1);\n\n // Reset the p5.Graphics object when the\n // user presses the mouse.\n if (mouseIsPressed === true) {\n pg.reset();\n }\n}\n
\n\n\n\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Graphics object.\n pg = createGraphics(60, 60);\n\n describe('A white circle at the center of a dark gray square. The image is drawn on a light gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Translate the p5.Graphics object's coordinate system.\n pg.translate(30, 30);\n\n // Draw to the p5.Graphics object.\n pg.background(100);\n pg.circle(0, 0, 10);\n\n // Display the p5.Graphics object.\n image(pg, 20, 20);\n\n // Reset the p5.Graphics object automatically.\n pg.reset();\n}\n
\n\n\n\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Graphics object using WebGL mode.\n pg = createGraphics(100, 100, WEBGL);\n\n describe(\"A sphere lit from above with a red light. The sphere's surface becomes glossy while the user clicks and holds the mouse.\");\n}\n\nfunction draw() {\n background(200);\n\n // Add a red point light from the top-right.\n pg.pointLight(255, 0, 0, 50, -100, 50);\n\n // Style the sphere.\n // It should appear glossy when the\n // lighting values are reset.\n pg.noStroke();\n pg.specularMaterial(255);\n pg.shininess(100);\n\n // Draw the sphere.\n pg.sphere(30);\n\n // Display the p5.Graphics object.\n image(pg, -50, -50);\n\n // Reset the p5.Graphics object when\n // the user presses the mouse.\n if (mouseIsPressed === true) {\n pg.reset();\n }\n}\n
\n\n\n\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Graphics object using WebGL mode.\n pg = createGraphics(100, 100, WEBGL);\n\n describe('A sphere with a glossy surface is lit from the top-right by a red light.');\n}\n\nfunction draw() {\n background(200);\n\n // Add a red point light from the top-right.\n pg.pointLight(255, 0, 0, 50, -100, 50);\n\n // Style the sphere.\n pg.noStroke();\n pg.specularMaterial(255);\n pg.shininess(100);\n\n // Draw the sphere.\n pg.sphere(30);\n\n // Display the p5.Graphics object.\n image(pg, 0, 0);\n\n // Reset the p5.Graphics object automatically.\n pg.reset();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Graphics/reset"]}],"render":[0,null]}]]]}],[0,{"name":[0,"p5.Renderer"],"entry":[0,{"id":[0,"en/p5/p5.Renderer.mdx"],"slug":[0,"en/p5/p5renderer"],"body":[0,"\n\n# p5.Renderer\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"p5.Renderer"],"module":[0,"Rendering"],"submodule":[0,"Rendering"],"file":[0,"src/core/p5.Renderer.js"],"description":[0,"Main graphics and rendering context, as well as the base API\nimplementation for p5.js \"core\". To be used as the superclass for\nRenderer2D and Renderer3D classes, respectively.
\n"],"line":[0,10],"params":[1,[[0,{"name":[0,"elt"],"description":[0,"DOM node that is wrapped
\n"],"type":[0,"HTMLElement"]}],[0,{"name":[0,"pInst"],"description":[0,"pointer to p5 instance
\n"],"type":[0,"P5"],"optional":[0,true]}],[0,{"name":[0,"isMainCanvas"],"description":[0,"whether we're using it as main canvas
\n"],"type":[0,"Boolean"],"optional":[0,true]}]]],"chainable":[0,false],"isConstructor":[0,true],"path":[0,"p5/p5.Renderer"]}],"render":[0,null]}],"entries":[1,[]]}]]]}],[0,{"name":[0,"Math"],"subcats":[1,[[0,{"name":[0],"entry":[0],"entries":[1,[]]}],[0,{"name":[0,"Calculation"],"entry":[0],"entries":[1,[[0,{"id":[0,"en/p5/abs.mdx"],"slug":[0,"en/p5/abs"],"body":[0,"\n\n# abs\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"abs()"],"module":[0,"Math"],"submodule":[0,"Calculation"],"file":[0,"src/math/calculation.js"],"description":[0,"Calculates the absolute value of a number.
\nA number's absolute value is its distance from zero on the number line.\n-5 and 5 are both five units away from zero, so calling abs(-5)
and\nabs(5)
both return 5. The absolute value of a number is always positive.
\n"],"line":[0,10],"params":[1,[[0,{"name":[0,"n"],"description":[0,"number to compute.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"absolute value of given number."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Divide the canvas.\n line(50, 0, 50, 100);\n\n // Calculate the mouse's distance from the middle.\n let h = abs(mouseX - 50);\n\n // Draw a rectangle based on the mouse's distance\n // from the middle.\n rect(0, 100 - h, 100, h);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/abs"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/ceil.mdx"],"slug":[0,"en/p5/ceil"],"body":[0,"\n\n# ceil\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"ceil()"],"module":[0,"Math"],"submodule":[0,"Calculation"],"file":[0,"src/math/calculation.js"],"description":[0,"Calculates the closest integer value that is greater than or equal to a\nnumber.
\nFor example, calling ceil(9.03)
and ceil(9.97)
both return the value\n10.
\n"],"line":[0,48],"params":[1,[[0,{"name":[0,"n"],"description":[0,"number to round up.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"rounded up number."],"type":[0,"Integer"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use RGB color with values from 0 to 1.\n colorMode(RGB, 1);\n\n noStroke();\n\n // Draw the left rectangle.\n let r = 0.3;\n fill(r, 0, 0);\n rect(0, 0, 50, 100);\n\n // Round r up to 1.\n r = ceil(r);\n\n // Draw the right rectangle.\n fill(r, 0, 0);\n rect(50, 0, 50, 100);\n\n describe('Two rectangles. The one on the left is dark red and the one on the right is bright red.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/ceil"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/constrain.mdx"],"slug":[0,"en/p5/constrain"],"body":[0,"\n\n# constrain\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"constrain()"],"module":[0,"Math"],"submodule":[0,"Calculation"],"file":[0,"src/math/calculation.js"],"description":[0,"Constrains a number between a minimum and maximum value.
\n"],"line":[0,91],"params":[1,[[0,{"name":[0,"n"],"description":[0,"number to constrain.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"low"],"description":[0,"minimum limit.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"high"],"description":[0,"maximum limit.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"constrained number."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n let x = constrain(mouseX, 33, 67);\n let y = 50;\n\n strokeWeight(5);\n point(x, y);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Two vertical lines. Two circles move horizontally with the mouse. One circle stops at the vertical lines.');\n}\n\nfunction draw() {\n background(200);\n\n // Set boundaries and draw them.\n let leftWall = 25;\n let rightWall = 75;\n line(leftWall, 0, leftWall, 100);\n line(rightWall, 0, rightWall, 100);\n\n // Draw a circle that follows the mouse freely.\n fill(255);\n circle(mouseX, 33, 9);\n\n // Draw a circle that's constrained.\n let xc = constrain(mouseX, leftWall, rightWall);\n fill(0);\n circle(xc, 67, 9);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/constrain"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/dist.mdx"],"slug":[0,"en/p5/dist"],"body":[0,"\n\n# dist\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"dist()"],"module":[0,"Math"],"submodule":[0,"Calculation"],"file":[0,"src/math/calculation.js"],"description":[0,"Calculates the distance between two points.
\nThe version of dist()
with four parameters calculates distance in two\ndimensions.
\nThe version of dist()
with six parameters calculates distance in three\ndimensions.
\nUse p5.Vector.dist() to calculate the\ndistance between two p5.Vector objects.
\n"],"line":[0,155],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"x1"],"description":[0,"x-coordinate of the first point.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y1"],"description":[0,"y-coordinate of the first point.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"x2"],"description":[0,"x-coordinate of the second point.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y2"],"description":[0,"y-coordinate of the second point.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"x1"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"y1"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"z1"],"description":[0,"z-coordinate of the first point.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"x2"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"y2"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"z2"],"description":[0,"z-coordinate of the second point.
\n"],"type":[0,"Number"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"distance between the two points."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Set the coordinates.\n let x1 = 10;\n let y1 = 50;\n let x2 = 90;\n let y2 = 50;\n\n // Draw the points and a line connecting them.\n line(x1, y1, x2, y2);\n strokeWeight(5);\n point(x1, y1);\n point(x2, y2);\n\n // Calculate the distance.\n let d = dist(x1, y1, x2, y2);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the distance.\n text(d, 43, 40);\n\n describe('Two dots connected by a horizontal line. The number 80 is written above the center of the line.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/dist"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/exp.mdx"],"slug":[0,"en/p5/exp"],"body":[0,"\n\n# exp\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"exp()"],"module":[0,"Math"],"submodule":[0,"Calculation"],"file":[0,"src/math/calculation.js"],"description":[0,"Calculates the value of Euler's number e (2.71828...) raised to the power\nof a number.
\n"],"line":[0,230],"params":[1,[[0,{"name":[0,"n"],"description":[0,"exponent to raise.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"e^n"],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Top-left.\n let d = exp(1);\n circle(10, 10, d);\n\n // Left-center.\n d = exp(2);\n circle(20, 20, d);\n\n // Right-center.\n d = exp(3);\n circle(40, 40, d);\n\n // Bottom-right.\n d = exp(4);\n circle(80, 80, d);\n\n describe('A series of circles that grow exponentially from top left to bottom right.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots that grow exponentially from left to right.');\n}\n\nfunction draw() {\n // Invert the y-axis.\n scale(1, -1);\n translate(0, -100);\n\n // Calculate the coordinates.\n let x = frameCount;\n let y = 0.005 * exp(x * 0.1);\n\n // Draw a point.\n point(x, y);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/exp"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/floor.mdx"],"slug":[0,"en/p5/floor"],"body":[0,"\n\n# floor\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"floor()"],"module":[0,"Math"],"submodule":[0,"Calculation"],"file":[0,"src/math/calculation.js"],"description":[0,"Calculates the closest integer value that is less than or equal to the\nvalue of a number.
\n"],"line":[0,294],"params":[1,[[0,{"name":[0,"n"],"description":[0,"number to round down.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"rounded down number."],"type":[0,"Integer"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use RGB color with values from 0 to 1.\n colorMode(RGB, 1);\n\n noStroke();\n\n // Draw the left rectangle.\n let r = 0.8;\n fill(r, 0, 0);\n rect(0, 0, 50, 100);\n\n // Round r down to 0.\n r = floor(r);\n\n // Draw the right rectangle.\n fill(r, 0, 0);\n rect(50, 0, 50, 100);\n\n describe('Two rectangles. The one on the left is bright red and the one on the right is black.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/floor"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/fract.mdx"],"slug":[0,"en/p5/fract"],"body":[0,"\n\n# fract\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"fract()"],"module":[0,"Math"],"submodule":[0,"Calculation"],"file":[0,"src/math/calculation.js"],"description":[0,"Calculates the fractional part of a number.
\nA number's fractional part includes its decimal values. For example,\nfract(12.34)
returns 0.34.
\n"],"line":[0,1048],"params":[1,[[0,{"name":[0,"n"],"description":[0,"number whose fractional part will be found.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"fractional part of n."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Original number.\n let n = 56.78;\n text(n, 50, 33);\n\n // Fractional part.\n let f = fract(n);\n text(f, 50, 67);\n\n describe('The number 56.78 written above the number 0.78.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/fract"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/lerp.mdx"],"slug":[0,"en/p5/lerp"],"body":[0,"\n\n# lerp\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"lerp()"],"module":[0,"Math"],"submodule":[0,"Calculation"],"file":[0,"src/math/calculation.js"],"description":[0,"Calculates a number between two numbers at a specific increment.
\nThe amt
parameter is the amount to interpolate between the two numbers.\n0.0 is equal to the first number, 0.1 is very near the first number, 0.5 is\nhalf-way in between, and 1.0 is equal to the second number. The lerp()
\nfunction is convenient for creating motion along a straight path and for\ndrawing dotted lines.
\nIf the value of amt
is less than 0 or more than 1, lerp()
will return a\nnumber outside of the original interval. For example, calling\nlerp(0, 10, 1.5)
will return 15.
\n"],"line":[0,332],"params":[1,[[0,{"name":[0,"start"],"description":[0,"first value.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"stop"],"description":[0,"second value.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"amt"],"description":[0,"number.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"lerped value."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Declare variables for coordinates.\n let a = 20;\n let b = 80;\n let c = lerp(a, b, 0.2);\n let d = lerp(a, b, 0.5);\n let e = lerp(a, b, 0.8);\n\n strokeWeight(5);\n\n // Draw the original points in black.\n stroke(0);\n point(a, 50);\n point(b, 50);\n\n // Draw the lerped points in gray.\n stroke(100);\n point(c, 50);\n point(d, 50);\n point(e, 50);\n\n describe('Five points in a horizontal line. The outer points are black and the inner points are gray.');\n}\n
\n\n\n\n\nlet x = 50;\nlet y = 50;\nlet targetX = 50;\nlet targetY = 50;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n 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.');\n}\n\nfunction draw() {\n background(220);\n\n // Move x and y toward the target.\n x = lerp(x, targetX, 0.05);\n y = lerp(y, targetY, 0.05);\n\n // Draw the circle.\n circle(x, y, 20);\n}\n\n// Set x and y when the user clicks the mouse.\nfunction mouseClicked() {\n x = mouseX;\n y = mouseY;\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/lerp"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/log.mdx"],"slug":[0,"en/p5/log"],"body":[0,"\n\n# log\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"log()"],"module":[0,"Math"],"submodule":[0,"Calculation"],"file":[0,"src/math/calculation.js"],"description":[0,"Calculates the natural logarithm (the base-e logarithm) of a number.
\nlog()
expects the n
parameter to be a value greater than 0 because\nthe natural logarithm is defined that way.
\n"],"line":[0,423],"params":[1,[[0,{"name":[0,"n"],"description":[0,"number greater than 0.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"natural logarithm of n."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Top-left.\n let d = log(50);\n circle(33, 33, d);\n\n // Bottom-right.\n d = log(500000000);\n circle(67, 67, d);\n\n describe('Two white circles. The circle at the top-left is small. The circle at the bottom-right is about five times larger.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots that get higher slowly from left to right.');\n}\n\nfunction draw() {\n // Invert the y-axis.\n scale(1, -1);\n translate(0, -100);\n\n // Calculate coordinates.\n let x = frameCount;\n let y = 15 * log(x);\n\n // Draw a point.\n point(x, y);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/log"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/mag.mdx"],"slug":[0,"en/p5/mag"],"body":[0,"\n\n# mag\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"mag()"],"module":[0,"Math"],"submodule":[0,"Calculation"],"file":[0,"src/math/calculation.js"],"description":[0,"Calculates the magnitude, or length, of a vector.
\nA vector can be thought of in different ways. In one view, a vector is a\npoint in space. The vector's components, x
and y
, are the point's\ncoordinates (x, y)
. A vector's magnitude is the distance from the origin\n(0, 0)
to (x, y)
. mag(x, y)
is a shortcut for calling\ndist(0, 0, x, y)
.
\nA vector can also be thought of as an arrow pointing in space. This view is\nhelpful for programming motion. See p5.Vector for\nmore details.
\nUse p5.Vector.mag() to calculate the\nmagnitude of a p5.Vector object.
\n"],"line":[0,481],"params":[1,[[0,{"name":[0,"x"],"description":[0,"first component.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"second component.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"magnitude of vector."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Set the vector's components.\n let x = 30;\n let y = 40;\n\n // Calculate the magnitude.\n let m = mag(x, y);\n\n // Style the text.\n textSize(16);\n\n // Display the vector and its magnitude.\n line(0, 0, x, y);\n text(m, x, y);\n\n describe('A diagonal line is drawn from the top left of the canvas. The number 50 is written at the end of the line.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/mag"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/map.mdx"],"slug":[0,"en/p5/map"],"body":[0,"\n\n# map\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"map()"],"module":[0,"Math"],"submodule":[0,"Calculation"],"file":[0,"src/math/calculation.js"],"description":[0,"Re-maps a number from one range to another.
\nFor example, calling map(2, 0, 10, 0, 100)
returns 20. The first three\narguments set the original value to 2 and the original range from 0 to 10.\nThe last two arguments set the target range from 0 to 100. 20's position\nin the target range [0, 100] is proportional to 2's position in the\noriginal range [0, 10].
\nThe sixth parameter, withinBounds
, is optional. By default, map()
can\nreturn values outside of the target range. For example,\nmap(11, 0, 10, 0, 100)
returns 110. Passing true
as the sixth parameter\nconstrains the remapped value to the target range. For example,\nmap(11, 0, 10, 0, 100, true)
returns 100.
\n"],"line":[0,534],"params":[1,[[0,{"name":[0,"value"],"description":[0,"the value to be remapped.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"start1"],"description":[0,"lower bound of the value's current range.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"stop1"],"description":[0,"upper bound of the value's current range.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"start2"],"description":[0,"lower bound of the value's target range.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"stop2"],"description":[0,"upper bound of the value's target range.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"withinBounds"],"description":[0,"constrain the value to the newly mapped range.
\n"],"type":[0,"Boolean"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"remapped number."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw the top line.\n line(0, 25, mouseX, 25);\n\n // Remap mouseX from [0, 100] to [0, 50].\n let x = map(mouseX, 0, 100, 0, 50);\n\n // Draw the bottom line.\n line(0, 75, x, 75);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A circle changes color from black to white as the mouse moves from left to right.');\n}\n\nfunction draw() {\n background(200);\n\n // Remap mouseX from [0, 100] to [0, 255]\n let c = map(mouseX, 0, 100, 0, 255);\n\n // Style the circle.\n fill(c);\n\n // Draw the circle.\n circle(50, 50, 20);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/map"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/max.mdx"],"slug":[0,"en/p5/max"],"body":[0,"\n\n# max\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"max()"],"module":[0,"Math"],"submodule":[0,"Calculation"],"file":[0,"src/math/calculation.js"],"description":[0,"Returns the largest value in a sequence of numbers.
\nThe version of max()
with one parameter interprets it as an array of\nnumbers and returns the largest number.
\nThe version of max()
with two or more parameters interprets them as\nindividual numbers and returns the largest number.
\n"],"line":[0,618],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"n0"],"description":[0,"first number to compare.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"n1"],"description":[0,"second number to compare.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"nums"],"description":[0,"numbers to compare.
\n"],"type":[0,"Number[]"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"maximum number."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate the maximum of 10, 5, and 20.\n let m = max(10, 5, 20);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the max.\n text(m, 50, 50);\n\n describe('The number 20 written in the middle of a gray square.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of numbers.\n let numbers = [10, 5, 20];\n\n // Calculate the maximum of the array.\n let m = max(numbers);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the max.\n text(m, 50, 50);\n\n describe('The number 20 written in the middle of a gray square.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/max"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/min.mdx"],"slug":[0,"en/p5/min"],"body":[0,"\n\n# min\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"min()"],"module":[0,"Math"],"submodule":[0,"Calculation"],"file":[0,"src/math/calculation.js"],"description":[0,"Returns the smallest value in a sequence of numbers.
\nThe version of min()
with one parameter interprets it as an array of\nnumbers and returns the smallest number.
\nThe version of min()
with two or more parameters interprets them as\nindividual numbers and returns the smallest number.
\n"],"line":[0,695],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"n0"],"description":[0,"first number to compare.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"n1"],"description":[0,"second number to compare.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"nums"],"description":[0,"numbers to compare.
\n"],"type":[0,"Number[]"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"minimum number."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate the minimum of 10, 5, and 20.\n let m = min(10, 5, 20);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the min.\n text(m, 50, 50);\n\n describe('The number 5 written in the middle of a gray square.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of numbers.\n let numbers = [10, 5, 20];\n\n // Calculate the minimum of the array.\n let m = min(numbers);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the min.\n text(m, 50, 50);\n\n describe('The number 5 written in the middle of a gray square.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/min"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/norm.mdx"],"slug":[0,"en/p5/norm"],"body":[0,"\n\n# norm\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"norm()"],"module":[0,"Math"],"submodule":[0,"Calculation"],"file":[0,"src/math/calculation.js"],"description":[0,"Maps a number from one range to a value between 0 and 1.
\nFor example, norm(2, 0, 10)
returns 0.2. 2's position in the original\nrange [0, 10] is proportional to 0.2's position in the range [0, 1]. This\nis the same as calling map(2, 0, 10, 0, 1)
.
\nNumbers outside of the original range are not constrained between 0 and 1.\nOut-of-range values are often intentional and useful.
\n"],"line":[0,772],"params":[1,[[0,{"name":[0,"value"],"description":[0,"incoming value to be normalized.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"start"],"description":[0,"lower bound of the value's current range.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"stop"],"description":[0,"upper bound of the value's current range.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"normalized number."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use RGB color with values from 0 to 1.\n colorMode(RGB, 1);\n\n describe('A square changes color from black to red as the mouse moves from left to right.');\n}\n\nfunction draw() {\n // Calculate the redValue.\n let redValue = norm(mouseX, 0, 100);\n\n // Paint the background.\n background(redValue, 0, 0);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/norm"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/pow.mdx"],"slug":[0,"en/p5/pow"],"body":[0,"\n\n# pow\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"pow()"],"module":[0,"Math"],"submodule":[0,"Calculation"],"file":[0,"src/math/calculation.js"],"description":[0,"Calculates exponential expressions such as 23.
\nFor example, pow(2, 3)
evaluates the expression\n2 × 2 × 2. pow(2, -3)
evaluates 1 ÷\n(2 × 2 × 2).
\n"],"line":[0,815],"params":[1,[[0,{"name":[0,"n"],"description":[0,"base of the exponential expression.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"e"],"description":[0,"power by which to raise the base.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"n^e."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Set the base of the exponent.\n let base = 3;\n\n // Top-left.\n let d = pow(base, 1);\n circle(10, 10, d);\n\n // Left-center.\n d = pow(base, 2);\n circle(20, 20, d);\n\n // Right-center.\n d = pow(base, 3);\n circle(40, 40, d);\n\n // Bottom-right.\n d = pow(base, 4);\n circle(80, 80, d);\n\n describe('A series of circles that grow exponentially from top left to bottom right.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/pow"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/round.mdx"],"slug":[0,"en/p5/round"],"body":[0,"\n\n# round\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"round()"],"module":[0,"Math"],"submodule":[0,"Calculation"],"file":[0,"src/math/calculation.js"],"description":[0,"Calculates the integer closest to a number.
\nFor example, round(133.8)
returns the value 134.
\nThe second parameter, decimals
, is optional. It sets the number of\ndecimal places to use when rounding. For example, round(12.34, 1)
returns\n12.3. decimals
is 0 by default.
\n"],"line":[0,861],"params":[1,[[0,{"name":[0,"n"],"description":[0,"number to round.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"decimals"],"description":[0,"number of decimal places to round to, default is 0.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"rounded number."],"type":[0,"Integer"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Round a number.\n let x = round(4.2);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the rounded number.\n text(x, 50, 50);\n\n describe('The number 4 written in middle of the canvas.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Round a number to 2 decimal places.\n let x = round(12.782383, 2);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the rounded number.\n text(x, 50, 50);\n\n describe('The number 12.78 written in middle of canvas.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/round"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/sq.mdx"],"slug":[0,"en/p5/sq"],"body":[0,"\n\n# sq\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"sq()"],"module":[0,"Math"],"submodule":[0,"Calculation"],"file":[0,"src/math/calculation.js"],"description":[0,"Calculates the square of a number.
\nSquaring a number means multiplying the number by itself. For example,\nsq(3)
evaluates 3 × 3 which is 9. sq(-3)
evaluates -3 × -3\nwhich is also 9. Multiplying two negative numbers produces a positive\nnumber. The value returned by sq()
is always positive.
\n"],"line":[0,928],"params":[1,[[0,{"name":[0,"n"],"description":[0,"number to square.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"squared number."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Top-left.\n let d = sq(3);\n circle(33, 33, d);\n\n // Bottom-right.\n d = sq(6);\n circle(67, 67, d);\n\n describe('Two white circles. The circle at the top-left is small. The circle at the bottom-right is four times larger.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots that get higher quickly from left to right.');\n}\n\nfunction draw() {\n // Invert the y-axis.\n scale(1, -1);\n translate(0, -100);\n\n // Calculate the coordinates.\n let x = frameCount;\n let y = 0.01 * sq(x);\n\n // Draw the point.\n point(x, y);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/sq"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/sqrt.mdx"],"slug":[0,"en/p5/sqrt"],"body":[0,"\n\n# sqrt\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"sqrt()"],"module":[0,"Math"],"submodule":[0,"Calculation"],"file":[0,"src/math/calculation.js"],"description":[0,"Calculates the square root of a number.
\nA number's square root can be multiplied by itself to produce the original\nnumber. For example, sqrt(9)
returns 3 because 3 × 3 = 9. sqrt()
\nalways returns a positive value. sqrt()
doesn't work with negative arguments\nsuch as sqrt(-9)
.
\n"],"line":[0,988],"params":[1,[[0,{"name":[0,"n"],"description":[0,"non-negative number to square root.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"square root of number."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Top-left.\n let d = sqrt(16);\n circle(33, 33, d);\n\n // Bottom-right.\n d = sqrt(1600);\n circle(67, 67, d);\n\n describe('Two white circles. The circle at the top-left is small. The circle at the bottom-right is ten times larger.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots that get higher slowly from left to right.');\n}\n\nfunction draw() {\n // Invert the y-axis.\n scale(1, -1);\n translate(0, -100);\n\n // Calculate the coordinates.\n let x = frameCount;\n let y = 5 * sqrt(x);\n\n // Draw the point.\n point(x, y);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/sqrt"]}],"render":[0,null]}]]]}],[0,{"name":[0,"Noise"],"entry":[0],"entries":[1,[[0,{"id":[0,"en/p5/noise.mdx"],"slug":[0,"en/p5/noise"],"body":[0,"\n\n# noise\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"noise()"],"module":[0,"Math"],"submodule":[0,"Noise"],"file":[0,"src/math/noise.js"],"description":[0,"Returns random numbers that can be tuned to feel organic.
\nValues returned by random() and\nrandomGaussian() can change by large\namounts between function calls. By contrast, values returned by noise()
\ncan be made \"smooth\". Calls to noise()
with similar inputs will produce\nsimilar outputs. noise()
is used to create textures, motion, shapes,\nterrains, and so on. Ken Perlin invented noise()
while animating the\noriginal Tron film in the 1980s.
\nnoise()
always returns values between 0 and 1. It returns the same value\nfor a given input while a sketch is running. noise()
produces different\nresults each time a sketch runs. The\nnoiseSeed() function can be used to generate\nthe same sequence of Perlin noise values each time a sketch runs.
\nThe character of the noise can be adjusted in two ways. The first way is to\nscale the inputs. noise()
interprets inputs as coordinates. The sequence\nof noise values will be smoother when the input coordinates are closer. The\nsecond way is to use the noiseDetail()\nfunction.
\nThe version of noise()
with one parameter computes noise values in one\ndimension. This dimension can be thought of as space, as in noise(x)
, or\ntime, as in noise(t)
.
\nThe version of noise()
with two parameters computes noise values in two\ndimensions. These dimensions can be thought of as space, as in\nnoise(x, y)
, or space and time, as in noise(x, t)
.
\nThe version of noise()
with three parameters computes noise values in\nthree dimensions. These dimensions can be thought of as space, as in\nnoise(x, y, z)
, or space and time, as in noise(x, y, t)
.
\n"],"line":[0,36],"params":[1,[[0,{"name":[0,"x"],"description":[0,"x-coordinate in noise space.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"y-coordinate in noise space.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"z"],"description":[0,"z-coordinate in noise space.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"Perlin noise value at specified coordinates."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A black dot moves randomly on a gray square.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the coordinates.\n let x = 100 * noise(0.005 * frameCount);\n let y = 100 * noise(0.005 * frameCount + 10000);\n\n // Draw the point.\n strokeWeight(5);\n point(x, y);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A black dot moves randomly on a gray square.');\n}\n\nfunction draw() {\n background(200);\n\n // Set the noise level and scale.\n let noiseLevel = 100;\n let noiseScale = 0.005;\n\n // Scale the input coordinate.\n let nt = noiseScale * frameCount;\n\n // Compute the noise values.\n let x = noiseLevel * noise(nt);\n let y = noiseLevel * noise(nt + 10000);\n\n // Draw the point.\n strokeWeight(5);\n point(x, y);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A hilly terrain drawn in gray against a black sky.');\n}\n\nfunction draw() {\n // Set the noise level and scale.\n let noiseLevel = 100;\n let noiseScale = 0.02;\n\n // Scale the input coordinate.\n let x = frameCount;\n let nx = noiseScale * x;\n\n // Compute the noise value.\n let y = noiseLevel * noise(nx);\n\n // Draw the line.\n line(x, 0, x, y);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A calm sea drawn in gray against a black sky.');\n}\n\nfunction draw() {\n background(200);\n\n // Set the noise level and scale.\n let noiseLevel = 100;\n let noiseScale = 0.002;\n\n // Iterate from left to right.\n for (let x = 0; x < width; x += 1) {\n // Scale the input coordinates.\n let nx = noiseScale * x;\n let nt = noiseScale * frameCount;\n\n // Compute the noise value.\n let y = noiseLevel * noise(nx, nt);\n\n // Draw the line.\n line(x, 0, x, y);\n }\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Set the noise level and scale.\n let noiseLevel = 255;\n let noiseScale = 0.01;\n\n // Iterate from top to bottom.\n for (let y = 0; y < height; y += 1) {\n // Iterate from left to right.\n for (let x = 0; x < width; x += 1) {\n // Scale the input coordinates.\n let nx = noiseScale * x;\n let ny = noiseScale * y;\n\n // Compute the noise value.\n let c = noiseLevel * noise(nx, ny);\n\n // Draw the point.\n stroke(c);\n point(x, y);\n }\n }\n\n describe('A gray cloudy pattern.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A gray cloudy pattern that changes.');\n}\n\nfunction draw() {\n // Set the noise level and scale.\n let noiseLevel = 255;\n let noiseScale = 0.009;\n\n // Iterate from top to bottom.\n for (let y = 0; y < height; y += 1) {\n // Iterate from left to right.\n for (let x = 0; x < width; x += 1) {\n // Scale the input coordinates.\n let nx = noiseScale * x;\n let ny = noiseScale * y;\n let nt = noiseScale * frameCount;\n\n // Compute the noise value.\n let c = noiseLevel * noise(nx, ny, nt);\n\n // Draw the point.\n stroke(c);\n point(x, y);\n }\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/noise"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/noiseDetail.mdx"],"slug":[0,"en/p5/noisedetail"],"body":[0,"\n\n# noiseDetail\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"noiseDetail()"],"module":[0,"Math"],"submodule":[0,"Noise"],"file":[0,"src/math/noise.js"],"description":[0,"Adjusts the character of the noise produced by the\nnoise() function.
\nPerlin noise values are created by adding layers of noise together. The\nnoise layers, called octaves, are similar to harmonics in music. Lower\noctaves contribute more to the output signal. They define the overall\nintensity of the noise. Higher octaves create finer-grained details.
\nBy default, noise values are created by combining four octaves. Each higher\noctave contributes half as much (50% less) compared to its predecessor.\nnoiseDetail()
changes the number of octaves and the falloff amount. For\nexample, calling noiseDetail(6, 0.25)
ensures that\nnoise() will use six octaves. Each higher octave\nwill contribute 25% as much (75% less) compared to its predecessor. Falloff\nvalues between 0 and 1 are valid. However, falloff values greater than 0.5\nmight result in noise values greater than 1.
\n"],"line":[0,331],"params":[1,[[0,{"name":[0,"lod"],"description":[0,"number of octaves to be used by the noise.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"falloff"],"description":[0,"falloff factor for each octave.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Set the noise level and scale.\n let noiseLevel = 255;\n let noiseScale = 0.02;\n\n // Iterate from top to bottom.\n for (let y = 0; y < height; y += 1) {\n // Iterate from left to right.\n for (let x = 0; x < width / 2; x += 1) {\n // Scale the input coordinates.\n let nx = noiseScale * x;\n let ny = noiseScale * y;\n\n // Compute the noise value with six octaves\n // and a low falloff factor.\n noiseDetail(6, 0.25);\n let c = noiseLevel * noise(nx, ny);\n\n // Draw the left side.\n stroke(c);\n point(x, y);\n\n // Compute the noise value with four octaves\n // and a high falloff factor.\n noiseDetail(4, 0.5);\n c = noiseLevel * noise(nx, ny);\n\n // Draw the right side.\n stroke(c);\n point(x + 50, y);\n }\n }\n\n describe('Two gray cloudy patterns. The pattern on the right is cloudier than the pattern on the left.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/noiseDetail"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/noiseSeed.mdx"],"slug":[0,"en/p5/noiseseed"],"body":[0,"\n\n# noiseSeed\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"noiseSeed()"],"module":[0,"Math"],"submodule":[0,"Noise"],"file":[0,"src/math/noise.js"],"description":[0,"Sets the seed value for the noise() function.
\nBy default, noise() produces different results\neach time a sketch is run. Calling noiseSeed()
with a constant argument,\nsuch as noiseSeed(99)
, makes noise() produce the\nsame results each time a sketch is run.
\n"],"line":[0,405],"params":[1,[[0,{"name":[0,"seed"],"description":[0,"seed value.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Set the noise seed for consistent results.\n noiseSeed(99);\n\n describe('A black rectangle that grows randomly, first to the right and then to the left.');\n}\n\nfunction draw() {\n // Set the noise level and scale.\n let noiseLevel = 100;\n let noiseScale = 0.005;\n\n // Scale the input coordinate.\n let nt = noiseScale * frameCount;\n\n // Compute the noise value.\n let x = noiseLevel * noise(nt);\n\n // Draw the line.\n line(x, 0, x, height);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/noiseSeed"]}],"render":[0,null]}]]]}],[0,{"name":[0,"Random"],"entry":[0],"entries":[1,[[0,{"id":[0,"en/p5/random.mdx"],"slug":[0,"en/p5/random"],"body":[0,"\n\n# random\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"random()"],"module":[0,"Math"],"submodule":[0,"Random"],"file":[0,"src/math/random.js"],"description":[0,"Returns a random number or a random element from an array.
\nrandom()
follows uniform distribution, which means that all outcomes are\nequally likely. When random()
is used to generate numbers, all\nnumbers in the output range are equally likely to be returned. When\nrandom()
is used to select elements from an array, all elements are\nequally likely to be chosen.
\nBy default, random()
produces different results each time a sketch runs.\nThe randomSeed() function can be used to\ngenerate the same sequence of numbers or choices each time a sketch runs.
\nThe version of random()
with no parameters returns a random number from 0\nup to but not including 1.
\nThe version of random()
with one parameter works one of two ways. If the\nargument passed is a number, random()
returns a random number from 0 up\nto but not including the number. For example, calling random(5)
returns\nvalues between 0 and 5. If the argument passed is an array, random()
\nreturns a random element from that array. For example, calling\nrandom(['🦁', '🐯', '🐻'])
returns either a lion, tiger, or bear emoji.
\nThe version of random()
with two parameters returns a random number from\na given range. The arguments passed set the range's lower and upper bounds.\nFor example, calling random(-5, 10.2)
returns values from -5 up to but\nnot including 10.2.
\n"],"line":[0,86],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"min"],"description":[0,"lower bound (inclusive).
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"max"],"description":[0,"upper bound (exclusive).
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"choices"],"description":[0,"array to choose from.
\n"],"type":[0,"Array"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"random number."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get random coordinates between 0 and 100.\n let x = random(0, 100);\n let y = random(0, 100);\n\n // Draw a point.\n strokeWeight(5);\n point(x, y);\n\n describe('A black dot appears in a random position on a gray square.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get random coordinates between 0 and 100.\n let x = random(100);\n let y = random(100);\n\n // Draw the point.\n strokeWeight(5);\n point(x, y);\n\n describe('A black dot appears in a random position on a gray square.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of emoji strings.\n let animals = ['🦁', '🐯', '🐻'];\n\n // Choose a random element from the array.\n let choice = random(animals);\n\n // Style the text.\n textAlign(CENTER);\n textSize(20);\n\n // Display the emoji.\n text(choice, 50, 50);\n\n describe('An animal face is displayed at random. Either a lion, tiger, or bear.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(5);\n\n describe('A black dot moves around randomly on a gray square.');\n}\n\nfunction draw() {\n background(200);\n\n // Get random coordinates between 0 and 100.\n let x = random(100);\n let y = random(100);\n\n // Draw the point.\n strokeWeight(5);\n point(x, y);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(5);\n\n describe('A black dot moves around randomly in the middle of a gray square.');\n}\n\nfunction draw() {\n background(200);\n\n // Get random coordinates between 45 and 55.\n let x = random(45, 55);\n let y = random(45, 55);\n\n // Draw the point.\n strokeWeight(5);\n point(x, y);\n}\n
\n\n\n\n\nlet x = 50;\nlet y = 50;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A black dot moves around randomly leaving a trail.');\n}\n\nfunction draw() {\n // Update x and y randomly.\n x += random(-1, 1);\n y += random(-1, 1);\n\n // Draw the point.\n point(x, y);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/random"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/randomGaussian.mdx"],"slug":[0,"en/p5/randomgaussian"],"body":[0,"\n\n# randomGaussian\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"randomGaussian()"],"module":[0,"Math"],"submodule":[0,"Random"],"file":[0,"src/math/random.js"],"description":[0,"Returns a random number fitting a Gaussian, or normal, distribution.
\nNormal distributions look like bell curves when plotted. Values from a\nnormal distribution cluster around a central value called the mean. The\ncluster's standard deviation describes its spread.
\nBy default, randomGaussian()
produces different results each time a\nsketch runs. The randomSeed() function can be\nused to generate the same sequence of numbers each time a sketch runs.
\nThere's no minimum or maximum value that randomGaussian()
might return.\nValues far from the mean are very unlikely and values near the mean are\nvery likely.
\nThe version of randomGaussian()
with no parameters returns values with a\nmean of 0 and standard deviation of 1.
\nThe version of randomGaussian()
with one parameter interprets the\nargument passed as the mean. The standard deviation is 1.
\nThe version of randomGaussian()
with two parameters interprets the first\nargument passed as the mean and the second as the standard deviation.
\n"],"line":[0,292],"params":[1,[[0,{"name":[0,"mean"],"description":[0,"mean.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"sd"],"description":[0,"standard deviation.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"random number."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n 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.');\n}\n\nfunction draw() {\n // Style the circles.\n noStroke();\n fill(0, 10);\n\n // Uniform distribution between 0 and 100.\n let x = random(100);\n let y = 25;\n circle(x, y, 5);\n\n // Gaussian distribution with a mean of 50 and sd of 1.\n x = randomGaussian(50);\n y = 50;\n circle(x, y, 5);\n\n // Gaussian distribution with a mean of 50 and sd of 10.\n x = randomGaussian(50, 10);\n y = 75;\n circle(x, y, 5);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/randomGaussian"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/randomSeed.mdx"],"slug":[0,"en/p5/randomseed"],"body":[0,"\n\n# randomSeed\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"randomSeed()"],"module":[0,"Math"],"submodule":[0,"Random"],"file":[0,"src/math/random.js"],"description":[0,"Sets the seed value for the random() and\nrandomGaussian() functions.
\nBy default, random() and\nrandomGaussian() produce different\nresults each time a sketch is run. Calling randomSeed()
with a constant\nargument, such as randomSeed(99)
, makes these functions produce the same\nresults each time a sketch is run.
\n"],"line":[0,37],"params":[1,[[0,{"name":[0,"seed"],"description":[0,"seed value.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get random coordinates.\n let x = random(0, 100);\n let y = random(0, 100);\n\n // Draw the white circle.\n circle(x, y, 10);\n\n // Set a random seed for consistency.\n randomSeed(99);\n\n // Get random coordinates.\n x = random(0, 100);\n y = random(0, 100);\n\n // Draw the black circle.\n fill(0);\n circle(x, y, 10);\n\n describe('A white circle appears at a random position. A black circle appears at (27.4, 25.8).');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/randomSeed"]}],"render":[0,null]}]]]}],[0,{"name":[0,"Trigonometry"],"entry":[0],"entries":[1,[[0,{"id":[0,"en/p5/acos.mdx"],"slug":[0,"en/p5/acos"],"body":[0,"\n\n# acos\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"acos()"],"module":[0,"Math"],"submodule":[0,"Trigonometry"],"file":[0,"src/math/trigonometry.js"],"description":[0,"Calculates the arc cosine of a number.
\nacos()
is the inverse of cos(). It expects\narguments in the range -1 to 1. By default, acos()
returns values in the\nrange 0 to π (about 3.14). If the\nangleMode() is DEGREES
, then values are\nreturned in the range 0 to 180.
\n"],"line":[0,18],"params":[1,[[0,{"name":[0,"value"],"description":[0,"value whose arc cosine is to be returned.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"arc cosine of the given value."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate cos() and acos() values.\n let a = PI;\n let c = cos(a);\n let ac = acos(c);\n\n // Display the values.\n text(`${round(a, 3)}`, 35, 25);\n text(`${round(c, 3)}`, 35, 50);\n text(`${round(ac, 3)}`, 35, 75);\n\n describe('The numbers 3.142, -1, and 3.142 written on separate rows.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate cos() and acos() values.\n let a = PI + QUARTER_PI;\n let c = cos(a);\n let ac = acos(c);\n\n // Display the values.\n text(`${round(a, 3)}`, 35, 25);\n text(`${round(c, 3)}`, 35, 50);\n text(`${round(ac, 3)}`, 35, 75);\n\n describe('The numbers 3.927, -0.707, and 2.356 written on separate rows.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/acos"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/angleMode.mdx"],"slug":[0,"en/p5/anglemode"],"body":[0,"\n\n# angleMode\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"angleMode()"],"module":[0,"Math"],"submodule":[0,"Trigonometry"],"file":[0,"src/math/trigonometry.js"],"description":[0,"Changes the unit system used to measure angles.
\nDegrees and radians are both units for measuring angles. There are 360˚ in\none full rotation. A full rotation is 2 × π (about 6.28) radians.
\nFunctions such as rotate() and\nsin() expect angles measured radians by default.\nCalling angleMode(DEGREES)
switches to degrees. Calling\nangleMode(RADIANS)
switches back to radians.
\nCalling angleMode()
with no arguments returns current angle mode, which\nis either RADIANS
or DEGREES
.
\n"],"line":[0,551],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"mode"],"description":[0,"either RADIANS or DEGREES.
\n"],"type":[0,"Constant"]}]]]}],[0,{"params":[1,[]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Rotate 1/8 turn.\n rotate(QUARTER_PI);\n\n // Draw a line.\n line(0, 0, 80, 0);\n\n describe('A diagonal line radiating from the top-left corner of a square.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use degrees.\n angleMode(DEGREES);\n\n // Rotate 1/8 turn.\n rotate(45);\n\n // Draw a line.\n line(0, 0, 80, 0);\n\n describe('A diagonal line radiating from the top-left corner of a square.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Calculate the angle to rotate.\n let angle = TWO_PI / 7;\n\n // Move the origin to the center.\n translate(50, 50);\n\n // Style the flower.\n noStroke();\n fill(255, 50);\n\n // Draw the flower.\n for (let i = 0; i < 7; i += 1) {\n ellipse(0, 0, 80, 20);\n rotate(angle);\n }\n\n describe('A translucent white flower on a dark background.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Use degrees.\n angleMode(DEGREES);\n\n // Calculate the angle to rotate.\n let angle = 360 / 7;\n\n // Move the origin to the center.\n translate(50, 50);\n\n // Style the flower.\n noStroke();\n fill(255, 50);\n\n // Draw the flower.\n for (let i = 0; i < 7; i += 1) {\n ellipse(0, 0, 80, 20);\n rotate(angle);\n }\n\n describe('A translucent white flower on a dark background.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white ball on a string oscillates left and right.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the coordinates.\n let x = 30 * cos(frameCount * 0.05) + 50;\n let y = 50;\n\n // Draw the oscillator.\n line(50, y, x, y);\n circle(x, y, 20);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use degrees.\n angleMode(DEGREES);\n\n describe('A white ball on a string oscillates left and right.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the coordinates.\n let x = 30 * cos(frameCount * 2.86) + 50;\n let y = 50;\n\n // Draw the oscillator.\n line(50, y, x, y);\n circle(x, y, 20);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw the upper line.\n rotate(PI / 6);\n line(0, 0, 80, 0);\n\n // Use degrees.\n angleMode(DEGREES);\n\n // Draw the lower line.\n rotate(30);\n line(0, 0, 80, 0);\n\n 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.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/angleMode"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/asin.mdx"],"slug":[0,"en/p5/asin"],"body":[0,"\n\n# asin\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"asin()"],"module":[0,"Math"],"submodule":[0,"Trigonometry"],"file":[0,"src/math/trigonometry.js"],"description":[0,"Calculates the arc sine of a number.
\nasin()
is the inverse of sin(). It expects input\nvalues in the range of -1 to 1. By default, asin()
returns values in the\nrange -π ÷ 2 (about -1.57) to π ÷ 2 (about 1.57). If\nthe angleMode() is DEGREES
then values are\nreturned in the range -90 to 90.
\n"],"line":[0,80],"params":[1,[[0,{"name":[0,"value"],"description":[0,"value whose arc sine is to be returned.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"arc sine of the given value."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate sin() and asin() values.\n let a = PI / 3;\n let s = sin(a);\n let as = asin(s);\n\n // Display the values.\n text(`${round(a, 3)}`, 35, 25);\n text(`${round(s, 3)}`, 35, 50);\n text(`${round(as, 3)}`, 35, 75);\n\n describe('The numbers 1.047, 0.866, and 1.047 written on separate rows.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate sin() and asin() values.\n let a = PI + PI / 3;\n let s = sin(a);\n let as = asin(s);\n\n // Display the values.\n text(`${round(a, 3)}`, 35, 25);\n text(`${round(s, 3)}`, 35, 50);\n text(`${round(as, 3)}`, 35, 75);\n\n describe('The numbers 4.189, -0.866, and -1.047 written on separate rows.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/asin"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/atan.mdx"],"slug":[0,"en/p5/atan"],"body":[0,"\n\n# atan\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"atan()"],"module":[0,"Math"],"submodule":[0,"Trigonometry"],"file":[0,"src/math/trigonometry.js"],"description":[0,"Calculates the arc tangent of a number.
\natan()
is the inverse of tan(). It expects input\nvalues in the range of -Infinity to Infinity. By default, atan()
returns\nvalues in the range -π ÷ 2 (about -1.57) to π ÷ 2\n(about 1.57). If the angleMode() is DEGREES
\nthen values are returned in the range -90 to 90.
\n"],"line":[0,142],"params":[1,[[0,{"name":[0,"value"],"description":[0,"value whose arc tangent is to be returned.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"arc tangent of the given value."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate tan() and atan() values.\n let a = PI / 3;\n let t = tan(a);\n let at = atan(t);\n\n // Display the values.\n text(`${round(a, 3)}`, 35, 25);\n text(`${round(t, 3)}`, 35, 50);\n text(`${round(at, 3)}`, 35, 75);\n\n describe('The numbers 1.047, 1.732, and 1.047 written on separate rows.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate tan() and atan() values.\n let a = PI + PI / 3;\n let t = tan(a);\n let at = atan(t);\n\n // Display the values.\n text(`${round(a, 3)}`, 35, 25);\n text(`${round(t, 3)}`, 35, 50);\n text(`${round(at, 3)}`, 35, 75);\n\n describe('The numbers 4.189, 1.732, and 1.047 written on separate rows.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/atan"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/atan2.mdx"],"slug":[0,"en/p5/atan2"],"body":[0,"\n\n# atan2\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"atan2()"],"module":[0,"Math"],"submodule":[0,"Trigonometry"],"file":[0,"src/math/trigonometry.js"],"description":[0,"Calculates the angle formed by a point, the origin, and the positive\nx-axis.
\natan2()
is most often used for orienting geometry to the mouse's\nposition, as in atan2(mouseY, mouseX)
. The first parameter is the point's\ny-coordinate and the second parameter is its x-coordinate.
\nBy default, atan2()
returns values in the range\n-π (about -3.14) to π (3.14). If the\nangleMode() is DEGREES
, then values are\nreturned in the range -180 to 180.
\n"],"line":[0,204],"params":[1,[[0,{"name":[0,"y"],"description":[0,"y-coordinate of the point.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"x"],"description":[0,"x-coordinate of the point.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"arc tangent of the given point."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A rectangle at the top-left of the canvas rotates with mouse movements.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the angle between the mouse\n // and the origin.\n let a = atan2(mouseY, mouseX);\n\n // Rotate.\n rotate(a);\n\n // Draw the shape.\n rect(0, 0, 60, 10);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A rectangle at the center of the canvas rotates with mouse movements.');\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Get the mouse's coordinates relative to the origin.\n let x = mouseX - 50;\n let y = mouseY - 50;\n\n // Calculate the angle between the mouse and the origin.\n let a = atan2(y, x);\n\n // Rotate.\n rotate(a);\n\n // Draw the shape.\n rect(-30, -5, 60, 10);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/atan2"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/cos.mdx"],"slug":[0,"en/p5/cos"],"body":[0,"\n\n# cos\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"cos()"],"module":[0,"Math"],"submodule":[0,"Trigonometry"],"file":[0,"src/math/trigonometry.js"],"description":[0,"Calculates the cosine of an angle.
\ncos()
is useful for many geometric tasks in creative coding. The values\nreturned oscillate between -1 and 1 as the input angle increases. cos()
\ntakes into account the current angleMode().
\n"],"line":[0,281],"params":[1,[[0,{"name":[0,"angle"],"description":[0,"the angle in radians unless specified by angleMode().
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"cosine of the angle."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white ball on a string oscillates left and right.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the coordinates.\n let x = 30 * cos(frameCount * 0.05) + 50;\n let y = 50;\n\n // Draw the oscillator.\n line(50, y, x, y);\n circle(x, y, 20);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots form a wave pattern.');\n}\n\nfunction draw() {\n // Calculate the coordinates.\n let x = frameCount;\n let y = 30 * cos(x * 0.1) + 50;\n\n // Draw the point.\n point(x, y);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots form an infinity symbol.');\n}\n\nfunction draw() {\n // Calculate the coordinates.\n let x = 30 * cos(frameCount * 0.1) + 50;\n let y = 10 * sin(frameCount * 0.2) + 50;\n\n // Draw the point.\n point(x, y);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/cos"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/degrees.mdx"],"slug":[0,"en/p5/degrees"],"body":[0,"\n\n# degrees\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"degrees()"],"module":[0,"Math"],"submodule":[0,"Trigonometry"],"file":[0,"src/math/trigonometry.js"],"description":[0,"Converts an angle measured in radians to its value in degrees.
\nDegrees and radians are both units for measuring angles. There are 360˚ in\none full rotation. A full rotation is 2 × π (about 6.28) radians.
\nThe same angle can be expressed in with either unit. For example, 90° is a\nquarter of a full rotation. The same angle is 2 × π ÷ 4\n(about 1.57) radians.
\n"],"line":[0,479],"params":[1,[[0,{"name":[0,"radians"],"description":[0,"radians value to convert to degrees.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"converted angle."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate the angle conversion.\n let rad = QUARTER_PI;\n let deg = degrees(rad);\n\n // Display the conversion.\n text(`${round(rad, 2)} rad = ${deg}˚`, 10, 50);\n\n describe('The text \"0.79 rad = 45˚\".');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/degrees"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/radians.mdx"],"slug":[0,"en/p5/radians"],"body":[0,"\n\n# radians\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"radians()"],"module":[0,"Math"],"submodule":[0,"Trigonometry"],"file":[0,"src/math/trigonometry.js"],"description":[0,"Converts an angle measured in degrees to its value in radians.
\nDegrees and radians are both units for measuring angles. There are 360˚ in\none full rotation. A full rotation is 2 × π (about 6.28) radians.
\nThe same angle can be expressed in with either unit. For example, 90° is a\nquarter of a full rotation. The same angle is 2 × π ÷ 4\n(about 1.57) radians.
\n"],"line":[0,515],"params":[1,[[0,{"name":[0,"degrees"],"description":[0,"degree value to convert to radians.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"converted angle."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Caclulate the angle conversion.\n let deg = 45;\n let rad = radians(deg);\n\n // Display the angle conversion.\n text(`${deg}˚ = ${round(rad, 3)} rad`, 10, 50);\n\n describe('The text \"45˚ = 0.785 rad\".');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/radians"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/sin.mdx"],"slug":[0,"en/p5/sin"],"body":[0,"\n\n# sin\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"sin()"],"module":[0,"Math"],"submodule":[0,"Trigonometry"],"file":[0,"src/math/trigonometry.js"],"description":[0,"Calculates the sine of an angle.
\nsin()
is useful for many geometric tasks in creative coding. The values\nreturned oscillate between -1 and 1 as the input angle increases. sin()
\ntakes into account the current angleMode().
\n"],"line":[0,361],"params":[1,[[0,{"name":[0,"angle"],"description":[0,"the angle in radians unless specified by angleMode().
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"sine of the angle."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white ball on a string oscillates up and down.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the coordinates.\n let x = 50;\n let y = 30 * sin(frameCount * 0.05) + 50;\n\n // Draw the oscillator.\n line(50, y, x, y);\n circle(x, y, 20);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots form a wave pattern.');\n}\n\nfunction draw() {\n // Calculate the coordinates.\n let x = frameCount;\n let y = 30 * sin(x * 0.1) + 50;\n\n // Draw the point.\n point(x, y);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots form an infinity symbol.');\n}\n\nfunction draw() {\n // Calculate the coordinates.\n let x = 30 * cos(frameCount * 0.1) + 50;\n let y = 10 * sin(frameCount * 0.2) + 50;\n\n // Draw the point.\n point(x, y);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/sin"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/tan.mdx"],"slug":[0,"en/p5/tan"],"body":[0,"\n\n# tan\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"tan()"],"module":[0,"Math"],"submodule":[0,"Trigonometry"],"file":[0,"src/math/trigonometry.js"],"description":[0,"Calculates the tangent of an angle.
\ntan()
is useful for many geometric tasks in creative coding. The values\nreturned range from -Infinity to Infinity and repeat periodically as the\ninput angle increases. tan()
takes into account the current\nangleMode().
\n"],"line":[0,441],"params":[1,[[0,{"name":[0,"angle"],"description":[0,"the angle in radians unless specified by angleMode().
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"tangent of the angle."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n 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.');\n}\n\nfunction draw() {\n // Calculate the coordinates.\n let x = frameCount;\n let y = 5 * tan(x * 0.1) + 50;\n\n // Draw the point.\n point(x, y);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/tan"]}],"render":[0,null]}]]]}],[0,{"name":[0,"Vector"],"entry":[0],"entries":[1,[[0,{"id":[0,"en/p5/createVector.mdx"],"slug":[0,"en/p5/createvector"],"body":[0,"\n\n# createVector\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createVector()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/math.js"],"description":[0,"Creates a new p5.Vector object.
\nA vector can be thought of in different ways. In one view, a vector is like\nan arrow pointing in space. Vectors have both magnitude (length) and\ndirection. This view is helpful for programming motion.
\nA vector's components determine its magnitude and direction. For example,\ncalling createVector(3, 4)
creates a new\np5.Vector object with an x-component of 3 and a\ny-component of 4. From the origin, this vector's tip is 3 units to the\nright and 4 units down.
\np5.Vector objects are often used to program\nmotion because they simplify the math. For example, a moving ball has a\nposition and a velocity. Position describes where the ball is in space. The\nball's position vector extends from the origin to the ball's center.\nVelocity describes the ball's speed and the direction it's moving. If the\nball is moving straight up, its velocity vector points straight up. Adding\nthe ball's velocity vector to its position vector moves it, as in\npos.add(vel)
. Vector math relies on methods inside the\np5.Vector class.
\n"],"line":[0,10],"params":[1,[[0,{"name":[0,"x"],"description":[0,"x component of the vector.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"y"],"description":[0,"y component of the vector.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"z"],"description":[0,"z component of the vector.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.Vector object."],"type":[0,"p5.Vector"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create p5.Vector objects.\n let p1 = createVector(25, 25);\n let p2 = createVector(50, 50);\n let p3 = createVector(75, 75);\n\n // Draw the dots.\n strokeWeight(5);\n point(p1);\n point(p2);\n point(p3);\n\n describe('Three black dots form a diagonal line from top left to bottom right.');\n}\n
\n\n\n\n\nlet pos;\nlet vel;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create p5.Vector objects.\n pos = createVector(50, 100);\n vel = createVector(0, -1);\n\n describe('A black dot moves from bottom to top on a gray square. The dot reappears at the bottom when it reaches the top.');\n}\n\nfunction draw() {\n background(200);\n\n // Add velocity to position.\n pos.add(vel);\n\n // If the dot reaches the top of the canvas,\n // restart from the bottom.\n if (pos.y < 0) {\n pos.y = 100;\n }\n\n // Draw the dot.\n strokeWeight(5);\n point(pos);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/createVector"]}],"render":[0,null]}]]]}],[0,{"name":[0,"p5.Vector"],"entry":[0,{"id":[0,"en/p5/p5.Vector.mdx"],"slug":[0,"en/p5/p5vector"],"body":[0,"\n\n# p5.Vector\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"p5.Vector"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"A class to describe a two or three-dimensional vector.
\nA vector can be thought of in different ways. In one view, a vector is like\nan arrow pointing in space. Vectors have both magnitude (length) and\ndirection.
\np5.Vector
objects are often used to program motion because they simplify\nthe math. For example, a moving ball has a position and a velocity.\nPosition describes where the ball is in space. The ball's position vector\nextends from the origin to the ball's center. Velocity describes the ball's\nspeed and the direction it's moving. If the ball is moving straight up, its\nvelocity vector points straight up. Adding the ball's velocity vector to\nits position vector moves it, as in pos.add(vel)
. Vector math relies on\nmethods inside the p5.Vector
class.
\nNote: createVector() is the recommended way\nto make an instance of this class.
\n"],"line":[0,11],"params":[1,[[0,{"name":[0,"x"],"description":[0,"x component of the vector.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"y"],"description":[0,"y component of the vector.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"z"],"description":[0,"z component of the vector.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"chainable":[0,false],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create p5.Vector objects.\n let p1 = createVector(25, 25);\n let p2 = createVector(75, 75);\n\n // Style the points.\n strokeWeight(5);\n\n // Draw the first point using a p5.Vector.\n point(p1);\n\n // Draw the second point using a p5.Vector's components.\n point(p2.x, p2.y);\n\n describe('Two black dots on a gray square, one at the top left and the other at the bottom right.');\n}\n
\n\n\n\n\nlet pos;\nlet vel;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create p5.Vector objects.\n pos = createVector(50, 100);\n vel = createVector(0, -1);\n\n describe('A black dot moves from bottom to top on a gray square. The dot reappears at the bottom when it reaches the top.');\n}\n\nfunction draw() {\n background(200);\n\n // Add velocity to position.\n pos.add(vel);\n\n // If the dot reaches the top of the canvas,\n // restart from the bottom.\n if (pos.y < 0) {\n pos.y = 100;\n }\n\n // Draw the dot.\n strokeWeight(5);\n point(pos);\n}\n
\n"]]],"methods":[0,{"toString":[0,{"description":[0,"Returns a string representation of a vector.
\nCalling toString()
is useful for printing vectors to the console while\ndebugging.
\n"],"path":[0,"p5.Vector/toString"]}],"set":[0,{"description":[0,"Sets the vector's x
, y
, and z
components.
\nset()
can use separate numbers, as in v.set(1, 2, 3)
, a\np5.Vector object, as in v.set(v2)
, or an\narray of numbers, as in v.set([1, 2, 3])
.
\nIf a value isn't provided for a component, it will be set to 0. For\nexample, v.set(4, 5)
sets v.x
to 4, v.y
to 5, and v.z
to 0.\nCalling set()
with no arguments, as in v.set()
, sets all the vector's\ncomponents to 0.
\n"],"path":[0,"p5.Vector/set"]}],"copy":[0,{"description":[0,"Returns a copy of the p5.Vector object.
\n"],"path":[0,"p5.Vector/copy"]}],"add":[0,{"description":[0,"Adds to a vector's x
, y
, and z
components.
\nadd()
can use separate numbers, as in v.add(1, 2, 3)
,\nanother p5.Vector object, as in v.add(v2)
, or\nan array of numbers, as in v.add([1, 2, 3])
.
\nIf a value isn't provided for a component, it won't change. For\nexample, v.add(4, 5)
adds 4 to v.x
, 5 to v.y
, and 0 to v.z
.\nCalling add()
with no arguments, as in v.add()
, has no effect.
\nThe static version of add()
, as in p5.Vector.add(v2, v1)
, returns a new\np5.Vector object and doesn't change the\noriginals.
\n"],"path":[0,"p5.Vector/add"]}],"rem":[0,{"description":[0,"Performs modulo (remainder) division with a vector's x
, y
, and z
\ncomponents.
\nrem()
can use separate numbers, as in v.rem(1, 2, 3)
,\nanother p5.Vector object, as in v.rem(v2)
, or\nan array of numbers, as in v.rem([1, 2, 3])
.
\nIf only one value is provided, as in v.rem(2)
, then all the components\nwill be set to their values modulo 2. If two values are provided, as in\nv.rem(2, 3)
, then v.z
won't change. Calling rem()
with no\narguments, as in v.rem()
, has no effect.
\nThe static version of rem()
, as in p5.Vector.rem(v2, v1)
, returns a\nnew p5.Vector object and doesn't change the\noriginals.
\n"],"path":[0,"p5.Vector/rem"]}],"sub":[0,{"description":[0,"Subtracts from a vector's x
, y
, and z
components.
\nsub()
can use separate numbers, as in v.sub(1, 2, 3)
, another\np5.Vector object, as in v.sub(v2)
, or an array\nof numbers, as in v.sub([1, 2, 3])
.
\nIf a value isn't provided for a component, it won't change. For\nexample, v.sub(4, 5)
subtracts 4 from v.x
, 5 from v.y
, and 0 from v.z
.\nCalling sub()
with no arguments, as in v.sub()
, has no effect.
\nThe static version of sub()
, as in p5.Vector.sub(v2, v1)
, returns a new\np5.Vector object and doesn't change the\noriginals.
\n"],"path":[0,"p5.Vector/sub"]}],"mult":[0,{"description":[0,"Multiplies a vector's x
, y
, and z
components.
\nmult()
can use separate numbers, as in v.mult(1, 2, 3)
, another\np5.Vector object, as in v.mult(v2)
, or an array\nof numbers, as in v.mult([1, 2, 3])
.
\nIf only one value is provided, as in v.mult(2)
, then all the components\nwill be multiplied by 2. If a value isn't provided for a component, it\nwon't change. For example, v.mult(4, 5)
multiplies v.x
by 4, v.y
by 5,\nand v.z
by 1. Calling mult()
with no arguments, as in v.mult()
, has\nno effect.
\nThe static version of mult()
, as in p5.Vector.mult(v, 2)
, returns a new\np5.Vector object and doesn't change the\noriginals.
\n"],"path":[0,"p5.Vector/mult"]}],"div":[0,{"description":[0,"Divides a vector's x
, y
, and z
components.
\ndiv()
can use separate numbers, as in v.div(1, 2, 3)
, another\np5.Vector object, as in v.div(v2)
, or an array\nof numbers, as in v.div([1, 2, 3])
.
\nIf only one value is provided, as in v.div(2)
, then all the components\nwill be divided by 2. If a value isn't provided for a component, it\nwon't change. For example, v.div(4, 5)
divides v.x
by, v.y
by 5,\nand v.z
by 1. Calling div()
with no arguments, as in v.div()
, has\nno effect.
\nThe static version of div()
, as in p5.Vector.div(v, 2)
, returns a new\np5.Vector object and doesn't change the\noriginals.
\n"],"path":[0,"p5.Vector/div"]}],"mag":[0,{"description":[0,"Calculates the magnitude (length) of the vector.
\nUse mag() to calculate the magnitude of a 2D vector\nusing components as in mag(x, y)
.
\n"],"path":[0,"p5.Vector/mag"]}],"magSq":[0,{"description":[0,"Calculates the magnitude (length) of the vector squared.
\n"],"path":[0,"p5.Vector/magSq"]}],"dot":[0,{"description":[0,"Calculates the dot product of two vectors.
\nThe dot product is a number that describes the overlap between two vectors.\nVisually, the dot product can be thought of as the \"shadow\" one vector\ncasts on another. The dot product's magnitude is largest when two vectors\npoint in the same or opposite directions. Its magnitude is 0 when two\nvectors form a right angle.
\nThe version of dot()
with one parameter interprets it as another\np5.Vector object.
\nThe version of dot()
with multiple parameters interprets them as the\nx
, y
, and z
components of another vector.
\nThe static version of dot()
, as in p5.Vector.dot(v1, v2)
, is the same\nas calling v1.dot(v2)
.
\n"],"path":[0,"p5.Vector/dot"]}],"cross":[0,{"description":[0,"Calculates the cross product of two vectors.
\nThe cross product is a vector that points straight out of the plane created\nby two vectors. The cross product's magnitude is the area of the parallelogram\nformed by the original two vectors.
\nThe static version of cross()
, as in p5.Vector.cross(v1, v2)
, is the same\nas calling v1.cross(v2)
.
\n"],"path":[0,"p5.Vector/cross"]}],"dist":[0,{"description":[0,"Calculates the distance between two points represented by vectors.
\nA point's coordinates can be represented by the components of a vector\nthat extends from the origin to the point.
\nThe static version of dist()
, as in p5.Vector.dist(v1, v2)
, is the same\nas calling v1.dist(v2)
.
\nUse dist() to calculate the distance between points\nusing coordinates as in dist(x1, y1, x2, y2)
.
\n"],"path":[0,"p5.Vector/dist"]}],"normalize":[0,{"description":[0,"Scales the components of a p5.Vector object so\nthat its magnitude is 1.
\nThe static version of normalize()
, as in p5.Vector.normalize(v)
,\nreturns a new p5.Vector object and doesn't change\nthe original.
\n"],"path":[0,"p5.Vector/normalize"]}],"limit":[0,{"description":[0,"Limits a vector's magnitude to a maximum value.
\nThe static version of limit()
, as in p5.Vector.limit(v, 5)
, returns a\nnew p5.Vector object and doesn't change the\noriginal.
\n"],"path":[0,"p5.Vector/limit"]}],"setMag":[0,{"description":[0,"Sets a vector's magnitude to a given value.
\nThe static version of setMag()
, as in p5.Vector.setMag(v, 10)
, returns\na new p5.Vector object and doesn't change the\noriginal.
\n"],"path":[0,"p5.Vector/setMag"]}],"heading":[0,{"description":[0,"Calculates the angle a 2D vector makes with the positive x-axis.
\nBy convention, the positive x-axis has an angle of 0. Angles increase in\nthe clockwise direction.
\nIf the vector was created with\ncreateVector(), heading()
returns angles\nin the units of the current angleMode().
\nThe static version of heading()
, as in p5.Vector.heading(v)
, works the\nsame way.
\n"],"path":[0,"p5.Vector/heading"]}],"setHeading":[0,{"description":[0,"Rotates a 2D vector to a specific angle without changing its magnitude.
\nBy convention, the positive x-axis has an angle of 0. Angles increase in\nthe clockwise direction.
\nIf the vector was created with\ncreateVector(), setHeading()
uses\nthe units of the current angleMode().
\n"],"path":[0,"p5.Vector/setHeading"]}],"rotate":[0,{"description":[0,"Rotates a 2D vector by an angle without changing its magnitude.
\nBy convention, the positive x-axis has an angle of 0. Angles increase in\nthe clockwise direction.
\nIf the vector was created with\ncreateVector(), rotate()
uses\nthe units of the current angleMode().
\nThe static version of rotate()
, as in p5.Vector.rotate(v, PI)
,\nreturns a new p5.Vector object and doesn't change\nthe original.
\n"],"path":[0,"p5.Vector/rotate"]}],"angleBetween":[0,{"description":[0,"Calculates the angle between two vectors.
\nThe angles returned are signed, which means that\nv1.angleBetween(v2) === -v2.angleBetween(v1)
.
\nIf the vector was created with\ncreateVector(), angleBetween()
returns\nangles in the units of the current\nangleMode().
\n"],"path":[0,"p5.Vector/angleBetween"]}],"lerp":[0,{"description":[0,"Calculates new x
, y
, and z
components that are proportionally the\nsame distance between two vectors.
\nThe amt
parameter is the amount to interpolate between the old vector and\nthe new vector. 0.0 keeps all components equal to the old vector's, 0.5 is\nhalfway between, and 1.0 sets all components equal to the new vector's.
\nThe static version of lerp()
, as in p5.Vector.lerp(v0, v1, 0.5)
,\nreturns a new p5.Vector object and doesn't change\nthe original.
\n"],"path":[0,"p5.Vector/lerp"]}],"slerp":[0,{"description":[0,"Calculates a new heading and magnitude that are between two vectors.
\nThe amt
parameter is the amount to interpolate between the old vector and\nthe new vector. 0.0 keeps the heading and magnitude equal to the old\nvector's, 0.5 sets them halfway between, and 1.0 sets the heading and\nmagnitude equal to the new vector's.
\nslerp()
differs from lerp() because\nit interpolates magnitude. Calling v0.slerp(v1, 0.5)
sets v0
's\nmagnitude to a value halfway between its original magnitude and v1
's.\nCalling v0.lerp(v1, 0.5)
makes no such guarantee.
\nThe static version of slerp()
, as in p5.Vector.slerp(v0, v1, 0.5)
,\nreturns a new p5.Vector object and doesn't change\nthe original.
\n"],"path":[0,"p5.Vector/slerp"]}],"reflect":[0,{"description":[0,"Reflects a vector about a line in 2D or a plane in 3D.
\nThe orientation of the line or plane is described by a normal vector that\npoints away from the shape.
\nThe static version of reflect()
, as in p5.Vector.reflect(v, n)
,\nreturns a new p5.Vector object and doesn't change\nthe original.
\n"],"path":[0,"p5.Vector/reflect"]}],"array":[0,{"description":[0,"Returns the vector's components as an array of numbers.
\n"],"path":[0,"p5.Vector/array"]}],"equals":[0,{"description":[0,"Checks whether all the vector's components are equal to another vector's.
\nequals()
returns true
if the vector's components are all the same as another\nvector's and false
if not.
\nThe version of equals()
with one parameter interprets it as another\np5.Vector object.
\nThe version of equals()
with multiple parameters interprets them as the\ncomponents of another vector. Any missing parameters are assigned the value\n0.
\nThe static version of equals()
, as in p5.Vector.equals(v0, v1)
,\ninterprets both parameters as p5.Vector objects.
\n"],"path":[0,"p5.Vector/equals"]}],"fromAngle":[0,{"description":[0,"Creates a new 2D vector from an angle.
\n"],"path":[0,"p5.Vector/fromAngle"]}],"fromAngles":[0,{"description":[0,"Creates a new 3D vector from a pair of ISO spherical angles.
\n"],"path":[0,"p5.Vector/fromAngles"]}],"random2D":[0,{"description":[0,"Creates a new 2D unit vector with a random heading.
\n"],"path":[0,"p5.Vector/random2D"]}],"random3D":[0,{"description":[0,"Creates a new 3D unit vector with a random heading.
\n"],"path":[0,"p5.Vector/random3D"]}],"clampToZero":[0,{"description":[0,"Replaces the components of a p5.Vector that are very close to zero with zero.
\nIn computers, handling numbers with decimals can give slightly imprecise answers due to the way those numbers are represented.\nThis can make it hard to check if a number is zero, as it may be close but not exactly zero.\nThis method rounds very close numbers to zero to make those checks easier
\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON
\n"],"path":[0,"p5.Vector/clampToZero"]}]}],"properties":[0,{"x":[0,{"description":[0,"The x component of the vector
\n"],"path":[0,"p5.Vector/x"]}],"y":[0,{"description":[0,"The y component of the vector
\n"],"path":[0,"p5.Vector/y"]}],"z":[0,{"description":[0,"The z component of the vector
\n"],"path":[0,"p5.Vector/z"]}]}],"isConstructor":[0,true],"path":[0,"p5/p5.Vector"]}],"render":[0,null]}],"entries":[1,[[0,{"id":[0,"en/p5.Vector/add.mdx"],"slug":[0,"en/p5vector/add"],"body":[0,"\n\n# add\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"add()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Adds to a vector's x
, y
, and z
components.
\nadd()
can use separate numbers, as in v.add(1, 2, 3)
,\nanother p5.Vector object, as in v.add(v2)
, or\nan array of numbers, as in v.add([1, 2, 3])
.
\nIf a value isn't provided for a component, it won't change. For\nexample, v.add(4, 5)
adds 4 to v.x
, 5 to v.y
, and 0 to v.z
.\nCalling add()
with no arguments, as in v.add()
, has no effect.
\nThe static version of add()
, as in p5.Vector.add(v2, v1)
, returns a new\np5.Vector object and doesn't change the\noriginals.
\n"],"line":[0,282],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"x"],"description":[0,"x component of the vector to be added.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"y component of the vector to be added.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"z"],"description":[0,"z component of the vector to be added.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"value"],"description":[0,"The vector to add
\n"],"type":[0,"p5.Vector|Number[]"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,"A p5.Vector to add
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"v2"],"description":[0,"A p5.Vector to add
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"target"],"description":[0,"vector to receive the result.
\n"],"type":[0,"p5.Vector"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,true],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Top left.\n let pos = createVector(25, 25);\n point(pos);\n\n // Top right.\n // Add numbers.\n pos.add(50, 0);\n point(pos);\n\n // Bottom right.\n // Add a p5.Vector.\n let p2 = createVector(0, 50);\n pos.add(p2);\n point(pos);\n\n // Bottom left.\n // Add an array.\n let arr = [-50, 0];\n pos.add(arr);\n point(pos);\n\n describe('Four black dots arranged in a square on a gray background.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Top left.\n let p1 = createVector(25, 25);\n\n // Center.\n let p2 = createVector(50, 50);\n\n // Bottom right.\n // Add p1 and p2.\n let p3 = p5.Vector.add(p1, p2);\n\n // Draw the points.\n strokeWeight(5);\n point(p1);\n point(p2);\n point(p3);\n\n describe('Three black dots in a diagonal line from top left to bottom right.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n let origin = createVector(0, 0);\n\n // Draw the red arrow.\n let v1 = createVector(50, 50);\n drawArrow(origin, v1, 'red');\n\n // Draw the blue arrow.\n let v2 = createVector(-30, 20);\n drawArrow(v1, v2, 'blue');\n\n // Purple arrow.\n let v3 = p5.Vector.add(v1, v2);\n drawArrow(origin, v3, 'purple');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/add"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/angleBetween.mdx"],"slug":[0,"en/p5vector/anglebetween"],"body":[0,"\n\n# angleBetween\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"angleBetween()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Calculates the angle between two vectors.
\nThe angles returned are signed, which means that\nv1.angleBetween(v2) === -v2.angleBetween(v1)
.
\nIf the vector was created with\ncreateVector(), angleBetween()
returns\nangles in the units of the current\nangleMode().
\n"],"line":[0,2384],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"value"],"description":[0,"x, y, and z components of a p5.Vector.
\n"],"type":[0,"p5.Vector"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,"the first vector.
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"v2"],"description":[0,"the second vector.
\n"],"type":[0,"p5.Vector"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,false],"return":[0,{"description":[0,"angle between the vectors."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n // Create p5.Vector objects.\n let v0 = createVector(1, 0);\n let v1 = createVector(0, 1);\n\n // Prints \"1.570...\" to the console.\n print(v0.angleBetween(v1));\n\n // Prints \"-1.570...\" to the console.\n print(v1.angleBetween(v0));\n}\n
\n\n\n\n\nfunction setup() {\n // Use degrees.\n angleMode(DEGREES);\n // Create p5.Vector objects.\n let v0 = createVector(1, 0);\n let v1 = createVector(0, 1);\n\n // Prints \"90\" to the console.\n print(v0.angleBetween(v1));\n\n // Prints \"-90\" to the console.\n print(v1.angleBetween(v0));\n}\n
\n\n\n\n\nfunction setup() {\n // Create p5.Vector objects.\n let v0 = createVector(1, 0);\n let v1 = createVector(0, 1);\n\n // Prints \"1.570...\" to the console.\n print(p5.Vector.angleBetween(v0, v1));\n\n // Prints \"-1.570...\" to the console.\n print(p5.Vector.angleBetween(v1, v0));\n}\n
\n\n\n\n\nfunction setup() {\n // Use degrees.\n angleMode(DEGREES);\n\n // Create p5.Vector objects.\n let v0 = createVector(1, 0);\n let v1 = createVector(0, 1);\n\n // Prints \"90\" to the console.\n print(p5.Vector.angleBetween(v0, v1));\n\n // Prints \"-90\" to the console.\n print(p5.Vector.angleBetween(v1, v0));\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n 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.');\n}\nfunction draw() {\n background(200);\n\n // Create p5.Vector objects.\n let v0 = createVector(50, 50);\n let v1 = createVector(30, 0);\n let v2 = createVector(0, 30);\n\n // Draw the red arrow.\n drawArrow(v0, v1, 'red');\n\n // Draw the blue arrow.\n drawArrow(v0, v2, 'blue');\n\n // Use radians.\n angleMode(RADIANS);\n\n // Display the angle in radians.\n let angle = round(v1.angleBetween(v2), 2);\n text(`Radians: ${angle}`, 20, 20);\n\n // Use degrees.\n angleMode(DEGREES);\n\n // Display the angle in degrees.\n angle = round(v1.angleBetween(v2), 2);\n text(`Degrees: ${angle}`, 20, 35);\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/angleBetween"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/array.mdx"],"slug":[0,"en/p5vector/array"],"body":[0,"\n\n# array\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"array()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Returns the vector's components as an array of numbers.
\n"],"line":[0,2979],"overloads":[1,[[0,{"params":[1,[]]}],[0,{"params":[1,[[0,{"name":[0,"v"],"description":[0,"the vector to convert to an array
\n"],"type":[0,"p5.Vector"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,false],"return":[0,{"description":[0,"array with the vector's components."],"type":[0,"Number[]"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(20, 30);\n\n // Prints \"[20, 30, 0]\" to the console.\n print(v.array());\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/array"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/clampToZero.mdx"],"slug":[0,"en/p5vector/clamptozero"],"body":[0,"\n\n# clampToZero\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"clampToZero()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Replaces the components of a p5.Vector that are very close to zero with zero.
\nIn computers, handling numbers with decimals can give slightly imprecise answers due to the way those numbers are represented.\nThis can make it hard to check if a number is zero, as it may be close but not exactly zero.\nThis method rounds very close numbers to zero to make those checks easier
\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON
\n"],"line":[0,3892],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,true],"return":[0,{"description":[0,"with components very close to zero replaced with zero."],"type":[0,"p5.Vector"]}],"isConstructor":[0,false],"path":[0,"p5.Vector/clampToZero"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/copy.mdx"],"slug":[0,"en/p5vector/copy"],"body":[0,"\n\n# copy\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"copy()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Returns a copy of the p5.Vector object.
\n"],"line":[0,239],"overloads":[1,[[0,{"params":[1,[]]}],[0,{"params":[1,[[0,{"name":[0,"v"],"description":[0,"the p5.Vector to create a copy of
\n"],"type":[0,"p5.Vector"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,false],"return":[0,{"description":[0,"copy of the p5.Vector object."],"type":[0,"p5.Vector"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100 ,100);\n\n background(200);\n\n // Create a p5.Vector object.\n let pos = createVector(50, 50);\n\n // Make a copy.\n let pc = pos.copy();\n\n // Draw the point.\n strokeWeight(5);\n point(pc);\n\n describe('A black point drawn in the middle of a gray square.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/copy"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/cross.mdx"],"slug":[0,"en/p5vector/cross"],"body":[0,"\n\n# cross\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"cross()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Calculates the cross product of two vectors.
\nThe cross product is a vector that points straight out of the plane created\nby two vectors. The cross product's magnitude is the area of the parallelogram\nformed by the original two vectors.
\nThe static version of cross()
, as in p5.Vector.cross(v1, v2)
, is the same\nas calling v1.cross(v2)
.
\n"],"line":[0,1554],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"v"],"description":[0,"p5.Vector to be crossed.
\n"],"type":[0,"p5.Vector"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,"first p5.Vector.
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"v2"],"description":[0,"second p5.Vector.
\n"],"type":[0,"p5.Vector"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,false],"return":[0,{"description":[0,"cross product as a p5.Vector."],"type":[0,"p5.Vector"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n // Create p5.Vector objects.\n let v1 = createVector(1, 0);\n let v2 = createVector(3, 4);\n\n // Calculate the cross product.\n let cp = v1.cross(v2);\n\n // Prints \"p5.Vector Object : [0, 0, 4]\" to the console.\n print(cp.toString());\n}\n
\n\n\n\n\nfunction setup() {\n // Create p5.Vector objects.\n let v1 = createVector(1, 0);\n let v2 = createVector(3, 4);\n\n // Calculate the cross product.\n let cp = p5.Vector.cross(v1, v2);\n\n // Prints \"p5.Vector Object : [0, 0, 4]\" to the console.\n print(cp.toString());\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/cross"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/dist.mdx"],"slug":[0,"en/p5vector/dist"],"body":[0,"\n\n# dist\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"dist()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Calculates the distance between two points represented by vectors.
\nA point's coordinates can be represented by the components of a vector\nthat extends from the origin to the point.
\nThe static version of dist()
, as in p5.Vector.dist(v1, v2)
, is the same\nas calling v1.dist(v2)
.
\nUse dist() to calculate the distance between points\nusing coordinates as in dist(x1, y1, x2, y2)
.
\n"],"line":[0,1612],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"v"],"description":[0,"x, y, and z coordinates of a p5.Vector.
\n"],"type":[0,"p5.Vector"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,"The first p5.Vector
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"v2"],"description":[0,"The second p5.Vector
\n"],"type":[0,"p5.Vector"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,false],"return":[0,{"description":[0,"distance."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create p5.Vector objects.\n let v1 = createVector(1, 0);\n let v2 = createVector(0, 1);\n\n // Calculate the distance between them.\n let d = v1.dist(v2);\n\n // Prints \"1.414...\" to the console.\n print(d);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create p5.Vector objects.\n let v1 = createVector(1, 0);\n let v2 = createVector(0, 1);\n\n // Calculate the distance between them.\n let d = p5.Vector.dist(v1, v2);\n\n // Prints \"1.414...\" to the console.\n print(d);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n let origin = createVector(0, 0);\n\n // Draw the red arrow.\n let v1 = createVector(50, 50);\n drawArrow(origin, v1, 'red');\n\n // Draw the blue arrow.\n let v2 = createVector(20, 70);\n drawArrow(origin, v2, 'blue');\n\n // Purple arrow.\n let v3 = p5.Vector.sub(v2, v1);\n drawArrow(v1, v3, 'purple');\n\n // Style the text.\n textAlign(CENTER);\n\n // Display the magnitude. The same as floor(v3.mag());\n let m = floor(p5.Vector.dist(v1, v2));\n text(m, 50, 75);\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/dist"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/div.mdx"],"slug":[0,"en/p5vector/div"],"body":[0,"\n\n# div\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"div()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Divides a vector's x
, y
, and z
components.
\ndiv()
can use separate numbers, as in v.div(1, 2, 3)
, another\np5.Vector object, as in v.div(v2)
, or an array\nof numbers, as in v.div([1, 2, 3])
.
\nIf only one value is provided, as in v.div(2)
, then all the components\nwill be divided by 2. If a value isn't provided for a component, it\nwon't change. For example, v.div(4, 5)
divides v.x
by, v.y
by 5,\nand v.z
by 1. Calling div()
with no arguments, as in v.div()
, has\nno effect.
\nThe static version of div()
, as in p5.Vector.div(v, 2)
, returns a new\np5.Vector object and doesn't change the\noriginals.
\n"],"line":[0,1065],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"n"],"description":[0,"The number to divide the vector by
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"x"],"description":[0,"number to divide with the x component of the vector.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"number to divide with the y component of the vector.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,"number to divide with the z component of the vector.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"arr"],"description":[0,"array to divide the components of the vector by.
\n"],"type":[0,"Number[]"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v"],"description":[0,"vector to divide the components of the original vector by.
\n"],"type":[0,"p5.Vector"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"x"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"n"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"target"],"description":[0,"The vector to receive the result
\n"],"type":[0,"p5.Vector"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v0"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"v1"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"target"],"description":[0,""],"type":[0,"p5.Vector"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v0"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"arr"],"description":[0,""],"type":[0,"Number[]"]}],[0,{"name":[0,"target"],"description":[0,""],"type":[0,"p5.Vector"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,true],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Center.\n let p = createVector(50, 50);\n point(p);\n\n // Top-left.\n // Divide p.x / 2 and p.y / 2\n p.div(2);\n point(p);\n\n describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the center.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Bottom-right.\n let p = createVector(50, 75);\n point(p);\n\n // Top-left.\n // Divide p.x / 2 and p.y / 3\n p.div(2, 3);\n point(p);\n\n 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.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Bottom-right.\n let p = createVector(50, 75);\n point(p);\n\n // Top-left.\n // Divide p.x / 2 and p.y / 3\n let arr = [2, 3];\n p.div(arr);\n point(p);\n\n 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.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Bottom-right.\n let p = createVector(50, 75);\n point(p);\n\n // Top-left.\n // Divide p.x / 2 and p.y / 3\n let p2 = createVector(2, 3);\n p.div(p2);\n point(p);\n\n 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.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Bottom-right.\n let p = createVector(50, 75);\n point(p);\n\n // Top-left.\n // Create a new p5.Vector with\n // p3.x = p.x / p2.x\n // p3.y = p.y / p2.y\n let p2 = createVector(2, 3);\n let p3 = p5.Vector.div(p, p2);\n point(p3);\n\n 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.');\n}\n
\n\n\n\n\nfunction draw() {\n background(200);\n\n let origin = createVector(0, 0);\n\n // Draw the red arrow.\n let v1 = createVector(50, 50);\n drawArrow(origin, v1, 'red');\n\n // Draw the blue arrow.\n let v2 = p5.Vector.div(v1, 2);\n drawArrow(origin, v2, 'blue');\n\n describe('Two arrows extending from the top left corner. The blue arrow is half the length of the red arrow.');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/div"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/dot.mdx"],"slug":[0,"en/p5vector/dot"],"body":[0,"\n\n# dot\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"dot()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Calculates the dot product of two vectors.
\nThe dot product is a number that describes the overlap between two vectors.\nVisually, the dot product can be thought of as the \"shadow\" one vector\ncasts on another. The dot product's magnitude is largest when two vectors\npoint in the same or opposite directions. Its magnitude is 0 when two\nvectors form a right angle.
\nThe version of dot()
with one parameter interprets it as another\np5.Vector object.
\nThe version of dot()
with multiple parameters interprets them as the\nx
, y
, and z
components of another vector.
\nThe static version of dot()
, as in p5.Vector.dot(v1, v2)
, is the same\nas calling v1.dot(v2)
.
\n"],"line":[0,1441],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"x"],"description":[0,"x component of the vector.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"y component of the vector.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"z"],"description":[0,"z component of the vector.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v"],"description":[0,"p5.Vector to be dotted.
\n"],"type":[0,"p5.Vector"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,"first p5.Vector.
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"v2"],"description":[0,"second p5.Vector.
\n"],"type":[0,"p5.Vector"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,false],"return":[0,{"description":[0,"dot product."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n // Create p5.Vector objects.\n let v1 = createVector(3, 4);\n let v2 = createVector(3, 0);\n\n // Calculate the dot product.\n let dp = v1.dot(v2);\n\n // Prints \"9\" to the console.\n print(dp);\n}\n
\n\n\n\n\nfunction setup() {\n // Create p5.Vector objects.\n let v1 = createVector(1, 0);\n let v2 = createVector(0, 1);\n\n // Calculate the dot product.\n let dp = p5.Vector.dot(v1, v2);\n\n // Prints \"0\" to the console.\n print(dp);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Center.\n let v0 = createVector(50, 50);\n\n // Draw the black arrow.\n let v1 = createVector(30, 0);\n drawArrow(v0, v1, 'black');\n\n // Draw the red arrow.\n let v2 = createVector(mouseX - 50, mouseY - 50);\n drawArrow(v0, v2, 'red');\n\n // Display the dot product.\n let dp = v2.dot(v1);\n text(`v2 • v1 = ${dp}`, 10, 20);\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/dot"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/equals.mdx"],"slug":[0,"en/p5vector/equals"],"body":[0,"\n\n# equals\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"equals()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Checks whether all the vector's components are equal to another vector's.
\nequals()
returns true
if the vector's components are all the same as another\nvector's and false
if not.
\nThe version of equals()
with one parameter interprets it as another\np5.Vector object.
\nThe version of equals()
with multiple parameters interprets them as the\ncomponents of another vector. Any missing parameters are assigned the value\n0.
\nThe static version of equals()
, as in p5.Vector.equals(v0, v1)
,\ninterprets both parameters as p5.Vector objects.
\n"],"line":[0,3001],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"x"],"description":[0,"x component of the vector.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"y"],"description":[0,"y component of the vector.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"z"],"description":[0,"z component of the vector.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"value"],"description":[0,"vector to compare.
\n"],"type":[0,"p5.Vector|Array"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,"the first vector to compare
\n"],"type":[0,"p5.Vector|Array"]}],[0,{"name":[0,"v2"],"description":[0,"the second vector to compare
\n"],"type":[0,"p5.Vector|Array"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,false],"return":[0,{"description":[0,"whether the vectors are equal."],"type":[0,"Boolean"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n // Create p5.Vector objects.\n let v0 = createVector(10, 20, 30);\n let v1 = createVector(10, 20, 30);\n let v2 = createVector(0, 0, 0);\n\n // Prints \"true\" to the console.\n print(v0.equals(v1));\n\n // Prints \"false\" to the console.\n print(v0.equals(v2));\n}\n
\n\n\n\n\nfunction setup() {\n // Create p5.Vector objects.\n let v0 = createVector(5, 10, 20);\n let v1 = createVector(5, 10, 20);\n let v2 = createVector(13, 10, 19);\n\n // Prints \"true\" to the console.\n print(v0.equals(v1.x, v1.y, v1.z));\n\n // Prints \"false\" to the console.\n print(v0.equals(v2.x, v2.y, v2.z));\n}\n
\n\n\n\n\nfunction setup() {\n // Create p5.Vector objects.\n let v0 = createVector(10, 20, 30);\n let v1 = createVector(10, 20, 30);\n let v2 = createVector(0, 0, 0);\n\n // Prints \"true\" to the console.\n print(p5.Vector.equals(v0, v1));\n\n // Prints \"false\" to the console.\n print(p5.Vector.equals(v0, v2));\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/equals"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/fromAngle.mdx"],"slug":[0,"en/p5vector/fromangle"],"body":[0,"\n\n# fromAngle\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"fromAngle()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Creates a new 2D vector from an angle.
\n"],"line":[0,3099],"params":[1,[[0,{"name":[0,"angle"],"description":[0,"desired angle, in radians. Unaffected by angleMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"length"],"description":[0,"length of the new vector (defaults to 1).
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.Vector object."],"type":[0,"p5.Vector"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = p5.Vector.fromAngle(0);\n\n // Prints \"p5.Vector Object : [1, 0, 0]\" to the console.\n print(v.toString());\n}\n
\n\n\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = p5.Vector.fromAngle(0, 30);\n\n // Prints \"p5.Vector Object : [30, 0, 0]\" to the console.\n print(v.toString());\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A black arrow extends from the center of a gray square. It points to the right.');\n}\nfunction draw() {\n background(200);\n\n // Create a p5.Vector to the center.\n let v0 = createVector(50, 50);\n\n // Create a p5.Vector with an angle 0 and magnitude 30.\n let v1 = p5.Vector.fromAngle(0, 30);\n\n // Draw the black arrow.\n drawArrow(v0, v1, 'black');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/fromAngle"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/fromAngles.mdx"],"slug":[0,"en/p5vector/fromangles"],"body":[0,"\n\n# fromAngles\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"fromAngles()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Creates a new 3D vector from a pair of ISO spherical angles.
\n"],"line":[0,3174],"params":[1,[[0,{"name":[0,"theta"],"description":[0,"polar angle in radians (zero is up).
\n"],"type":[0,"Number"]}],[0,{"name":[0,"phi"],"description":[0,"azimuthal angle in radians\n (zero is out of the screen).
\n"],"type":[0,"Number"]}],[0,{"name":[0,"length"],"description":[0,"length of the new vector (defaults to 1).
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.Vector object."],"type":[0,"p5.Vector"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = p5.Vector.fromAngles(0, 0);\n\n // Prints \"p5.Vector Object : [0, -1, 0]\" to the console.\n print(v.toString());\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A light shines on a pink sphere as it orbits.');\n}\n\nfunction draw() {\n background(0);\n\n // Calculate the ISO angles.\n let theta = frameCount * 0.05;\n let phi = 0;\n\n // Create a p5.Vector object.\n let v = p5.Vector.fromAngles(theta, phi, 100);\n\n // Create a point light using the p5.Vector.\n let c = color('deeppink');\n pointLight(c, v);\n\n // Style the sphere.\n fill(255);\n noStroke();\n\n // Draw the sphere.\n sphere(35);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/fromAngles"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/heading.mdx"],"slug":[0,"en/p5vector/heading"],"body":[0,"\n\n# heading\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"heading()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Calculates the angle a 2D vector makes with the positive x-axis.
\nBy convention, the positive x-axis has an angle of 0. Angles increase in\nthe clockwise direction.
\nIf the vector was created with\ncreateVector(), heading()
returns angles\nin the units of the current angleMode().
\nThe static version of heading()
, as in p5.Vector.heading(v)
, works the\nsame way.
\n"],"line":[0,2026],"overloads":[1,[[0,{"params":[1,[]]}],[0,{"params":[1,[[0,{"name":[0,"v"],"description":[0,"the vector to find the angle of
\n"],"type":[0,"p5.Vector"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,false],"return":[0,{"description":[0,"angle of rotation."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(1, 1);\n\n // Prints \"0.785...\" to the console.\n print(v.heading());\n\n // Use degrees.\n angleMode(DEGREES);\n\n // Prints \"45\" to the console.\n print(v.heading());\n}\n
\n\n\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(1, 1);\n\n // Prints \"0.785...\" to the console.\n print(p5.Vector.heading(v));\n\n // Use degrees.\n angleMode(DEGREES);\n\n // Prints \"45\" to the console.\n print(p5.Vector.heading(v));\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n let origin = createVector(0, 0);\n let v = createVector(50, 50);\n\n // Draw the black arrow.\n drawArrow(origin, v, 'black');\n\n // Use radians.\n angleMode(RADIANS);\n\n // Display the heading in radians.\n let h = round(v.heading(), 2);\n text(`Radians: ${h}`, 20, 70);\n\n // Use degrees.\n angleMode(DEGREES);\n\n // Display the heading in degrees.\n h = v.heading();\n text(`Degrees: ${h}`, 20, 85);\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/heading"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/lerp.mdx"],"slug":[0,"en/p5vector/lerp"],"body":[0,"\n\n# lerp\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"lerp()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Calculates new x
, y
, and z
components that are proportionally the\nsame distance between two vectors.
\nThe amt
parameter is the amount to interpolate between the old vector and\nthe new vector. 0.0 keeps all components equal to the old vector's, 0.5 is\nhalfway between, and 1.0 sets all components equal to the new vector's.
\nThe static version of lerp()
, as in p5.Vector.lerp(v0, v1, 0.5)
,\nreturns a new p5.Vector object and doesn't change\nthe original.
\n"],"line":[0,2538],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"x"],"description":[0,"x component.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"y component.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,"z component.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"amt"],"description":[0,"amount of interpolation between 0.0 (old vector)\n and 1.0 (new vector). 0.5 is halfway between.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v"],"description":[0,"p5.Vector to lerp toward.
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"amt"],"description":[0,""],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"v2"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"amt"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"target"],"description":[0,"The vector to receive the result
\n"],"type":[0,"p5.Vector"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,true],"example":[1,[[0,"\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v0 = createVector(1, 1, 1);\n let v1 = createVector(3, 3, 3);\n\n // Interpolate.\n v0.lerp(v1, 0.5);\n\n // Prints \"p5.Vector Object : [2, 2, 2]\" to the console.\n print(v0.toString());\n}\n
\n\n\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(1, 1, 1);\n\n // Interpolate.\n v.lerp(3, 3, 3, 0.5);\n\n // Prints \"p5.Vector Object : [2, 2, 2]\" to the console.\n print(v.toString());\n}\n
\n\n\n\n\nfunction setup() {\n // Create p5.Vector objects.\n let v0 = createVector(1, 1, 1);\n let v1 = createVector(3, 3, 3);\n\n // Interpolate.\n let v2 = p5.Vector.lerp(v0, v1, 0.5);\n\n // Prints \"p5.Vector Object : [2, 2, 2]\" to the console.\n print(v2.toString());\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n 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.');\n}\nfunction draw() {\n background(200);\n\n // Create p5.Vector objects.\n let v0 = createVector(50, 50);\n let v1 = createVector(30, 0);\n let v2 = createVector(0, 30);\n\n // Interpolate.\n let v3 = p5.Vector.lerp(v1, v2, 0.5);\n\n // Draw the red arrow.\n drawArrow(v0, v1, 'red');\n\n // Draw the blue arrow.\n drawArrow(v0, v2, 'blue');\n\n // Draw the purple arrow.\n drawArrow(v0, v3, 'purple');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/lerp"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/limit.mdx"],"slug":[0,"en/p5vector/limit"],"body":[0,"\n\n# limit\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"limit()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Limits a vector's magnitude to a maximum value.
\nThe static version of limit()
, as in p5.Vector.limit(v, 5)
, returns a\nnew p5.Vector object and doesn't change the\noriginal.
\n"],"line":[0,1835],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"max"],"description":[0,"maximum magnitude for the vector.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v"],"description":[0,"the vector to limit
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"max"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"target"],"description":[0,"the vector to receive the result (Optional)
\n"],"type":[0,"p5.Vector"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,true],"example":[1,[[0,"\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(10, 20, 2);\n\n // Limit its magnitude.\n v.limit(5);\n\n // Prints \"p5.Vector Object : [2.227..., 4.454..., 0.445...]\" to the console.\n print(v.toString());\n}\n
\n\n\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v0 = createVector(10, 20, 2);\n\n // Create a copy an limit its magintude.\n let v1 = p5.Vector.limit(v0, 5);\n\n // Prints \"p5.Vector Object : [2.227..., 4.454..., 0.445...]\" to the console.\n print(v1.toString());\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n 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.\");\n}\nfunction draw() {\n background(240);\n\n // Vector to the center.\n let v0 = createVector(50, 50);\n\n // Vector from the center to the mouse.\n let v1 = createVector(mouseX - 50, mouseY - 50);\n\n // Circle's radius.\n let r = 25;\n\n // Draw the red arrow.\n drawArrow(v0, v1, 'red');\n\n // Draw the blue arrow.\n drawArrow(v0, v1.limit(r), 'blue');\n\n // Draw the circle.\n noFill();\n circle(50, 50, r * 2);\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/limit"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/mag.mdx"],"slug":[0,"en/p5vector/mag"],"body":[0,"\n\n# mag\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"mag()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Calculates the magnitude (length) of the vector.
\nUse mag() to calculate the magnitude of a 2D vector\nusing components as in mag(x, y)
.
\n"],"line":[0,1362],"overloads":[1,[[0,{"params":[1,[]]}],[0,{"params":[1,[[0,{"name":[0,"vecT"],"description":[0,"The vector to return the magnitude of
\n"],"type":[0,"p5.Vector"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,false],"return":[0,{"description":[0,"magnitude of the vector."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Vector object.\n let p = createVector(30, 40);\n\n // Draw a line from the origin.\n line(0, 0, p.x, p.y);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the vector's magnitude.\n let m = p.mag();\n text(m, p.x, p.y);\n\n 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.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/mag"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/magSq.mdx"],"slug":[0,"en/p5vector/magsq"],"body":[0,"\n\n# magSq\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"magSq()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Calculates the magnitude (length) of the vector squared.
\n"],"line":[0,1402],"overloads":[1,[[0,{"params":[1,[]]}],[0,{"params":[1,[[0,{"name":[0,"vecT"],"description":[0,"the vector to return the squared magnitude of
\n"],"type":[0,"p5.Vector"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,false],"return":[0,{"description":[0,"squared magnitude of the vector."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Vector object.\n let p = createVector(30, 40);\n\n // Draw a line from the origin.\n line(0, 0, p.x, p.y);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the vector's magnitude squared.\n let m = p.magSq();\n text(m, p.x, p.y);\n\n 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.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/magSq"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/mult.mdx"],"slug":[0,"en/p5vector/mult"],"body":[0,"\n\n# mult\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"mult()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Multiplies a vector's x
, y
, and z
components.
\nmult()
can use separate numbers, as in v.mult(1, 2, 3)
, another\np5.Vector object, as in v.mult(v2)
, or an array\nof numbers, as in v.mult([1, 2, 3])
.
\nIf only one value is provided, as in v.mult(2)
, then all the components\nwill be multiplied by 2. If a value isn't provided for a component, it\nwon't change. For example, v.mult(4, 5)
multiplies v.x
by 4, v.y
by 5,\nand v.z
by 1. Calling mult()
with no arguments, as in v.mult()
, has\nno effect.
\nThe static version of mult()
, as in p5.Vector.mult(v, 2)
, returns a new\np5.Vector object and doesn't change the\noriginals.
\n"],"line":[0,785],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"n"],"description":[0,"The number to multiply with the vector
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"x"],"description":[0,"number to multiply with the x component of the vector.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"number to multiply with the y component of the vector.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,"number to multiply with the z component of the vector.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"arr"],"description":[0,"array to multiply with the components of the vector.
\n"],"type":[0,"Number[]"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v"],"description":[0,"vector to multiply with the components of the original vector.
\n"],"type":[0,"p5.Vector"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"x"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"n"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"target"],"description":[0,"vector to receive the result.
\n"],"type":[0,"p5.Vector"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v0"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"v1"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"target"],"description":[0,""],"type":[0,"p5.Vector"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v0"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"arr"],"description":[0,""],"type":[0,"Number[]"]}],[0,{"name":[0,"target"],"description":[0,""],"type":[0,"p5.Vector"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,true],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Top-left.\n let p = createVector(25, 25);\n point(p);\n\n // Center.\n // Multiply all components by 2.\n p.mult(2);\n point(p);\n\n describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the center.');\n}\n
\n\n\n\n\nfunction setup() {\n strokeWeight(5);\n\n // Top-left.\n let p = createVector(25, 25);\n point(p);\n\n // Bottom-right.\n // Multiply p.x * 2 and p.y * 3\n p.mult(2, 3);\n point(p);\n\n 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.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Top-left.\n let p = createVector(25, 25);\n point(p);\n\n // Bottom-right.\n // Multiply p.x * 2 and p.y * 3\n let arr = [2, 3];\n p.mult(arr);\n point(p);\n\n 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.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Top-left.\n let p = createVector(25, 25);\n point(p);\n\n // Bottom-right.\n // Multiply p.x * p2.x and p.y * p2.y\n let p2 = createVector(2, 3);\n p.mult(p2);\n point(p);\n\n 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.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Top-left.\n let p = createVector(25, 25);\n point(p);\n\n // Bottom-right.\n // Create a new p5.Vector with\n // p3.x = p.x * p2.x\n // p3.y = p.y * p2.y\n let p2 = createVector(2, 3);\n let p3 = p5.Vector.mult(p, p2);\n point(p3);\n\n 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.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Two arrows extending from the top left corner. The blue arrow is twice the length of the red arrow.');\n}\nfunction draw() {\n background(200);\n\n let origin = createVector(0, 0);\n\n // Draw the red arrow.\n let v1 = createVector(25, 25);\n drawArrow(origin, v1, 'red');\n\n // Draw the blue arrow.\n let v2 = p5.Vector.mult(v1, 2);\n drawArrow(origin, v2, 'blue');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/mult"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/normalize.mdx"],"slug":[0,"en/p5vector/normalize"],"body":[0,"\n\n# normalize\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"normalize()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Scales the components of a p5.Vector object so\nthat its magnitude is 1.
\nThe static version of normalize()
, as in p5.Vector.normalize(v)
,\nreturns a new p5.Vector object and doesn't change\nthe original.
\n"],"line":[0,1726],"overloads":[1,[[0,{"params":[1,[]]}],[0,{"params":[1,[[0,{"name":[0,"v"],"description":[0,"The vector to normalize
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"target"],"description":[0,"The vector to receive the result
\n"],"type":[0,"p5.Vector"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,false],"return":[0,{"description":[0,"normalized p5.Vector."],"type":[0,"p5.Vector"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Vector.\n let v = createVector(10, 20, 2);\n\n // Normalize.\n v.normalize();\n\n // Prints \"p5.Vector Object : [0.445..., 0.890..., 0.089...]\" to the console.\n print(v.toString());\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Vector.\n let v0 = createVector(10, 20, 2);\n\n // Create a normalized copy.\n let v1 = p5.Vector.normalize(v0);\n\n // Prints \"p5.Vector Object : [10, 20, 2]\" to the console.\n print(v0.toString());\n // Prints \"p5.Vector Object : [0.445..., 0.890..., 0.089...]\" to the console.\n print(v1.toString());\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n 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.\");\n}\n\nfunction draw() {\n background(240);\n\n // Vector to the center.\n let v0 = createVector(50, 50);\n\n // Vector from the center to the mouse.\n let v1 = createVector(mouseX - 50, mouseY - 50);\n\n // Circle's radius.\n let r = 25;\n\n // Draw the red arrow.\n drawArrow(v0, v1, 'red');\n\n // Draw the blue arrow.\n v1.normalize();\n drawArrow(v0, v1.mult(r), 'blue');\n\n // Draw the circle.\n noFill();\n circle(50, 50, r * 2);\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/normalize"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/random2D.mdx"],"slug":[0,"en/p5vector/random2d"],"body":[0,"\n\n# random2D\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"random2D()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Creates a new 2D unit vector with a random heading.
\n"],"line":[0,3243],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.Vector object."],"type":[0,"p5.Vector"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = p5.Vector.random2D();\n\n // Prints \"p5.Vector Object : [x, y, 0]\" to the console\n // where x and y are small random numbers.\n print(v.toString());\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(1);\n\n describe('A black arrow in extends from the center of a gray square. It changes direction once per second.');\n}\n\nfunction draw() {\n background(200);\n\n // Create a p5.Vector to the center.\n let v0 = createVector(50, 50);\n\n // Create a random p5.Vector.\n let v1 = p5.Vector.random2D();\n\n // Scale v1 for drawing.\n v1.mult(30);\n\n // Draw the black arrow.\n drawArrow(v0, v1, 'black');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/random2D"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/random3D.mdx"],"slug":[0,"en/p5vector/random3d"],"body":[0,"\n\n# random3D\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"random3D()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Creates a new 3D unit vector with a random heading.
\n"],"line":[0,3311],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.Vector object."],"type":[0,"p5.Vector"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = p5.Vector.random3D();\n\n // Prints \"p5.Vector Object : [x, y, z]\" to the console\n // where x, y, and z are small random numbers.\n print(v.toString());\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/random3D"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/reflect.mdx"],"slug":[0,"en/p5vector/reflect"],"body":[0,"\n\n# reflect\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"reflect()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Reflects a vector about a line in 2D or a plane in 3D.
\nThe orientation of the line or plane is described by a normal vector that\npoints away from the shape.
\nThe static version of reflect()
, as in p5.Vector.reflect(v, n)
,\nreturns a new p5.Vector object and doesn't change\nthe original.
\n"],"line":[0,2869],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"surfaceNormal"],"description":[0,"p5.Vector\n to reflect about.
\n"],"type":[0,"p5.Vector"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"incidentVector"],"description":[0,"vector to be reflected.
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"surfaceNormal"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"target"],"description":[0,"vector to receive the result.
\n"],"type":[0,"p5.Vector"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,true],"example":[1,[[0,"\n\n\nfunction setup() {\n // Create a normal vector.\n let n = createVector(0, 1);\n // Create a vector to reflect.\n let v = createVector(4, 6);\n\n // Reflect v about n.\n v.reflect(n);\n\n // Prints \"p5.Vector Object : [4, -6, 0]\" to the console.\n print(v.toString());\n}\n
\n\n\n\n\nfunction setup() {\n // Create a normal vector.\n let n = createVector(0, 1);\n\n // Create a vector to reflect.\n let v0 = createVector(4, 6);\n\n // Create a reflected vector.\n let v1 = p5.Vector.reflect(v0, n);\n\n // Prints \"p5.Vector Object : [4, -6, 0]\" to the console.\n print(v1.toString());\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n 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.');\n}\nfunction draw() {\n background(200);\n\n // Draw a vertical line.\n line(50, 0, 50, 100);\n\n // Create a normal vector.\n let n = createVector(1, 0);\n\n // Center.\n let v0 = createVector(50, 50);\n\n // Create a vector to reflect.\n let v1 = createVector(30, 40);\n\n // Create a reflected vector.\n let v2 = p5.Vector.reflect(v1, n);\n\n // Scale the normal vector for drawing.\n n.setMag(30);\n\n // Draw the black arrow.\n drawArrow(v0, n, 'black');\n\n // Draw the red arrow.\n drawArrow(v0, v1, 'red');\n\n // Draw the blue arrow.\n drawArrow(v0, v2, 'blue');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/reflect"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/rem.mdx"],"slug":[0,"en/p5vector/rem"],"body":[0,"\n\n# rem\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"rem()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Performs modulo (remainder) division with a vector's x
, y
, and z
\ncomponents.
\nrem()
can use separate numbers, as in v.rem(1, 2, 3)
,\nanother p5.Vector object, as in v.rem(v2)
, or\nan array of numbers, as in v.rem([1, 2, 3])
.
\nIf only one value is provided, as in v.rem(2)
, then all the components\nwill be set to their values modulo 2. If two values are provided, as in\nv.rem(2, 3)
, then v.z
won't change. Calling rem()
with no\narguments, as in v.rem()
, has no effect.
\nThe static version of rem()
, as in p5.Vector.rem(v2, v1)
, returns a\nnew p5.Vector object and doesn't change the\noriginals.
\n"],"line":[0,466],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"x"],"description":[0,"x component of divisor vector.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"y component of divisor vector.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,"z component of divisor vector.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"value"],"description":[0,"divisor vector.
\n"],"type":[0,"p5.Vector | Number[]"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,"The dividend p5.Vector
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"v2"],"description":[0,"The divisor p5.Vector
\n"],"type":[0,"p5.Vector"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"v2"],"description":[0,""],"type":[0,"p5.Vector"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,true],"example":[1,[[0,"\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(3, 4, 5);\n\n // Divide numbers.\n v.rem(2);\n\n // Prints 'p5.Vector Object : [1, 0, 1]'.\n print(v.toString());\n}\n
\n\n\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(3, 4, 5);\n\n // Divide numbers.\n v.rem(2, 3);\n\n // Prints 'p5.Vector Object : [1, 1, 5]'.\n print(v.toString());\n}\n
\n\n\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(3, 4, 5);\n\n // Divide numbers.\n v.rem(2, 3, 4);\n\n // Prints 'p5.Vector Object : [1, 1, 1]'.\n print(v.toString());\n}\n
\n\n\n\n\nfunction setup() {\n // Create p5.Vector objects.\n let v1 = createVector(3, 4, 5);\n let v2 = createVector(2, 3, 4);\n\n // Divide a p5.Vector.\n v1.rem(v2);\n\n // Prints 'p5.Vector Object : [1, 1, 1]'.\n print(v1.toString());\n}\n
\n\n\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(3, 4, 5);\n\n // Divide an array.\n let arr = [2, 3, 4];\n v.rem(arr);\n\n // Prints 'p5.Vector Object : [1, 1, 1]'.\n print(v.toString());\n}\n
\n\n\n\n\nfunction setup() {\n // Create p5.Vector objects.\n let v1 = createVector(3, 4, 5);\n let v2 = createVector(2, 3, 4);\n\n // Divide without modifying the original vectors.\n let v3 = p5.Vector.rem(v1, v2);\n\n // Prints 'p5.Vector Object : [1, 1, 1]'.\n print(v3.toString());\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/rem"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/rotate.mdx"],"slug":[0,"en/p5vector/rotate"],"body":[0,"\n\n# rotate\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"rotate()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Rotates a 2D vector by an angle without changing its magnitude.
\nBy convention, the positive x-axis has an angle of 0. Angles increase in\nthe clockwise direction.
\nIf the vector was created with\ncreateVector(), rotate()
uses\nthe units of the current angleMode().
\nThe static version of rotate()
, as in p5.Vector.rotate(v, PI)
,\nreturns a new p5.Vector object and doesn't change\nthe original.
\n"],"line":[0,2238],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"angle"],"description":[0,"angle of rotation.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"angle"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"target"],"description":[0,"The vector to receive the result
\n"],"type":[0,"p5.Vector"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,true],"example":[1,[[0,"\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(1, 0);\n\n // Prints \"p5.Vector Object : [1, 0, 0]\" to the console.\n print(v.toString());\n\n // Rotate a quarter turn.\n v.rotate(HALF_PI);\n\n // Prints \"p5.Vector Object : [0, 1, 0]\" to the console.\n print(v.toString());\n}\n
\n\n\n\n\nfunction setup() {\n // Use degrees.\n angleMode(DEGREES);\n\n // Create a p5.Vector object.\n let v = createVector(1, 0);\n\n // Prints \"p5.Vector Object : [1, 0, 0]\" to the console.\n print(v.toString());\n\n // Rotate a quarter turn.\n v.rotate(90);\n\n // Prints \"p5.Vector Object : [0, 1, 0]\" to the console.\n print(v.toString());\n}\n
\n\n\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v0 = createVector(1, 0);\n\n // Create a rotated copy.\n let v1 = p5.Vector.rotate(v0, HALF_PI);\n\n // Prints \"p5.Vector Object : [1, 0, 0]\" to the console.\n print(v0.toString());\n // Prints \"p5.Vector Object : [0, 1, 0]\" to the console.\n print(v1.toString());\n}\n
\n\n\n\n\nfunction setup() {\n // Use degrees.\n angleMode(DEGREES);\n\n // Create a p5.Vector object.\n let v0 = createVector(1, 0);\n\n // Create a rotated copy.\n let v1 = p5.Vector.rotate(v0, 90);\n\n // Prints \"p5.Vector Object : [1, 0, 0]\" to the console.\n print(v0.toString());\n\n // Prints \"p5.Vector Object : [0, 1, 0]\" to the console.\n print(v1.toString());\n}\n
\n\n\n\n\nlet v0;\nlet v1;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create p5.Vector objects.\n v0 = createVector(50, 50);\n v1 = createVector(30, 0);\n\n describe('A black arrow extends from the center of a gray square. The arrow rotates clockwise.');\n}\n\nfunction draw() {\n background(240);\n\n // Rotate v1.\n v1.rotate(0.01);\n\n // Draw the black arrow.\n drawArrow(v0, v1, 'black');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/rotate"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/set.mdx"],"slug":[0,"en/p5vector/set"],"body":[0,"\n\n# set\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"set()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Sets the vector's x
, y
, and z
components.
\nset()
can use separate numbers, as in v.set(1, 2, 3)
, a\np5.Vector object, as in v.set(v2)
, or an\narray of numbers, as in v.set([1, 2, 3])
.
\nIf a value isn't provided for a component, it will be set to 0. For\nexample, v.set(4, 5)
sets v.x
to 4, v.y
to 5, and v.z
to 0.\nCalling set()
with no arguments, as in v.set()
, sets all the vector's\ncomponents to 0.
\n"],"line":[0,161],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"x"],"description":[0,"x component of the vector.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"y"],"description":[0,"y component of the vector.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"z"],"description":[0,"z component of the vector.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"value"],"description":[0,"vector to set.
\n"],"type":[0,"p5.Vector|Number[]"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,true],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Top left.\n let pos = createVector(25, 25);\n point(pos);\n\n // Top right.\n // set() with numbers.\n pos.set(75, 25);\n point(pos);\n\n // Bottom right.\n // set() with a p5.Vector.\n let p2 = createVector(75, 75);\n pos.set(p2);\n point(pos);\n\n // Bottom left.\n // set() with an array.\n let arr = [25, 75];\n pos.set(arr);\n point(pos);\n\n describe('Four black dots arranged in a square on a gray background.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/set"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/setHeading.mdx"],"slug":[0,"en/p5vector/setheading"],"body":[0,"\n\n# setHeading\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"setHeading()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Rotates a 2D vector to a specific angle without changing its magnitude.
\nBy convention, the positive x-axis has an angle of 0. Angles increase in\nthe clockwise direction.
\nIf the vector was created with\ncreateVector(), setHeading()
uses\nthe units of the current angleMode().
\n"],"line":[0,2134],"params":[1,[[0,{"name":[0,"angle"],"description":[0,"angle of rotation.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,true],"example":[1,[[0,"\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(0, 1);\n\n // Prints \"1.570...\" to the console.\n print(v.heading());\n\n // Point to the left.\n v.setHeading(PI);\n\n // Prints \"3.141...\" to the console.\n print(v.heading());\n}\n
\n\n\n\n\nfunction setup() {\n // Use degrees.\n angleMode(DEGREES);\n\n // Create a p5.Vector object.\n let v = createVector(0, 1);\n\n // Prints \"90\" to the console.\n print(v.heading());\n\n // Point to the left.\n v.setHeading(180);\n\n // Prints \"180\" to the console.\n print(v.heading());\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Two arrows extend from the center of a gray square. The red arrow points to the right and the blue arrow points down.');\n}\n\nfunction draw() {\n background(200);\n\n // Create p5.Vector objects.\n let v0 = createVector(50, 50);\n let v1 = createVector(30, 0);\n\n // Draw the red arrow.\n drawArrow(v0, v1, 'red');\n\n // Point down.\n v1.setHeading(HALF_PI);\n\n // Draw the blue arrow.\n drawArrow(v0, v1, 'blue');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/setHeading"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/setMag.mdx"],"slug":[0,"en/p5vector/setmag"],"body":[0,"\n\n# setMag\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"setMag()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Sets a vector's magnitude to a given value.
\nThe static version of setMag()
, as in p5.Vector.setMag(v, 10)
, returns\na new p5.Vector object and doesn't change the\noriginal.
\n"],"line":[0,1933],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"len"],"description":[0,"new length for this vector.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v"],"description":[0,"the vector to set the magnitude of
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"len"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"target"],"description":[0,"the vector to receive the result (Optional)
\n"],"type":[0,"p5.Vector"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,true],"example":[1,[[0,"\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(3, 4, 0);\n\n // Prints \"5\" to the console.\n print(v.mag());\n\n // Set its magnitude to 10.\n v.setMag(10);\n\n // Prints \"p5.Vector Object : [6, 8, 0]\" to the console.\n print(v.toString());\n}\n
\n\n\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v0 = createVector(3, 4, 0);\n\n // Create a copy with a magnitude of 10.\n let v1 = p5.Vector.setMag(v0, 10);\n\n // Prints \"5\" to the console.\n print(v0.mag());\n\n // Prints \"p5.Vector Object : [6, 8, 0]\" to the console.\n print(v1.toString());\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n 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.');\n}\n\nfunction draw() {\n background(240);\n\n let origin = createVector(0, 0);\n let v = createVector(50, 50);\n\n // Draw the red arrow.\n drawArrow(origin, v, 'red');\n\n // Set v's magnitude to 30.\n v.setMag(30);\n\n // Draw the blue arrow.\n drawArrow(origin, v, 'blue');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/setMag"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/slerp.mdx"],"slug":[0,"en/p5vector/slerp"],"body":[0,"\n\n# slerp\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"slerp()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Calculates a new heading and magnitude that are between two vectors.
\nThe amt
parameter is the amount to interpolate between the old vector and\nthe new vector. 0.0 keeps the heading and magnitude equal to the old\nvector's, 0.5 sets them halfway between, and 1.0 sets the heading and\nmagnitude equal to the new vector's.
\nslerp()
differs from lerp() because\nit interpolates magnitude. Calling v0.slerp(v1, 0.5)
sets v0
's\nmagnitude to a value halfway between its original magnitude and v1
's.\nCalling v0.lerp(v1, 0.5)
makes no such guarantee.
\nThe static version of slerp()
, as in p5.Vector.slerp(v0, v1, 0.5)
,\nreturns a new p5.Vector object and doesn't change\nthe original.
\n"],"line":[0,2667],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"v"],"description":[0,"p5.Vector to slerp toward.
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"amt"],"description":[0,"amount of interpolation between 0.0 (old vector)\n and 1.0 (new vector). 0.5 is halfway between.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,"old vector.
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"v2"],"description":[0,"new vector.
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"amt"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"target"],"description":[0,"vector to receive the result.
\n"],"type":[0,"p5.Vector"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"p5.Vector"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v0 = createVector(3, 0);\n\n // Prints \"3\" to the console.\n print(v0.mag());\n\n // Prints \"0\" to the console.\n print(v0.heading());\n\n // Create a p5.Vector object.\n let v1 = createVector(0, 1);\n\n // Prints \"1\" to the console.\n print(v1.mag());\n\n // Prints \"1.570...\" to the console.\n print(v1.heading());\n\n // Interpolate halfway between v0 and v1.\n v0.slerp(v1, 0.5);\n\n // Prints \"2\" to the console.\n print(v0.mag());\n\n // Prints \"0.785...\" to the console.\n print(v0.heading());\n}\n
\n\n\n\n\nfunction setup() {\n // Create a p5.Vector object.\n let v0 = createVector(3, 0);\n\n // Prints \"3\" to the console.\n print(v0.mag());\n\n // Prints \"0\" to the console.\n print(v0.heading());\n\n // Create a p5.Vector object.\n let v1 = createVector(0, 1);\n\n // Prints \"1\" to the console.\n print(v1.mag());\n\n // Prints \"1.570...\" to the console.\n print(v1.heading());\n\n // Create a p5.Vector that's halfway between v0 and v1.\n let v3 = p5.Vector.slerp(v0, v1, 0.5);\n\n // Prints \"2\" to the console.\n print(v3.mag());\n\n // Prints \"0.785...\" to the console.\n print(v3.heading());\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Create p5.Vector objects.\n let v0 = createVector(50, 50);\n let v1 = createVector(20, 0);\n let v2 = createVector(-40, 0);\n\n // Create a p5.Vector that's halfway between v1 and v2.\n let v3 = p5.Vector.slerp(v1, v2, 0.5);\n\n // Draw the red arrow.\n drawArrow(v0, v1, 'red');\n\n // Draw the blue arrow.\n drawArrow(v0, v2, 'blue');\n\n // Draw the purple arrow.\n drawArrow(v0, v3, 'purple');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/slerp"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/sub.mdx"],"slug":[0,"en/p5vector/sub"],"body":[0,"\n\n# sub\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"sub()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Subtracts from a vector's x
, y
, and z
components.
\nsub()
can use separate numbers, as in v.sub(1, 2, 3)
, another\np5.Vector object, as in v.sub(v2)
, or an array\nof numbers, as in v.sub([1, 2, 3])
.
\nIf a value isn't provided for a component, it won't change. For\nexample, v.sub(4, 5)
subtracts 4 from v.x
, 5 from v.y
, and 0 from v.z
.\nCalling sub()
with no arguments, as in v.sub()
, has no effect.
\nThe static version of sub()
, as in p5.Vector.sub(v2, v1)
, returns a new\np5.Vector object and doesn't change the\noriginals.
\n"],"line":[0,635],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"x"],"description":[0,"x component of the vector to subtract.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"y component of the vector to subtract.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"z"],"description":[0,"z component of the vector to subtract.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"value"],"description":[0,"the vector to subtract
\n"],"type":[0,"p5.Vector|Number[]"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,"A p5.Vector to subtract from
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"v2"],"description":[0,"A p5.Vector to subtract
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"target"],"description":[0,"vector to receive the result.
\n"],"type":[0,"p5.Vector"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,true],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Bottom right.\n let pos = createVector(75, 75);\n point(pos);\n\n // Top right.\n // Subtract numbers.\n pos.sub(0, 50);\n point(pos);\n\n // Top left.\n // Subtract a p5.Vector.\n let p2 = createVector(50, 0);\n pos.sub(p2);\n point(pos);\n\n // Bottom left.\n // Subtract an array.\n let arr = [0, -50];\n pos.sub(arr);\n point(pos);\n\n describe('Four black dots arranged in a square on a gray background.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create p5.Vector objects.\n let p1 = createVector(75, 75);\n let p2 = createVector(50, 50);\n\n // Subtract without modifying the original vectors.\n let p3 = p5.Vector.sub(p1, p2);\n\n // Draw the points.\n strokeWeight(5);\n point(p1);\n point(p2);\n point(p3);\n\n describe('Three black dots in a diagonal line from top left to bottom right.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n let origin = createVector(0, 0);\n\n // Draw the red arrow.\n let v1 = createVector(50, 50);\n drawArrow(origin, v1, 'red');\n\n // Draw the blue arrow.\n let v2 = createVector(20, 70);\n drawArrow(origin, v2, 'blue');\n\n // Purple arrow.\n let v3 = p5.Vector.sub(v2, v1);\n drawArrow(v1, v3, 'purple');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/sub"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/toString.mdx"],"slug":[0,"en/p5vector/tostring"],"body":[0,"\n\n# toString\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"toString()"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"Returns a string representation of a vector.
\nCalling toString()
is useful for printing vectors to the console while\ndebugging.
\n"],"line":[0,136],"itemtype":[0,"method"],"class":[0,"p5.Vector"],"chainable":[0,false],"return":[0,{"description":[0,"string representation of the vector."],"type":[0,"String"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n let v = createVector(20, 30);\n\n // Prints 'p5.Vector Object : [20, 30, 0]'.\n print(v.toString());\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Vector/toString"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/x.mdx"],"slug":[0,"en/p5vector/x"],"body":[0,"\n\n# x\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"x"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"The x component of the vector
\n"],"line":[0,113],"itemtype":[0,"property"],"class":[0,"p5.Vector"],"isConstructor":[0,false],"path":[0,"p5.Vector/x"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/y.mdx"],"slug":[0,"en/p5vector/y"],"body":[0,"\n\n# y\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"y"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"The y component of the vector
\n"],"line":[0,120],"itemtype":[0,"property"],"class":[0,"p5.Vector"],"isConstructor":[0,false],"path":[0,"p5.Vector/y"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Vector/z.mdx"],"slug":[0,"en/p5vector/z"],"body":[0,"\n\n# z\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"z"],"module":[0,"Math"],"submodule":[0,"Vector"],"file":[0,"src/math/p5.Vector.js"],"description":[0,"The z component of the vector
\n"],"line":[0,127],"itemtype":[0,"property"],"class":[0,"p5.Vector"],"isConstructor":[0,false],"path":[0,"p5.Vector/z"]}],"render":[0,null]}]]]}]]]}],[0,{"name":[0,"IO"],"subcats":[1,[[0,{"name":[0],"entry":[0],"entries":[1,[]]}],[0,{"name":[0,"Input"],"entry":[0],"entries":[1,[[0,{"id":[0,"en/p5/httpDo.mdx"],"slug":[0,"en/p5/httpdo"],"body":[0,"\n\n# httpDo\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"httpDo()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/files.js"],"description":[0,"Method for executing an HTTP request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text.
\nFor more advanced use, you may also pass in the path as the first argument\nand a object as the second argument, the signature follows the one specified\nin the Fetch API specification.\nThis method is suitable for fetching files up to size of 64MB when \"GET\" is used.
\n"],"line":[0,1208],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"path"],"description":[0,"name of the file or url to load
\n"],"type":[0,"String"]}],[0,{"name":[0,"method"],"description":[0,"either \"GET\", \"POST\", or \"PUT\",\n defaults to \"GET\"
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"datatype"],"description":[0,"\"json\", \"jsonp\", \"xml\", or \"text\"
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"data"],"description":[0,"param data passed sent with request
\n"],"type":[0,"Object"],"optional":[0,true]}],[0,{"name":[0,"callback"],"description":[0,"function to be executed after\n httpGet() completes, data is passed in\n as first argument
\n"],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"errorCallback"],"description":[0,"function to be executed if\n there is an error, response is passed\n in as first argument
\n"],"type":[0,"Function"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"path"],"description":[0,""],"type":[0,"String"]}],[0,{"name":[0,"options"],"description":[0,"Request object options as documented in the\n \"fetch\" API\nreference
\n"],"type":[0,"Object"]}],[0,{"name":[0,"callback"],"description":[0,""],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"errorCallback"],"description":[0,""],"type":[0,"Function"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"A promise that resolves with the data when the operation\n completes successfully or rejects with the error after\n one occurs."],"type":[0,"Promise"]}],"example":[1,[[0,"\n\n\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\n\n// displays an animation of all USGS earthquakes\nlet earthquakes;\nlet eqFeatureIndex = 0;\n\nfunction preload() {\n let url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson';\n httpDo(\n url,\n {\n method: 'GET',\n // Other Request options, like special headers for apis\n headers: { authorization: 'Bearer secretKey' }\n },\n function(res) {\n earthquakes = res;\n }\n );\n}\n\nfunction draw() {\n // wait until the data is loaded\n if (!earthquakes || !earthquakes.features[eqFeatureIndex]) {\n return;\n }\n clear();\n\n let feature = earthquakes.features[eqFeatureIndex];\n let mag = feature.properties.mag;\n let rad = mag / 11 * ((width + height) / 2);\n fill(255, 0, 0, 100);\n ellipse(width / 2 + random(-2, 2), height / 2 + random(-2, 2), rad, rad);\n\n if (eqFeatureIndex >= earthquakes.features.length) {\n eqFeatureIndex = 0;\n } else {\n eqFeatureIndex += 1;\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/httpDo"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/httpGet.mdx"],"slug":[0,"en/p5/httpget"],"body":[0,"\n\n# httpGet\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"httpGet()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/files.js"],"description":[0,"Method for executing an HTTP GET request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text. This is equivalent to\ncalling httpDo(path, 'GET')
. The 'binary' datatype will return\na Blob object, and the 'arrayBuffer' datatype will return an ArrayBuffer\nwhich can be used to initialize typed arrays (such as Uint8Array).
\n"],"line":[0,1043],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"path"],"description":[0,"name of the file or url to load
\n"],"type":[0,"String"]}],[0,{"name":[0,"datatype"],"description":[0,"\"json\", \"jsonp\", \"binary\", \"arrayBuffer\",\n \"xml\", or \"text\"
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"data"],"description":[0,"param data passed sent with request
\n"],"type":[0,"Object|Boolean"],"optional":[0,true]}],[0,{"name":[0,"callback"],"description":[0,"function to be executed after\n httpGet() completes, data is passed in\n as first argument
\n"],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"errorCallback"],"description":[0,"function to be executed if\n there is an error, response is passed\n in as first argument
\n"],"type":[0,"Function"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"path"],"description":[0,""],"type":[0,"String"]}],[0,{"name":[0,"data"],"description":[0,""],"type":[0,"Object|Boolean"]}],[0,{"name":[0,"callback"],"description":[0,""],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"errorCallback"],"description":[0,""],"type":[0,"Function"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"path"],"description":[0,""],"type":[0,"String"]}],[0,{"name":[0,"callback"],"description":[0,""],"type":[0,"Function"]}],[0,{"name":[0,"errorCallback"],"description":[0,""],"type":[0,"Function"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"A promise that resolves with the data when the operation\n completes successfully or rejects with the error after\n one occurs."],"type":[0,"Promise"]}],"example":[1,[[0,"\n\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\nlet earthquakes;\nfunction preload() {\n // Get the most recent earthquake in the database\n let url =\n 'https://earthquake.usgs.gov/fdsnws/event/1/query?' +\n 'format=geojson&limit=1&orderby=time';\n httpGet(url, 'jsonp', false, function(response) {\n // when the HTTP request completes, populate the variable that holds the\n // earthquake data used in the visualization.\n earthquakes = response;\n });\n}\n\nfunction draw() {\n if (!earthquakes) {\n // Wait until the earthquake data has loaded before drawing.\n return;\n }\n background(200);\n // Get the magnitude and name of the earthquake out of the loaded JSON\n let earthquakeMag = earthquakes.features[0].properties.mag;\n let earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n noLoop();\n}\n
"]]],"isConstructor":[0,false],"path":[0,"p5/httpGet"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/httpPost.mdx"],"slug":[0,"en/p5/httppost"],"body":[0,"\n\n# httpPost\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"httpPost()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/files.js"],"description":[0,"Method for executing an HTTP POST request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text. This is equivalent to\ncalling httpDo(path, 'POST')
.
\n"],"line":[0,1119],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"path"],"description":[0,"name of the file or url to load
\n"],"type":[0,"String"]}],[0,{"name":[0,"datatype"],"description":[0,"\"json\", \"jsonp\", \"xml\", or \"text\".\n If omitted, httpPost() will guess.
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"data"],"description":[0,"param data passed sent with request
\n"],"type":[0,"Object|Boolean"],"optional":[0,true]}],[0,{"name":[0,"callback"],"description":[0,"function to be executed after\n httpPost() completes, data is passed in\n as first argument
\n"],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"errorCallback"],"description":[0,"function to be executed if\n there is an error, response is passed\n in as first argument
\n"],"type":[0,"Function"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"path"],"description":[0,""],"type":[0,"String"]}],[0,{"name":[0,"data"],"description":[0,""],"type":[0,"Object|Boolean"]}],[0,{"name":[0,"callback"],"description":[0,""],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"errorCallback"],"description":[0,""],"type":[0,"Function"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"path"],"description":[0,""],"type":[0,"String"]}],[0,{"name":[0,"callback"],"description":[0,""],"type":[0,"Function"]}],[0,{"name":[0,"errorCallback"],"description":[0,""],"type":[0,"Function"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"A promise that resolves with the data when the operation\n completes successfully or rejects with the error after\n one occurs."],"type":[0,"Promise"]}],"example":[1,[[0,"\n\n\n// Examples use jsonplaceholder.typicode.com for a Mock Data API\n\nlet url = 'https://jsonplaceholder.typicode.com/posts';\nlet postData = { userId: 1, title: 'p5 Clicked!', body: 'p5.js is very cool.' };\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n}\n\nfunction mousePressed() {\n httpPost(url, 'json', postData, function(result) {\n strokeWeight(2);\n text(result.body, mouseX, mouseY);\n });\n}\n
\n\n\n\nlet url = 'ttps://invalidURL'; // A bad URL that will cause errors\nlet postData = { title: 'p5 Clicked!', body: 'p5.js is very cool.' };\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n}\n\nfunction mousePressed() {\n httpPost(\n url,\n 'json',\n postData,\n function(result) {\n // ... won't be called\n },\n function(error) {\n strokeWeight(2);\n text(error.toString(), mouseX, mouseY);\n }\n );\n}\n
"]]],"isConstructor":[0,false],"path":[0,"p5/httpPost"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/loadBytes.mdx"],"slug":[0,"en/p5/loadbytes"],"body":[0,"\n\n# loadBytes\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"loadBytes()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/files.js"],"description":[0,"This method is suitable for fetching files up to size of 64MB.
\n"],"line":[0,986],"params":[1,[[0,{"name":[0,"file"],"description":[0,"name of the file or URL to load
\n"],"type":[0,"String"]}],[0,{"name":[0,"callback"],"description":[0,"function to be executed after loadBytes()\n completes
\n"],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"errorCallback"],"description":[0,"function to be executed if there\n is an error
\n"],"type":[0,"Function"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"an object whose 'bytes' property will be the loaded buffer"],"type":[0,"Object"]}],"example":[1,[[0,"\n\nlet data;\n\nfunction preload() {\n data = loadBytes('/assets/mammals.xml');\n}\n\nfunction setup() {\n for (let i = 0; i < 5; i++) {\n console.log(data.bytes[i].toString(16));\n }\n describe('no image displayed');\n}\n
"]]],"isConstructor":[0,false],"path":[0,"p5/loadBytes"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/loadJSON.mdx"],"slug":[0,"en/p5/loadjson"],"body":[0,"\n\n# loadJSON\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"loadJSON()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/files.js"],"description":[0,"Loads a JSON file to create an Object
.
\nJavaScript Object Notation\n(JSON)\nis a standard format for sending data between applications. The format is\nbased on JavaScript objects which have keys and values. JSON files store\ndata in an object with strings as keys. Values can be strings, numbers,\nBooleans, arrays, null
, or other objects.
\nThe first parameter, path
, is always a string with the path to the file.\nPaths to local files should be relative, as in\nloadJSON('/assets/data.json')
. URLs such as\n'https://example.com/data.json'
may be blocked due to browser security.
\nThe second parameter, successCallback
, is optional. If a function is\npassed, as in loadJSON('/assets/data.json', handleData)
, then the\nhandleData()
function will be called once the data loads. The object\ncreated from the JSON data will be passed to handleData()
as its only argument.
\nThe third parameter, failureCallback
, is also optional. If a function is\npassed, as in loadJSON('/assets/data.json', handleData, handleFailure)
,\nthen the handleFailure()
function will be called if an error occurs while\nloading. The Error
object will be passed to handleFailure()
as its only\nargument.
\nNote: Data can take time to load. Calling loadJSON()
within\npreload() ensures data loads before it's used in\nsetup() or draw().
\n"],"line":[0,17],"params":[1,[[0,{"name":[0,"path"],"description":[0,"path of the JSON file to be loaded.
\n"],"type":[0,"String"]}],[0,{"name":[0,"successCallback"],"description":[0,"function to call once the data is loaded. Will be passed the object.
\n"],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"errorCallback"],"description":[0,"function to call if the data fails to load. Will be passed an Error
event object.
\n"],"type":[0,"Function"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"object containing the loaded data."],"type":[0,"Object"]}],"example":[1,[[0,"\n\n\n\nlet myData;\n\n// Load the JSON and create an object.\nfunction preload() {\n myData = loadJSON('/assets/data.json');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the circle.\n fill(myData.color);\n noStroke();\n\n // Draw the circle.\n circle(myData.x, myData.y, myData.d);\n\n describe('A pink circle on a gray background.');\n}\n
\n\n\n\n\nlet myData;\n\n// Load the JSON and create an object.\nfunction preload() {\n myData = loadJSON('/assets/data.json');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object and make it transparent.\n let c = color(myData.color);\n c.setAlpha(80);\n\n // Style the circles.\n fill(c);\n noStroke();\n\n // Iterate over the myData.bubbles array.\n for (let b of myData.bubbles) {\n // Draw a circle for each bubble.\n circle(b.x, b.y, b.d);\n }\n\n describe('Several pink bubbles floating in a blue sky.');\n}\n
\n\n\n\n\nlet myData;\n\n// Load the GeoJSON and create an object.\nfunction preload() {\n myData = loadJSON('https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get data about the most recent earthquake.\n let quake = myData.features[0].properties;\n\n // Draw a circle based on the earthquake's magnitude.\n circle(50, 50, quake.mag * 10);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(11);\n\n // Display the earthquake's location.\n text(quake.place, 5, 80, 100);\n\n describe(`A white circle on a gray background. The text \"${quake.place}\" is written beneath the circle.`);\n}\n
\n\n\n\n\nlet bigQuake;\n\n// Load the GeoJSON and preprocess it.\nfunction preload() {\n loadJSON(\n 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson',\n handleData\n );\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw a circle based on the earthquake's magnitude.\n circle(50, 50, bigQuake.mag * 10);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(11);\n\n // Display the earthquake's location.\n text(bigQuake.place, 5, 80, 100);\n\n describe(`A white circle on a gray background. The text \"${bigQuake.place}\" is written beneath the circle.`);\n}\n\n// Find the biggest recent earthquake.\nfunction handleData(data) {\n let maxMag = 0;\n // Iterate over the earthquakes array.\n for (let quake of data.features) {\n // Reassign bigQuake if a larger\n // magnitude quake is found.\n if (quake.properties.mag > maxMag) {\n bigQuake = quake.properties;\n }\n }\n}\n
\n\n\n\n\nlet bigQuake;\n\n// Load the GeoJSON and preprocess it.\nfunction preload() {\n loadJSON(\n 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson',\n handleData,\n handleError\n );\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw a circle based on the earthquake's magnitude.\n circle(50, 50, bigQuake.mag * 10);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(11);\n\n // Display the earthquake's location.\n text(bigQuake.place, 5, 80, 100);\n\n describe(`A white circle on a gray background. The text \"${bigQuake.place}\" is written beneath the circle.`);\n}\n\n// Find the biggest recent earthquake.\nfunction handleData(data) {\n let maxMag = 0;\n // Iterate over the earthquakes array.\n for (let quake of data.features) {\n // Reassign bigQuake if a larger\n // magnitude quake is found.\n if (quake.properties.mag > maxMag) {\n bigQuake = quake.properties;\n }\n }\n}\n\n// Log any errors to the console.\nfunction handleError(error) {\n console.log('Oops!', error);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/loadJSON"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/loadStrings.mdx"],"slug":[0,"en/p5/loadstrings"],"body":[0,"\n\n# loadStrings\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"loadStrings()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/files.js"],"description":[0,"Loads a text file to create an Array
.
\nThe first parameter, path
, is always a string with the path to the file.\nPaths to local files should be relative, as in\nloadStrings('/assets/data.txt')
. URLs such as\n'https://example.com/data.txt'
may be blocked due to browser security.
\nThe second parameter, successCallback
, is optional. If a function is\npassed, as in loadStrings('/assets/data.txt', handleData)
, then the\nhandleData()
function will be called once the data loads. The array\ncreated from the text data will be passed to handleData()
as its only\nargument.
\nThe third parameter, failureCallback
, is also optional. If a function is\npassed, as in loadStrings('/assets/data.txt', handleData, handleFailure)
,\nthen the handleFailure()
function will be called if an error occurs while\nloading. The Error
object will be passed to handleFailure()
as its only\nargument.
\nNote: Data can take time to load. Calling loadStrings()
within\npreload() ensures data loads before it's used in\nsetup() or draw().
\n"],"line":[0,309],"params":[1,[[0,{"name":[0,"path"],"description":[0,"path of the text file to be loaded.
\n"],"type":[0,"String"]}],[0,{"name":[0,"successCallback"],"description":[0,"function to call once the data is\n loaded. Will be passed the array.
\n"],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"errorCallback"],"description":[0,"function to call if the data fails to\n load. Will be passed an Error
event\n object.
\n"],"type":[0,"Function"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new array containing the loaded text."],"type":[0,"String[]"]}],"example":[1,[[0,"\n\n\n\nlet myData;\n\n// Load the text and create an array.\nfunction preload() {\n myData = loadStrings('/assets/test.txt');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Select a random line from the text.\n let phrase = random(myData);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display the text.\n text(phrase, 10, 50, 90);\n\n describe(`The text \"${phrase}\" written in black on a gray background.`);\n}\n
\n\n\n\n\nlet lastLine;\n\n// Load the text and preprocess it.\nfunction preload() {\n loadStrings('/assets/test.txt', handleData);\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display the text.\n text(lastLine, 10, 50, 90);\n\n describe('The text \"I talk like an orange\" written in black on a gray background.');\n}\n\n// Select the last line from the text.\nfunction handleData(data) {\n lastLine = data[data.length - 1];\n}\n
\n\n\n\n\nlet lastLine;\n\n// Load the text and preprocess it.\nfunction preload() {\n loadStrings('/assets/test.txt', handleData, handleError);\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display the text.\n text(lastLine, 10, 50, 90);\n\n describe('The text \"I talk like an orange\" written in black on a gray background.');\n}\n\n// Select the last line from the text.\nfunction handleData(data) {\n lastLine = data[data.length - 1];\n}\n\n// Log any errors to the console.\nfunction handleError(error) {\n console.error('Oops!', error);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/loadStrings"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/loadTable.mdx"],"slug":[0,"en/p5/loadtable"],"body":[0,"\n\n# loadTable\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"loadTable()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/files.js"],"description":[0,"Reads the contents of a file or URL and creates a p5.Table object with\nits values. If a file is specified, it must be located in the sketch's\n\"data\" folder. The filename parameter can also be a URL to a file found\nonline. By default, the file is assumed to be comma-separated (in CSV\nformat). Table only looks for a header row if the 'header' option is\nincluded.
\nThis method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed. Calling loadTable() inside preload()\nguarantees to complete the operation before setup() and draw() are called.\nOutside of preload(), you may supply a callback function to handle the\nobject:
\nAll files loaded and saved use UTF-8 encoding. This method is suitable for fetching files up to size of 64MB.
\n"],"line":[0,505],"params":[1,[[0,{"name":[0,"filename"],"description":[0,"name of the file or URL to load
\n"],"type":[0,"String"]}],[0,{"name":[0,"extension"],"description":[0,"parse the table by comma-separated values \"csv\", semicolon-separated\n values \"ssv\", or tab-separated values \"tsv\"
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"header"],"description":[0,"\"header\" to indicate table has header row
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"callback"],"description":[0,"function to be executed after\n loadTable() completes. On success, the\n Table object is passed in as the\n first argument.
\n"],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"errorCallback"],"description":[0,"function to be executed if\n there is an error, response is passed\n in as first argument
\n"],"type":[0,"Function"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"Table object containing data"],"type":[0,"Object"]}],"example":[1,[[0,"\n\n\n// Given the following CSV file called \"mammals.csv\"\n// located in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n //the file can be remote\n //table = loadTable(\"http://p5js.org/reference//assets/mammals.csv\",\n // \"csv\", \"header\");\n}\n\nfunction setup() {\n //count the columns\n print(table.getRowCount() + ' total rows in table');\n print(table.getColumnCount() + ' total columns in table');\n\n print(table.getColumn('name'));\n //[\"Goat\", \"Leopard\", \"Zebra\"]\n\n //cycle through the table\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++) {\n print(table.getString(r, c));\n }\n describe(`randomly generated text from a file,\n for example \"i smell like butter\"`);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/loadTable"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/loadXML.mdx"],"slug":[0,"en/p5/loadxml"],"body":[0,"\n\n# loadXML\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"loadXML()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/files.js"],"description":[0,"Loads an XML file to create a p5.XML object.
\nExtensible Markup Language\n(XML)\nis a standard format for sending data between applications. Like HTML, the\nXML format is based on tags and attributes, as in\n
.
\nThe first parameter, path
, is always a string with the path to the file.\nPaths to local files should be relative, as in\nloadXML('/assets/data.xml')
. URLs such as 'https://example.com/data.xml'
\nmay be blocked due to browser security.
\nThe second parameter, successCallback
, is optional. If a function is\npassed, as in loadXML('/assets/data.xml', handleData)
, then the\nhandleData()
function will be called once the data loads. The\np5.XML object created from the data will be passed\nto handleData()
as its only argument.
\nThe third parameter, failureCallback
, is also optional. If a function is\npassed, as in loadXML('/assets/data.xml', handleData, handleFailure)
, then\nthe handleFailure()
function will be called if an error occurs while\nloading. The Error
object will be passed to handleFailure()
as its only\nargument.
\nNote: Data can take time to load. Calling loadXML()
within\npreload() ensures data loads before it's used in\nsetup() or draw().
\n"],"line":[0,780],"params":[1,[[0,{"name":[0,"path"],"description":[0,"path of the XML file to be loaded.
\n"],"type":[0,"String"]}],[0,{"name":[0,"successCallback"],"description":[0,"function to call once the data is\n loaded. Will be passed the\n p5.XML object.
\n"],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"errorCallback"],"description":[0,"function to call if the data fails to\n load. Will be passed an Error
event\n object.
\n"],"type":[0,"Function"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"XML data loaded into a p5.XML\n object."],"type":[0,"p5.XML"]}],"example":[1,[[0,"\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get an array with all mammal tags.\n let mammals = myXML.getChildren('mammal');\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Iterate over the mammals array.\n for (let i = 0; i < mammals.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 25;\n\n // Get the mammal's common name.\n let name = mammals[i].getContent();\n\n // Display the mammal's name.\n text(name, 20, y);\n }\n\n describe(\n 'The words \"Goat\", \"Leopard\", and \"Zebra\" written on three separate lines. The text is black on a gray background.'\n );\n}\n
\n\n\n\n\nlet lastMammal;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n loadXML('/assets/animals.xml', handleData);\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(16);\n\n // Display the content of the last mammal element.\n text(lastMammal, 50, 50);\n\n describe('The word \"Zebra\" written in black on a gray background.');\n}\n\n// Get the content of the last mammal element.\nfunction handleData(data) {\n // Get an array with all mammal elements.\n let mammals = data.getChildren('mammal');\n\n // Get the content of the last mammal.\n lastMammal = mammals[mammals.length - 1].getContent();\n}\n
\n\n\n\n\nlet lastMammal;\n\n// Load the XML and preprocess it.\nfunction preload() {\n loadXML('/assets/animals.xml', handleData, handleError);\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(16);\n\n // Display the content of the last mammal element.\n text(lastMammal, 50, 50);\n\n describe('The word \"Zebra\" written in black on a gray background.');\n}\n\n// Get the content of the last mammal element.\nfunction handleData(data) {\n // Get an array with all mammal elements.\n let mammals = data.getChildren('mammal');\n\n // Get the content of the last mammal.\n lastMammal = mammals[mammals.length - 1].getContent();\n}\n\n// Log any errors to the console.\nfunction handleError(error) {\n console.error('Oops!', error);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/loadXML"]}],"render":[0,null]}]]]}],[0,{"name":[0,"Output"],"entry":[0],"entries":[1,[[0,{"id":[0,"en/p5/createWriter.mdx"],"slug":[0,"en/p5/createwriter"],"body":[0,"\n\n# createWriter\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createWriter()"],"module":[0,"IO"],"submodule":[0,"Output"],"file":[0,"src/io/files.js"],"description":[0,"Creates a new p5.PrintWriter object.
\np5.PrintWriter objects provide a way to\nsave a sequence of text data, called the print stream, to the user's\ncomputer. They're low-level objects that enable precise control of text\noutput. Functions such as\nsaveStrings() and\nsaveJSON() are easier to use for simple file\nsaving.
\nThe first parameter, filename
, is the name of the file to be written. If\na string is passed, as in createWriter('words.txt')
, a new\np5.PrintWriter object will be created that\nwrites to a file named words.txt
.
\nThe second parameter, extension
, is optional. If a string is passed, as\nin createWriter('words', 'csv')
, the first parameter will be interpreted\nas the file name and the second parameter as the extension.
\n"],"line":[0,1444],"params":[1,[[0,{"name":[0,"name"],"description":[0,"name of the file to create.
\n"],"type":[0,"String"]}],[0,{"name":[0,"extension"],"description":[0,"format to use for the file.
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"stream for writing data."],"type":[0,"p5.PrintWriter"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display instructions.\n text('Double-click to save', 5, 50, 90);\n\n describe('The text \"Double-click to save\" written in black on a gray background.');\n}\n\n// Save the file when the user double-clicks.\nfunction doubleClicked() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n // Create a p5.PrintWriter object.\n let myWriter = createWriter('xo.txt');\n\n // Add some lines to the print stream.\n myWriter.print('XOO');\n myWriter.print('OXO');\n myWriter.print('OOX');\n\n // Save the file and close the print stream.\n myWriter.close();\n }\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display instructions.\n text('Double-click to save', 5, 50, 90);\n\n describe('The text \"Double-click to save\" written in black on a gray background.');\n}\n\n// Save the file when the user double-clicks.\nfunction doubleClicked() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n // Create a p5.PrintWriter object.\n // Use the file format .csv.\n let myWriter = createWriter('mauna_loa_co2', 'csv');\n\n // Add some lines to the print stream.\n myWriter.print('date,ppm_co2');\n myWriter.print('1960-01-01,316.43');\n myWriter.print('1970-01-01,325.06');\n myWriter.print('1980-01-01,337.9');\n myWriter.print('1990-01-01,353.86');\n myWriter.print('2000-01-01,369.45');\n myWriter.print('2020-01-01,413.61');\n\n // Save the file and close the print stream.\n myWriter.close();\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/createWriter"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/p5.PrintWriter.mdx"],"slug":[0,"en/p5/p5printwriter"],"body":[0,"\n\n# p5.PrintWriter\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"p5.PrintWriter"],"module":[0,"IO"],"submodule":[0,"Output"],"file":[0,"src/io/files.js"],"description":[0,"A class to describe a print stream.
\nEach p5.PrintWriter
object provides a way to save a sequence of text\ndata, called the print stream, to the user's computer. It's a low-level\nobject that enables precise control of text output. Functions such as\nsaveStrings() and\nsaveJSON() are easier to use for simple file\nsaving.
\nNote: createWriter() is the recommended way\nto make an instance of this class.
\n"],"line":[0,1565],"path":[0,"p5/p5.PrintWriter"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/save.mdx"],"slug":[0,"en/p5/save"],"body":[0,"\n\n# save\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"save()"],"module":[0,"IO"],"submodule":[0,"Output"],"file":[0,"src/io/files.js"],"description":[0,"Saves a given element(image, text, json, csv, wav, or html) to the client's\ncomputer. The first parameter can be a pointer to element we want to save.\nThe element can be one of p5.Element,an Array of\nStrings, an Array of JSON, a JSON object, a p5.Table\n, a p5.Image, or a p5.SoundFile (requires\np5.sound). The second parameter is a filename (including extension).The\nthird parameter is for options specific to this type of object. This method\nwill save a file that fits the given parameters.\nIf it is called without specifying an element, by default it will save the\nwhole canvas as an image file. You can optionally specify a filename as\nthe first parameter in such a case.\nNote that it is not recommended to\ncall this method within draw, as it will open a new save dialog on every\nrender.
\n"],"line":[0,1835],"params":[1,[[0,{"name":[0,"objectOrFilename"],"description":[0,"If filename is provided, will\n save canvas as an image with\n either png or jpg extension\n depending on the filename.\n If object is provided, will\n save depending on the object\n and filename (see examples\n above).
\n"],"type":[0,"Object|String"],"optional":[0,true]}],[0,{"name":[0,"filename"],"description":[0,"If an object is provided as the first\n parameter, then the second parameter\n indicates the filename,\n and should include an appropriate\n file extension (see examples above).
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"options"],"description":[0,"Additional options depend on\n filetype. For example, when saving JSON,\n true
indicates that the\n output will be optimized for filesize,\n rather than readability.
\n"],"type":[0,"Boolean|String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n \n // Saves the canvas as an image\n cnv = createCanvas(300, 300);\n save(cnv, 'myCanvas.jpg');\n\n // Saves the canvas as an image by default\n save('myCanvas.jpg');\n describe('An example for saving a canvas as an image.');\n
\n\n \n // Saves p5.Image as an image\n img = createImage(10, 10);\n save(img, 'myImage.png');\n describe('An example for saving a p5.Image element as an image.');\n
\n\n \n // Saves p5.Renderer object as an image\n obj = createGraphics(100, 100);\n save(obj, 'myObject.png');\n describe('An example for saving a p5.Renderer element.');\n
\n\n \n let myTable = new p5.Table();\n // Saves table as html file\n save(myTable, 'myTable.html');\n\n // Comma Separated Values\n save(myTable, 'myTable.csv');\n\n // Tab Separated Values\n save(myTable, 'myTable.tsv');\n\n describe(`An example showing how to save a table in formats of\n HTML, CSV and TSV.`);\n
\n\n \n let myJSON = { a: 1, b: true };\n\n // Saves pretty JSON\n save(myJSON, 'my.json');\n\n // Optimizes JSON filesize\n save(myJSON, 'my.json', true);\n\n describe('An example for saving JSON to a txt file with some extra arguments.');\n
\n\n \n // Saves array of strings to text file with line breaks after each item\n let arrayOfStrings = ['a', 'b'];\n save(arrayOfStrings, 'my.txt');\n describe(`An example for saving an array of strings to text file\n with line breaks.`);\n
"]]],"isConstructor":[0,false],"path":[0,"p5/save"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/saveJSON.mdx"],"slug":[0,"en/p5/savejson"],"body":[0,"\n\n# saveJSON\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"saveJSON()"],"module":[0,"IO"],"submodule":[0,"Output"],"file":[0,"src/io/files.js"],"description":[0,"Saves an Object
or Array
to a JSON file.
\nJavaScript Object Notation\n(JSON)\nis a standard format for sending data between applications. The format is\nbased on JavaScript objects which have keys and values. JSON files store\ndata in an object with strings as keys. Values can be strings, numbers,\nBooleans, arrays, null
, or other objects.
\nThe first parameter, json
, is the data to save. The data can be an array,\nas in [1, 2, 3]
, or an object, as in\n{ x: 50, y: 50, color: 'deeppink' }
.
\nThe second parameter, filename
, is a string that sets the file's name.\nFor example, calling saveJSON([1, 2, 3], 'data.json')
saves the array\n[1, 2, 3]
to a file called data.json
on the user's computer.
\nThe third parameter, optimize
, is optional. If true
is passed, as in\nsaveJSON([1, 2, 3], 'data.json', true)
, then all unneeded whitespace will\nbe removed to reduce the file size.
\nNote: The browser will either save the file immediately or prompt the user\nwith a dialogue window.
\n"],"line":[0,1979],"params":[1,[[0,{"name":[0,"json"],"description":[0,"data to save.
\n"],"type":[0,"Array|Object"]}],[0,{"name":[0,"filename"],"description":[0,"name of the file to be saved.
\n"],"type":[0,"String"]}],[0,{"name":[0,"optimize"],"description":[0,"whether to trim unneeded whitespace. Defaults\n to true
.
\n"],"type":[0,"Boolean"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display instructions.\n text('Double-click to save', 5, 50, 90);\n\n describe('The text \"Double-click to save\" written in black on a gray background.');\n}\n\n// Save the file when the user double-clicks.\nfunction doubleClicked() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n // Create an array.\n let data = [1, 2, 3];\n\n // Save the JSON file.\n saveJSON(data, 'numbers.json');\n }\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display instructions.\n text('Double-click to save', 5, 50, 90);\n\n describe('The text \"Double-click to save\" written in black on a gray background.');\n}\n\n// Save the file when the user double-clicks.\nfunction doubleClicked() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n // Create an object.\n let data = { x: mouseX, y: mouseY };\n\n // Save the JSON file.\n saveJSON(data, 'state.json');\n }\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display instructions.\n text('Double-click to save', 5, 50, 90);\n\n describe('The text \"Double-click to save\" written in black on a gray background.');\n}\n\n// Save the file when the user double-clicks.\nfunction doubleClicked() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n // Create an object.\n let data = { x: mouseX, y: mouseY };\n\n // Save the JSON file and reduce its size.\n saveJSON(data, 'state.json', true);\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/saveJSON"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/saveStrings.mdx"],"slug":[0,"en/p5/savestrings"],"body":[0,"\n\n# saveStrings\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"saveStrings()"],"module":[0,"IO"],"submodule":[0,"Output"],"file":[0,"src/io/files.js"],"description":[0,"Saves an Array
of String
s to a file, one per line.
\nThe first parameter, list
, is an array with the strings to save.
\nThe second parameter, filename
, is a string that sets the file's name.\nFor example, calling saveStrings(['0', '01', '011'], 'data.txt')
saves\nthe array ['0', '01', '011']
to a file called data.txt
on the user's\ncomputer.
\nThe third parameter, extension
, is optional. If a string is passed, as in\nsaveStrings(['0', '01', '0
1'], 'data', 'txt')`, the second parameter will\nbe interpreted as the file name and the third parameter as the extension.
\nThe fourth parameter, isCRLF
, is also optional, If true
is passed, as\nin saveStrings(['0', '01', '011'], 'data', 'txt', true)
, then two\ncharacters, \\r\\n
, will be added to the end of each string to create new\nlines in the saved file. \\r
is a carriage return (CR) and \\n
is a line\nfeed (LF). By default, only \\n
(line feed) is added to each string in\norder to create new lines.
\nNote: The browser will either save the file immediately or prompt the user\nwith a dialogue window.
\n"],"line":[0,2118],"params":[1,[[0,{"name":[0,"list"],"description":[0,"data to save.
\n"],"type":[0,"String[]"]}],[0,{"name":[0,"filename"],"description":[0,"name of file to be saved.
\n"],"type":[0,"String"]}],[0,{"name":[0,"extension"],"description":[0,"format to use for the file.
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"isCRLF"],"description":[0,"whether to add \\r\\n
to the end of each\n string. Defaults to false
.
\n"],"type":[0,"Boolean"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display instructions.\n text('Double-click to save', 5, 50, 90);\n\n describe('The text \"Double-click to save\" written in black on a gray background.');\n}\n\n// Save the file when the user double-clicks.\nfunction doubleClicked() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n // Create an array.\n let data = ['0', '01', '011'];\n\n // Save the text file.\n saveStrings(data, 'data.txt');\n }\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display instructions.\n text('Double-click to save', 5, 50, 90);\n\n describe('The text \"Double-click to save\" written in black on a gray background.');\n}\n\n// Save the file when the user double-clicks.\nfunction doubleClicked() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n // Create an array.\n // ASCII art courtesy Wikipedia:\n // https://en.wikipedia.org/wiki/ASCII_art\n let data = [' (\\\\_/) ', \"(='.'=)\", '(\")_(\")'];\n\n // Save the text file.\n saveStrings(data, 'cat', 'txt');\n }\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display instructions.\n text('Double-click to save', 5, 50, 90);\n\n describe('The text \"Double-click to save\" written in black on a gray background.');\n}\n\n// Save the file when the user double-clicks.\nfunction doubleClicked() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n // Create an array.\n // +--+\n // / /|\n // +--+ +\n // | |/\n // +--+\n let data = [' +--+', ' / /|', '+--+ +', '| |/', '+--+'];\n\n // Save the text file.\n // Use CRLF for line endings.\n saveStrings(data, 'box', 'txt', true);\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/saveStrings"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/saveTable.mdx"],"slug":[0,"en/p5/savetable"],"body":[0,"\n\n# saveTable\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"saveTable()"],"module":[0,"IO"],"submodule":[0,"Output"],"file":[0,"src/io/files.js"],"description":[0,"Writes the contents of a Table object to a file. Defaults to a\ntext file with comma-separated-values ('csv') but can also\nuse tab separation ('tsv'), or generate an HTML table ('html').\nThe file saving process and location of the saved file will\nvary between web browsers.
\n"],"line":[0,2275],"params":[1,[[0,{"name":[0,"Table"],"description":[0,"the Table object to save to a file
\n"],"type":[0,"p5.Table"]}],[0,{"name":[0,"filename"],"description":[0,"the filename to which the Table should be saved
\n"],"type":[0,"String"]}],[0,{"name":[0,"options"],"description":[0,"can be one of \"tsv\", \"csv\", or \"html\"
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n let table;\n\n function setup() {\n table = new p5.Table();\n\n table.addColumn('id');\n table.addColumn('species');\n table.addColumn('name');\n\n let newRow = table.addRow();\n newRow.setNum('id', table.getRowCount() - 1);\n newRow.setString('species', 'Panthera leo');\n newRow.setString('name', 'Lion');\n\n // To save, un-comment next line then click 'run'\n // saveTable(table, 'new.csv');\n\n describe('no image displayed');\n }\n\n // Saves the following to a file called 'new.csv':\n // id,species,name\n // 0,Panthera leo,Lion\n
"]]],"isConstructor":[0,false],"path":[0,"p5/saveTable"]}],"render":[0,null]}]]]}],[0,{"name":[0,"Time & Date"],"entry":[0],"entries":[1,[[0,{"id":[0,"en/p5/day.mdx"],"slug":[0,"en/p5/day"],"body":[0,"\n\n# day\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"day()"],"module":[0,"IO"],"submodule":[0,"Time & Date"],"file":[0,"src/utilities/time_date.js"],"description":[0,"Returns the current day as a number from 1–31.
\n"],"line":[0,10],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"current day between 1 and 31."],"type":[0,"Integer"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the current day.\n let d = day();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textSize(12);\n textFont('Courier New');\n\n // Display the day.\n text(`Current day: ${d}`, 20, 50, 60);\n\n describe(`The text 'Current day: ${d}' written in black on a gray background.`);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/day"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/hour.mdx"],"slug":[0,"en/p5/hour"],"body":[0,"\n\n# hour\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"hour()"],"module":[0,"IO"],"submodule":[0,"Time & Date"],"file":[0,"src/utilities/time_date.js"],"description":[0,"Returns the current hour as a number from 0–23.
\n"],"line":[0,44],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"current hour between 0 and 23."],"type":[0,"Integer"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the current hour.\n let h = hour();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textSize(12);\n textFont('Courier New');\n\n // Display the hour.\n text(`Current hour: ${h}`, 20, 50, 60);\n\n describe(`The text 'Current hour: ${h}' written in black on a gray background.`);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/hour"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/millis.mdx"],"slug":[0,"en/p5/millis"],"body":[0,"\n\n# millis\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"millis()"],"module":[0,"IO"],"submodule":[0,"Time & Date"],"file":[0,"src/utilities/time_date.js"],"description":[0,"Returns the number of milliseconds since a sketch started running.
\nmillis()
keeps track of how long a sketch has been running in\nmilliseconds (thousandths of a second). This information is often\nhelpful for timing events and animations.
\nIf a sketch has a\nsetup() function, then millis()
begins tracking\ntime before the code in setup() runs. If a\nsketch includes a preload() function, then\nmillis()
begins tracking time as soon as the code in\npreload() starts running.
\n"],"line":[0,112],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"number of milliseconds since starting the sketch."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the number of milliseconds the sketch has run.\n let ms = millis();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textSize(10);\n textFont('Courier New');\n\n // Display how long it took setup() to be called.\n text(`Startup time: ${round(ms, 2)} ms`, 5, 50, 90);\n\n describe(\n `The text 'Startup time: ${round(ms, 2)} ms' written in black on a gray background.`\n );\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('The text \"Running time: S sec\" written in black on a gray background. The number S increases as the sketch runs.');\n}\n\nfunction draw() {\n background(200);\n\n // Get the number of seconds the sketch has run.\n let s = millis() / 1000;\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textSize(10);\n textFont('Courier New');\n\n // Display how long the sketch has run.\n text(`Running time: ${nf(s, 1, 1)} sec`, 5, 50, 90);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle oscillates left and right on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Get the number of seconds the sketch has run.\n let s = millis() / 1000;\n\n // Calculate an x-coordinate.\n let x = 30 * sin(s) + 50;\n\n // Draw the circle.\n circle(x, 50, 30);\n}\n
\n\n\n\n\n// Load the GeoJSON.\nfunction preload() {\n loadJSON('https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the number of milliseconds the sketch has run.\n let ms = millis();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(11);\n\n // Display how long it took to load the data.\n text(`It took ${round(ms, 2)} ms to load the data`, 5, 50, 100);\n\n describe(\n `The text \"It took ${round(ms, 2)} ms to load the data\" written in black on a gray background.`\n );\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/millis"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/minute.mdx"],"slug":[0,"en/p5/minute"],"body":[0,"\n\n# minute\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"minute()"],"module":[0,"IO"],"submodule":[0,"Time & Date"],"file":[0,"src/utilities/time_date.js"],"description":[0,"Returns the current minute as a number from 0–59.
\n"],"line":[0,78],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"current minute between 0 and 59."],"type":[0,"Integer"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the current minute.\n let m = minute();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textSize(12);\n textFont('Courier New');\n\n // Display the minute.\n text(`Current minute: ${m}`, 10, 50, 80);\n\n describe(`The text 'Current minute: ${m}' written in black on a gray background.`);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/minute"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/month.mdx"],"slug":[0,"en/p5/month"],"body":[0,"\n\n# month\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"month()"],"module":[0,"IO"],"submodule":[0,"Time & Date"],"file":[0,"src/utilities/time_date.js"],"description":[0,"Returns the current month as a number from 1–12.
\n"],"line":[0,242],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"current month between 1 and 12."],"type":[0,"Integer"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the current month.\n let m = month();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textSize(12);\n textFont('Courier New');\n\n // Display the month.\n text(`Current month: ${m}`, 10, 50, 80);\n\n describe(`The text 'Current month: ${m}' written in black on a gray background.`);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/month"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/second.mdx"],"slug":[0,"en/p5/second"],"body":[0,"\n\n# second\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"second()"],"module":[0,"IO"],"submodule":[0,"Time & Date"],"file":[0,"src/utilities/time_date.js"],"description":[0,"Returns the current second as a number from 0–59.
\n"],"line":[0,277],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"current second between 0 and 59."],"type":[0,"Integer"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the current second.\n let s = second();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textSize(12);\n textFont('Courier New');\n\n // Display the second.\n text(`Current second: ${s}`, 10, 50, 80);\n\n describe(`The text 'Current second: ${s}' written in black on a gray background.`);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/second"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/year.mdx"],"slug":[0,"en/p5/year"],"body":[0,"\n\n# year\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"year()"],"module":[0,"IO"],"submodule":[0,"Time & Date"],"file":[0,"src/utilities/time_date.js"],"description":[0,"Returns the current year as a number such as 1999.
\n"],"line":[0,311],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"current year."],"type":[0,"Integer"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the current year.\n let y = year();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textSize(12);\n textFont('Courier New');\n\n // Display the year.\n text(`Current year: ${y}`, 10, 50, 80);\n\n describe(`The text 'Current year: ${y}' written in black on a gray background.`);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/year"]}],"render":[0,null]}]]]}],[0,{"name":[0,"p5.Table"],"entry":[0,{"id":[0,"en/p5/p5.Table.mdx"],"slug":[0,"en/p5/p5table"],"body":[0,"\n\n# p5.Table\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"p5.Table"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Table objects store data with multiple rows and columns, much\nlike in a traditional spreadsheet. Tables can be generated from\nscratch, dynamically, or using data from an existing file.
\n"],"line":[0,33],"params":[1,[[0,{"name":[0,"rows"],"description":[0,"An array of p5.TableRow objects
\n"],"type":[0,"p5.TableRow[]"],"optional":[0,true]}]]],"chainable":[0,false],"methods":[0,{"addRow":[0,{"description":[0,"Use addRow() to add a new row of data to a p5.Table object. By default,\nan empty row is created. Typically, you would store a reference to\nthe new row in a TableRow object (see newRow in the example above),\nand then set individual values using set().
\nIf a p5.TableRow object is included as a parameter, then that row is\nduplicated and added to the table.
\n"],"path":[0,"p5.Table/addRow"]}],"removeRow":[0,{"description":[0,"Removes a row from the table object.
\n"],"path":[0,"p5.Table/removeRow"]}],"getRow":[0,{"description":[0,"Returns a reference to the specified p5.TableRow. The reference\ncan then be used to get and set values of the selected row.
\n"],"path":[0,"p5.Table/getRow"]}],"getRows":[0,{"description":[0,"Gets all rows from the table. Returns an array of p5.TableRows.
\n"],"path":[0,"p5.Table/getRows"]}],"findRow":[0,{"description":[0,"Finds the first row in the Table that contains the value\nprovided, and returns a reference to that row. Even if\nmultiple rows are possible matches, only the first matching\nrow is returned. The column to search may be specified by\neither its ID or title.
\n"],"path":[0,"p5.Table/findRow"]}],"findRows":[0,{"description":[0,"Finds the rows in the Table that contain the value\nprovided, and returns references to those rows. Returns an\nArray, so for must be used to iterate through all the rows,\nas shown in the example above. The column to search may be\nspecified by either its ID or title.
\n"],"path":[0,"p5.Table/findRows"]}],"matchRow":[0,{"description":[0,"Finds the first row in the Table that matches the regular\nexpression provided, and returns a reference to that row.\nEven if multiple rows are possible matches, only the first\nmatching row is returned. The column to search may be\nspecified by either its ID or title.
\n"],"path":[0,"p5.Table/matchRow"]}],"matchRows":[0,{"description":[0,"Finds the rows in the Table that match the regular expression provided,\nand returns references to those rows. Returns an array, so for must be\nused to iterate through all the rows, as shown in the example. The\ncolumn to search may be specified by either its ID or title.
\n"],"path":[0,"p5.Table/matchRows"]}],"getColumn":[0,{"description":[0,"Retrieves all values in the specified column, and returns them\nas an array. The column may be specified by either its ID or title.
\n"],"path":[0,"p5.Table/getColumn"]}],"clearRows":[0,{"description":[0,"Removes all rows from a Table. While all rows are removed,\ncolumns and column titles are maintained.
\n"],"path":[0,"p5.Table/clearRows"]}],"addColumn":[0,{"description":[0,"Use addColumn() to add a new column to a Table object.\nTypically, you will want to specify a title, so the column\nmay be easily referenced later by name. (If no title is\nspecified, the new column's title will be null.)
\n"],"path":[0,"p5.Table/addColumn"]}],"getColumnCount":[0,{"description":[0,"Returns the total number of columns in a Table.
\n"],"path":[0,"p5.Table/getColumnCount"]}],"getRowCount":[0,{"description":[0,"Returns the total number of rows in a Table.
\n"],"path":[0,"p5.Table/getRowCount"]}],"removeTokens":[0,{"description":[0,"Removes any of the specified characters (or \"tokens\").
\nIf no column is specified, then the values in all columns and\nrows are processed. A specific column may be referenced by\neither its ID or title.
\n"],"path":[0,"p5.Table/removeTokens"]}],"trim":[0,{"description":[0,"Trims leading and trailing whitespace, such as spaces and tabs,\nfrom String table values. If no column is specified, then the\nvalues in all columns and rows are trimmed. A specific column\nmay be referenced by either its ID or title.
\n"],"path":[0,"p5.Table/trim"]}],"removeColumn":[0,{"description":[0,"Use removeColumn() to remove an existing column from a Table\nobject. The column to be removed may be identified by either\nits title (a String) or its index value (an int).\nremoveColumn(0) would remove the first column, removeColumn(1)\nwould remove the second column, and so on.
\n"],"path":[0,"p5.Table/removeColumn"]}],"set":[0,{"description":[0,"Stores a value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
\n"],"path":[0,"p5.Table/set"]}],"setNum":[0,{"description":[0,"Stores a Float value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
\n"],"path":[0,"p5.Table/setNum"]}],"setString":[0,{"description":[0,"Stores a String value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
\n"],"path":[0,"p5.Table/setString"]}],"get":[0,{"description":[0,"Retrieves a value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n"],"path":[0,"p5.Table/get"]}],"getNum":[0,{"description":[0,"Retrieves a Float value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n"],"path":[0,"p5.Table/getNum"]}],"getString":[0,{"description":[0,"Retrieves a String value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n"],"path":[0,"p5.Table/getString"]}],"getObject":[0,{"description":[0,"Retrieves all table data and returns as an object. If a column name is\npassed in, each row object will be stored with that attribute as its\ntitle.
\n"],"path":[0,"p5.Table/getObject"]}],"getArray":[0,{"description":[0,"Retrieves all table data and returns it as a multidimensional array.
\n"],"path":[0,"p5.Table/getArray"]}]}],"properties":[0,{"columns":[0,{"description":[0,"An array containing the names of the columns in the table, if the \"header\" the table is\nloaded with the \"header\" parameter.
\n"],"path":[0,"p5.Table/columns"]}],"rows":[0,{"description":[0,"An array containing the p5.TableRow objects that make up the\nrows of the table. The same result as calling getRows()
\n"],"path":[0,"p5.Table/rows"]}]}],"isConstructor":[0,true],"path":[0,"p5/p5.Table"]}],"render":[0,null]}],"entries":[1,[[0,{"id":[0,"en/p5.Table/addColumn.mdx"],"slug":[0,"en/p5table/addcolumn"],"body":[0,"\n\n# addColumn\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"addColumn()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Use addColumn() to add a new column to a Table object.\nTypically, you will want to specify a title, so the column\nmay be easily referenced later by name. (If no title is\nspecified, the new column's title will be null.)
\n"],"line":[0,631],"params":[1,[[0,{"name":[0,"title"],"description":[0,"title of the given column
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"example":[1,[[0,"\n \n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.addColumn('carnivore');\n table.set(0, 'carnivore', 'no');\n table.set(1, 'carnivore', 'yes');\n table.set(2, 'carnivore', 'no');\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n\n describe('no image displayed');\n }\n
\n "]]],"isConstructor":[0,false],"path":[0,"p5.Table/addColumn"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/addRow.mdx"],"slug":[0,"en/p5table/addrow"],"body":[0,"\n\n# addRow\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"addRow()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Use addRow() to add a new row of data to a p5.Table object. By default,\nan empty row is created. Typically, you would store a reference to\nthe new row in a TableRow object (see newRow in the example above),\nand then set individual values using set().
\nIf a p5.TableRow object is included as a parameter, then that row is\nduplicated and added to the table.
\n"],"line":[0,90],"params":[1,[[0,{"name":[0,"row"],"description":[0,"row to be added to the table
\n"],"type":[0,"p5.TableRow"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,"the row that was added"],"type":[0,"p5.TableRow"]}],"example":[1,[[0,"\n \n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //add a row\n let newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Canis Lupus');\n newRow.setString('name', 'Wolf');\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n\n describe('no image displayed');\n }\n
\n "]]],"isConstructor":[0,false],"path":[0,"p5.Table/addRow"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/clearRows.mdx"],"slug":[0,"en/p5table/clearrows"],"body":[0,"\n\n# clearRows\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"clearRows()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Removes all rows from a Table. While all rows are removed,\ncolumns and column titles are maintained.
\n"],"line":[0,592],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"example":[1,[[0,"\n \n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.clearRows();\n print(table.getRowCount() + ' total rows in table');\n print(table.getColumnCount() + ' total columns in table');\n describe('no image displayed');\n }\n
\n "]]],"isConstructor":[0,false],"path":[0,"p5.Table/clearRows"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/columns.mdx"],"slug":[0,"en/p5table/columns"],"body":[0,"\n\n# columns\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"columns"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"An array containing the names of the columns in the table, if the \"header\" the table is\nloaded with the \"header\" parameter.
\n"],"line":[0,43],"itemtype":[0,"property"],"class":[0,"p5.Table"],"example":[1,[[0,"\n\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //print the column names\n for (let c = 0; c < table.getColumnCount(); c++) {\n print('column ' + c + ' is named ' + table.columns[c]);\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Table/columns"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/findRow.mdx"],"slug":[0,"en/p5table/findrow"],"body":[0,"\n\n# findRow\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"findRow()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Finds the first row in the Table that contains the value\nprovided, and returns a reference to that row. Even if\nmultiple rows are possible matches, only the first matching\nrow is returned. The column to search may be specified by\neither its ID or title.
\n"],"line":[0,289],"params":[1,[[0,{"name":[0,"value"],"description":[0,"The value to match
\n"],"type":[0,"String"]}],[0,{"name":[0,"column"],"description":[0,"ID number or title of the\n column to search
\n"],"type":[0,"Integer|String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"p5.TableRow"]}],"example":[1,[[0,"\n \n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //find the animal named zebra\n let row = table.findRow('Zebra', 'name');\n //find the corresponding species\n print(row.getString('species'));\n describe('no image displayed');\n }\n
\n "]]],"isConstructor":[0,false],"path":[0,"p5.Table/findRow"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/findRows.mdx"],"slug":[0,"en/p5table/findrows"],"body":[0,"\n\n# findRows\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"findRows()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Finds the rows in the Table that contain the value\nprovided, and returns references to those rows. Returns an\nArray, so for must be used to iterate through all the rows,\nas shown in the example above. The column to search may be\nspecified by either its ID or title.
\n"],"line":[0,351],"params":[1,[[0,{"name":[0,"value"],"description":[0,"The value to match
\n"],"type":[0,"String"]}],[0,{"name":[0,"column"],"description":[0,"ID number or title of the\n column to search
\n"],"type":[0,"Integer|String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,"An Array of TableRow objects"],"type":[0,"p5.TableRow[]"]}],"example":[1,[[0,"\n \n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //add another goat\n let newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Scape Goat');\n newRow.setString('name', 'Goat');\n\n //find the rows containing animals named Goat\n let rows = table.findRows('Goat', 'name');\n print(rows.length + ' Goats found');\n describe('no image displayed');\n }\n
\n "]]],"isConstructor":[0,false],"path":[0,"p5.Table/findRows"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/get.mdx"],"slug":[0,"en/p5table/get"],"body":[0,"\n\n# get\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"get()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Retrieves a value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n"],"line":[0,1087],"params":[1,[[0,{"name":[0,"row"],"description":[0,"row ID
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"column"],"description":[0,"columnName (string) or\n ID (number)
\n"],"type":[0,"String|Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"String|Number"]}],"example":[1,[[0,"\n\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.get(0, 1));\n //Capra hircus\n print(table.get(0, 'species'));\n //Capra hircus\n describe('no image displayed');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Table/get"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/getArray.mdx"],"slug":[0,"en/p5table/getarray"],"body":[0,"\n\n# getArray\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"getArray()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Retrieves all table data and returns it as a multidimensional array.
\n"],"line":[0,1285],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"Array"]}],"example":[1,[[0,"\n\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leoperd\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n // table is comma separated value \"CSV\"\n // and has specifiying header for column labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n let tableArray = table.getArray();\n for (let i = 0; i < tableArray.length; i++) {\n print(tableArray[i]);\n }\n describe('no image displayed');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Table/getArray"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/getColumn.mdx"],"slug":[0,"en/p5table/getcolumn"],"body":[0,"\n\n# getColumn\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"getColumn()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Retrieves all values in the specified column, and returns them\nas an array. The column may be specified by either its ID or title.
\n"],"line":[0,542],"params":[1,[[0,{"name":[0,"column"],"description":[0,"String or Number of the column to return
\n"],"type":[0,"String|Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,"Array of column values"],"type":[0,"Array"]}],"example":[1,[[0,"\n \n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //getColumn returns an array that can be printed directly\n print(table.getColumn('species'));\n //outputs [\"Capra hircus\", \"Panthera pardus\", \"Equus zebra\"]\n describe('no image displayed');\n }\n
\n "]]],"isConstructor":[0,false],"path":[0,"p5.Table/getColumn"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/getColumnCount.mdx"],"slug":[0,"en/p5table/getcolumncount"],"body":[0,"\n\n# getColumnCount\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"getColumnCount()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Returns the total number of columns in a Table.
\n"],"line":[0,680],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,"Number of columns in this table"],"type":[0,"Integer"]}],"example":[1,[[0,"\n \n \n // given the cvs file \"blobs.csv\" in /assets directory\n // ID, Name, Flavor, Shape, Color\n // Blob1, Blobby, Sweet, Blob, Pink\n // Blob2, Saddy, Savory, Blob, Blue\n\n let table;\n\n function preload() {\n table = loadTable('/assets/blobs.csv');\n }\n\n function setup() {\n createCanvas(200, 100);\n textAlign(CENTER);\n background(255);\n }\n\n function draw() {\n let numOfColumn = table.getColumnCount();\n text('There are ' + numOfColumn + ' columns in the table.', 100, 50);\n }\n
\n "]]],"isConstructor":[0,false],"path":[0,"p5.Table/getColumnCount"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/getNum.mdx"],"slug":[0,"en/p5table/getnum"],"body":[0,"\n\n# getNum\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"getNum()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Retrieves a Float value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n"],"line":[0,1131],"params":[1,[[0,{"name":[0,"row"],"description":[0,"row ID
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"column"],"description":[0,"columnName (string) or\n ID (number)
\n"],"type":[0,"String|Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.getNum(1, 0) + 100);\n //id 1 + 100 = 101\n describe('no image displayed');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Table/getNum"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/getObject.mdx"],"slug":[0,"en/p5table/getobject"],"body":[0,"\n\n# getObject\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"getObject()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Retrieves all table data and returns as an object. If a column name is\npassed in, each row object will be stored with that attribute as its\ntitle.
\n"],"line":[0,1223],"params":[1,[[0,{"name":[0,"headerColumn"],"description":[0,"Name of the column which should be used to\n title each row object (optional)
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"Object"]}],"example":[1,[[0,"\n\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n let tableObject = table.getObject();\n\n print(tableObject);\n //outputs an object\n\n describe('no image displayed');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Table/getObject"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/getRow.mdx"],"slug":[0,"en/p5table/getrow"],"body":[0,"\n\n# getRow\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"getRow()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Returns a reference to the specified p5.TableRow. The reference\ncan then be used to get and set values of the selected row.
\n"],"line":[0,198],"params":[1,[[0,{"name":[0,"rowID"],"description":[0,"ID number of the row to get
\n"],"type":[0,"Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,"p5.TableRow object"],"type":[0,"p5.TableRow"]}],"example":[1,[[0,"\n\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n let row = table.getRow(1);\n //print it column by column\n //note: a row is an object, not an array\n for (let c = 0; c < table.getColumnCount(); c++) {\n print(row.getString(c));\n }\n\n describe('no image displayed');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Table/getRow"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/getRowCount.mdx"],"slug":[0,"en/p5table/getrowcount"],"body":[0,"\n\n# getRowCount\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"getRowCount()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Returns the total number of rows in a Table.
\n"],"line":[0,716],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,"Number of rows in this table"],"type":[0,"Integer"]}],"example":[1,[[0,"\n \n \n // given the cvs file \"blobs.csv\" in /assets directory\n //\n // ID, Name, Flavor, Shape, Color\n // Blob1, Blobby, Sweet, Blob, Pink\n // Blob2, Saddy, Savory, Blob, Blue\n\n let table;\n\n function preload() {\n table = loadTable('/assets/blobs.csv');\n }\n\n function setup() {\n createCanvas(200, 100);\n textAlign(CENTER);\n background(255);\n }\n\n function draw() {\n text('There are ' + table.getRowCount() + ' rows in the table.', 100, 50);\n }\n
\n "]]],"isConstructor":[0,false],"path":[0,"p5.Table/getRowCount"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/getRows.mdx"],"slug":[0,"en/p5table/getrows"],"body":[0,"\n\n# getRows\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"getRows()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Gets all rows from the table. Returns an array of p5.TableRows.
\n"],"line":[0,242],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,"Array of p5.TableRows"],"type":[0,"p5.TableRow[]"]}],"example":[1,[[0,"\n \n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n\n //warning: rows is an array of objects\n for (let r = 0; r < rows.length; r++) {\n rows[r].set('name', 'Unicorn');\n }\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n\n describe('no image displayed');\n }\n
\n "]]],"isConstructor":[0,false],"path":[0,"p5.Table/getRows"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/getString.mdx"],"slug":[0,"en/p5table/getstring"],"body":[0,"\n\n# getString\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"getString()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Retrieves a String value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n"],"line":[0,1173],"params":[1,[[0,{"name":[0,"row"],"description":[0,"row ID
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"column"],"description":[0,"columnName (string) or\n ID (number)
\n"],"type":[0,"String|Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"String"]}],"example":[1,[[0,"\n\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n // table is comma separated value \"CSV\"\n // and has specifiying header for column labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.getString(0, 0)); // 0\n print(table.getString(0, 1)); // Capra hircus\n print(table.getString(0, 2)); // Goat\n print(table.getString(1, 0)); // 1\n print(table.getString(1, 1)); // Panthera pardus\n print(table.getString(1, 2)); // Leopard\n print(table.getString(2, 0)); // 2\n print(table.getString(2, 1)); // Equus zebra\n print(table.getString(2, 2)); // Zebra\n describe('no image displayed');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Table/getString"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/matchRow.mdx"],"slug":[0,"en/p5table/matchrow"],"body":[0,"\n\n# matchRow\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"matchRow()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Finds the first row in the Table that matches the regular\nexpression provided, and returns a reference to that row.\nEven if multiple rows are possible matches, only the first\nmatching row is returned. The column to search may be\nspecified by either its ID or title.
\n"],"line":[0,417],"params":[1,[[0,{"name":[0,"regexp"],"description":[0,"The regular expression to match
\n"],"type":[0,"String|RegExp"]}],[0,{"name":[0,"column"],"description":[0,"The column ID (number) or\n title (string)
\n"],"type":[0,"String|Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,"TableRow object"],"type":[0,"p5.TableRow"]}],"example":[1,[[0,"\n\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //Search using specified regex on a given column, return TableRow object\n let mammal = table.matchRow(new RegExp('ant'), 1);\n print(mammal.getString(1));\n //Output \"Panthera pardus\"\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Table/matchRow"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/matchRows.mdx"],"slug":[0,"en/p5table/matchrows"],"body":[0,"\n\n# matchRows\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"matchRows()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Finds the rows in the Table that match the regular expression provided,\nand returns references to those rows. Returns an array, so for must be\nused to iterate through all the rows, as shown in the example. The\ncolumn to search may be specified by either its ID or title.
\n"],"line":[0,475],"params":[1,[[0,{"name":[0,"regexp"],"description":[0,"The regular expression to match
\n"],"type":[0,"String"]}],[0,{"name":[0,"column"],"description":[0,"The column ID (number) or\n title (string)
\n"],"type":[0,"String|Integer"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,"An Array of TableRow objects"],"type":[0,"p5.TableRow[]"]}],"example":[1,[[0,"\n\n\nlet table;\n\nfunction setup() {\n table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n let newRow = table.addRow();\n newRow.setString('name', 'Lion');\n newRow.setString('type', 'Mammal');\n\n newRow = table.addRow();\n newRow.setString('name', 'Snake');\n newRow.setString('type', 'Reptile');\n\n newRow = table.addRow();\n newRow.setString('name', 'Mosquito');\n newRow.setString('type', 'Insect');\n\n newRow = table.addRow();\n newRow.setString('name', 'Lizard');\n newRow.setString('type', 'Reptile');\n\n let rows = table.matchRows('R.*', 'type');\n for (let i = 0; i < rows.length; i++) {\n print(rows[i].getString('name') + ': ' + rows[i].getString('type'));\n }\n}\n// Sketch prints:\n// Snake: Reptile\n// Lizard: Reptile\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Table/matchRows"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/removeColumn.mdx"],"slug":[0,"en/p5table/removecolumn"],"body":[0,"\n\n# removeColumn\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"removeColumn()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Use removeColumn() to remove an existing column from a Table\nobject. The column to be removed may be identified by either\nits title (a String) or its index value (an int).\nremoveColumn(0) would remove the first column, removeColumn(1)\nwould remove the second column, and so on.
\n"],"line":[0,888],"params":[1,[[0,{"name":[0,"column"],"description":[0,"columnName (string) or ID (number)
\n"],"type":[0,"String|Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"example":[1,[[0,"\n \n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.removeColumn('id');\n print(table.getColumnCount());\n describe('no image displayed');\n }\n
\n "]]],"isConstructor":[0,false],"path":[0,"p5.Table/removeColumn"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/removeRow.mdx"],"slug":[0,"en/p5table/removerow"],"body":[0,"\n\n# removeRow\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"removeRow()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Removes a row from the table object.
\n"],"line":[0,152],"params":[1,[[0,{"name":[0,"id"],"description":[0,"ID number of the row to remove
\n"],"type":[0,"Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"example":[1,[[0,"\n\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //remove the first row\n table.removeRow(0);\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n\n describe('no image displayed');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Table/removeRow"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/removeTokens.mdx"],"slug":[0,"en/p5table/removetokens"],"body":[0,"\n\n# removeTokens\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"removeTokens()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Removes any of the specified characters (or \"tokens\").
\nIf no column is specified, then the values in all columns and\nrows are processed. A specific column may be referenced by\neither its ID or title.
\n"],"line":[0,752],"params":[1,[[0,{"name":[0,"chars"],"description":[0,"String listing characters to be removed
\n"],"type":[0,"String"]}],[0,{"name":[0,"column"],"description":[0,"Column ID (number)\n or name (string)
\n"],"type":[0,"String|Integer"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"example":[1,[[0,"\n \n function setup() {\n let table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n let newRow = table.addRow();\n newRow.setString('name', ' $Lion ,');\n newRow.setString('type', ',,,Mammal');\n\n newRow = table.addRow();\n newRow.setString('name', '$Snake ');\n newRow.setString('type', ',,,Reptile');\n\n table.removeTokens(',$ ');\n print(table.getArray());\n }\n\n // prints:\n // 0 \"Lion\" \"Mamal\"\n // 1 \"Snake\" \"Reptile\"\n
"]]],"isConstructor":[0,false],"path":[0,"p5.Table/removeTokens"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/rows.mdx"],"slug":[0,"en/p5table/rows"],"body":[0,"\n\n# rows\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"rows"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"An array containing the p5.TableRow objects that make up the\nrows of the table. The same result as calling getRows()
\n"],"line":[0,80],"itemtype":[0,"property"],"class":[0,"p5.Table"],"isConstructor":[0,false],"path":[0,"p5.Table/rows"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/set.mdx"],"slug":[0,"en/p5table/set"],"body":[0,"\n\n# set\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"set()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Stores a value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
\n"],"line":[0,950],"params":[1,[[0,{"name":[0,"row"],"description":[0,"row ID
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"column"],"description":[0,"column ID (Number)\n or title (String)
\n"],"type":[0,"String|Integer"]}],[0,{"name":[0,"value"],"description":[0,"value to assign
\n"],"type":[0,"String|Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"example":[1,[[0,"\n\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n table.set(0, 'species', 'Canis Lupus');\n table.set(0, 'name', 'Wolf');\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n\n describe('no image displayed');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Table/set"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/setNum.mdx"],"slug":[0,"en/p5table/setnum"],"body":[0,"\n\n# setNum\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"setNum()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Stores a Float value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
\n"],"line":[0,998],"params":[1,[[0,{"name":[0,"row"],"description":[0,"row ID
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"column"],"description":[0,"column ID (Number)\n or title (String)
\n"],"type":[0,"String|Integer"]}],[0,{"name":[0,"value"],"description":[0,"value to assign
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"example":[1,[[0,"\n\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n table.setNum(1, 'id', 1);\n\n print(table.getColumn(0));\n //[\"0\", 1, \"2\"]\n\n describe('no image displayed');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Table/setNum"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/setString.mdx"],"slug":[0,"en/p5table/setstring"],"body":[0,"\n\n# setString\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"setString()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Stores a String value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
\n"],"line":[0,1043],"params":[1,[[0,{"name":[0,"row"],"description":[0,"row ID
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"column"],"description":[0,"column ID (Number)\n or title (String)
\n"],"type":[0,"String|Integer"]}],[0,{"name":[0,"value"],"description":[0,"value to assign
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"example":[1,[[0,"\n\n// Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //add a row\n let newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Canis Lupus');\n newRow.setString('name', 'Wolf');\n\n print(table.getArray());\n\n describe('no image displayed');\n}\n
"]]],"isConstructor":[0,false],"path":[0,"p5.Table/setString"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/trim.mdx"],"slug":[0,"en/p5table/trim"],"body":[0,"\n\n# trim\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"trim()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Trims leading and trailing whitespace, such as spaces and tabs,\nfrom String table values. If no column is specified, then the\nvalues in all columns and rows are trimmed. A specific column\nmay be referenced by either its ID or title.
\n"],"line":[0,824],"params":[1,[[0,{"name":[0,"column"],"description":[0,"Column ID (number)\n or name (string)
\n"],"type":[0,"String|Integer"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"example":[1,[[0,"\n \n function setup() {\n let table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n let newRow = table.addRow();\n newRow.setString('name', ' Lion ,');\n newRow.setString('type', ' Mammal ');\n\n newRow = table.addRow();\n newRow.setString('name', ' Snake ');\n newRow.setString('type', ' Reptile ');\n\n table.trim();\n print(table.getArray());\n }\n\n // prints:\n // 0 \"Lion\" \"Mamal\"\n // 1 \"Snake\" \"Reptile\"\n
"]]],"isConstructor":[0,false],"path":[0,"p5.Table/trim"]}],"render":[0,null]}]]]}],[0,{"name":[0,"p5.TableRow"],"entry":[0,{"id":[0,"en/p5/p5.TableRow.mdx"],"slug":[0,"en/p5/p5tablerow"],"body":[0,"\n\n# p5.TableRow\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"p5.TableRow"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.TableRow.js"],"description":[0,"A TableRow object represents a single row of data values,\nstored in columns, from a table.
\nA Table Row contains both an ordered array, and an unordered\nJSON object.
\n"],"line":[0,9],"params":[1,[[0,{"name":[0,"str"],"description":[0,"optional: populate the row with a\n string of values, separated by the\n separator
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"separator"],"description":[0,"comma separated values (csv) by default
\n"],"type":[0,"String"],"optional":[0,true]}]]],"chainable":[0,false],"methods":[0,{"set":[0,{"description":[0,"Stores a value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n"],"path":[0,"p5.TableRow/set"]}],"setNum":[0,{"description":[0,"Stores a Float value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n"],"path":[0,"p5.TableRow/setNum"]}],"setString":[0,{"description":[0,"Stores a String value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n"],"path":[0,"p5.TableRow/setString"]}],"get":[0,{"description":[0,"Retrieves a value from the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n"],"path":[0,"p5.TableRow/get"]}],"getNum":[0,{"description":[0,"Retrieves a Float value from the TableRow's specified\ncolumn. The column may be specified by either its ID or\ntitle.
\n"],"path":[0,"p5.TableRow/getNum"]}],"getString":[0,{"description":[0,"Retrieves an String value from the TableRow's specified\ncolumn. The column may be specified by either its ID or\ntitle.
\n"],"path":[0,"p5.TableRow/getString"]}]}],"isConstructor":[0,true],"path":[0,"p5/p5.TableRow"]}],"render":[0,null]}],"entries":[1,[[0,{"id":[0,"en/p5.TableRow/get.mdx"],"slug":[0,"en/p5tablerow/get"],"body":[0,"\n\n# get\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"get()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.TableRow.js"],"description":[0,"Retrieves a value from the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n"],"line":[0,184],"params":[1,[[0,{"name":[0,"column"],"description":[0,"columnName (string) or\n ID (number)
\n"],"type":[0,"String|Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.TableRow"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"String|Number"]}],"example":[1,[[0,"\n \n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let names = [];\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n names.push(rows[r].get('name'));\n }\n\n print(names);\n\n describe('no image displayed');\n }\n
"]]],"isConstructor":[0,false],"path":[0,"p5.TableRow/get"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.TableRow/getNum.mdx"],"slug":[0,"en/p5tablerow/getnum"],"body":[0,"\n\n# getNum\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"getNum()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.TableRow.js"],"description":[0,"Retrieves a Float value from the TableRow's specified\ncolumn. The column may be specified by either its ID or\ntitle.
\n"],"line":[0,231],"params":[1,[[0,{"name":[0,"column"],"description":[0,"columnName (string) or\n ID (number)
\n"],"type":[0,"String|Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.TableRow"],"chainable":[0,false],"return":[0,{"description":[0,"Float Floating point number"],"type":[0,"Number"]}],"example":[1,[[0,"\n \n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n let minId = Infinity;\n let maxId = -Infinity;\n for (let r = 0; r < rows.length; r++) {\n let id = rows[r].getNum('id');\n minId = min(minId, id);\n maxId = min(maxId, id);\n }\n print('minimum id = ' + minId + ', maximum id = ' + maxId);\n describe('no image displayed');\n }\n
"]]],"isConstructor":[0,false],"path":[0,"p5.TableRow/getNum"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.TableRow/getString.mdx"],"slug":[0,"en/p5tablerow/getstring"],"body":[0,"\n\n# getString\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"getString()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.TableRow.js"],"description":[0,"Retrieves an String value from the TableRow's specified\ncolumn. The column may be specified by either its ID or\ntitle.
\n"],"line":[0,285],"params":[1,[[0,{"name":[0,"column"],"description":[0,"columnName (string) or\n ID (number)
\n"],"type":[0,"String|Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.TableRow"],"chainable":[0,false],"return":[0,{"description":[0,"String"],"type":[0,"String"]}],"example":[1,[[0,"\n \n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n let longest = '';\n for (let r = 0; r < rows.length; r++) {\n let species = rows[r].getString('species');\n if (longest.length < species.length) {\n longest = species;\n }\n }\n\n print('longest: ' + longest);\n\n describe('no image displayed');\n }\n
"]]],"isConstructor":[0,false],"path":[0,"p5.TableRow/getString"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.TableRow/set.mdx"],"slug":[0,"en/p5tablerow/set"],"body":[0,"\n\n# set\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"set()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.TableRow.js"],"description":[0,"Stores a value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n"],"line":[0,36],"params":[1,[[0,{"name":[0,"column"],"description":[0,"Column ID (Number)\n or Title (String)
\n"],"type":[0,"String|Integer"]}],[0,{"name":[0,"value"],"description":[0,"The value to be stored
\n"],"type":[0,"String|Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.TableRow"],"chainable":[0,false],"example":[1,[[0,"\n \n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n rows[r].set('name', 'Unicorn');\n }\n\n //print the results\n print(table.getArray());\n\n describe('no image displayed');\n }\n
"]]],"isConstructor":[0,false],"path":[0,"p5.TableRow/set"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.TableRow/setNum.mdx"],"slug":[0,"en/p5tablerow/setnum"],"body":[0,"\n\n# setNum\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"setNum()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.TableRow.js"],"description":[0,"Stores a Float value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n"],"line":[0,97],"params":[1,[[0,{"name":[0,"column"],"description":[0,"Column ID (Number)\n or Title (String)
\n"],"type":[0,"String|Integer"]}],[0,{"name":[0,"value"],"description":[0,"The value to be stored\n as a Float
\n"],"type":[0,"Number|String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.TableRow"],"chainable":[0,false],"example":[1,[[0,"\n \n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n rows[r].setNum('id', r + 10);\n }\n\n print(table.getArray());\n\n describe('no image displayed');\n }\n
"]]],"isConstructor":[0,false],"path":[0,"p5.TableRow/setNum"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.TableRow/setString.mdx"],"slug":[0,"en/p5tablerow/setstring"],"body":[0,"\n\n# setString\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"setString()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.TableRow.js"],"description":[0,"Stores a String value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n"],"line":[0,140],"params":[1,[[0,{"name":[0,"column"],"description":[0,"Column ID (Number)\n or Title (String)
\n"],"type":[0,"String|Integer"]}],[0,{"name":[0,"value"],"description":[0,"The value to be stored\n as a String
\n"],"type":[0,"String|Number|Boolean|Object"]}]]],"itemtype":[0,"method"],"class":[0,"p5.TableRow"],"chainable":[0,false],"example":[1,[[0,"\n \n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n let name = rows[r].getString('name');\n rows[r].setString('name', 'A ' + name + ' named George');\n }\n\n print(table.getArray());\n\n describe('no image displayed');\n }\n
"]]],"isConstructor":[0,false],"path":[0,"p5.TableRow/setString"]}],"render":[0,null]}]]]}],[0,{"name":[0,"p5.XML"],"entry":[0,{"id":[0,"en/p5/p5.XML.mdx"],"slug":[0,"en/p5/p5xml"],"body":[0,"\n\n# p5.XML\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"p5.XML"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/p5.XML.js"],"description":[0,"A class to describe an XML object.
\nEach p5.XML
object provides an easy way to interact with XML data.\nExtensible Markup Language\n(XML)\nis a standard format for sending data between applications. Like HTML, the\nXML format is based on tags and attributes, as in\n
.
\nNote: Use loadXML() to load external XML files.
\n"],"line":[0,9],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get an array with all mammal tags.\n let mammals = myXML.getChildren('mammal');\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Iterate over the mammals array.\n for (let i = 0; i < mammals.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 25;\n\n // Get the mammal's common name.\n let name = mammals[i].getContent();\n\n // Display the mammal's name.\n text(name, 20, y);\n }\n\n describe(\n 'The words \"Goat\", \"Leopard\", and \"Zebra\" written on three separate lines. The text is black on a gray background.'\n );\n}\n
\n"]]],"methods":[0,{"getParent":[0,{"description":[0,"Returns the element's parent element as a new p5.XML\nobject.
\n"],"path":[0,"p5.XML/getParent"]}],"getName":[0,{"description":[0,"Returns the element's name as a String
.
\nAn XML element's name is given by its tag. For example, the element\nJavaScript
has the name language
.
\n"],"path":[0,"p5.XML/getName"]}],"setName":[0,{"description":[0,"Sets the element's tag name.
\nAn XML element's name is given by its tag. For example, the element\nJavaScript
has the name language
.
\nThe parameter, name
, is the element's new name as a string. For example,\ncalling myXML.setName('planet')
will make the element's new tag name\n
.
\n"],"path":[0,"p5.XML/setName"]}],"hasChildren":[0,{"description":[0,"Returns true
if the element has child elements and false
if not.
\n"],"path":[0,"p5.XML/hasChildren"]}],"listChildren":[0,{"description":[0,"Returns an array with the names of the element's child elements as\nString
s.
\n"],"path":[0,"p5.XML/listChildren"]}],"getChildren":[0,{"description":[0,"Returns an array with the element's child elements as new\np5.XML objects.
\nThe parameter, name
, is optional. If a string is passed, as in\nmyXML.getChildren('cat')
, then the method will only return child elements\nwith the tag
.
\n"],"path":[0,"p5.XML/getChildren"]}],"getChild":[0,{"description":[0,"Returns the first matching child element as a new\np5.XML object.
\nThe parameter, name
, is optional. If a string is passed, as in\nmyXML.getChild('cat')
, then the first child element with the tag\n
will be returned. If a number is passed, as in\nmyXML.getChild(1)
, then the child element at that index will be returned.
\n"],"path":[0,"p5.XML/getChild"]}],"addChild":[0,{"description":[0,"Adds a new child element and returns a reference to it.
\nThe parameter, child
, is the p5.XML object to add\nas a child element. For example, calling myXML.addChild(otherXML)
inserts\notherXML
as a child element of myXML
.
\n"],"path":[0,"p5.XML/addChild"]}],"removeChild":[0,{"description":[0,"Removes the first matching child element.
\nThe parameter, name
, is the child element to remove. If a string is\npassed, as in myXML.removeChild('cat')
, then the first child element\nwith the tag
will be removed. If a number is passed, as in\nmyXML.removeChild(1)
, then the child element at that index will be\nremoved.
\n"],"path":[0,"p5.XML/removeChild"]}],"getAttributeCount":[0,{"description":[0,"Returns the number of attributes the element has.
\n"],"path":[0,"p5.XML/getAttributeCount"]}],"listAttributes":[0,{"description":[0,"Returns an Array
with the names of the element's attributes.
\nNote: Use\nmyXML.getString() or\nmyXML.getNum() to return an attribute's value.
\n"],"path":[0,"p5.XML/listAttributes"]}],"hasAttribute":[0,{"description":[0,"Returns true
if the element has a given attribute and false
if not.
\nThe parameter, name
, is a string with the name of the attribute being\nchecked.
\nNote: Use\nmyXML.getString() or\nmyXML.getNum() to return an attribute's value.
\n"],"path":[0,"p5.XML/hasAttribute"]}],"getNum":[0,{"description":[0,"Return an attribute's value as a Number
.
\nThe first parameter, name
, is a string with the name of the attribute\nbeing checked. For example, calling myXML.getNum('id')
returns the\nelement's id
attribute as a number.
\nThe second parameter, defaultValue
, is optional. If a number is passed,\nas in myXML.getNum('id', -1)
, it will be returned if the attribute\ndoesn't exist or can't be converted to a number.
\nNote: Use\nmyXML.getString() or\nmyXML.getNum() to return an attribute's value.
\n"],"path":[0,"p5.XML/getNum"]}],"getString":[0,{"description":[0,"Return an attribute's value as a string.
\nThe first parameter, name
, is a string with the name of the attribute\nbeing checked. For example, calling myXML.getString('color')
returns the\nelement's id
attribute as a string.
\nThe second parameter, defaultValue
, is optional. If a string is passed,\nas in myXML.getString('color', 'deeppink')
, it will be returned if the\nattribute doesn't exist.
\nNote: Use\nmyXML.getString() or\nmyXML.getNum() to return an attribute's value.
\n"],"path":[0,"p5.XML/getString"]}],"setAttribute":[0,{"description":[0,"Sets an attribute to a given value.
\nThe first parameter, name
, is a string with the name of the attribute\nbeing set.
\nThe second parameter, value
, is the attribute's new value. For example,\ncalling myXML.setAttribute('id', 123)
sets the id
attribute to the\nvalue 123.
\n"],"path":[0,"p5.XML/setAttribute"]}],"getContent":[0,{"description":[0,"Returns the element's content as a String
.
\nThe parameter, defaultValue
, is optional. If a string is passed, as in\nmyXML.getContent('???')
, it will be returned if the element has no\ncontent.
\n"],"path":[0,"p5.XML/getContent"]}],"setContent":[0,{"description":[0,"Sets the element's content.
\nAn element's content is the text between its tags. For example, the element\nJavaScript
has the content JavaScript
.
\nThe parameter, content
, is a string with the element's new content.
\n"],"path":[0,"p5.XML/setContent"]}],"serialize":[0,{"description":[0,"Returns the element as a String
.
\nmyXML.serialize()
is useful for sending the element over the network or\nsaving it to a file.
\n"],"path":[0,"p5.XML/serialize"]}]}],"isConstructor":[0,true],"path":[0,"p5/p5.XML"]}],"render":[0,null]}],"entries":[1,[[0,{"id":[0,"en/p5.XML/addChild.mdx"],"slug":[0,"en/p5xml/addchild"],"body":[0,"\n\n# addChild\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"addChild()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/p5.XML.js"],"description":[0,"Adds a new child element and returns a reference to it.
\nThe parameter, child
, is the p5.XML object to add\nas a child element. For example, calling myXML.addChild(otherXML)
inserts\notherXML
as a child element of myXML
.
\n"],"line":[0,538],"params":[1,[[0,{"name":[0,"child"],"description":[0,"child element to add.
\n"],"type":[0,"p5.XML"]}]]],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"added child element."],"type":[0,"p5.XML"]}],"example":[1,[[0,"\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a new p5.XML object.\n let newAnimal = new p5.XML();\n\n // Set its properties.\n newAnimal.setName('hydrozoa');\n newAnimal.setAttribute('id', 4);\n newAnimal.setAttribute('species', 'Physalia physalis');\n newAnimal.setContent('Bluebottle');\n\n // Add the child element.\n myXML.addChild(newAnimal);\n\n // Get the first child element that is a hydrozoa.\n let blueBottle = myXML.getChild('hydrozoa');\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Get the child element's content.\n let content = blueBottle.getContent();\n\n // Display the child element's content.\n text(content, 50, 50);\n\n describe('The word \"Bluebottle\" written in black on a gray background.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.XML/addChild"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.XML/getAttributeCount.mdx"],"slug":[0,"en/p5xml/getattributecount"],"body":[0,"\n\n# getAttributeCount\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"getAttributeCount()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/p5.XML.js"],"description":[0,"Returns the number of attributes the element has.
\n"],"line":[0,723],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"number of attributes."],"type":[0,"Integer"]}],"example":[1,[[0,"\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the first child element.\n let first = myXML.getChild(0);\n\n // Get the number of attributes.\n let numAttributes = first.getAttributeCount();\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the number of attributes.\n text(numAttributes, 50, 50);\n\n describe('The number \"2\" written in black on a gray background.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.XML/getAttributeCount"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.XML/getChild.mdx"],"slug":[0,"en/p5xml/getchild"],"body":[0,"\n\n# getChild\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"getChild()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/p5.XML.js"],"description":[0,"Returns the first matching child element as a new\np5.XML object.
\nThe parameter, name
, is optional. If a string is passed, as in\nmyXML.getChild('cat')
, then the first child element with the tag\n
will be returned. If a number is passed, as in\nmyXML.getChild(1)
, then the child element at that index will be returned.
\n"],"line":[0,448],"params":[1,[[0,{"name":[0,"name"],"description":[0,"element name or index.
\n"],"type":[0,"String|Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"child element."],"type":[0,"p5.XML"]}],"example":[1,[[0,"\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the first child element that is a mammal.\n let goat = myXML.getChild('mammal');\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Get the child element's content.\n let content = goat.getContent();\n\n // Display the child element's content.\n text(content, 50, 50);\n\n describe('The word \"Goat\" written in black on a gray background.');\n}\n
\n\n\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the child element at index 1.\n let leopard = myXML.getChild(1);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Get the child element's content.\n let content = leopard.getContent();\n\n // Display the child element's content.\n text(content, 50, 50);\n\n describe('The word \"Leopard\" written in black on a gray background.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.XML/getChild"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.XML/getChildren.mdx"],"slug":[0,"en/p5xml/getchildren"],"body":[0,"\n\n# getChildren\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"getChildren()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/p5.XML.js"],"description":[0,"Returns an array with the element's child elements as new\np5.XML objects.
\nThe parameter, name
, is optional. If a string is passed, as in\nmyXML.getChildren('cat')
, then the method will only return child elements\nwith the tag
.
\n"],"line":[0,342],"params":[1,[[0,{"name":[0,"name"],"description":[0,"name of the elements to return.
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"child elements."],"type":[0,"p5.XML[]"]}],"example":[1,[[0,"\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get an array of the child elements.\n let children = myXML.getChildren();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Iterate over the array.\n for (let i = 0; i < children.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 20;\n\n // Get the child element's content.\n let content = children[i].getContent();\n\n // Display the child element's content.\n text(content, 10, y);\n }\n\n describe(\n 'The words \"Goat\", \"Leopard\", \"Zebra\", and \"Turtle\" written on separate lines. The text is black on a gray background.'\n );\n}\n
\n\n\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get an array of the child elements\n // that are mammals.\n let children = myXML.getChildren('mammal');\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Iterate over the array.\n for (let i = 0; i < children.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 20;\n\n // Get the child element's content.\n let content = children[i].getContent();\n\n // Display the child element's content.\n text(content, 10, y);\n }\n\n describe(\n 'The words \"Goat\", \"Leopard\", and \"Zebra\" written on separate lines. The text is black on a gray background.'\n );\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.XML/getChildren"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.XML/getContent.mdx"],"slug":[0,"en/p5xml/getcontent"],"body":[0,"\n\n# getContent\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"getContent()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/p5.XML.js"],"description":[0,"Returns the element's content as a String
.
\nThe parameter, defaultValue
, is optional. If a string is passed, as in\nmyXML.getContent('???')
, it will be returned if the element has no\ncontent.
\n"],"line":[0,1153],"params":[1,[[0,{"name":[0,"defaultValue"],"description":[0,"value to return if the element has no\n content.
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"element's content as a string."],"type":[0,"String"]}],"example":[1,[[0,"\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the first reptile child element.\n let reptile = myXML.getChild('reptile');\n\n // Get the reptile's content.\n let content = reptile.getContent();\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the element's content.\n text(content, 5, 50, 90);\n\n describe(`The text \"${content}\" written in green on a gray background.`);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.XML object.\n let blankSpace = new p5.XML();\n\n // Get the element's content and use a default value.\n let content = blankSpace.getContent('Your name');\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the element's content.\n text(content, 5, 50, 90);\n\n describe(`The text \"${content}\" written in green on a gray background.`);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.XML/getContent"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.XML/getName.mdx"],"slug":[0,"en/p5xml/getname"],"body":[0,"\n\n# getName\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"getName()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/p5.XML.js"],"description":[0,"Returns the element's name as a String
.
\nAn XML element's name is given by its tag. For example, the element\nJavaScript
has the name language
.
\n"],"line":[0,128],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"name of the element."],"type":[0,"String"]}],"example":[1,[[0,"\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get an array with all mammal elements.\n let mammals = myXML.getChildren('mammal');\n\n // Get the first mammal element.\n let firstMammal = mammals[0];\n\n // Get the mammal element's name.\n let name = firstMammal.getName();\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the element's name.\n text(name, 50, 50);\n\n describe('The word \"mammal\" written in black on a gray background.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.XML/getName"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.XML/getNum.mdx"],"slug":[0,"en/p5xml/getnum"],"body":[0,"\n\n# getNum\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"getNum()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/p5.XML.js"],"description":[0,"Return an attribute's value as a Number
.
\nThe first parameter, name
, is a string with the name of the attribute\nbeing checked. For example, calling myXML.getNum('id')
returns the\nelement's id
attribute as a number.
\nThe second parameter, defaultValue
, is optional. If a number is passed,\nas in myXML.getNum('id', -1)
, it will be returned if the attribute\ndoesn't exist or can't be converted to a number.
\nNote: Use\nmyXML.getString() or\nmyXML.getNum() to return an attribute's value.
\n"],"line":[0,884],"params":[1,[[0,{"name":[0,"name"],"description":[0,"name of the attribute to be checked.
\n"],"type":[0,"String"]}],[0,{"name":[0,"defaultValue"],"description":[0,"value to return if the attribute doesn't exist.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"attribute value as a number."],"type":[0,"Number"]}],"example":[1,[[0,"\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the first reptile child element.\n let reptile = myXML.getChild('reptile');\n\n // Get the reptile's content.\n let content = reptile.getContent();\n\n // Get the reptile's ID.\n let id = reptile.getNum('id');\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the ID attribute.\n text(`${content} is ${id + 1}th`, 5, 50, 90);\n\n describe(`The text \"${content} is ${id + 1}th\" written in black on a gray background.`);\n}\n
\n\n\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the first reptile child element.\n let reptile = myXML.getChild('reptile');\n\n // Get the reptile's content.\n let content = reptile.getContent();\n\n // Get the reptile's size.\n let weight = reptile.getNum('weight', 135);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the ID attribute.\n text(`${content} is ${weight}kg`, 5, 50, 90);\n\n describe(\n `The text \"${content} is ${weight}kg\" written in black on a gray background.`\n );\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.XML/getNum"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.XML/getParent.mdx"],"slug":[0,"en/p5xml/getparent"],"body":[0,"\n\n# getParent\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"getParent()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/p5.XML.js"],"description":[0,"Returns the element's parent element as a new p5.XML\nobject.
\n"],"line":[0,77],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"parent element."],"type":[0,"p5.XML"]}],"example":[1,[[0,"\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get an array with all mammal elements.\n let mammals = myXML.getChildren('mammal');\n\n // Get the first mammal element.\n let firstMammal = mammals[0];\n\n // Get the parent element.\n let parent = firstMammal.getParent();\n\n // Get the parent element's name.\n let name = parent.getName();\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the parent element's name.\n text(name, 50, 50);\n\n describe('The word \"animals\" written in black on a gray background.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.XML/getParent"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.XML/getString.mdx"],"slug":[0,"en/p5xml/getstring"],"body":[0,"\n\n# getString\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"getString()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/p5.XML.js"],"description":[0,"Return an attribute's value as a string.
\nThe first parameter, name
, is a string with the name of the attribute\nbeing checked. For example, calling myXML.getString('color')
returns the\nelement's id
attribute as a string.
\nThe second parameter, defaultValue
, is optional. If a string is passed,\nas in myXML.getString('color', 'deeppink')
, it will be returned if the\nattribute doesn't exist.
\nNote: Use\nmyXML.getString() or\nmyXML.getNum() to return an attribute's value.
\n"],"line":[0,989],"params":[1,[[0,{"name":[0,"name"],"description":[0,"name of the attribute to be checked.
\n"],"type":[0,"String"]}],[0,{"name":[0,"defaultValue"],"description":[0,"value to return if the attribute doesn't exist.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"attribute value as a string."],"type":[0,"String"]}],"example":[1,[[0,"\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the first reptile child element.\n let reptile = myXML.getChild('reptile');\n\n // Get the reptile's content.\n let content = reptile.getContent();\n\n // Get the reptile's species.\n let species = reptile.getString('species');\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the species attribute.\n text(`${content}: ${species}`, 5, 50, 90);\n\n describe(`The text \"${content}: ${species}\" written in black on a gray background.`);\n}\n
\n\n\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the first reptile child element.\n let reptile = myXML.getChild('reptile');\n\n // Get the reptile's content.\n let content = reptile.getContent();\n\n // Get the reptile's color.\n let attribute = reptile.getString('color', 'green');\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n fill(attribute);\n\n // Display the element's content.\n text(content, 50, 50);\n\n describe(`The text \"${content}\" written in green on a gray background.`);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.XML/getString"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.XML/hasAttribute.mdx"],"slug":[0,"en/p5xml/hasattribute"],"body":[0,"\n\n# hasAttribute\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"hasAttribute()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/p5.XML.js"],"description":[0,"Returns true
if the element has a given attribute and false
if not.
\nThe parameter, name
, is a string with the name of the attribute being\nchecked.
\nNote: Use\nmyXML.getString() or\nmyXML.getNum() to return an attribute's value.
\n"],"line":[0,821],"params":[1,[[0,{"name":[0,"name"],"description":[0,"name of the attribute to be checked.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"whether the element has the attribute."],"type":[0,"Boolean"]}],"example":[1,[[0,"\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the first mammal child element.\n let mammal = myXML.getChild('mammal');\n\n // Check whether the element has an\n // species attribute.\n let hasSpecies = mammal.hasAttribute('species');\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display whether the element has a species attribute.\n if (hasSpecies === true) {\n text('Species', 50, 50);\n } else {\n text('No species', 50, 50);\n }\n\n describe('The text \"Species\" written in black on a gray background.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.XML/hasAttribute"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.XML/hasChildren.mdx"],"slug":[0,"en/p5xml/haschildren"],"body":[0,"\n\n# hasChildren\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"hasChildren()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/p5.XML.js"],"description":[0,"Returns true
if the element has child elements and false
if not.
\n"],"line":[0,242],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"whether the element has children."],"type":[0,"Boolean"]}],"example":[1,[[0,"\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Check whether the element has child elements.\n let isParent = myXML.hasChildren();\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Style the text.\n if (isParent === true) {\n text('Parent', 50, 50);\n } else {\n text('Not Parent', 50, 50);\n }\n\n describe('The word \"Parent\" written in black on a gray background.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.XML/hasChildren"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.XML/listAttributes.mdx"],"slug":[0,"en/p5xml/listattributes"],"body":[0,"\n\n# listAttributes\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"listAttributes()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/p5.XML.js"],"description":[0,"Returns an Array
with the names of the element's attributes.
\nNote: Use\nmyXML.getString() or\nmyXML.getNum() to return an attribute's value.
\n"],"line":[0,767],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"attribute names."],"type":[0,"String[]"]}],"example":[1,[[0,"\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the first child element.\n let first = myXML.getChild(0);\n\n // Get the number of attributes.\n let attributes = first.listAttributes();\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the element's attributes.\n text(attributes, 50, 50);\n\n describe('The text \"id,species\" written in black on a gray background.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.XML/listAttributes"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.XML/listChildren.mdx"],"slug":[0,"en/p5xml/listchildren"],"body":[0,"\n\n# listChildren\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"listChildren()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/p5.XML.js"],"description":[0,"Returns an array with the names of the element's child elements as\nString
s.
\n"],"line":[0,287],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"names of the child elements."],"type":[0,"String[]"]}],"example":[1,[[0,"\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the names of the element's children as an array.\n let children = myXML.listChildren();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Iterate over the array.\n for (let i = 0; i < children.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 25;\n\n // Display the child element's name.\n text(children[i], 10, y);\n }\n\n describe(\n 'The words \"mammal\", \"mammal\", \"mammal\", and \"reptile\" written on separate lines. The text is black on a gray background.'\n );\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.XML/listChildren"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.XML/removeChild.mdx"],"slug":[0,"en/p5xml/removechild"],"body":[0,"\n\n# removeChild\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"removeChild()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/p5.XML.js"],"description":[0,"Removes the first matching child element.
\nThe parameter, name
, is the child element to remove. If a string is\npassed, as in myXML.removeChild('cat')
, then the first child element\nwith the tag
will be removed. If a number is passed, as in\nmyXML.removeChild(1)
, then the child element at that index will be\nremoved.
\n"],"line":[0,603],"params":[1,[[0,{"name":[0,"name"],"description":[0,"name or index of the child element to remove.
\n"],"type":[0,"String|Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Remove the first mammal element.\n myXML.removeChild('mammal');\n\n // Get an array of child elements.\n let children = myXML.getChildren();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Iterate over the array.\n for (let i = 0; i < children.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 25;\n\n // Get the child element's content.\n let content = children[i].getContent();\n\n // Display the child element's content.\n text(content, 10, y);\n }\n\n describe(\n 'The words \"Leopard\", \"Zebra\", and \"Turtle\" written on separate lines. The text is black on a gray background.'\n );\n}\n
\n\n\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Remove the element at index 2.\n myXML.removeChild(2);\n\n // Get an array of child elements.\n let children = myXML.getChildren();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Iterate over the array.\n for (let i = 0; i < children.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 25;\n\n // Get the child element's content.\n let content = children[i].getContent();\n\n // Display the child element's content.\n text(content, 10, y);\n }\n\n describe(\n 'The words \"Goat\", \"Leopard\", and \"Turtle\" written on separate lines. The text is black on a gray background.'\n );\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.XML/removeChild"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.XML/serialize.mdx"],"slug":[0,"en/p5xml/serialize"],"body":[0,"\n\n# serialize\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"serialize()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/p5.XML.js"],"description":[0,"Returns the element as a String
.
\nmyXML.serialize()
is useful for sending the element over the network or\nsaving it to a file.
\n"],"line":[0,1291],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"element as a string."],"type":[0,"String"]}],"example":[1,[[0,"\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display instructions.\n text('Double-click to save', 5, 50, 90);\n\n describe('The text \"Double-click to save\" written in black on a gray background.');\n}\n\n// Save the file when the user double-clicks.\nfunction doubleClicked() {\n // Create a p5.PrintWriter object.\n // Use the file format .xml.\n let myWriter = createWriter('animals', 'xml');\n\n // Serialize the XML data to a string.\n let data = myXML.serialize();\n\n // Write the data to the print stream.\n myWriter.write(data);\n\n // Save the file and close the print stream.\n myWriter.close();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.XML/serialize"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.XML/setAttribute.mdx"],"slug":[0,"en/p5xml/setattribute"],"body":[0,"\n\n# setAttribute\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"setAttribute()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/p5.XML.js"],"description":[0,"Sets an attribute to a given value.
\nThe first parameter, name
, is a string with the name of the attribute\nbeing set.
\nThe second parameter, value
, is the attribute's new value. For example,\ncalling myXML.setAttribute('id', 123)
sets the id
attribute to the\nvalue 123.
\n"],"line":[0,1093],"params":[1,[[0,{"name":[0,"name"],"description":[0,"name of the attribute to be set.
\n"],"type":[0,"String"]}],[0,{"name":[0,"value"],"description":[0,"attribute's new value.
\n"],"type":[0,"Number|String|Boolean"]}]]],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the first reptile child element.\n let reptile = myXML.getChild('reptile');\n\n // Set the reptile's color.\n reptile.setAttribute('color', 'green');\n\n // Get the reptile's content.\n let content = reptile.getContent();\n\n // Get the reptile's color.\n let attribute = reptile.getString('color');\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the element's content.\n text(`${content} is ${attribute}`, 5, 50, 90);\n\n describe(\n `The text \"${content} is ${attribute}\" written in green on a gray background.`\n );\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.XML/setAttribute"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.XML/setContent.mdx"],"slug":[0,"en/p5xml/setcontent"],"body":[0,"\n\n# setContent\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"setContent()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/p5.XML.js"],"description":[0,"Sets the element's content.
\nAn element's content is the text between its tags. For example, the element\nJavaScript
has the content JavaScript
.
\nThe parameter, content
, is a string with the element's new content.
\n"],"line":[0,1232],"params":[1,[[0,{"name":[0,"content"],"description":[0,"new content for the element.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the first reptile child element.\n let reptile = myXML.getChild('reptile');\n\n // Get the reptile's original content.\n let oldContent = reptile.getContent();\n\n // Set the reptile's content.\n reptile.setContent('Loggerhead');\n\n // Get the reptile's new content.\n let newContent = reptile.getContent();\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the element's old and new content.\n text(`${oldContent}: ${newContent}`, 5, 50, 90);\n\n describe(\n `The text \"${oldContent}: ${newContent}\" written in green on a gray background.`\n );\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.XML/setContent"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.XML/setName.mdx"],"slug":[0,"en/p5xml/setname"],"body":[0,"\n\n# setName\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"setName()"],"module":[0,"IO"],"submodule":[0,"Input"],"file":[0,"src/io/p5.XML.js"],"description":[0,"Sets the element's tag name.
\nAn XML element's name is given by its tag. For example, the element\nJavaScript
has the name language
.
\nThe parameter, name
, is the element's new name as a string. For example,\ncalling myXML.setName('planet')
will make the element's new tag name\n
.
\n"],"line":[0,178],"params":[1,[[0,{"name":[0,"name"],"description":[0,"new tag name of the element.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the element's original name.\n let oldName = myXML.getName();\n\n // Set the element's name.\n myXML.setName('monsters');\n\n // Get the element's new name.\n let newName = myXML.getName();\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the element's names.\n text(oldName, 50, 33);\n text(newName, 50, 67);\n\n describe(\n 'The words \"animals\" and \"monsters\" written on separate lines. The text is black on a gray background.'\n );\n}\n
"]]],"isConstructor":[0,false],"path":[0,"p5.XML/setName"]}],"render":[0,null]}]]]}]]]}],[0,{"name":[0,"Events"],"subcats":[1,[[0,{"name":[0],"entry":[0],"entries":[1,[]]}],[0,{"name":[0,"Acceleration"],"entry":[0],"entries":[1,[[0,{"id":[0,"en/p5/accelerationX.mdx"],"slug":[0,"en/p5/accelerationx"],"body":[0,"\n\n# accelerationX\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"accelerationX"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"The system variable accelerationX always contains the acceleration of the\ndevice along the x axis. Value is represented as meters per second squared.
\n"],"line":[0,23],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\n// Move a touchscreen device to register\n// acceleration changes.\nfunction draw() {\n background(220, 50);\n fill('magenta');\n ellipse(width / 2, height / 2, accelerationX);\n describe('Magnitude of device acceleration is displayed as ellipse size.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/accelerationX"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/accelerationY.mdx"],"slug":[0,"en/p5/accelerationy"],"body":[0,"\n\n# accelerationY\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"accelerationY"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"The system variable accelerationY always contains the acceleration of the\ndevice along the y axis. Value is represented as meters per second squared.
\n"],"line":[0,45],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\n// Move a touchscreen device to register\n// acceleration changes.\nfunction draw() {\n background(220, 50);\n fill('magenta');\n ellipse(width / 2, height / 2, accelerationY);\n describe('Magnitude of device acceleration is displayed as ellipse size');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/accelerationY"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/accelerationZ.mdx"],"slug":[0,"en/p5/accelerationz"],"body":[0,"\n\n# accelerationZ\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"accelerationZ"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"The system variable accelerationZ always contains the acceleration of the\ndevice along the z axis. Value is represented as meters per second squared.
\n"],"line":[0,67],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\n// Move a touchscreen device to register\n// acceleration changes.\nfunction draw() {\n background(220, 50);\n fill('magenta');\n ellipse(width / 2, height / 2, accelerationZ);\n describe('Magnitude of device acceleration is displayed as ellipse size');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/accelerationZ"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/deviceMoved.mdx"],"slug":[0,"en/p5/devicemoved"],"body":[0,"\n\n# deviceMoved\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"deviceMoved()"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"The deviceMoved() function is called when the device is moved by more than\nthe threshold value along X, Y or Z axis. The default threshold is set to 0.5.\nThe threshold value can be changed using setMoveThreshold().
\n"],"line":[0,501],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\n// Run this example on a mobile device\n// Move the device around\n// to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when device moves`);\n}\nfunction deviceMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/deviceMoved"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/deviceOrientation.mdx"],"slug":[0,"en/p5/deviceorientation"],"body":[0,"\n\n# deviceOrientation\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"deviceOrientation"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"The system variable deviceOrientation always contains the orientation of\nthe device. The value of this variable will either be set 'landscape'\nor 'portrait'. If no data is available it will be set to 'undefined'.\neither LANDSCAPE or PORTRAIT.
\n"],"line":[0,11],"itemtype":[0,"property"],"class":[0,"p5"],"isConstructor":[0,false],"path":[0,"p5/deviceOrientation"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/deviceShaken.mdx"],"slug":[0,"en/p5/deviceshaken"],"body":[0,"\n\n# deviceShaken\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"deviceShaken()"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"The deviceShaken() function is called when the device total acceleration\nchanges of accelerationX and accelerationY values is more than\nthe threshold value. The default threshold is set to 30.\nThe threshold value can be changed using setShakeThreshold().
\n"],"line":[0,589],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\n// Run this example on a mobile device\n// Shake the device to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when device shakes`);\n}\nfunction deviceShaken() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/deviceShaken"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/deviceTurned.mdx"],"slug":[0,"en/p5/deviceturned"],"body":[0,"\n\n# deviceTurned\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"deviceTurned()"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"The deviceTurned() function is called when the device rotates by\nmore than 90 degrees continuously.
\nThe axis that triggers the deviceTurned() method is stored in the turnAxis\nvariable. The deviceTurned() method can be locked to trigger on any axis:\nX, Y or Z by comparing the turnAxis variable to 'X', 'Y' or 'Z'.
\n"],"line":[0,531],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees\n// to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when device turns`);\n}\nfunction deviceTurned() {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n}\n
\n\n\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees in the\n// X-axis to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when x-axis turns`);\n}\nfunction deviceTurned() {\n if (turnAxis === 'X') {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/deviceTurned"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/pAccelerationX.mdx"],"slug":[0,"en/p5/paccelerationx"],"body":[0,"\n\n# pAccelerationX\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"pAccelerationX"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"The system variable pAccelerationX always contains the acceleration of the\ndevice along the x axis in the frame previous to the current frame. Value\nis represented as meters per second squared.
\n"],"line":[0,90],"itemtype":[0,"property"],"class":[0,"p5"],"isConstructor":[0,false],"path":[0,"p5/pAccelerationX"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/pAccelerationY.mdx"],"slug":[0,"en/p5/paccelerationy"],"body":[0,"\n\n# pAccelerationY\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"pAccelerationY"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"The system variable pAccelerationY always contains the acceleration of the\ndevice along the y axis in the frame previous to the current frame. Value\nis represented as meters per second squared.
\n"],"line":[0,100],"itemtype":[0,"property"],"class":[0,"p5"],"isConstructor":[0,false],"path":[0,"p5/pAccelerationY"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/pAccelerationZ.mdx"],"slug":[0,"en/p5/paccelerationz"],"body":[0,"\n\n# pAccelerationZ\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"pAccelerationZ"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"The system variable pAccelerationZ always contains the acceleration of the\ndevice along the z axis in the frame previous to the current frame. Value\nis represented as meters per second squared.
\n"],"line":[0,110],"itemtype":[0,"property"],"class":[0,"p5"],"isConstructor":[0,false],"path":[0,"p5/pAccelerationZ"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/pRotationX.mdx"],"slug":[0,"en/p5/protationx"],"body":[0,"\n\n# pRotationX\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"pRotationX"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"The system variable pRotationX always contains the rotation of the\ndevice along the x axis in the frame previous to the current frame.\nIf the sketch angleMode() is set to DEGREES,\nthe value will be -180 to 180. If it is set to RADIANS, the value will\nbe -PI to PI.
\npRotationX can also be used with rotationX to determine the rotate\ndirection of the device along the X-axis.
\n"],"line":[0,234],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\n// A simple if statement looking at whether\n// rotationX - pRotationX < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nlet rotateDirection = 'clockwise';\n\n// Simple range conversion to make things simpler.\n// This is not absolutely necessary but the logic\n// will be different in that case.\n\nlet rX = rotationX + 180;\nlet pRX = pRotationX + 180;\n\nif ((rX - pRX > 0 && rX - pRX < 270) || rX - pRX < -270) {\n rotateDirection = 'clockwise';\n} else if (rX - pRX < 0 || rX - pRX > 270) {\n rotateDirection = 'counter-clockwise';\n}\n\nprint(rotateDirection);\ndescribe('no image to display.');\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/pRotationX"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/pRotationY.mdx"],"slug":[0,"en/p5/protationy"],"body":[0,"\n\n# pRotationY\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"pRotationY"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"The system variable pRotationY always contains the rotation of the\ndevice along the y axis in the frame previous to the current frame.\nIf the sketch angleMode() is set to DEGREES,\nthe value will be -90 to 90. If it is set to RADIANS, the value will\nbe -PI/2 to PI/2.
\npRotationY can also be used with rotationY to determine the rotate\ndirection of the device along the Y-axis.
\n"],"line":[0,278],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\n// A simple if statement looking at whether\n// rotationY - pRotationY < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nlet rotateDirection = 'clockwise';\n\n// Simple range conversion to make things simpler.\n// This is not absolutely necessary but the logic\n// will be different in that case.\n\nlet rY = rotationY + 180;\nlet pRY = pRotationY + 180;\n\nif ((rY - pRY > 0 && rY - pRY < 270) || rY - pRY < -270) {\n rotateDirection = 'clockwise';\n} else if (rY - pRY < 0 || rY - pRY > 270) {\n rotateDirection = 'counter-clockwise';\n}\nprint(rotateDirection);\ndescribe('no image to display.');\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/pRotationY"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/pRotationZ.mdx"],"slug":[0,"en/p5/protationz"],"body":[0,"\n\n# pRotationZ\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"pRotationZ"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"The system variable pRotationZ always contains the rotation of the\ndevice along the z axis in the frame previous to the current frame.\nIf the sketch angleMode() is set to DEGREES,\nthe value will be 0 to 360. If it is set to RADIANS, the value will\nbe 0 to 2*PI.
\npRotationZ can also be used with rotationZ to determine the rotate\ndirection of the device along the Z-axis.
\n"],"line":[0,321],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\n// A simple if statement looking at whether\n// rotationZ - pRotationZ < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nlet rotateDirection = 'clockwise';\n\nif (\n (rotationZ - pRotationZ > 0 && rotationZ - pRotationZ < 270) ||\n rotationZ - pRotationZ < -270\n) {\n rotateDirection = 'clockwise';\n} else if (rotationZ - pRotationZ < 0 || rotationZ - pRotationZ > 270) {\n rotateDirection = 'counter-clockwise';\n}\nprint(rotateDirection);\ndescribe('no image to display.');\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/pRotationZ"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/rotationX.mdx"],"slug":[0,"en/p5/rotationx"],"body":[0,"\n\n# rotationX\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"rotationX"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"The system variable rotationX always contains the rotation of the\ndevice along the x axis. If the sketch \nangleMode() is set to DEGREES, the value will be -180 to 180. If\nit is set to RADIANS, the value will be -PI to PI.
\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.
\n"],"line":[0,131],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n //rotateZ(radians(rotationZ));\n rotateX(radians(rotationX));\n //rotateY(radians(rotationY));\n box(200, 200, 200);\n describe(`red horizontal line right, green vertical line bottom.\n black background.`);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/rotationX"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/rotationY.mdx"],"slug":[0,"en/p5/rotationy"],"body":[0,"\n\n# rotationY\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"rotationY"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"The system variable rotationY always contains the rotation of the\ndevice along the y axis. If the sketch \nangleMode() is set to DEGREES, the value will be -90 to 90. If\nit is set to RADIANS, the value will be -PI/2 to PI/2.
\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.
\n"],"line":[0,164],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n //rotateZ(radians(rotationZ));\n //rotateX(radians(rotationX));\n rotateY(radians(rotationY));\n box(200, 200, 200);\n describe(`red horizontal line right, green vertical line bottom.\n black background.`);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/rotationY"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/rotationZ.mdx"],"slug":[0,"en/p5/rotationz"],"body":[0,"\n\n# rotationZ\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"rotationZ"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"The system variable rotationZ always contains the rotation of the\ndevice along the z axis. If the sketch \nangleMode() is set to DEGREES, the value will be 0 to 360. If\nit is set to RADIANS, the value will be 0 to 2*PI.
\nUnlike rotationX and rotationY, this variable is available for devices\nwith a built-in compass only.
\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.
\n"],"line":[0,197],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateZ(radians(rotationZ));\n //rotateX(radians(rotationX));\n //rotateY(radians(rotationY));\n box(200, 200, 200);\n describe(`red horizontal line right, green vertical line bottom.\n black background.`);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/rotationZ"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/setMoveThreshold.mdx"],"slug":[0,"en/p5/setmovethreshold"],"body":[0,"\n\n# setMoveThreshold\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"setMoveThreshold()"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"The setMoveThreshold() function is used to set the movement threshold for\nthe deviceMoved() function. The default threshold is set to 0.5.
\n"],"line":[0,417],"params":[1,[[0,{"name":[0,"value"],"description":[0,"The threshold value
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\n// Run this example on a mobile device\n// You will need to move the device incrementally further\n// the closer the square's color gets to white in order to change the value.\n\nlet value = 0;\nlet threshold = 0.5;\nfunction setup() {\n setMoveThreshold(threshold);\n}\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when device moves`);\n}\nfunction deviceMoved() {\n value = value + 5;\n threshold = threshold + 0.1;\n if (value > 255) {\n value = 0;\n threshold = 30;\n }\n setMoveThreshold(threshold);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/setMoveThreshold"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/setShakeThreshold.mdx"],"slug":[0,"en/p5/setshakethreshold"],"body":[0,"\n\n# setShakeThreshold\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"setShakeThreshold()"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"The setShakeThreshold() function is used to set the movement threshold for\nthe deviceShaken() function. The default threshold is set to 30.
\n"],"line":[0,459],"params":[1,[[0,{"name":[0,"value"],"description":[0,"The threshold value
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\n// Run this example on a mobile device\n// You will need to shake the device more firmly\n// the closer the box's fill gets to white in order to change the value.\n\nlet value = 0;\nlet threshold = 30;\nfunction setup() {\n setShakeThreshold(threshold);\n}\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when device is being shaked`);\n}\nfunction deviceMoved() {\n value = value + 5;\n threshold = threshold + 5;\n if (value > 255) {\n value = 0;\n threshold = 30;\n }\n setShakeThreshold(threshold);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/setShakeThreshold"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/turnAxis.mdx"],"slug":[0,"en/p5/turnaxis"],"body":[0,"\n\n# turnAxis\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"turnAxis"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"When a device is rotated, the axis that triggers the deviceTurned()\nmethod is stored in the turnAxis variable. The turnAxis variable is only defined within\nthe scope of deviceTurned().
\n"],"line":[0,378],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees in the\n// X-axis to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when device turns`);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when x-axis turns`);\n}\nfunction deviceTurned() {\n if (turnAxis === 'X') {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/turnAxis"]}],"render":[0,null]}]]]}],[0,{"name":[0,"Keyboard"],"entry":[0],"entries":[1,[[0,{"id":[0,"en/p5/key.mdx"],"slug":[0,"en/p5/key"],"body":[0,"\n\n# key\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"key"],"module":[0,"Events"],"submodule":[0,"Keyboard"],"file":[0,"src/events/keyboard.js"],"description":[0,"A String
system variable that contains the value of the last key typed.
\nThe key variable is helpful for checking whether an\nASCII\nkey has been typed. For example, the expression key === \"a\"
evaluates to\ntrue
if the a
key was typed and false
if not. key
doesn’t update\nfor special keys such as LEFT_ARROW
and ENTER
. Use keyCode instead for\nspecial keys. The keyIsDown() function should\nbe used to check for multiple different key presses at the same time.
\n"],"line":[0,102],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\n// Click on the canvas to begin detecting key presses.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. The last key pressed is displayed at the center.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the last key pressed.\n text(key, 50, 50);\n}\n
\n\n\n\n\n// Click on the canvas to begin detecting key presses.\n\nlet x = 50;\nlet y = 50;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n // Update x and y if a key is pressed.\n if (keyIsPressed === true) {\n if (key === 'w') {\n y -= 1;\n } else if (key === 's') {\n y += 1;\n } else if (key === 'a') {\n x -= 1;\n } else if (key === 'd') {\n x += 1;\n }\n }\n\n // Style the circle.\n fill(0);\n\n // Draw the circle at (x, y).\n circle(x, y, 5);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/key"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/keyCode.mdx"],"slug":[0,"en/p5/keycode"],"body":[0,"\n\n# keyCode\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"keyCode"],"module":[0,"Events"],"submodule":[0,"Keyboard"],"file":[0,"src/events/keyboard.js"],"description":[0,"A Number
system variable that contains the code of the last key typed.
\nAll keys have a keyCode
. For example, the a
key has the keyCode
65.\nThe keyCode
variable is helpful for checking whether a special key has\nbeen typed. For example, the following conditional checks whether the enter\nkey has been typed:
\nif (keyCode === 13) {\n // Code to run if the enter key was pressed.\n}\n
\nThe same code can be written more clearly using the system variable ENTER
\nwhich has a value of 13:
\nif (keyCode === ENTER) {\n // Code to run if the enter key was pressed.\n}\n
\nThe system variables BACKSPACE
, DELETE
, ENTER
, RETURN
, TAB
,\nESCAPE
, SHIFT
, CONTROL
, OPTION
, ALT
, UP_ARROW
, DOWN_ARROW
,\nLEFT_ARROW
, and RIGHT_ARROW
are all helpful shorthands the key codes of\nspecial keys. Key codes can be found on websites such as\nkeycode.info.
\n"],"line":[0,184],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\n// Click on the canvas to begin detecting key presses.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. The last key pressed and its code are displayed at the center.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the last key pressed and its code.\n text(`${key} : ${keyCode}`, 50, 50);\n}\n
\n\n\n\n\n// Click on the canvas to begin detecting key presses.\n\nlet x = 50;\nlet y = 50;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n // Update x and y if an arrow key is pressed.\n if (keyIsPressed === true) {\n if (keyCode === UP_ARROW) {\n y -= 1;\n } else if (keyCode === DOWN_ARROW) {\n y += 1;\n } else if (keyCode === LEFT_ARROW) {\n x -= 1;\n } else if (keyCode === RIGHT_ARROW) {\n x += 1;\n }\n }\n\n // Style the circle.\n fill(0);\n\n // Draw the circle at (x, y).\n circle(x, y, 5);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/keyCode"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/keyIsDown.mdx"],"slug":[0,"en/p5/keyisdown"],"body":[0,"\n\n# keyIsDown\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"keyIsDown()"],"module":[0,"Events"],"submodule":[0,"Keyboard"],"file":[0,"src/events/keyboard.js"],"description":[0,"Returns true
if the key it’s checking is pressed and false
if not.
\nkeyIsDown()
is helpful when checking for multiple different key presses.\nFor example, keyIsDown()
can be used to check if both LEFT_ARROW
and\nUP_ARROW
are pressed:
\nif (keyIsDown(LEFT_ARROW) && keyIsDown(UP_ARROW)) {\n // Move diagonally.\n}\n
\nkeyIsDown()
can check for key presses using\nkeyCode values, as in keyIsDown(37)
or\nkeyIsDown(LEFT_ARROW)
. Key codes can be found on websites such as\nkeycode.info.
\n"],"line":[0,809],"params":[1,[[0,{"name":[0,"code"],"description":[0,"key to check.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"whether the key is down or not."],"type":[0,"Boolean"]}],"example":[1,[[0,"\n\n\n// Click on the canvas to begin detecting key presses.\n\nlet x = 50;\nlet y = 50;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n // Update x and y if an arrow key is pressed.\n if (keyIsDown(LEFT_ARROW) === true) {\n x -= 1;\n }\n\n if (keyIsDown(RIGHT_ARROW) === true) {\n x += 1;\n }\n\n if (keyIsDown(UP_ARROW) === true) {\n y -= 1;\n }\n\n if (keyIsDown(DOWN_ARROW) === true) {\n y += 1;\n }\n\n // Style the circle.\n fill(0);\n\n // Draw the circle.\n circle(x, y, 5);\n}\n
\n\n\n\n\n// Click on the canvas to begin detecting key presses.\n\nlet x = 50;\nlet y = 50;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n // Update x and y if an arrow key is pressed.\n if (keyIsDown(37) === true) {\n x -= 1;\n }\n\n if (keyIsDown(39) === true) {\n x += 1;\n }\n\n if (keyIsDown(38) === true) {\n y -= 1;\n }\n\n if (keyIsDown(40) === true) {\n y += 1;\n }\n\n // Style the circle.\n fill(0);\n\n // Draw the circle.\n circle(x, y, 5);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/keyIsDown"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/keyIsPressed.mdx"],"slug":[0,"en/p5/keyispressed"],"body":[0,"\n\n# keyIsPressed\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"keyIsPressed"],"module":[0,"Events"],"submodule":[0,"Keyboard"],"file":[0,"src/events/keyboard.js"],"description":[0,"A Boolean
system variable that's true
if any key is currently pressed\nand false
if not.
\n"],"line":[0,10],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\n// Click on the canvas to begin detecting key presses.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a white square at its center. The white square turns black when the user presses a key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n if (keyIsPressed === true) {\n fill(0);\n } else {\n fill(255);\n }\n\n // Draw the square.\n square(25, 25, 50);\n}\n
\n\n\n\n\n// Click on the canvas to begin detecting key presses.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a white square at its center. The white square turns black when the user presses a key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n if (keyIsPressed) {\n fill(0);\n } else {\n fill(255);\n }\n\n // Draw the square.\n square(25, 25, 50);\n}\n
\n\n\n\n\n// Click on the canvas to begin detecting key presses.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with the word \"false\" at its center. The word switches to \"true\" when the user presses a key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the value of keyIsPressed.\n text(keyIsPressed, 50, 50);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/keyIsPressed"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/keyPressed.mdx"],"slug":[0,"en/p5/keypressed"],"body":[0,"\n\n# keyPressed\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"keyPressed()"],"module":[0,"Events"],"submodule":[0,"Keyboard"],"file":[0,"src/events/keyboard.js"],"description":[0,"A function that's called once when any key is pressed.
\nDeclaring the function keyPressed()
sets a code block to run once\nautomatically when the user presses any key:
\nfunction keyPressed() {\n // Code to run.\n}\n
\nThe key and keyCode\nvariables will be updated with the most recently typed value when\nkeyPressed()
is called by p5.js:
\nfunction keyPressed() {\n if (key === 'c') {\n // Code to run.\n }\n\n if (keyCode === ENTER) {\n // Code to run.\n }\n}\n
\nThe parameter, event
, is optional. keyPressed()
is always passed a\nKeyboardEvent\nobject with properties that describe the key press event:
\nfunction keyPressed(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\nBrowsers may have default behaviors attached to various key events. For\nexample, some browsers may jump to the bottom of a web page when the\nSPACE
key is pressed. To prevent any default behavior for this event, add\nreturn false;
to the end of the function.
\n"],"line":[0,284],"params":[1,[[0,{"name":[0,"event"],"description":[0,"optional KeyboardEvent
callback argument.
\n"],"type":[0,"KeyboardEvent"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\n// Click on the canvas to begin detecting key presses.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square changes color when the user presses a key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle the background color when the user presses a key.\nfunction keyPressed() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\n\n\n\n// Click on the canvas to begin detecting key presses.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Reassign value when the user presses the 'a' or 'b' key.\nfunction keyPressed() {\n if (key === 'a') {\n value = 255;\n } else if (key === 'b') {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\n\n\n\n// Click on the canvas to begin detecting key presses.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle the background color when the user presses an arrow key.\nfunction keyPressed() {\n if (keyCode === LEFT_ARROW) {\n value = 255;\n } else if (keyCode === RIGHT_ARROW) {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/keyPressed"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/keyReleased.mdx"],"slug":[0,"en/p5/keyreleased"],"body":[0,"\n\n# keyReleased\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"keyReleased()"],"module":[0,"Events"],"submodule":[0,"Keyboard"],"file":[0,"src/events/keyboard.js"],"description":[0,"A function that's called once when any key is released.
\nDeclaring the function keyReleased()
sets a code block to run once\nautomatically when the user releases any key:
\nfunction keyReleased() {\n // Code to run.\n}\n
\nThe key and keyCode\nvariables will be updated with the most recently released value when\nkeyReleased()
is called by p5.js:
\nfunction keyReleased() {\n if (key === 'c') {\n // Code to run.\n }\n\n if (keyCode === ENTER) {\n // Code to run.\n }\n}\n
\nThe parameter, event
, is optional. keyReleased()
is always passed a\nKeyboardEvent\nobject with properties that describe the key press event:
\nfunction keyReleased(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\nBrowsers may have default behaviors attached to various key events. To\nprevent any default behavior for this event, add return false;
to the end\nof the function.
\n"],"line":[0,472],"params":[1,[[0,{"name":[0,"event"],"description":[0,"optional KeyboardEvent
callback argument.
\n"],"type":[0,"KeyboardEvent"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\n// Click on the canvas to begin detecting key presses.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square changes color when the user releases a key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle value when the user releases a key.\nfunction keyReleased() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\n\n\n\n// Click on the canvas to begin detecting key presses.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square becomes white when the user releases the \"w\" key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Set value to 255 the user releases the 'w' key.\nfunction keyReleased() {\n if (key === 'w') {\n value = 255;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\n\n\n\n// Click on the canvas to begin detecting key presses.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle the background color when the user releases an arrow key.\nfunction keyReleased() {\n if (keyCode === LEFT_ARROW) {\n value = 255;\n } else if (keyCode === RIGHT_ARROW) {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/keyReleased"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/keyTyped.mdx"],"slug":[0,"en/p5/keytyped"],"body":[0,"\n\n# keyTyped\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"keyTyped()"],"module":[0,"Events"],"submodule":[0,"Keyboard"],"file":[0,"src/events/keyboard.js"],"description":[0,"A function that's called once when keys with printable characters are pressed.
\nDeclaring the function keyTyped()
sets a code block to run once\nautomatically when the user presses any key with a printable character such\nas a
or 1. Modifier keys such as SHIFT
, CONTROL
, and the arrow keys\nwill be ignored:
\nfunction keyTyped() {\n // Code to run.\n}\n
\nThe key and keyCode\nvariables will be updated with the most recently released value when\nkeyTyped()
is called by p5.js:
\nfunction keyTyped() {\n // Check for the \"c\" character using key.\n if (key === 'c') {\n // Code to run.\n }\n\n // Check for \"c\" using keyCode.\n if (keyCode === 67) {\n // Code to run.\n }\n}\n
\nThe parameter, event
, is optional. keyTyped()
is always passed a\nKeyboardEvent\nobject with properties that describe the key press event:
\nfunction keyReleased(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\nNote: Use the keyPressed() function and\nkeyCode system variable to respond to modifier\nkeys such as ALT
.
\nBrowsers may have default behaviors attached to various key events. To\nprevent any default behavior for this event, add return false;
to the end\nof the function.
\n"],"line":[0,653],"params":[1,[[0,{"name":[0,"event"],"description":[0,"optional KeyboardEvent
callback argument.
\n"],"type":[0,"KeyboardEvent"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\n// Click on the canvas to begin detecting key presses.\n// Note: Pressing special keys such as SPACE have no effect.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a white square at its center. The inner square changes color when the user presses a key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle the square's color when the user types a printable key.\nfunction keyTyped() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\n\n\n\n// Click on the canvas to begin detecting key presses.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Reassign value when the user types the 'a' or 'b' key.\nfunction keyTyped() {\n if (key === 'a') {\n value = 255;\n } else if (key === 'b') {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/keyTyped"]}],"render":[0,null]}]]]}],[0,{"name":[0,"Mouse"],"entry":[0],"entries":[1,[[0,{"id":[0,"en/p5/doubleClicked.mdx"],"slug":[0,"en/p5/doubleclicked"],"body":[0,"\n\n# doubleClicked\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"doubleClicked()"],"module":[0,"Events"],"submodule":[0,"Mouse"],"file":[0,"src/events/mouse.js"],"description":[0,"A function that's called once when a mouse button is clicked twice quickly.
\nDeclaring the function doubleClicked()
sets a code block to run\nautomatically when the user presses and releases the mouse button twice\nquickly:
\nfunction doubleClicked() {\n // Code to run.\n}\n
\nThe mouse system variables, such as mouseX and\nmouseY, will be updated with their most recent\nvalue when doubleClicked()
is called by p5.js:
\nfunction doubleClicked() {\n if (mouseX < 50) {\n // Code to run if the mouse is on the left.\n }\n\n if (mouseY > 50) {\n // Code to run if the mouse is near the bottom.\n }\n}\n
\nThe parameter, event
, is optional. doubleClicked()
is always passed a\nMouseEvent\nobject with properties that describe the double-click event:
\nfunction doubleClicked(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\nOn touchscreen devices, code placed in doubleClicked()
will run after two\ntouches that occur within a short time.
\nBrowsers may have default behaviors attached to various mouse events. For\nexample, some browsers highlight text when the user moves the mouse while\npressing a mouse button. To prevent any default behavior for this event,\nadd return false;
to the end of the function.
\n"],"line":[0,1585],"params":[1,[[0,{"name":[0,"event"],"description":[0,"optional MouseEvent
argument.
\n"],"type":[0,"MouseEvent"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square changes color when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle the square's color when the user double-clicks.\nfunction doubleClicked() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\n\n\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black circle at its center. When the user double-clicks on the circle, it changes color to white.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the circle.\n fill(value);\n\n // Draw the circle.\n circle(50, 50, 80);\n}\n\n// Reassign value to 255 when the user double-clicks on the circle.\nfunction doubleClicked() {\n if (dist(50, 50, mouseX, mouseY) < 40) {\n value = 255;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/doubleClicked"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/exitPointerLock.mdx"],"slug":[0,"en/p5/exitpointerlock"],"body":[0,"\n\n# exitPointerLock\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"exitPointerLock()"],"module":[0,"Events"],"submodule":[0,"Mouse"],"file":[0,"src/events/mouse.js"],"description":[0,"Exits a pointer lock started with\nrequestPointerLock.
\nCalling requestPointerLock()
locks the values of\nmouseX, mouseY,\npmouseX, and pmouseY.\nCalling exitPointerLock()
resumes updating the mouse system variables.
\nNote: Most browsers require an input, such as a click, before calling\nrequestPointerLock()
. It’s recommended to call requestPointerLock()
in\nan event function such as doubleClicked().
\n"],"line":[0,1932],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet isLocked = false;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a word at its center. The word changes between \"Unlocked\" and \"Locked\" when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Tell the user whether the pointer is locked.\n if (isLocked === true) {\n text('Locked', 50, 50);\n } else {\n text('Unlocked', 50, 50);\n }\n}\n\n// Toggle the pointer lock when the user double-clicks.\nfunction doubleClicked() {\n if (isLocked === true) {\n exitPointerLock();\n isLocked = false;\n } else {\n requestPointerLock();\n isLocked = true;\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/exitPointerLock"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/mouseButton.mdx"],"slug":[0,"en/p5/mousebutton"],"body":[0,"\n\n# mouseButton\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"mouseButton"],"module":[0,"Events"],"submodule":[0,"Mouse"],"file":[0,"src/events/mouse.js"],"description":[0,"A String system variable that contains the value of the last mouse button\npressed.
\nThe mouseButton
variable is either LEFT
, RIGHT
, or CENTER
,\ndepending on which button was pressed last.
\nNote: Different browsers may track mouseButton
differently. See\nMDN\nfor more information.
\n"],"line":[0,693],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the mouse button.\n text(mouseButton, 50, 50);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n \"A gray square. Different shapes appear at its center depending on the mouse button that's clicked.\"\n );\n}\n\nfunction draw() {\n background(200);\n\n if (mouseIsPressed === true) {\n if (mouseButton === LEFT) {\n circle(50, 50, 50);\n }\n if (mouseButton === RIGHT) {\n square(25, 25, 50);\n }\n if (mouseButton === CENTER) {\n triangle(23, 75, 50, 20, 78, 75);\n }\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/mouseButton"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/mouseClicked.mdx"],"slug":[0,"en/p5/mouseclicked"],"body":[0,"\n\n# mouseClicked\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"mouseClicked()"],"module":[0,"Events"],"submodule":[0,"Mouse"],"file":[0,"src/events/mouse.js"],"description":[0,"A function that's called once after a mouse button is pressed and released.
\nDeclaring the function mouseClicked()
sets a code block to run\nautomatically when the user releases a mouse button after having pressed\nit:
\nfunction mouseClicked() {\n // Code to run.\n}\n
\nThe mouse system variables, such as mouseX and\nmouseY, will be updated with their most recent\nvalue when mouseClicked()
is called by p5.js:
\nfunction mouseClicked() {\n if (mouseX < 50) {\n // Code to run if the mouse is on the left.\n }\n\n if (mouseY > 50) {\n // Code to run if the mouse is near the bottom.\n }\n}\n
\nThe parameter, event
, is optional. mouseClicked()
is always passed a\nMouseEvent\nobject with properties that describe the mouse click event:
\nfunction mouseClicked(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\nOn touchscreen devices, mouseClicked()
will run when a user’s touch\nends if touchEnded() isn’t declared. If\ntouchEnded() is declared, then\ntouchEnded() will run when a user’s touch\nends and mouseClicked()
won’t.
\nBrowsers may have default behaviors attached to various mouse events. For\nexample, some browsers highlight text when the user moves the mouse while\npressing a mouse button. To prevent any default behavior for this event,\nadd return false;
to the end of the function.
\nNote: mousePressed(),\nmouseReleased(),\nand mouseClicked()
are all related.\nmousePressed() runs as soon as the user\nclicks the mouse. mouseReleased() runs as\nsoon as the user releases the mouse click. mouseClicked()
runs\nimmediately after mouseReleased().
\n"],"line":[0,1429],"params":[1,[[0,{"name":[0,"event"],"description":[0,"optional MouseEvent
argument.
\n"],"type":[0,"MouseEvent"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square changes color when the user presses and releases a mouse button.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle the square's color when the user clicks.\nfunction mouseClicked() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Style the circle.\n fill('orange');\n stroke('royalblue');\n strokeWeight(10);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(220);\n\n // Draw the circle.\n circle(50, 50, 20);\n}\n\n// Set the stroke color and weight as soon as the user clicks.\nfunction mousePressed() {\n stroke('deeppink');\n strokeWeight(3);\n}\n\n// Set the stroke and fill colors as soon as the user releases\n// the mouse.\nfunction mouseReleased() {\n stroke('royalblue');\n\n // This is never visible because fill() is called\n // in mouseClicked() which runs immediately after\n // mouseReleased();\n fill('limegreen');\n}\n\n// Set the fill color and stroke weight after\n// mousePressed() and mouseReleased() are called.\nfunction mouseClicked() {\n fill('orange');\n strokeWeight(10);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/mouseClicked"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/mouseDragged.mdx"],"slug":[0,"en/p5/mousedragged"],"body":[0,"\n\n# mouseDragged\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"mouseDragged()"],"module":[0,"Events"],"submodule":[0,"Mouse"],"file":[0,"src/events/mouse.js"],"description":[0,"A function that's called when the mouse moves while a button is pressed.
\nDeclaring the function mouseDragged()
sets a code block to run\nautomatically when the user clicks and drags the mouse:
\nfunction mouseDragged() {\n // Code to run.\n}\n
\nThe mouse system variables, such as mouseX and\nmouseY, will be updated with their most recent\nvalue when mouseDragged()
is called by p5.js:
\nfunction mouseDragged() {\n if (mouseX < 50) {\n // Code to run if the mouse is on the left.\n }\n\n if (mouseY > 50) {\n // Code to run if the mouse is near the bottom.\n }\n}\n
\nThe parameter, event
, is optional. mouseDragged()
is always passed a\nMouseEvent\nobject with properties that describe the mouse drag event:
\nfunction mouseDragged(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\nOn touchscreen devices, mouseDragged()
will run when a user moves a touch\npoint if touchMoved() isn’t declared. If\ntouchMoved() is declared, then\ntouchMoved() will run when a user moves a\ntouch point and mouseDragged()
won’t.
\nBrowsers may have default behaviors attached to various mouse events. For\nexample, some browsers highlight text when the user moves the mouse while\npressing a mouse button. To prevent any default behavior for this event,\nadd return false;
to the end of the function.
\n"],"line":[0,968],"params":[1,[[0,{"name":[0,"event"],"description":[0,"optional MouseEvent
argument.
\n"],"type":[0,"MouseEvent"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square becomes lighter as the user drags the mouse.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\nfunction mouseDragged() {\n // Update the grayscale value.\n value += 5;\n\n // Reset the grayscale value.\n if (value > 255) {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/mouseDragged"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/mouseIsPressed.mdx"],"slug":[0,"en/p5/mouseispressed"],"body":[0,"\n\n# mouseIsPressed\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"mouseIsPressed"],"module":[0,"Events"],"submodule":[0,"Mouse"],"file":[0,"src/events/mouse.js"],"description":[0,"A Boolean
system variable that's true
if the mouse is pressed and\nfalse
if not.
\n"],"line":[0,761],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with the word \"false\" at its center. The word changes to \"true\" when the user presses a mouse button.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the mouseIsPressed variable.\n text(mouseIsPressed, 25, 50);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a white square at its center. The inner square turns black when the user presses the mouse.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n if (mouseIsPressed === true) {\n fill(0);\n } else {\n fill(255);\n }\n\n // Draw the square.\n square(25, 25, 50);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/mouseIsPressed"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/mouseMoved.mdx"],"slug":[0,"en/p5/mousemoved"],"body":[0,"\n\n# mouseMoved\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"mouseMoved()"],"module":[0,"Events"],"submodule":[0,"Mouse"],"file":[0,"src/events/mouse.js"],"description":[0,"A function that's called when the mouse moves.
\nDeclaring the function mouseMoved()
sets a code block to run\nautomatically when the user moves the mouse without clicking any mouse\nbuttons:
\nfunction mouseMoved() {\n // Code to run.\n}\n
\nThe mouse system variables, such as mouseX and\nmouseY, will be updated with their most recent\nvalue when mouseMoved()
is called by p5.js:
\nfunction mouseMoved() {\n if (mouseX < 50) {\n // Code to run if the mouse is on the left.\n }\n\n if (mouseY > 50) {\n // Code to run if the mouse is near the bottom.\n }\n}\n
\nThe parameter, event
, is optional. mouseMoved()
is always passed a\nMouseEvent\nobject with properties that describe the mouse move event:
\nfunction mouseMoved(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\nBrowsers may have default behaviors attached to various mouse events. For\nexample, some browsers highlight text when the user moves the mouse while\npressing a mouse button. To prevent any default behavior for this event,\nadd return false;
to the end of the function.
\n"],"line":[0,882],"params":[1,[[0,{"name":[0,"event"],"description":[0,"optional MouseEvent
argument.
\n"],"type":[0,"MouseEvent"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square becomes lighter as the mouse moves.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\nfunction mouseMoved() {\n // Update the grayscale value.\n value += 5;\n\n // Reset the grayscale value.\n if (value > 255) {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/mouseMoved"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/mousePressed.mdx"],"slug":[0,"en/p5/mousepressed"],"body":[0,"\n\n# mousePressed\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"mousePressed()"],"module":[0,"Events"],"submodule":[0,"Mouse"],"file":[0,"src/events/mouse.js"],"description":[0,"A function that's called once when a mouse button is pressed.
\nDeclaring the function mousePressed()
sets a code block to run\nautomatically when the user presses a mouse button:
\nfunction mousePressed() {\n // Code to run.\n}\n
\nThe mouse system variables, such as mouseX and\nmouseY, will be updated with their most recent\nvalue when mousePressed()
is called by p5.js:
\nfunction mousePressed() {\n if (mouseX < 50) {\n // Code to run if the mouse is on the left.\n }\n\n if (mouseY > 50) {\n // Code to run if the mouse is near the bottom.\n }\n}\n
\nThe parameter, event
, is optional. mousePressed()
is always passed a\nMouseEvent\nobject with properties that describe the mouse press event:
\nfunction mousePressed(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\nOn touchscreen devices, mousePressed()
will run when a user’s touch\nbegins if touchStarted() isn’t declared. If\ntouchStarted() is declared, then\ntouchStarted() will run when a user’s touch\nbegins and mousePressed()
won’t.
\nBrowsers may have default behaviors attached to various mouse events. For\nexample, some browsers highlight text when the user moves the mouse while\npressing a mouse button. To prevent any default behavior for this event,\nadd return false;
to the end of the function.
\nNote: mousePressed()
, mouseReleased(),\nand mouseClicked() are all related.\nmousePressed()
runs as soon as the user clicks the mouse.\nmouseReleased() runs as soon as the user\nreleases the mouse click. mouseClicked()\nruns immediately after mouseReleased().
\n"],"line":[0,1084],"params":[1,[[0,{"name":[0,"event"],"description":[0,"optional MouseEvent
argument.
\n"],"type":[0,"MouseEvent"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square becomes lighter when the user presses a mouse button.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\nfunction mousePressed() {\n // Update the grayscale value.\n value += 5;\n\n // Reset the grayscale value.\n if (value > 255) {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Style the circle.\n fill('orange');\n stroke('royalblue');\n strokeWeight(10);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(220);\n\n // Draw the circle.\n circle(50, 50, 20);\n}\n\n// Set the stroke color and weight as soon as the user clicks.\nfunction mousePressed() {\n stroke('deeppink');\n strokeWeight(3);\n}\n\n// Set the stroke and fill colors as soon as the user releases\n// the mouse.\nfunction mouseReleased() {\n stroke('royalblue');\n\n // This is never visible because fill() is called\n // in mouseClicked() which runs immediately after\n // mouseReleased();\n fill('limegreen');\n}\n\n// Set the fill color and stroke weight after\n// mousePressed() and mouseReleased() are called.\nfunction mouseClicked() {\n fill('orange');\n strokeWeight(10);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/mousePressed"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/mouseReleased.mdx"],"slug":[0,"en/p5/mousereleased"],"body":[0,"\n\n# mouseReleased\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"mouseReleased()"],"module":[0,"Events"],"submodule":[0,"Mouse"],"file":[0,"src/events/mouse.js"],"description":[0,"A function that's called once when a mouse button is released.
\nDeclaring the function mouseReleased()
sets a code block to run\nautomatically when the user releases a mouse button after having pressed\nit:
\nfunction mouseReleased() {\n // Code to run.\n}\n
\nThe mouse system variables, such as mouseX and\nmouseY, will be updated with their most recent\nvalue when mouseReleased()
is called by p5.js:
\nfunction mouseReleased() {\n if (mouseX < 50) {\n // Code to run if the mouse is on the left.\n }\n\n if (mouseY > 50) {\n // Code to run if the mouse is near the bottom.\n }\n}\n
\nThe parameter, event
, is optional. mouseReleased()
is always passed a\nMouseEvent\nobject with properties that describe the mouse release event:
\nfunction mouseReleased(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\nOn touchscreen devices, mouseReleased()
will run when a user’s touch\nends if touchEnded() isn’t declared. If\ntouchEnded() is declared, then\ntouchEnded() will run when a user’s touch\nends and mouseReleased()
won’t.
\nBrowsers may have default behaviors attached to various mouse events. For\nexample, some browsers highlight text when the user moves the mouse while\npressing a mouse button. To prevent any default behavior for this event,\nadd return false;
to the end of the function.
\nNote: mousePressed(), mouseReleased()
,\nand mouseClicked() are all related.\nmousePressed() runs as soon as the user\nclicks the mouse. mouseReleased()
runs as soon as the user releases the\nmouse click. mouseClicked() runs\nimmediately after mouseReleased()
.
\n"],"line":[0,1256],"params":[1,[[0,{"name":[0,"event"],"description":[0,"optional MouseEvent
argument.
\n"],"type":[0,"MouseEvent"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square becomes lighter when the user presses and releases a mouse button.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\nfunction mouseReleased() {\n // Update the grayscale value.\n value += 5;\n\n // Reset the grayscale value.\n if (value > 255) {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Style the circle.\n fill('orange');\n stroke('royalblue');\n strokeWeight(10);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(220);\n\n // Draw the circle.\n circle(50, 50, 20);\n}\n\n// Set the stroke color and weight as soon as the user clicks.\nfunction mousePressed() {\n stroke('deeppink');\n strokeWeight(3);\n}\n\n// Set the stroke and fill colors as soon as the user releases\n// the mouse.\nfunction mouseReleased() {\n stroke('royalblue');\n\n // This is never visible because fill() is called\n // in mouseClicked() which runs immediately after\n // mouseReleased();\n fill('limegreen');\n}\n\n// Set the fill color and stroke weight after\n// mousePressed() and mouseReleased() are called.\nfunction mouseClicked() {\n fill('orange');\n strokeWeight(10);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/mouseReleased"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/mouseWheel.mdx"],"slug":[0,"en/p5/mousewheel"],"body":[0,"\n\n# mouseWheel\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"mouseWheel()"],"module":[0,"Events"],"submodule":[0,"Mouse"],"file":[0,"src/events/mouse.js"],"description":[0,"A function that's called once when the mouse wheel moves.
\nDeclaring the function mouseWheel()
sets a code block to run\nautomatically when the user scrolls with the mouse wheel:
\nfunction mouseWheel() {\n // Code to run.\n}\n
\nThe mouse system variables, such as mouseX and\nmouseY, will be updated with their most recent\nvalue when mouseWheel()
is called by p5.js:
\nfunction mouseWheel() {\n if (mouseX < 50) {\n // Code to run if the mouse is on the left.\n }\n\n if (mouseY > 50) {\n // Code to run if the mouse is near the bottom.\n }\n}\n
\nThe parameter, event
, is optional. mouseWheel()
is always passed a\nMouseEvent\nobject with properties that describe the mouse scroll event:
\nfunction mouseWheel(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\nThe event
object has many properties including delta
, a Number
\ncontaining the distance that the user scrolled. For example, event.delta
\nmight have the value 5 when the user scrolls up. event.delta
is positive\nif the user scrolls up and negative if they scroll down. The signs are\nopposite on macOS with \"natural\" scrolling enabled.
\nBrowsers may have default behaviors attached to various mouse events. For\nexample, some browsers highlight text when the user moves the mouse while\npressing a mouse button. To prevent any default behavior for this event,\nadd return false;
to the end of the function.
\nNote: On Safari, mouseWheel()
may only work as expected if\nreturn false;
is added at the end of the function.
\n"],"line":[0,1732],"params":[1,[[0,{"name":[0,"event"],"description":[0,"optional WheelEvent
argument.
\n"],"type":[0,"WheelEvent"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet circleSize = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. A white circle at its center grows up when the user scrolls the mouse wheel.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Draw the circle\n circle(circleSize, 50, 50);\n}\n\n// Increment circleSize when the user scrolls the mouse wheel.\nfunction mouseWheel() {\n circleSize += 1;\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\n\n\n\nlet direction = '';\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. An arrow at its center points up when the user scrolls up. The arrow points down when the user scrolls down.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Draw an arrow that points where\n // the mouse last scrolled.\n text(direction, 50, 50);\n}\n\n// Change direction when the user scrolls the mouse wheel.\nfunction mouseWheel(event) {\n if (event.delta > 0) {\n direction = '▲';\n } else {\n direction = '▼';\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/mouseWheel"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/mouseX.mdx"],"slug":[0,"en/p5/mousex"],"body":[0,"\n\n# mouseX\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"mouseX"],"module":[0,"Events"],"submodule":[0,"Mouse"],"file":[0,"src/events/mouse.js"],"description":[0,"A Number
system variable that tracks the mouse's horizontal position.
\nIn 2D mode, mouseX
keeps track of the mouse's position relative to the\ntop-left corner of the canvas. For example, if the mouse is 50 pixels from\nthe left edge of the canvas, then mouseX
will be 50.
\nIn WebGL mode, mouseX
keeps track of the mouse's position relative to the\ncenter of the canvas. For example, if the mouse is 50 pixels to the right\nof the canvas' center, then mouseX
will be 50.
\nIf touch is used instead of the mouse, then mouseX
will hold the\nx-coordinate of the most recent touch point.
\n"],"line":[0,109],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\"A vertical black line moves left and right following the mouse's x-position.\");\n}\n\nfunction draw() {\n background(200);\n\n // Draw a vertical line that follows the mouse's x-coordinate.\n line(mouseX, 0, mouseX, 100);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\"A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse.\");\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the mouse's coordinates.\n text(`x: ${mouseX} y: ${mouseY}`, 50, 50);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\"A vertical black line moves left and right following the mouse's x-position.\");\n}\n\nfunction draw() {\n background(200);\n\n // Adjust coordinates for WebGL mode.\n // The origin (0, 0) is at the center of the canvas.\n let mx = mouseX - 50;\n\n // Draw the line.\n line(mx, -50, mx, 50);\n}\n
\n\n\n\n\nlet font;\n\n// Load a font for WebGL mode.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n \"A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse.\"\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Display the mouse's coordinates.\n text(`x: ${mouseX} y: ${mouseY}`, 0, 0);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/mouseX"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/mouseY.mdx"],"slug":[0,"en/p5/mousey"],"body":[0,"\n\n# mouseY\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"mouseY"],"module":[0,"Events"],"submodule":[0,"Mouse"],"file":[0,"src/events/mouse.js"],"description":[0,"A Number
system variable that tracks the mouse's vertical position.
\nIn 2D mode, mouseY
keeps track of the mouse's position relative to the\ntop-left corner of the canvas. For example, if the mouse is 50 pixels from\nthe top edge of the canvas, then mouseY
will be 50.
\nIn WebGL mode, mouseY
keeps track of the mouse's position relative to the\ncenter of the canvas. For example, if the mouse is 50 pixels below the\ncanvas' center, then mouseY
will be 50.
\nIf touch is used instead of the mouse, then mouseY
will hold the\ny-coordinate of the most recent touch point.
\n"],"line":[0,220],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\"A horizontal black line moves up and down following the mouse's y-position.\");\n}\n\nfunction draw() {\n background(200);\n\n // Draw a horizontal line that follows the mouse's y-coordinate.\n line(0, mouseY, 100, mouseY);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\"A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse.\");\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the mouse's coordinates.\n text(`x: ${mouseX} y: ${mouseY}`, 50, 50);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\"A horizontal black line moves up and down following the mouse's y-position.\");\n}\n\nfunction draw() {\n background(200);\n\n // Adjust coordinates for WebGL mode.\n // The origin (0, 0) is at the center of the canvas.\n let my = mouseY - 50;\n\n // Draw the line.\n line(-50, my, 50, my);\n}\n
\n\n\n\n\nlet font;\n\n// Load a font for WebGL mode.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n \"A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse.\"\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Display the mouse's coordinates.\n text(`x: ${mouseX} y: ${mouseY}`, 0, 0);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/mouseY"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/movedX.mdx"],"slug":[0,"en/p5/movedx"],"body":[0,"\n\n# movedX\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"movedX"],"module":[0,"Events"],"submodule":[0,"Mouse"],"file":[0,"src/events/mouse.js"],"description":[0,"A Number
system variable that tracks the mouse's horizontal movement.
\nmovedX
tracks how many pixels the mouse moves left or right between\nframes. movedX
will have a negative value if the mouse moves left between\nframes and a positive value if it moves right. movedX
can be calculated\nas mouseX - pmouseX
.
\nNote: movedX
continues updating even when\nrequestPointerLock() is active.
\n"],"line":[0,12],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display >> when movedX is positive and\n // << when it's negative.\n if (movedX > 0) {\n text('>>', 50, 50);\n } else if (movedX < 0) {\n text('<<', 50, 50);\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/movedX"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/movedY.mdx"],"slug":[0,"en/p5/movedy"],"body":[0,"\n\n# movedY\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"movedY"],"module":[0,"Events"],"submodule":[0,"Mouse"],"file":[0,"src/events/mouse.js"],"description":[0,"A Number
system variable that tracks the mouse's vertical movement.
\nmovedY
tracks how many pixels the mouse moves up or down between\nframes. movedY
will have a negative value if the mouse moves up between\nframes and a positive value if it moves down. movedY
can be calculated\nas mouseY - pmouseY
.
\nNote: movedY
continues updating even when\nrequestPointerLock() is active.
\n"],"line":[0,57],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. The text \"▲\" appears when the user moves the mouse upward. The text \"▼\" appears when the user moves the mouse downward.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display ▼ when movedY is positive and\n // ▲ when it's negative.\n if (movedY > 0) {\n text('▼', 50, 50);\n } else if (movedY < 0) {\n text('▲', 50, 50);\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/movedY"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/pmouseX.mdx"],"slug":[0,"en/p5/pmousex"],"body":[0,"\n\n# pmouseX\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"pmouseX"],"module":[0,"Events"],"submodule":[0,"Mouse"],"file":[0,"src/events/mouse.js"],"description":[0,"A Number
system variable that tracks the mouse's previous horizontal\nposition.
\nIn 2D mode, pmouseX
keeps track of the mouse's position relative to the\ntop-left corner of the canvas. Its value is\nmouseX from the previous frame. For example, if\nthe mouse was 50 pixels from the left edge of the canvas during the last\nframe, then pmouseX
will be 50.
\nIn WebGL mode, pmouseX
keeps track of the mouse's position relative to the\ncenter of the canvas. For example, if the mouse was 50 pixels to the right\nof the canvas' center during the last frame, then pmouseX
will be 50.
\nIf touch is used instead of the mouse, then pmouseX
will hold the\nx-coordinate of the last touch point.
\nNote: pmouseX
is reset to the current mouseX\nvalue at the start of each touch event.
\n"],"line":[0,331],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(10);\n\n describe('A line follows the mouse as it moves. The line grows longer with faster movements.');\n}\n\nfunction draw() {\n background(200);\n\n line(pmouseX, pmouseY, mouseX, mouseY);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A line follows the mouse as it moves. The line grows longer with faster movements.');\n}\n\nfunction draw() {\n background(200);\n\n // Adjust coordinates for WebGL mode.\n // The origin (0, 0) is at the center of the canvas.\n let pmx = pmouseX - 50;\n let pmy = pmouseY - 50;\n let mx = mouseX - 50;\n let my = mouseY - 50;\n\n // Draw the line.\n line(pmx, pmy, mx, my);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/pmouseX"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/pmouseY.mdx"],"slug":[0,"en/p5/pmousey"],"body":[0,"\n\n# pmouseY\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"pmouseY"],"module":[0,"Events"],"submodule":[0,"Mouse"],"file":[0,"src/events/mouse.js"],"description":[0,"A Number
system variable that tracks the mouse's previous vertical\nposition.
\nIn 2D mode, pmouseY
keeps track of the mouse's position relative to the\ntop-left corner of the canvas. Its value is\nmouseY from the previous frame. For example, if\nthe mouse was 50 pixels from the top edge of the canvas during the last\nframe, then pmouseY
will be 50.
\nIn WebGL mode, pmouseY
keeps track of the mouse's position relative to the\ncenter of the canvas. For example, if the mouse was 50 pixels below the\ncanvas' center during the last frame, then pmouseY
will be 50.
\nIf touch is used instead of the mouse, then pmouseY
will hold the\ny-coordinate of the last touch point.
\nNote: pmouseY
is reset to the current mouseY\nvalue at the start of each touch event.
\n"],"line":[0,400],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(10);\n\n describe('A line follows the mouse as it moves. The line grows longer with faster movements.');\n}\n\nfunction draw() {\n background(200);\n\n line(pmouseX, pmouseY, mouseX, mouseY);\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A line follows the mouse as it moves. The line grows longer with faster movements.');\n}\n\nfunction draw() {\n background(200);\n\n // Adjust coordinates for WebGL mode.\n // The origin (0, 0) is at the center of the canvas.\n let pmx = pmouseX - 50;\n let pmy = pmouseY - 50;\n let mx = mouseX - 50;\n let my = mouseY - 50;\n\n // Draw the line.\n line(pmx, pmy, mx, my);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/pmouseY"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/pwinMouseX.mdx"],"slug":[0,"en/p5/pwinmousex"],"body":[0,"\n\n# pwinMouseX\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"pwinMouseX"],"module":[0,"Events"],"submodule":[0,"Mouse"],"file":[0,"src/events/mouse.js"],"description":[0,"A Number
variable that tracks the mouse's previous horizontal position\nwithin the browser.
\npwinMouseX
keeps track of the mouse's position relative to the top-left\ncorner of the browser window. Its value is\nwinMouseX from the previous frame. For\nexample, if the mouse was 50 pixels from\nthe left edge of the browser during the last frame, then pwinMouseX
will\nbe 50.
\nOn a touchscreen device, pwinMouseX
will hold the x-coordinate of the most\nrecent touch point. pwinMouseX
is reset to the current\nwinMouseX value at the start of each touch\nevent.
\nNote: Use pmouseX to track the mouse’s previous\nx-coordinate within the canvas.
\n"],"line":[0,551],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(10);\n\n describe('A gray square. A white circle at its center grows larger when the mouse moves horizontally.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the circle's diameter.\n let d = winMouseX - pwinMouseX;\n\n // Draw the circle.\n circle(50, 50, d);\n}\n
\n\n\n\n\nfunction setup() {\n // Create the canvas and set its position.\n let cnv = createCanvas(100, 100);\n cnv.position(20, 20);\n\n describe('A gray square with a number at its center. The number changes as the user moves the mouse vertically.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display pwinMouseX.\n text(pwinMouseX, 50, 50);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/pwinMouseX"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/pwinMouseY.mdx"],"slug":[0,"en/p5/pwinmousey"],"body":[0,"\n\n# pwinMouseY\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"pwinMouseY"],"module":[0,"Events"],"submodule":[0,"Mouse"],"file":[0,"src/events/mouse.js"],"description":[0,"A Number
variable that tracks the mouse's previous vertical position\nwithin the browser.
\npwinMouseY
keeps track of the mouse's position relative to the top-left\ncorner of the browser window. Its value is\nwinMouseY from the previous frame. For\nexample, if the mouse was 50 pixels from\nthe top edge of the browser during the last frame, then pwinMouseY
will\nbe 50.
\nOn a touchscreen device, pwinMouseY
will hold the y-coordinate of the most\nrecent touch point. pwinMouseY
is reset to the current\nwinMouseY value at the start of each touch\nevent.
\nNote: Use pmouseY to track the mouse’s previous\ny-coordinate within the canvas.
\n"],"line":[0,622],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(10);\n\n describe('A gray square. A white circle at its center grows larger when the mouse moves vertically.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the circle's diameter.\n let d = winMouseY - pwinMouseY;\n\n // Draw the circle.\n circle(50, 50, d);\n}\n
\n\n\n\n\nfunction setup() {\n // Create the canvas and set its position.\n let cnv = createCanvas(100, 100);\n cnv.position(20, 20);\n\n describe('A gray square with a number at its center. The number changes as the user moves the mouse vertically.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display pwinMouseY.\n text(pwinMouseY, 50, 50);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/pwinMouseY"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/requestPointerLock.mdx"],"slug":[0,"en/p5/requestpointerlock"],"body":[0,"\n\n# requestPointerLock\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"requestPointerLock()"],"module":[0,"Events"],"submodule":[0,"Mouse"],"file":[0,"src/events/mouse.js"],"description":[0,"Locks the mouse pointer to its current position and makes it invisible.
\nrequestPointerLock()
allows the mouse to move forever without leaving the\nscreen. Calling requestPointerLock()
locks the values of\nmouseX, mouseY,\npmouseX, and pmouseY.\nmovedX and movedY\ncontinue updating and can be used to get the distance the mouse moved since\nthe last frame was drawn. Calling\nexitPointerLock() resumes updating the\nmouse system variables.
\nNote: Most browsers require an input, such as a click, before calling\nrequestPointerLock()
. It’s recommended to call requestPointerLock()
in\nan event function such as doubleClicked().
\n"],"line":[0,1866],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet score = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Update the score.\n score -= movedY;\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the score.\n text(`Score: ${score}`, 50, 50);\n}\n\n// Lock the pointer when the user double-clicks.\nfunction doubleClicked() {\n requestPointerLock();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/requestPointerLock"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/winMouseX.mdx"],"slug":[0,"en/p5/winmousex"],"body":[0,"\n\n# winMouseX\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"winMouseX"],"module":[0,"Events"],"submodule":[0,"Mouse"],"file":[0,"src/events/mouse.js"],"description":[0,"A Number
variable that tracks the mouse's horizontal position within the\nbrowser.
\nwinMouseX
keeps track of the mouse's position relative to the top-left\ncorner of the browser window. For example, if the mouse is 50 pixels from\nthe left edge of the browser, then winMouseX
will be 50.
\nOn a touchscreen device, winMouseX
will hold the x-coordinate of the most\nrecent touch point.
\nNote: Use mouseX to track the mouse’s\nx-coordinate within the canvas.
\n"],"line":[0,469],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\"A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse.\");\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the mouse's coordinates within the browser window.\n text(`x: ${winMouseX} y: ${winMouseY}`, 50, 50);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/winMouseX"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/winMouseY.mdx"],"slug":[0,"en/p5/winmousey"],"body":[0,"\n\n# winMouseY\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"winMouseY"],"module":[0,"Events"],"submodule":[0,"Mouse"],"file":[0,"src/events/mouse.js"],"description":[0,"A Number
variable that tracks the mouse's vertical position within the\nbrowser.
\nwinMouseY
keeps track of the mouse's position relative to the top-left\ncorner of the browser window. For example, if the mouse is 50 pixels from\nthe top edge of the browser, then winMouseY
will be 50.
\nOn a touchscreen device, winMouseY
will hold the y-coordinate of the most\nrecent touch point.
\nNote: Use mouseY to track the mouse’s\ny-coordinate within the canvas.
\n"],"line":[0,510],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\"A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse.\");\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the mouse's coordinates within the browser window.\n text(`x: ${winMouseX} y: ${winMouseY}`, 50, 50);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/winMouseY"]}],"render":[0,null]}]]]}],[0,{"name":[0,"Touch"],"entry":[0],"entries":[1,[[0,{"id":[0,"en/p5/touchEnded.mdx"],"slug":[0,"en/p5/touchended"],"body":[0,"\n\n# touchEnded\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"touchEnded()"],"module":[0,"Events"],"submodule":[0,"Touch"],"file":[0,"src/events/touch.js"],"description":[0,"A function that's called once each time a screen touch ends.
\nDeclaring the function touchEnded()
sets a code block to run\nautomatically when the user stops touching a touchscreen device:
\nfunction touchEnded() {\n // Code to run.\n}\n
\nThe touches array will be updated with the most\nrecent touch points when touchEnded()
is called by p5.js:
\nfunction touchEnded() {\n // Paint over the background.\n background(200);\n\n // Mark each remaining touch point when the user stops\n // a touch.\n for (let touch of touches) {\n circle(touch.x, touch.y, 40);\n }\n}\n
\nThe parameter, event, is optional. touchEnded()
will be passed a\nTouchEvent\nobject with properties that describe the touch event:
\nfunction touchEnded(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\nOn touchscreen devices, mouseReleased() will\nrun when the user’s touch ends if touchEnded()
isn’t declared. If\ntouchEnded()
is declared, then touchEnded()
will run when a user’s\ntouch ends and mouseReleased() won’t.
\nNote: touchStarted(),\ntouchEnded()
, and touchMoved() are all\nrelated. touchStarted() runs as soon as the\nuser touches a touchscreen device. touchEnded()
runs as soon as the user\nends a touch. touchMoved() runs repeatedly as\nthe user moves any touch points.
\n"],"line":[0,468],"params":[1,[[0,{"name":[0,"event"],"description":[0,"optional TouchEvent
argument.
\n"],"type":[0,"TouchEvent"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle colors when a touch ends.\nfunction touchEnded() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\n\n\n\n\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nlet bgColor = 50;\nlet fillColor = 255;\nlet borderWidth = 0.5;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(bgColor);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n fill(0);\n noStroke();\n\n // Display the number of touch points.\n text(touches.length, 50, 20);\n\n // Style the touch points.\n fill(fillColor);\n stroke(0);\n strokeWeight(borderWidth);\n\n // Display the touch points as circles.\n for (let touch of touches) {\n circle(touch.x, touch.y, 40);\n }\n}\n\n// Set the background color to a random grayscale value.\nfunction touchStarted() {\n bgColor = random(80, 255);\n}\n\n// Set the fill color to a random grayscale value.\nfunction touchEnded() {\n fillColor = random(0, 255);\n}\n\n// Set the stroke weight.\nfunction touchMoved() {\n // Increment the border width.\n borderWidth += 0.1;\n\n // Reset the border width once it's too thick.\n if (borderWidth > 20) {\n borderWidth = 0.5;\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/touchEnded"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/touchMoved.mdx"],"slug":[0,"en/p5/touchmoved"],"body":[0,"\n\n# touchMoved\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"touchMoved()"],"module":[0,"Events"],"submodule":[0,"Touch"],"file":[0,"src/events/touch.js"],"description":[0,"A function that's called when the user touches the screen and moves.
\nDeclaring the function touchMoved()
sets a code block to run\nautomatically when the user touches a touchscreen device and moves:
\nfunction touchMoved() {\n // Code to run.\n}\n
\nThe touches array will be updated with the most\nrecent touch points when touchMoved()
is called by p5.js:
\nfunction touchMoved() {\n // Paint over the background.\n background(200);\n\n // Mark each touch point while the user moves.\n for (let touch of touches) {\n circle(touch.x, touch.y, 40);\n }\n}\n
\nThe parameter, event, is optional. touchMoved()
will be passed a\nTouchEvent\nobject with properties that describe the touch event:
\nfunction touchMoved(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\nOn touchscreen devices, mouseDragged() will\nrun when the user’s touch points move if touchMoved()
isn’t declared. If\ntouchMoved()
is declared, then touchMoved()
will run when a user’s\ntouch points move and mouseDragged() won’t.
\nNote: touchStarted(),\ntouchEnded(), and\ntouchMoved()
are all related.\ntouchStarted() runs as soon as the user\ntouches a touchscreen device. touchEnded()\nruns as soon as the user ends a touch. touchMoved()
runs repeatedly as\nthe user moves any touch points.
\n"],"line":[0,295],"params":[1,[[0,{"name":[0,"event"],"description":[0,"optional TouchEvent argument.
\n"],"type":[0,"TouchEvent"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square becomes lighter when the user touches the screen and moves.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\nfunction touchMoved() {\n // Update the grayscale value.\n value += 5;\n\n // Reset the grayscale value.\n if (value > 255) {\n value = 0;\n }\n}\n
\n\n\n\n\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nlet bgColor = 50;\nlet fillColor = 255;\nlet borderWidth = 0.5;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(bgColor);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n fill(0);\n noStroke();\n\n // Display the number of touch points.\n text(touches.length, 50, 20);\n\n // Style the touch points.\n fill(fillColor);\n stroke(0);\n strokeWeight(borderWidth);\n\n // Display the touch points as circles.\n for (let touch of touches) {\n circle(touch.x, touch.y, 40);\n }\n}\n\n// Set the background color to a random grayscale value.\nfunction touchStarted() {\n bgColor = random(80, 255);\n}\n\n// Set the fill color to a random grayscale value.\nfunction touchEnded() {\n fillColor = random(0, 255);\n}\n\n// Set the stroke weight.\nfunction touchMoved() {\n // Increment the border width.\n borderWidth += 0.1;\n\n // Reset the border width once it's too thick.\n if (borderWidth > 20) {\n borderWidth = 0.5;\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/touchMoved"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/touchStarted.mdx"],"slug":[0,"en/p5/touchstarted"],"body":[0,"\n\n# touchStarted\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"touchStarted()"],"module":[0,"Events"],"submodule":[0,"Touch"],"file":[0,"src/events/touch.js"],"description":[0,"A function that's called once each time the user touches the screen.
\nDeclaring a function called touchStarted()
sets a code block to run\nautomatically each time the user begins touching a touchscreen device:
\nfunction touchStarted() {\n // Code to run.\n}\n
\nThe touches array will be updated with the most\nrecent touch points when touchStarted()
is called by p5.js:
\nfunction touchStarted() {\n // Paint over the background.\n background(200);\n\n // Mark each touch point once with a circle.\n for (let touch of touches) {\n circle(touch.x, touch.y, 40);\n }\n}\n
\nThe parameter, event, is optional. touchStarted()
will be passed a\nTouchEvent\nobject with properties that describe the touch event:
\nfunction touchStarted(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\nOn touchscreen devices, mousePressed() will\nrun when a user’s touch starts if touchStarted()
isn’t declared. If\ntouchStarted()
is declared, then touchStarted()
will run when a user’s\ntouch starts and mousePressed() won’t.
\nNote: touchStarted()
, touchEnded(), and\ntouchMoved() are all related.\ntouchStarted()
runs as soon as the user touches a touchscreen device.\ntouchEnded() runs as soon as the user ends a\ntouch. touchMoved() runs repeatedly as the\nuser moves any touch points.
\n"],"line":[0,125],"params":[1,[[0,{"name":[0,"event"],"description":[0,"optional TouchEvent
argument.
\n"],"type":[0,"TouchEvent"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle colors with each touch.\nfunction touchStarted() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\n\n\n\n\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nlet bgColor = 50;\nlet fillColor = 255;\nlet borderWidth = 0.5;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(bgColor);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n fill(0);\n noStroke();\n\n // Display the number of touch points.\n text(touches.length, 50, 20);\n\n // Style the touch points.\n fill(fillColor);\n stroke(0);\n strokeWeight(borderWidth);\n\n // Display the touch points as circles.\n for (let touch of touches) {\n circle(touch.x, touch.y, 40);\n }\n}\n\n// Set the background color to a random grayscale value.\nfunction touchStarted() {\n bgColor = random(80, 255);\n}\n\n// Set the fill color to a random grayscale value.\nfunction touchEnded() {\n fillColor = random(0, 255);\n}\n\n// Set the stroke weight.\nfunction touchMoved() {\n // Increment the border width.\n borderWidth += 0.1;\n\n // Reset the border width once it's too thick.\n if (borderWidth > 20) {\n borderWidth = 0.5;\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/touchStarted"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/touches.mdx"],"slug":[0,"en/p5/touches"],"body":[0,"\n\n# touches\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"touches"],"module":[0,"Events"],"submodule":[0,"Touch"],"file":[0,"src/events/touch.js"],"description":[0,"An Array
of all the current touch points on a touchscreen device.
\nThe touches
array is empty by default. When the user touches their\nscreen, a new touch point is tracked and added to the array. Touch points\nare Objects
with the following properties:
\n// Iterate over the touches array.\nfor (let touch of touches) {\n // x-coordinate relative to the top-left\n // corner of the canvas.\n console.log(touch.x);\n\n // y-coordinate relative to the top-left\n // corner of the canvas.\n console.log(touch.y);\n\n // x-coordinate relative to the top-left\n // corner of the browser.\n console.log(touch.winX);\n\n // y-coordinate relative to the top-left\n // corner of the browser.\n console.log(touch.winY);\n\n // ID number\n console.log(touch.id);\n}\n
\n"],"line":[0,10],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. White circles appear where the user touches the square.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Draw a circle at each touch point.\n for (let touch of touches) {\n circle(touch.x, touch.y, 40);\n }\n}\n
\n\n\n\n\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. Labels appear where the user touches the square, displaying the coordinates.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Draw a label above each touch point.\n for (let touch of touches) {\n text(`${touch.x}, ${touch.y}`, touch.x, touch.y - 40);\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/touches"]}],"render":[0,null]}]]]}]]]}],[0,{"name":[0,"DOM"],"subcats":[1,[[0,{"name":[0],"entry":[0],"entries":[1,[]]}],[0,{"name":[0],"entry":[0],"entries":[1,[[0,{"id":[0,"en/p5/changed.mdx"],"slug":[0,"en/p5/changed"],"body":[0,"\n\n# changed\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"changed()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Calls a function when the element changes.
\nCalling myElement.changed(false)
disables the function.
\n"],"line":[0,330],"params":[1,[[0,{"name":[0,"fxn"],"description":[0,"function to call when the element changes.\n false
disables the function.
\n"],"type":[0,"Function|Boolean"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n\nlet dropdown;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a dropdown menu and add a few color options.\n dropdown = createSelect();\n dropdown.position(0, 0);\n dropdown.option('red');\n dropdown.option('green');\n dropdown.option('blue');\n\n // Call paintBackground() when the color option changes.\n dropdown.changed(paintBackground);\n\n describe('A gray square with a dropdown menu at the top. The square changes color when an option is selected.');\n}\n\n// Paint the background with the selected color.\nfunction paintBackground() {\n let c = dropdown.value();\n background(c);\n}\n
\n\n\n\n\nlet checkbox;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a checkbox and place it beneath the canvas.\n checkbox = createCheckbox(' circle');\n checkbox.position(0, 100);\n\n // Call repaint() when the checkbox changes.\n checkbox.changed(repaint);\n\n describe('A gray square with a checkbox underneath it that says \"circle\". A white circle appears when the box is checked and disappears otherwise.');\n}\n\n// Paint the background gray and determine whether to draw a circle.\nfunction repaint() {\n background(200);\n if (checkbox.checked() === true) {\n circle(50, 50, 30);\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/changed"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/createA.mdx"],"slug":[0,"en/p5/createa"],"body":[0,"\n\n# createA\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createA()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Creates an
element that links to another web page.
\nThe first parmeter, href
, is a string that sets the URL of the linked\npage.
\nThe second parameter, html
, is a string that sets the inner HTML of the\nlink. It's common to use text, images, or buttons as links.
\nThe third parameter, target
, is optional. It's a string that tells the\nweb browser where to open the link. By default, links open in the current\nbrowser tab. Passing '_blank'
will cause the link to open in a new\nbrowser tab. MDN describes a few\nother options.
\n"],"line":[0,724],"params":[1,[[0,{"name":[0,"href"],"description":[0,"URL of linked page.
\n"],"type":[0,"String"]}],[0,{"name":[0,"html"],"description":[0,"inner HTML of link element to display.
\n"],"type":[0,"String"]}],[0,{"name":[0,"target"],"description":[0,"target where the new link should open,\n either '_blank'
, '_self'
, '_parent'
, or '_top'
.
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.Element object."],"type":[0,"p5.Element"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an anchor element that links to p5js.org.\n let a = createA('http://p5js.org/', 'p5*js');\n a.position(25, 35);\n\n describe('The text \"p5*js\" written at the center of a gray square.');\n}\n
\n\n\n\n\nfunction setup() {\n background(200);\n\n // Create an anchor tag that links to p5js.org.\n // Open the link in a new tab.\n let a = createA('http://p5js.org/', 'p5*js', '_blank');\n a.position(25, 35);\n\n describe('The text \"p5*js\" written at the center of a gray square.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/createA"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/createAudio.mdx"],"slug":[0,"en/p5/createaudio"],"body":[0,"\n\n# createAudio\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createAudio()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Creates a hidden
element for simple audio playback.
\ncreateAudio()
returns a new\np5.MediaElement object.
\nThe first parameter, src
, is the path the video. If a single string is\npassed, as in '/assets/video.mp4'
, a single video is loaded. An array\nof strings can be used to load the same video in different formats. For\nexample, ['/assets/video.mp4', '/assets/video.ogv', '/assets/video.webm']
.\nThis is useful for ensuring that the video can play across different\nbrowsers with different capabilities. See\nMDN\nfor more information about supported formats.
\nThe second parameter, callback
, is optional. It's a function to call once\nthe audio is ready to play.
\n"],"line":[0,2213],"params":[1,[[0,{"name":[0,"src"],"description":[0,"path to an audio file, or an array of paths\n for supporting different browsers.
\n"],"type":[0,"String|String[]"],"optional":[0,true]}],[0,{"name":[0,"callback"],"description":[0,"function to call once the audio is ready to play.
\n"],"type":[0,"Function"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.MediaElement object."],"type":[0,"p5.MediaElement"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n noCanvas();\n\n // Load the audio.\n let beat = createAudio('/assets/beat.mp3');\n\n // Show the default audio controls.\n beat.showControls();\n\n describe('An audio beat plays when the user double-clicks the square.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/createAudio"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/createButton.mdx"],"slug":[0,"en/p5/createbutton"],"body":[0,"\n\n# createButton\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createButton()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Creates a
element.
\nThe first parameter, label
, is a string that sets the label displayed on\nthe button.
\nThe second parameter, value
, is optional. It's a string that sets the\nbutton's value. See\nMDN\nfor more details.
\n"],"line":[0,924],"params":[1,[[0,{"name":[0,"label"],"description":[0,"label displayed on the button.
\n"],"type":[0,"String"]}],[0,{"name":[0,"value"],"description":[0,"value of the button.
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.Element object."],"type":[0,"p5.Element"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a button and place it beneath the canvas.\n let button = createButton('click me');\n button.position(0, 100);\n\n // Call repaint() when the button is pressed.\n button.mousePressed(repaint);\n\n describe('A gray square with a button that says \"click me\" beneath it. The square changes color when the button is clicked.');\n}\n\n// Change the background color.\nfunction repaint() {\n let g = random(255);\n background(g);\n}\n
\n\n\n\n\nlet button;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a button and set its value to 0.\n // Place the button beneath the canvas.\n button = createButton('click me', 'red');\n button.position(0, 100);\n\n // Call randomColor() when the button is pressed.\n button.mousePressed(randomColor);\n\n describe('A red square with a button that says \"click me\" beneath it. The square changes color when the button is clicked.');\n}\n\nfunction draw() {\n // Use the button's value to set the background color.\n let c = button.value();\n background(c);\n}\n\n// Set the button's value to a random color.\nfunction randomColor() {\n let c = random(['red', 'green', 'blue', 'yellow']);\n button.value(c);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/createButton"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/createCapture.mdx"],"slug":[0,"en/p5/createcapture"],"body":[0,"\n\n# createCapture\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createCapture()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Creates a
element that \"captures\" the audio/video stream from\nthe webcam and microphone.
\ncreateCapture()
returns a new\np5.MediaElement object. Videos are shown by\ndefault. They can be hidden by calling capture.hide()
and drawn to the\ncanvas using image().
\nThe first parameter, type
, is optional. It sets the type of capture to\nuse. By default, createCapture()
captures both audio and video. If VIDEO
\nis passed, as in createCapture(VIDEO)
, only video will be captured.\nIf AUDIO
is passed, as in createCapture(AUDIO)
, only audio will be\ncaptured. A constraints object can also be passed to customize the stream.\nSee the \nW3C documentation for possible properties. Different browsers support different\nproperties.
\nThe 'flipped' property is an optional property which can be set to {flipped:true}
\nto mirror the video output.If it is true then it means that video will be mirrored\nor flipped and if nothing is mentioned then by default it will be false
.
\nThe second parameter,callback
, is optional. It's a function to call once\nthe capture is ready for use. The callback function should have one\nparameter, stream
, that's a\nMediaStream object.
\nNote: createCapture()
only works when running a sketch locally or using HTTPS. Learn more\nhere\nand here.
\n"],"line":[0,2295],"params":[1,[[0,{"name":[0,"type"],"description":[0,"type of capture, either AUDIO or VIDEO,\n or a constraints object. Both video and audio\n audio streams are captured by default.
\n"],"type":[0,"String|Constant|Object"],"optional":[0,true]}],[0,{"name":[0,"flipped"],"description":[0,"flip the capturing video and mirror the output with {flipped:true}
. By\n default it is false.
\n"],"type":[0,"Object"],"optional":[0,true]}],[0,{"name":[0,"callback"],"description":[0,"function to call once the stream\n has loaded.
\n"],"type":[0,"Function"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.MediaElement object."],"type":[0,"p5.MediaElement"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n noCanvas();\n\n // Create the video capture.\n createCapture(VIDEO);\n\n describe('A video stream from the webcam.');\n}\n
\n\n\n\n\nlet capture;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create the video capture and hide the element.\n capture = createCapture(VIDEO);\n capture.hide();\n\n describe('A video stream from the webcam with inverted colors.');\n}\n\nfunction draw() {\n // Draw the video capture within the canvas.\n image(capture, 0, 0, width, width * capture.height / capture.width);\n\n // Invert the colors in the stream.\n filter(INVERT);\n}\n
\n\n\n\nlet capture;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create the video capture with mirrored output.\n capture = createCapture(VIDEO,{ flipped:true });\n capture.size(100,100);\n\n describe('A video stream from the webcam with flipped or mirrored output.');\n}\n\n
\n\n\n\n\nfunction setup() {\n createCanvas(480, 120);\n\n // Create a constraints object.\n let constraints = {\n video: {\n mandatory: {\n minWidth: 1280,\n minHeight: 720\n },\n optional: [{ maxFrameRate: 10 }]\n },\n audio: false\n };\n\n // Create the video capture.\n createCapture(constraints);\n\n describe('A video stream from the webcam.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/createCapture"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/createCheckbox.mdx"],"slug":[0,"en/p5/createcheckbox"],"body":[0,"\n\n# createCheckbox\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createCheckbox()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Creates a checkbox
element.
\nCheckboxes extend the p5.Element class with a\nchecked()
method. Calling myBox.checked()
returns true
if it the box\nis checked and false
if not.
\nThe first parameter, label
, is optional. It's a string that sets the label\nto display next to the checkbox.
\nThe second parameter, value
, is also optional. It's a boolean that sets the\ncheckbox's value.
\n"],"line":[0,1008],"params":[1,[[0,{"name":[0,"label"],"description":[0,"label displayed after the checkbox.
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"value"],"description":[0,"value of the checkbox. Checked is true
and unchecked is false
.
\n"],"type":[0,"Boolean"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.Element object."],"type":[0,"p5.Element"]}],"example":[1,[[0,"\n\n\nlet checkbox;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a checkbox and place it beneath the canvas.\n checkbox = createCheckbox();\n checkbox.position(0, 100);\n\n describe('A black square with a checkbox beneath it. The square turns white when the box is checked.');\n}\n\nfunction draw() {\n // Use the checkbox to set the background color.\n if (checkbox.checked()) {\n background(255);\n } else {\n background(0);\n }\n}\n
\n\n\n\n\nlet checkbox;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a checkbox and place it beneath the canvas.\n // Label the checkbox \"white\".\n checkbox = createCheckbox(' white');\n checkbox.position(0, 100);\n\n describe('A black square with a checkbox labeled \"white\" beneath it. The square turns white when the box is checked.');\n}\n\nfunction draw() {\n // Use the checkbox to set the background color.\n if (checkbox.checked()) {\n background(255);\n } else {\n background(0);\n }\n}\n
\n\n\n\n\nlet checkbox;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a checkbox and place it beneath the canvas.\n // Label the checkbox \"white\" and set its value to true.\n checkbox = createCheckbox(' white', true);\n checkbox.position(0, 100);\n\n describe('A white square with a checkbox labeled \"white\" beneath it. The square turns black when the box is unchecked.');\n}\n\nfunction draw() {\n // Use the checkbox to set the background color.\n if (checkbox.checked()) {\n background(255);\n } else {\n background(0);\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/createCheckbox"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/createColorPicker.mdx"],"slug":[0,"en/p5/createcolorpicker"],"body":[0,"\n\n# createColorPicker\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createColorPicker()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Creates a color picker element.
\nThe parameter, value
, is optional. If a color string or\np5.Color object is passed, it will set the default\ncolor.
\nColor pickers extend the p5.Element class with a\ncouple of helpful methods for managing colors:
\n\nmyPicker.value()
returns the current color as a hex string in the format '#rrggbb'
. \nmyPicker.color()
returns the current color as a p5.Color object. \n
\n"],"line":[0,1759],"params":[1,[[0,{"name":[0,"value"],"description":[0,"default color as a CSS color string.
\n"],"type":[0,"String|p5.Color"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.Element object."],"type":[0,"p5.Element"]}],"example":[1,[[0,"\n\n\nlet myPicker;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a color picker and set its position.\n myPicker = createColorPicker('deeppink');\n myPicker.position(0, 100);\n\n describe('A pink square with a color picker beneath it. The square changes color when the user picks a new color.');\n}\n\nfunction draw() {\n // Use the color picker to paint the background.\n let c = myPicker.color();\n background(c);\n}\n
\n\n\n\n\nlet myPicker;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a color picker and set its position.\n myPicker = createColorPicker('deeppink');\n myPicker.position(0, 100);\n\n 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.');\n}\n\nfunction draw() {\n // Use the color picker to paint the background.\n let c = myPicker.value();\n background(c);\n\n // Display the current color as a hex string.\n text(c, 25, 55);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/createColorPicker"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/createDiv.mdx"],"slug":[0,"en/p5/creatediv"],"body":[0,"\n\n# createDiv\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createDiv()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Creates a
element.
\n
elements are commonly used as containers for\nother elements.
\nThe parameter html
is optional. It accepts a string that sets the\ninner HTML of the new
.
\n"],"line":[0,491],"params":[1,[[0,{"name":[0,"html"],"description":[0,"inner HTML for the new <div></div>
element.
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.Element object."],"type":[0,"p5.Element"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a div element and set its position.\n let div = createDiv('p5*js');\n div.position(25, 35);\n\n describe('A gray square with the text \"p5*js\" written in its center.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an h3 element within the div.\n let div = createDiv('p5*js
');\n div.position(20, 5);\n\n describe('A gray square with the text \"p5*js\" written in its center.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/createDiv"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/createElement.mdx"],"slug":[0,"en/p5/createelement"],"body":[0,"\n\n# createElement\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createElement()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Creates a new p5.Element object.
\nThe first parameter, tag
, is a string an HTML tag such as 'h5'
.
\nThe second parameter, content
, is optional. It's a string that sets the\nHTML content to insert into the new element. New elements have no content\nby default.
\n"],"line":[0,2493],"params":[1,[[0,{"name":[0,"tag"],"description":[0,"tag for the new element.
\n"],"type":[0,"String"]}],[0,{"name":[0,"content"],"description":[0,"HTML content to insert into the element.
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.Element object."],"type":[0,"p5.Element"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an h5 element with nothing in it.\n createElement('h5');\n\n describe('A gray square.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an h5 element with the content \"p5*js\".\n let h5 = createElement('h5', 'p5*js');\n\n // Set the element's style and position.\n h5.style('color', 'deeppink');\n h5.position(30, 15);\n\n describe('The text \"p5*js\" written in pink in the middle of a gray square.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/createElement"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/createFileInput.mdx"],"slug":[0,"en/p5/createfileinput"],"body":[0,"\n\n# createFileInput\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createFileInput()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Creates an
element of type 'file'
.
\ncreateFileInput()
allows users to select local files for use in a sketch.\nIt returns a p5.File object.
\nThe first parameter, callback
, is a function that's called when the file\nloads. The callback function should have one parameter, file
, that's a\np5.File object.
\nThe second parameter, multiple
, is optional. It's a boolean value that\nallows loading multiple files if set to true
. If true
, callback
\nwill be called once per file.
\n"],"line":[0,1942],"params":[1,[[0,{"name":[0,"callback"],"description":[0,"function to call once the file loads.
\n"],"type":[0,"Function"]}],[0,{"name":[0,"multiple"],"description":[0,"allow multiple files to be selected.
\n"],"type":[0,"Boolean"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.File object."],"type":[0,"p5.File"]}],"example":[1,[[0,"\n\n\n// Use the file input to select an image to\n// load and display.\nlet input;\nlet img;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a file input and place it beneath\n // the canvas.\n input = createFileInput(handleImage);\n input.position(0, 100);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw the image if loaded.\n if (img) {\n image(img, 0, 0, width, height);\n }\n}\n\n// Create an image if the file is an image.\nfunction handleImage(file) {\n if (file.type === 'image') {\n img = createImg(file.data, '');\n img.hide();\n } else {\n img = null;\n }\n}\n
\n\n\n\n\n// Use the file input to select multiple images\n// to load and display.\nlet input;\nlet images = [];\n\nfunction setup() {\n // Create a file input and place it beneath\n // the canvas. Allow it to load multiple files.\n input = createFileInput(handleImage, true);\n input.position(0, 100);\n}\n\nfunction draw() {\n background(200);\n\n // Draw the images if loaded. Each image\n // is drawn 20 pixels lower than the\n // previous image.\n for (let i = 0; i < images.length; i += 1) {\n // Calculate the y-coordinate.\n let y = i * 20;\n\n // Draw the image.\n image(img, 0, y, 100, 100);\n }\n\n 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.');\n}\n\n// Create an image if the file is an image,\n// then add it to the images array.\nfunction handleImage(file) {\n if (file.type === 'image') {\n let img = createImg(file.data, '');\n img.hide();\n images.push(img);\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/createFileInput"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/createImg.mdx"],"slug":[0,"en/p5/createimg"],"body":[0,"\n\n# createImg\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createImg()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Creates an ![]()
element that can appear outside of the canvas.
\nThe first parameter, src
, is a string with the path to the image file.\nsrc
should be a relative path, as in '/assets/image.png'
, or a URL, as\nin 'https://example.com/image.png'
.
\nThe second parameter, alt
, is a string with the\nalternate text\nfor the image. An empty string ''
can be used for images that aren't displayed.
\nThe third parameter, crossOrigin
, is optional. It's a string that sets the\ncrossOrigin property\nof the image. Use 'anonymous'
or 'use-credentials'
to fetch the image\nwith cross-origin access.
\nThe fourth parameter, callback
, is also optional. It sets a function to\ncall after the image loads. The new image is passed to the callback\nfunction as a p5.Element object.
\n"],"line":[0,649],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"src"],"description":[0,"relative path or URL for the image.
\n"],"type":[0,"String"]}],[0,{"name":[0,"alt"],"description":[0,"alternate text for the image.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"src"],"description":[0,""],"type":[0,"String"]}],[0,{"name":[0,"alt"],"description":[0,""],"type":[0,"String"]}],[0,{"name":[0,"crossOrigin"],"description":[0,"crossOrigin property to use when fetching the image.
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"successCallback"],"description":[0,"function to call once the image loads. The new image will be passed\n to the function as a p5.Element object.
\n"],"type":[0,"Function"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.Element object."],"type":[0,"p5.Element"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n let img = createImg(\n 'https://p5js.org//assets/img/asterisk-01.png',\n 'The p5.js magenta asterisk.'\n );\n img.position(0, -10);\n\n describe('A gray square with a magenta asterisk in its center.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/createImg"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/createInput.mdx"],"slug":[0,"en/p5/createinput"],"body":[0,"\n\n# createInput\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createInput()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Creates a text
element.
\nCall myInput.size()
to set the length of the text box.
\nThe first parameter, value
, is optional. It's a string that sets the\ninput's default value. The input is blank by default.
\nThe second parameter, type
, is also optional. It's a string that\nspecifies the type of text being input. See MDN for a full\nlist of options.\nThe default is 'text'
.
\n"],"line":[0,1859],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"value"],"description":[0,"default value of the input box. Defaults to an empty string ''
.
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"type"],"description":[0,"type of input. Defaults to 'text'
.
\n"],"type":[0,"String"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"value"],"description":[0,""],"type":[0,"String"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.Element object."],"type":[0,"p5.Element"]}],"example":[1,[[0,"\n\n\nlet myInput;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create an input element and place it\n // beneath the canvas.\n myInput = createInput();\n myInput.position(0, 100);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Use the input to display a message.\n let msg = myInput.value();\n text(msg, 25, 55);\n}\n
\n\n\n\n\nlet myInput;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create an input element and place it\n // beneath the canvas. Set its default\n // text to \"hello!\".\n myInput = createInput('hello!');\n myInput.position(0, 100);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Use the input to display a message.\n let msg = myInput.value();\n text(msg, 25, 55);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/createInput"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/createP.mdx"],"slug":[0,"en/p5/createp"],"body":[0,"\n\n# createP\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createP()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Creates a
element.
\n
elements are commonly used for paragraph-length text.
\nThe parameter html
is optional. It accepts a string that sets the\ninner HTML of the new
.
\n"],"line":[0,543],"params":[1,[[0,{"name":[0,"html"],"description":[0,"inner HTML for the new <p></p>
element.
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.Element object."],"type":[0,"p5.Element"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element and set its position.\n let p = createP('Tell me a story.');\n p.position(5, 0);\n\n describe('A gray square displaying the text \"Tell me a story.\" written in black.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/createP"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/createRadio.mdx"],"slug":[0,"en/p5/createradio"],"body":[0,"\n\n# createRadio\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createRadio()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Creates a radio button element.
\nThe parameter is optional. If a string is passed, as in\nlet myRadio = createSelect('food')
, then each radio option will\nhave \"food\"
as its name
parameter:
.\nIf an existing
or
\nelement is passed, as in let myRadio = createSelect(container)
, it will\nbecome the radio button's parent element.
\nRadio buttons extend the p5.Element class with a few\nhelpful methods for managing options:
\n\nmyRadio.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. \nmyRadio.value()
returns the currently-selected option's value. \nmyRadio.selected()
returns the currently-selected option. \nmyRadio.selected(value)
selects the given option and returns it as an HTMLInputElement
. \nmyRadio.disable(shouldDisable)
Disables the radio button if true
is passed, and enables it if false
is passed. \n
\n"],"line":[0,1440],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"containerElement"],"description":[0,"container HTML Element, either a <div></div>
\nor <span></span>
.
\n"],"type":[0,"Object"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"name"],"description":[0,"name parameter assigned to each option's <input></input>
element.
\n"],"type":[0,"String"],"optional":[0,true]}]]]}],[0,{"params":[1,[]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.Element object."],"type":[0,"p5.Element"]}],"example":[1,[[0,"\n\n\nlet style = document.createElement('style');\nstyle.innerHTML = `\n.p5-radio label {\n display: flex;\n align-items: center;\n }\n .p5-radio input {\n margin-right: 5px;\n }\n `;\ndocument.head.appendChild(style);\n\nlet myRadio;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a radio button element and place it\n // in the top-left corner.\n myRadio = createRadio();\n myRadio.position(0, 0);\n myRadio.class('p5-radio');\n myRadio.size(60);\n\n // Add a few color options.\n myRadio.option('red');\n myRadio.option('yellow');\n myRadio.option('blue');\n\n // Choose a default option.\n myRadio.selected('yellow');\n\n describe('A yellow square with three color options listed, \"red\", \"yellow\", and \"blue\". The square changes color when the user selects a new option.');\n}\n\nfunction draw() {\n // Set the background color using the radio button.\n let g = myRadio.value();\n background(g);\n}\n
\n\n\n\n\nlet myRadio;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a radio button element and place it\n // in the top-left corner.\n myRadio = createRadio();\n myRadio.position(0, 0);\n myRadio.size(50);\n\n // Add a few color options.\n // Color values are labeled with\n // emotions they evoke.\n myRadio.option('red', 'love');\n myRadio.option('yellow', 'joy');\n myRadio.option('blue', 'trust');\n\n // Choose a default option.\n myRadio.selected('yellow');\n\n describe('A yellow square with three options listed, \"love\", \"joy\", and \"trust\". The square changes color when the user selects a new option.');\n}\n\nfunction draw() {\n // Set the background color using the radio button.\n let c = myRadio.value();\n background(c);\n}\n
\n\n\n\n\nlet myRadio;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a radio button element and place it\n // in the top-left corner.\n myRadio = createRadio();\n myRadio.position(0, 0);\n myRadio.class('p5-radio');\n myRadio.size(50);\n\n // Add a few color options.\n myRadio.option('red');\n myRadio.option('yellow');\n myRadio.option('blue');\n\n // Choose a default option.\n myRadio.selected('yellow');\n\n // Create a button and place it beneath the canvas.\n let btn = createButton('disable');\n btn.position(0, 100);\n\n // Call disableRadio() when btn is pressed.\n btn.mousePressed(disableRadio);\n\n 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.');\n}\n\nfunction draw() {\n // Set the background color using the radio button.\n let c = myRadio.value();\n background(c);\n}\n\n// Disable myRadio.\nfunction disableRadio() {\n myRadio.disable(true);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/createRadio"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/createSelect.mdx"],"slug":[0,"en/p5/createselect"],"body":[0,"\n\n# createSelect\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createSelect()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Creates a dropdown menu
element.
\nThe parameter is optional. If true
is passed, as in\nlet mySelect = createSelect(true)
, then the dropdown will support\nmultiple selections. If an existing
element\nis passed, as in let mySelect = createSelect(otherSelect)
, the existing\nelement will be wrapped in a new p5.Element\nobject.
\nDropdowns extend the p5.Element class with a few\nhelpful methods for managing options:
\n\nmySelect.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
. \nmySelect.value()
returns the currently-selected option's value. \nmySelect.selected()
returns the currently-selected option. \nmySelect.selected(option)
selects the given option by default. \nmySelect.disable()
marks the whole dropdown element as disabled. \nmySelect.disable(option)
marks a given option as disabled. \nmySelect.enable()
marks the whole dropdown element as enabled. \nmySelect.enable(option)
marks a given option as enabled. \n
\n"],"line":[0,1159],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"multiple"],"description":[0,"support multiple selections.
\n"],"type":[0,"Boolean"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"existing"],"description":[0,"select element to wrap, either as a p5.Element or\n a HTMLSelectElement.
\n"],"type":[0,"Object"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.Element object."],"type":[0,"p5.Element"]}],"example":[1,[[0,"\n\n\nlet mySelect;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a dropdown and place it beneath the canvas.\n mySelect = createSelect();\n mySelect.position(0, 100);\n\n // Add color options.\n mySelect.option('red');\n mySelect.option('green');\n mySelect.option('blue');\n mySelect.option('yellow');\n\n // Set the selected option to \"red\".\n mySelect.selected('red');\n\n describe('A red square with a dropdown menu beneath it. The square changes color when a new color is selected.');\n}\n\nfunction draw() {\n // Use the selected value to paint the background.\n let c = mySelect.selected();\n background(c);\n}\n
\n\n\n\n\nlet mySelect;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a dropdown and place it beneath the canvas.\n mySelect = createSelect();\n mySelect.position(0, 100);\n\n // Add color options.\n mySelect.option('red');\n mySelect.option('green');\n mySelect.option('blue');\n mySelect.option('yellow');\n\n // Set the selected option to \"red\".\n mySelect.selected('red');\n\n // Disable the \"yellow\" option.\n mySelect.disable('yellow');\n\n describe('A red square with a dropdown menu beneath it. The square changes color when a new color is selected.');\n}\n\nfunction draw() {\n // Use the selected value to paint the background.\n let c = mySelect.selected();\n background(c);\n}\n
\n\n\n\n\nlet mySelect;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a dropdown and place it beneath the canvas.\n mySelect = createSelect();\n mySelect.position(0, 100);\n\n // Add color options with names and values.\n mySelect.option('one', 'red');\n mySelect.option('two', 'green');\n mySelect.option('three', 'blue');\n mySelect.option('four', 'yellow');\n\n // Set the selected option to \"one\".\n mySelect.selected('one');\n\n describe('A red square with a dropdown menu beneath it. The square changes color when a new color is selected.');\n}\n\nfunction draw() {\n // Use the selected value to paint the background.\n let c = mySelect.selected();\n background(c);\n}\n
\n\n\n\n\n// Hold CTRL to select multiple options on Windows and Linux.\n// Hold CMD to select multiple options on macOS.\nlet mySelect;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a dropdown and allow multiple selections.\n // Place it beneath the canvas.\n mySelect = createSelect(true);\n mySelect.position(0, 100);\n\n // Add color options.\n mySelect.option('red');\n mySelect.option('green');\n mySelect.option('blue');\n mySelect.option('yellow');\n\n describe('A gray square with a dropdown menu beneath it. Colorful circles appear when their color is selected.');\n}\n\nfunction draw() {\n background(200);\n\n // Use the selected value(s) to draw circles.\n let colors = mySelect.selected();\n for (let i = 0; i < colors.length; i += 1) {\n // Calculate the x-coordinate.\n let x = 10 + i * 20;\n\n // Access the color.\n let c = colors[i];\n\n // Draw the circle.\n fill(c);\n circle(x, 50, 20);\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/createSelect"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/createSlider.mdx"],"slug":[0,"en/p5/createslider"],"body":[0,"\n\n# createSlider\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createSlider()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Creates a slider
element.
\nRange sliders are useful for quickly selecting numbers from a given range.
\nThe first two parameters, min
and max
, are numbers that set the\nslider's minimum and maximum.
\nThe third parameter, value
, is optional. It's a number that sets the\nslider's default value.
\nThe fourth parameter, step
, is also optional. It's a number that sets the\nspacing between each value in the slider's range. Setting step
to 0\nallows the slider to move smoothly from min
to max
.
\n"],"line":[0,789],"params":[1,[[0,{"name":[0,"min"],"description":[0,"minimum value of the slider.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"max"],"description":[0,"maximum value of the slider.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"value"],"description":[0,"default value of the slider.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"step"],"description":[0,"size for each step in the slider's range.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.Element object."],"type":[0,"p5.Element"]}],"example":[1,[[0,"\n\n\nlet slider;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a slider and place it at the top of the canvas.\n slider = createSlider(0, 255);\n slider.position(10, 10);\n slider.size(80);\n\n describe('A dark gray square with a range slider at the top. The square changes color when the slider is moved.');\n}\n\nfunction draw() {\n // Use the slider as a grayscale value.\n let g = slider.value();\n background(g);\n}\n
\n\n\n\n\nlet slider;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a slider and place it at the top of the canvas.\n // Set its default value to 0.\n slider = createSlider(0, 255, 0);\n slider.position(10, 10);\n slider.size(80);\n\n describe('A black square with a range slider at the top. The square changes color when the slider is moved.');\n}\n\nfunction draw() {\n // Use the slider as a grayscale value.\n let g = slider.value();\n background(g);\n}\n
\n\n\n\n\nlet slider;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a slider and place it at the top of the canvas.\n // Set its default value to 0.\n // Set its step size to 50.\n slider = createSlider(0, 255, 0, 50);\n slider.position(10, 10);\n slider.size(80);\n\n describe('A black square with a range slider at the top. The square changes color when the slider is moved.');\n}\n\nfunction draw() {\n // Use the slider as a grayscale value.\n let g = slider.value();\n background(g);\n}\n
\n\n\n\n\nlet slider;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a slider and place it at the top of the canvas.\n // Set its default value to 0.\n // Set its step size to 0 so that it moves smoothly.\n slider = createSlider(0, 255, 0, 0);\n slider.position(10, 10);\n slider.size(80);\n\n describe('A black square with a range slider at the top. The square changes color when the slider is moved.');\n}\n\nfunction draw() {\n // Use the slider as a grayscale value.\n let g = slider.value();\n background(g);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/createSlider"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/createSpan.mdx"],"slug":[0,"en/p5/createspan"],"body":[0,"\n\n# createSpan\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createSpan()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Creates a
element.
\n
elements are commonly used as containers\nfor inline elements. For example, a
\ncan hold part of a sentence that's a\ndifferent style.
\nThe parameter html
is optional. It accepts a string that sets the\ninner HTML of the new
.
\n"],"line":[0,578],"params":[1,[[0,{"name":[0,"html"],"description":[0,"inner HTML for the new <span></span>
element.
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.Element object."],"type":[0,"p5.Element"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a span element and set its position.\n let span = createSpan('p5*js');\n span.position(25, 35);\n\n describe('A gray square with the text \"p5*js\" written in its center.');\n}\n
\n\n\n\n\nfunction setup() {\n background(200);\n\n // Create a div element as a container.\n let div = createDiv();\n\n // Place the div at the center.\n div.position(25, 35);\n\n // Create a span element.\n let s1 = createSpan('p5');\n\n // Create a second span element.\n let s2 = createSpan('*');\n\n // Set the second span's font color.\n s2.style('color', 'deeppink');\n\n // Create a third span element.\n let s3 = createSpan('js');\n\n // Add all the spans to the container div.\n s1.parent(div);\n s2.parent(div);\n s3.parent(div);\n\n describe('A gray square with the text \"p5*js\" written in black at its center. The asterisk is pink.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/createSpan"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/createVideo.mdx"],"slug":[0,"en/p5/createvideo"],"body":[0,"\n\n# createVideo\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"createVideo()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Creates a
element for simple audio/video playback.
\ncreateVideo()
returns a new\np5.MediaElement object. Videos are shown by\ndefault. They can be hidden by calling video.hide()
and drawn to the\ncanvas using image().
\nThe first parameter, src
, is the path the video. If a single string is\npassed, as in '/assets/topsecret.mp4'
, a single video is loaded. An array\nof strings can be used to load the same video in different formats. For\nexample, ['/assets/topsecret.mp4', '/assets/topsecret.ogv', '/assets/topsecret.webm']
.\nThis is useful for ensuring that the video can play across different browsers with\ndifferent capabilities. See\nMDN\nfor more information about supported formats.
\nThe second parameter, callback
, is optional. It's a function to call once\nthe video is ready to play.
\n"],"line":[0,2115],"params":[1,[[0,{"name":[0,"src"],"description":[0,"path to a video file, or an array of paths for\n supporting different browsers.
\n"],"type":[0,"String|String[]"]}],[0,{"name":[0,"callback"],"description":[0,"function to call once the video is ready to play.
\n"],"type":[0,"Function"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new p5.MediaElement object."],"type":[0,"p5.MediaElement"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n noCanvas();\n\n // Load a video and add it to the page.\n // Note: this may not work in some browsers.\n let video = createVideo('/assets/small.mp4');\n\n // Show the default video controls.\n video.showControls();\n\n describe('A video of a toy robot with playback controls beneath it.');\n}\n
\n\n\n\n\nfunction setup() {\n noCanvas();\n\n // Load a video and add it to the page.\n // Provide an array options for different file formats.\n let video = createVideo(\n ['/assets/small.mp4', '/assets/small.ogv', '/assets/small.webm']\n );\n\n // Show the default video controls.\n video.showControls();\n\n describe('A video of a toy robot with playback controls beneath it.');\n}\n
\n\n\n\n\nlet video;\n\nfunction setup() {\n noCanvas();\n\n // Load a video and add it to the page.\n // Provide an array options for different file formats.\n // Call mute() once the video loads.\n video = createVideo(\n ['/assets/small.mp4', '/assets/small.ogv', '/assets/small.webm'],\n muteVideo\n );\n\n // Show the default video controls.\n video.showControls();\n\n describe('A video of a toy robot with playback controls beneath it.');\n}\n\n// Mute the video once it loads.\nfunction muteVideo() {\n video.volume(0);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/createVideo"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/input.mdx"],"slug":[0,"en/p5/input"],"body":[0,"\n\n# input\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"input()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Calls a function when the element receives input.
\nmyElement.input()
is often used to with text inputs and sliders. Calling\nmyElement.input(false)
disables the function.
\n"],"line":[0,405],"params":[1,[[0,{"name":[0,"fxn"],"description":[0,"function to call when input is detected within\n the element.\n false
disables the function.
\n"],"type":[0,"Function|Boolean"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n\nlet slider;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a slider and place it beneath the canvas.\n slider = createSlider(0, 255, 200);\n slider.position(0, 100);\n\n // Call repaint() when the slider changes.\n slider.input(repaint);\n\n describe('A gray square with a range slider underneath it. The background changes shades of gray when the slider is moved.');\n}\n\n// Paint the background using slider's value.\nfunction repaint() {\n let g = slider.value();\n background(g);\n}\n
\n\n\n\n\nlet input;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an input and place it beneath the canvas.\n input = createInput('');\n input.position(0, 100);\n\n // Call repaint() when input is detected.\n input.input(repaint);\n\n describe('A gray square with a text input bar beneath it. Any text written in the input appears in the middle of the square.');\n}\n\n// Paint the background gray and display the input's value.\nfunction repaint() {\n background(200);\n let msg = input.value();\n text(msg, 5, 50);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/input"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/removeElements.mdx"],"slug":[0,"en/p5/removeelements"],"body":[0,"\n\n# removeElements\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"removeElements()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Removes all elements created by p5.js, including any event handlers.
\nThere are two exceptions:\ncanvas elements created by createCanvas()\nand p5.Render objects created by\ncreateGraphics().
\n"],"line":[0,256],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element and place\n // it in the middle of the canvas.\n let p = createP('p5*js');\n p.position(25, 25);\n\n describe('A gray square with the text \"p5*js\" written in its center. The text disappears when the mouse is pressed.');\n}\n\n// Remove all elements when the mouse is pressed.\nfunction mousePressed() {\n removeElements();\n}\n
\n\n\n\n\nlet slider;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a paragraph element and place\n // it at the top of the canvas.\n let p = createP('p5*js');\n p.position(25, 25);\n\n // Create a slider element and place it\n // beneath the canvas.\n slider = createSlider(0, 255, 200);\n slider.position(0, 100);\n\n 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.');\n}\n\nfunction draw() {\n // Use the slider value to change the background color.\n let g = slider.value();\n background(g);\n}\n\n// Remove all elements when the mouse is double-clicked.\nfunction doubleClicked() {\n removeElements();\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/removeElements"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/select.mdx"],"slug":[0,"en/p5/select"],"body":[0,"\n\n# select\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"select()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Searches the page for the first element that matches the given\nCSS selector string.
\nThe selector string can be an ID, class, tag name, or a combination.\nselect()
returns a p5.Element object if it\nfinds a match and null
if not.
\nThe second parameter, container
, is optional. It specifies a container to\nsearch within. container
can be CSS selector string, a\np5.Element object, or an\nHTMLElement object.
\n"],"line":[0,21],"params":[1,[[0,{"name":[0,"selectors"],"description":[0,"CSS selector string of element to search for.
\n"],"type":[0,"String"]}],[0,{"name":[0,"container"],"description":[0,"CSS selector string, p5.Element, or\n HTMLElement to search within.
\n"],"type":[0,"String|p5.Element|HTMLElement"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"p5.Element containing the element."],"type":[0,"p5.Element|null"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n\n // Select the canvas by its tag.\n let cnv = select('canvas');\n cnv.style('border', '5px deeppink dashed');\n\n describe('A gray square with a dashed pink border.');\n}\n
\n\n\n\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n // Add a class attribute to the canvas.\n cnv.class('pinkborder');\n\n background(200);\n\n // Select the canvas by its class.\n cnv = select('.pinkborder');\n\n // Style its border.\n cnv.style('border', '5px deeppink dashed');\n\n describe('A gray square with a dashed pink border.');\n}\n
\n\n\n\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n // Set the canvas' ID.\n cnv.id('mycanvas');\n\n background(200);\n\n // Select the canvas by its ID.\n cnv = select('#mycanvas');\n\n // Style its border.\n cnv.style('border', '5px deeppink dashed');\n\n describe('A gray square with a dashed pink border.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/select"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/selectAll.mdx"],"slug":[0,"en/p5/selectall"],"body":[0,"\n\n# selectAll\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"selectAll()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Searches the page for all elements that matches the given\nCSS selector string.
\nThe selector string can be an ID, class, tag name, or a combination.\nselectAll()
returns an array of p5.Element\nobjects if it finds any matches and an empty array if none are found.
\nThe second parameter, container
, is optional. It specifies a container to\nsearch within. container
can be CSS selector string, a\np5.Element object, or an\nHTMLElement object.
\n"],"line":[0,109],"params":[1,[[0,{"name":[0,"selectors"],"description":[0,"CSS selector string of element to search for.
\n"],"type":[0,"String"]}],[0,{"name":[0,"container"],"description":[0,"CSS selector string, p5.Element, or\n HTMLElement to search within.
\n"],"type":[0,"String|p5.Element|HTMLElement"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"array of p5.Elements containing any elements found."],"type":[0,"p5.Element[]"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create three buttons.\n createButton('1');\n createButton('2');\n createButton('3');\n\n // Select the buttons by their tag.\n let buttons = selectAll('button');\n\n // Position the buttons.\n for (let i = 0; i < 3; i += 1) {\n buttons[i].position(0, i * 30);\n }\n\n describe('Three buttons stacked vertically. The buttons are labeled, \"1\", \"2\", and \"3\".');\n}\n
\n\n\n\n\nfunction setup() {\n // Create three buttons and position them.\n let b1 = createButton('1');\n b1.position(0, 0);\n let b2 = createButton('2');\n b2.position(0, 30);\n let b3 = createButton('3');\n b3.position(0, 60);\n\n // Add a class attribute to each button.\n b1.class('btn');\n b2.class('btn btn-pink');\n b3.class('btn');\n\n // Select the buttons by their class.\n let buttons = selectAll('.btn');\n let pinkButtons = selectAll('.btn-pink');\n\n // Style the selected buttons.\n buttons.forEach(setFont);\n pinkButtons.forEach(setColor);\n\n describe('Three buttons stacked vertically. The buttons are labeled, \"1\", \"2\", and \"3\". Buttons \"1\" and \"3\" are gray. Button \"2\" is pink.');\n}\n\n// Set a button's font to Comic Sans MS.\nfunction setFont(btn) {\n btn.style('font-family', 'Comic Sans MS');\n}\n\n// Set a button's background and font color.\nfunction setColor(btn) {\n btn.style('background', 'deeppink');\n btn.style('color', 'white');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5/selectAll"]}],"render":[0,null]}]]]}],[0,{"name":[0,"p5.Element"],"entry":[0,{"id":[0,"en/p5/p5.Element.mdx"],"slug":[0,"en/p5/p5element"],"body":[0,"\n\n# p5.Element\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"p5.Element"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/core/p5.Element.js"],"description":[0,"A class to describe an\nHTML element.
\nSketches can use many elements. Common elements include the drawing canvas,\nbuttons, sliders, webcam feeds, and so on.
\nAll elements share the methods of the p5.Element
class. They're created\nwith functions such as createCanvas() and\ncreateButton().
\n"],"line":[0,9],"params":[1,[[0,{"name":[0,"elt"],"description":[0,"wrapped DOM element.
\n"],"type":[0,"HTMLElement"]}],[0,{"name":[0,"pInst"],"description":[0,"pointer to p5 instance.
\n"],"type":[0,"P5"],"optional":[0,true]}]]],"chainable":[0,false],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a button element and\n // place it beneath the canvas.\n let btn = createButton('change');\n btn.position(0, 100);\n\n // Call randomColor() when\n // the button is pressed.\n btn.mousePressed(randomColor);\n\n describe('A gray square with a button that says \"change\" beneath it. The square changes color when the user presses the button.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\n"]]],"methods":[0,{"parent":[0,{"description":[0,"Attaches the element to a parent element.
\nFor example, a
element may be used as a box to\nhold two pieces of text, a header and a paragraph. The\n
is the parent element of both the header and\nparagraph.
\nThe parameter parent
can have one of three types. parent
can be a\nstring with the parent element's ID, as in\nmyElement.parent('container')
. It can also be another\np5.Element object, as in\nmyElement.parent(myDiv)
. Finally, parent
can be an HTMLElement
\nobject, as in myElement.parent(anotherElement)
.
\nCalling myElement.parent()
without an argument returns the element's\nparent.
\n"],"path":[0,"p5.Element/parent"]}],"id":[0,{"description":[0,"Sets the element's ID using a given string.
\nCalling myElement.id()
without an argument returns its ID as a string.
\n"],"path":[0,"p5.Element/id"]}],"class":[0,{"description":[0,"Adds a\nclass attribute\nto the element using a given string.
\nCalling myElement.class()
without an argument returns a string with its current classes.
\n"],"path":[0,"p5.Element/class"]}],"mousePressed":[0,{"description":[0,"Calls a function when the mouse is pressed over the element.
\nCalling myElement.mousePressed(false)
disables the function.
\nNote: Some mobile browsers may also trigger this event when the element\nreceives a quick tap.
\n"],"path":[0,"p5.Element/mousePressed"]}],"doubleClicked":[0,{"description":[0,"Calls a function when the mouse is pressed twice over the element.
\nCalling myElement.doubleClicked(false)
disables the function.
\n"],"path":[0,"p5.Element/doubleClicked"]}],"mouseWheel":[0,{"description":[0,"Calls a function when the mouse wheel scrolls over the element.
\nThe callback function, fxn
, is passed an event
object. event
has\ntwo numeric properties, deltaY
and deltaX
. event.deltaY
is\nnegative if the mouse wheel rotates away from the user. It's positive if\nthe mouse wheel rotates toward the user. event.deltaX
is positive if\nthe mouse wheel moves to the right. It's negative if the mouse wheel moves\nto the left.
\nCalling myElement.mouseWheel(false)
disables the function.
\n"],"path":[0,"p5.Element/mouseWheel"]}],"mouseReleased":[0,{"description":[0,"Calls a function when the mouse is released over the element.
\nCalling myElement.mouseReleased(false)
disables the function.
\nNote: Some mobile browsers may also trigger this event when the element\nreceives a quick tap.
\n"],"path":[0,"p5.Element/mouseReleased"]}],"mouseClicked":[0,{"description":[0,"Calls a function when the mouse is pressed and released over the element.
\nCalling myElement.mouseReleased(false)
disables the function.
\nNote: Some mobile browsers may also trigger this event when the element\nreceives a quick tap.
\n"],"path":[0,"p5.Element/mouseClicked"]}],"mouseMoved":[0,{"description":[0,"Calls a function when the mouse moves over the element.
\nCalling myElement.mouseMoved(false)
disables the function.
\n"],"path":[0,"p5.Element/mouseMoved"]}],"mouseOver":[0,{"description":[0,"Calls a function when the mouse moves onto the element.
\nCalling myElement.mouseOver(false)
disables the function.
\n"],"path":[0,"p5.Element/mouseOver"]}],"mouseOut":[0,{"description":[0,"Calls a function when the mouse moves off the element.
\nCalling myElement.mouseOut(false)
disables the function.
\n"],"path":[0,"p5.Element/mouseOut"]}],"touchStarted":[0,{"description":[0,"Calls a function when the element is touched.
\nCalling myElement.touchStarted(false)
disables the function.
\nNote: Touch functions only work on mobile devices.
\n"],"path":[0,"p5.Element/touchStarted"]}],"touchMoved":[0,{"description":[0,"Calls a function when the user touches the element and moves.
\nCalling myElement.touchMoved(false)
disables the function.
\nNote: Touch functions only work on mobile devices.
\n"],"path":[0,"p5.Element/touchMoved"]}],"touchEnded":[0,{"description":[0,"Calls a function when the user stops touching the element.
\nCalling myElement.touchMoved(false)
disables the function.
\nNote: Touch functions only work on mobile devices.
\n"],"path":[0,"p5.Element/touchEnded"]}],"dragOver":[0,{"description":[0,"Calls a function when a file is dragged over the element.
\nCalling myElement.dragOver(false)
disables the function.
\n"],"path":[0,"p5.Element/dragOver"]}],"dragLeave":[0,{"description":[0,"Calls a function when a file is dragged off the element.
\nCalling myElement.dragLeave(false)
disables the function.
\n"],"path":[0,"p5.Element/dragLeave"]}],"addClass":[0,{"description":[0,"Adds a class to the element.
\n"],"path":[0,"p5.Element/addClass"]}],"removeClass":[0,{"description":[0,"Removes a class from the element.
\n"],"path":[0,"p5.Element/removeClass"]}],"hasClass":[0,{"description":[0,"Checks if a class is already applied to element.
\n"],"path":[0,"p5.Element/hasClass"]}],"toggleClass":[0,{"description":[0,"Toggles whether a class is applied to the element.
\n"],"path":[0,"p5.Element/toggleClass"]}],"child":[0,{"description":[0,"Attaches the element as a child of another element.
\nmyElement.child()
accepts either a string ID, DOM node, or\np5.Element. For example,\nmyElement.child(otherElement)
. If no argument is provided, an array of\nchildren DOM nodes is returned.
\n"],"path":[0,"p5.Element/child"]}],"center":[0,{"description":[0,"Centers the element either vertically, horizontally, or both.
\ncenter()
will center the element relative to its parent or according to\nthe page's body if the element has no parent.
\nIf no argument is passed, as in myElement.center()
the element is aligned\nboth vertically and horizontally.
\n"],"path":[0,"p5.Element/center"]}],"html":[0,{"description":[0,"Sets the inner HTML of the element, replacing any existing HTML.
\nThe second parameter, append
, is optional. If true
is passed, as in\nmyElement.html('hi', true)
, the HTML is appended instead of replacing\nexisting HTML.
\nIf no arguments are passed, as in myElement.html()
, the element's inner\nHTML is returned.
\n"],"path":[0,"p5.Element/html"]}],"position":[0,{"description":[0,"Sets the element's position.
\nThe first two parameters, x
and y
, set the element's position relative\nto the top-left corner of the web page.
\nThe third parameter, positionType
, is optional. It sets the element's\npositioning scheme.\npositionType
is a string that can be either 'static'
, 'fixed'
,\n'relative'
, 'sticky'
, 'initial'
, or 'inherit'
.
\nIf no arguments passed, as in myElement.position()
, the method returns\nthe element's position in an object, as in { x: 0, y: 0 }
.
\n"],"path":[0,"p5.Element/position"]}],"style":[0,{"description":[0,"Applies a style to the element by adding a\nCSS declaration.
\nThe first parameter, property
, is a string. If the name of a style\nproperty is passed, as in myElement.style('color')
, the method returns\nthe current value as a string or null
if it hasn't been set. If a\nproperty:style
string is passed, as in\nmyElement.style('color:deeppink')
, the method sets the style property
\nto value
.
\nThe second parameter, value
, is optional. It sets the property's value.\nvalue
can be a string, as in\nmyElement.style('color', 'deeppink')
, or a\np5.Color object, as in\nmyElement.style('color', myColor)
.
\n"],"path":[0,"p5.Element/style"]}],"attribute":[0,{"description":[0,"Adds an\nattribute\nto the element.
\nThis method is useful for advanced tasks. Most commonly-used attributes,\nsuch as id
, can be set with their dedicated methods. For example,\nnextButton.id('next')
sets an element's id
attribute. Calling\nnextButton.attribute('id', 'next')
has the same effect.
\nThe first parameter, attr
, is the attribute's name as a string. Calling\nmyElement.attribute('align')
returns the attribute's current value as a\nstring or null
if it hasn't been set.
\nThe second parameter, value
, is optional. It's a string used to set the\nattribute's value. For example, calling\nmyElement.attribute('align', 'center')
sets the element's horizontal\nalignment to center
.
\n"],"path":[0,"p5.Element/attribute"]}],"removeAttribute":[0,{"description":[0,"Removes an attribute from the element.
\nThe parameter attr
is the attribute's name as a string. For example,\ncalling myElement.removeAttribute('align')
removes its align
\nattribute if it's been set.
\n"],"path":[0,"p5.Element/removeAttribute"]}],"value":[0,{"description":[0,"Returns or sets the element's value.
\nCalling myElement.value()
returns the element's current value.
\nThe parameter, value
, is an optional number or string. If provided,\nas in myElement.value(123)
, it's used to set the element's value.
\n"],"path":[0,"p5.Element/value"]}],"show":[0,{"description":[0,"Shows the current element.
\n"],"path":[0,"p5.Element/show"]}],"hide":[0,{"description":[0,"Hides the current element.
\n"],"path":[0,"p5.Element/hide"]}],"size":[0,{"description":[0,"Sets the element's width and height.
\nCalling myElement.size()
without an argument returns the element's size\nas an object with the properties width
and height
. For example,\n { width: 20, height: 10 }
.
\nThe first parameter, width
, is optional. It's a number used to set the\nelement's width. Calling myElement.size(10)
\nThe 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\nto 10 pixels.
\nThe constant AUTO
can be used to adjust one dimension at a time while\nmaintaining the aspect ratio, which is width / height
. For example,\nconsider an element that's 200 pixels wide and 100 pixels tall. Calling\nmyElement.size(20, AUTO)
sets the width to 20 pixels and height to 10\npixels.
\nNote: In the case of elements that need to load data, such as images, wait\nto call myElement.size()
until after the data loads.
\n"],"path":[0,"p5.Element/size"]}],"remove":[0,{"description":[0,"Removes the element, stops all audio/video streams, and removes all\ncallback functions.
\n"],"path":[0,"p5.Element/remove"]}],"drop":[0,{"description":[0,"Calls a function when the user drops a file on the element.
\nThe first parameter, callback
, is a function to call once the file loads.\nThe callback function should have one parameter, file
, that's a\np5.File object. If the user drops multiple files on\nthe element, callback
, is called once for each file.
\nThe second parameter, fxn
, is a function to call when the browser detects\none or more dropped files. The callback function should have one\nparameter, event
, that's a\nDragEvent.
\n"],"path":[0,"p5.Element/drop"]}],"draggable":[0,{"description":[0,"Makes the element draggable.
\nThe parameter, elmnt
, is optional. If another\np5.Element object is passed, as in\nmyElement.draggable(otherElement)
, the other element will become draggable.
\n"],"path":[0,"p5.Element/draggable"]}]}],"properties":[0,{"elt":[0,{"description":[0,"The element's underlying HTMLElement
object.
\nThe\nHTMLElement\nobject's properties and methods can be used directly.
\n"],"path":[0,"p5.Element/elt"]}],"width":[0,{"description":[0,"A Number
property that stores the element's width.
\n"],"path":[0,"p5.Element/width"]}],"height":[0,{"description":[0,"A Number
property that stores the element's height.
\n"],"path":[0,"p5.Element/height"]}]}],"isConstructor":[0,true],"path":[0,"p5/p5.Element"]}],"render":[0,null]}],"entries":[1,[[0,{"id":[0,"en/p5.Element/addClass.mdx"],"slug":[0,"en/p5element/addclass"],"body":[0,"\n\n# addClass\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"addClass()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Adds a class to the element.
\n"],"line":[0,2554],"params":[1,[[0,{"name":[0,"class"],"description":[0,"name of class to add.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n \n \n function setup() {\n createCanvas(100, 100);\n background(200);\n // Create a div element.\n let div = createDiv('div');\n // Add a class to the div.\n div.addClass('myClass');\n describe('A gray square.');\n }\n
\n "]]],"isConstructor":[0,false],"path":[0,"p5.Element/addClass"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Element/attribute.mdx"],"slug":[0,"en/p5element/attribute"],"body":[0,"\n\n# attribute\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"attribute()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Adds an\nattribute\nto the element.
\nThis method is useful for advanced tasks. Most commonly-used attributes,\nsuch as id
, can be set with their dedicated methods. For example,\nnextButton.id('next')
sets an element's id
attribute. Calling\nnextButton.attribute('id', 'next')
has the same effect.
\nThe first parameter, attr
, is the attribute's name as a string. Calling\nmyElement.attribute('align')
returns the attribute's current value as a\nstring or null
if it hasn't been set.
\nThe second parameter, value
, is optional. It's a string used to set the\nattribute's value. For example, calling\nmyElement.attribute('align', 'center')
sets the element's horizontal\nalignment to center
.
\n"],"line":[0,3275],"overloads":[1,[[0,{"params":[1,[]]}],[0,{"params":[1,[[0,{"name":[0,"attr"],"description":[0,"attribute to set.
\n"],"type":[0,"String"]}],[0,{"name":[0,"value"],"description":[0,"value to assign to the attribute.
\n"],"type":[0,"String"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,false],"return":[0,{"description":[0,"value of the attribute."],"type":[0,"String"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a container div element and place it at the top-left corner.\n let container = createDiv();\n container.position(0, 0);\n\n // Create a paragraph element and place it within the container.\n // Set its horizontal alignment to \"left\".\n let p1 = createP('hi');\n p1.parent(container);\n p1.attribute('align', 'left');\n\n // Create a paragraph element and place it within the container.\n // Set its horizontal alignment to \"center\".\n let p2 = createP('hi');\n p2.parent(container);\n p2.attribute('align', 'center');\n\n // Create a paragraph element and place it within the container.\n // Set its horizontal alignment to \"right\".\n let p3 = createP('hi');\n p3.parent(container);\n p3.attribute('align', 'right');\n\n describe('A gray square with the text \"hi\" written on three separate lines, each placed further to the right.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Element/attribute"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Element/center.mdx"],"slug":[0,"en/p5element/center"],"body":[0,"\n\n# center\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"center()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Centers the element either vertically, horizontally, or both.
\ncenter()
will center the element relative to its parent or according to\nthe page's body if the element has no parent.
\nIf no argument is passed, as in myElement.center()
the element is aligned\nboth vertically and horizontally.
\n"],"line":[0,2827],"params":[1,[[0,{"name":[0,"align"],"description":[0,"passing 'vertical', 'horizontal' aligns element accordingly
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create the div element and style it.\n let div = createDiv('');\n div.size(10, 10);\n div.style('background-color', 'orange');\n\n // Center the div relative to the page's body.\n div.center();\n\n describe('A gray square and an orange rectangle. The rectangle is at the center of the page.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Element/center"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Element/child.mdx"],"slug":[0,"en/p5element/child"],"body":[0,"\n\n# child\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"child()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Attaches the element as a child of another element.
\nmyElement.child()
accepts either a string ID, DOM node, or\np5.Element. For example,\nmyElement.child(otherElement)
. If no argument is provided, an array of\nchildren DOM nodes is returned.
\n"],"line":[0,2722],"overloads":[1,[[0,{"params":[1,[]]}],[0,{"params":[1,[[0,{"name":[0,"child"],"description":[0,"the ID, DOM node, or p5.Element\n to add to the current element
\n"],"type":[0,"String|p5.Element"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,false],"return":[0,{"description":[0,"an array of child nodes."],"type":[0,"Node[]"]}],"example":[1,[[0,"\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create the div elements.\n let div0 = createDiv('Parent');\n let div1 = createDiv('Child');\n\n // Make div1 the child of div0\n // using the p5.Element.\n div0.child(div1);\n\n describe('A gray square with the words \"Parent\" and \"Child\" written beneath it.');\n}\n
\n\n\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create the div elements.\n let div0 = createDiv('Parent');\n let div1 = createDiv('Child');\n\n // Give div1 an ID.\n div1.id('apples');\n\n // Make div1 the child of div0\n // using its ID.\n div0.child('apples');\n\n describe('A gray square with the words \"Parent\" and \"Child\" written beneath it.');\n}\n
\n\n\n\n\n// This example assumes there is a div already on the page\n// with id \"myChildDiv\".\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create the div elements.\n let div0 = createDiv('Parent');\n\n // Select the child element by its ID.\n let elt = document.getElementById('myChildDiv');\n\n // Make div1 the child of div0\n // using its HTMLElement object.\n div0.child(elt);\n\n describe('A gray square with the words \"Parent\" and \"Child\" written beneath it.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Element/child"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Element/class.mdx"],"slug":[0,"en/p5element/class"],"body":[0,"\n\n# class\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"class()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/core/p5.Element.js"],"description":[0,"Adds a\nclass attribute\nto the element using a given string.
\nCalling myElement.class()
without an argument returns a string with its current classes.
\n"],"line":[0,301],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"class"],"description":[0,"class to add.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\n\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Add the class \"small\" to the\n // canvas element.\n cnv.class('small');\n\n // Get the canvas element's class\n // and display it.\n let c = cnv.class();\n text(c, 35, 54);\n\n describe('The word \"small\" written in black on a gray canvas.');\n\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Element/class"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Element/doubleClicked.mdx"],"slug":[0,"en/p5element/doubleclicked"],"body":[0,"\n\n# doubleClicked\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"doubleClicked()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/core/p5.Element.js"],"description":[0,"Calls a function when the mouse is pressed twice over the element.
\nCalling myElement.doubleClicked(false)
disables the function.
\n"],"line":[0,405],"params":[1,[[0,{"name":[0,"fxn"],"description":[0,"function to call when the mouse is\n double clicked over the element.\n false
disables the function.
\n"],"type":[0,"Function|Boolean"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\n\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // canvas is double-clicked.\n cnv.doubleClicked(randomColor);\n\n describe('A gray square changes color when the user double-clicks the canvas.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Element/doubleClicked"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Element/dragLeave.mdx"],"slug":[0,"en/p5element/dragleave"],"body":[0,"\n\n# dragLeave\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"dragLeave()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/core/p5.Element.js"],"description":[0,"Calls a function when a file is dragged off the element.
\nCalling myElement.dragLeave(false)
disables the function.
\n"],"line":[0,923],"params":[1,[[0,{"name":[0,"fxn"],"description":[0,"function to call when the file is\n dragged off the element.\n false
disables the function.
\n"],"type":[0,"Function|Boolean"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\n\n// Drag a file over, then off\n// the canvas to test.\n\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call byeFile() when a\n // file is dragged over,\n // then off the canvas.\n cnv.dragLeave(byeFile);\n\n describe('A gray square. The text \"bye, file\" appears when a file is dragged over, then off the square.');\n}\n\nfunction byeFile() {\n text('bye, file', 50, 50);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Element/dragLeave"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Element/dragOver.mdx"],"slug":[0,"en/p5element/dragover"],"body":[0,"\n\n# dragOver\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"dragOver()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/core/p5.Element.js"],"description":[0,"Calls a function when a file is dragged over the element.
\nCalling myElement.dragOver(false)
disables the function.
\n"],"line":[0,881],"params":[1,[[0,{"name":[0,"fxn"],"description":[0,"function to call when the file is\n dragged over the element.\n false
disables the function.
\n"],"type":[0,"Function|Boolean"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\n\n// Drag a file over the canvas to test.\n\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call helloFile() when a\n // file is dragged over\n // the canvas.\n cnv.dragOver(helloFile);\n\n describe('A gray square. The text \"hello, file\" appears when a file is dragged over the square.');\n}\n\nfunction helloFile() {\n text('hello, file', 50, 50);\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Element/dragOver"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Element/draggable.mdx"],"slug":[0,"en/p5element/draggable"],"body":[0,"\n\n# draggable\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"draggable()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Makes the element draggable.
\nThe parameter, elmnt
, is optional. If another\np5.Element object is passed, as in\nmyElement.draggable(otherElement)
, the other element will become draggable.
\n"],"line":[0,3945],"params":[1,[[0,{"name":[0,"elmnt"],"description":[0,"another p5.Element.
\n"],"type":[0,"p5.Element"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\n\nlet stickyNote;\nlet textInput;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a div element and style it.\n stickyNote = createDiv('Note');\n stickyNote.position(5, 5);\n stickyNote.size(80, 20);\n stickyNote.style('font-size', '16px');\n stickyNote.style('font-family', 'Comic Sans MS');\n stickyNote.style('background', 'orchid');\n stickyNote.style('padding', '5px');\n\n // Make the note draggable.\n stickyNote.draggable();\n\n // Create a panel div and style it.\n let panel = createDiv('');\n panel.position(5, 40);\n panel.size(80, 50);\n panel.style('background', 'orchid');\n panel.style('font-size', '16px');\n panel.style('padding', '5px');\n panel.style('text-align', 'center');\n\n // Make the panel draggable.\n panel.draggable();\n\n // Create a text input and style it.\n textInput = createInput('Note');\n textInput.size(70);\n\n // Add the input to the panel.\n textInput.parent(panel);\n\n // Call handleInput() when text is input.\n textInput.input(handleInput);\n\n describe(\n 'A gray square with two purple rectangles that move when dragged. The top rectangle displays the text that is typed into the bottom rectangle.'\n );\n}\n\n// Update stickyNote's HTML when text is input.\nfunction handleInput() {\n stickyNote.html(textInput.value());\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Element/draggable"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Element/drop.mdx"],"slug":[0,"en/p5element/drop"],"body":[0,"\n\n# drop\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"drop()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Calls a function when the user drops a file on the element.
\nThe first parameter, callback
, is a function to call once the file loads.\nThe callback function should have one parameter, file
, that's a\np5.File object. If the user drops multiple files on\nthe element, callback
, is called once for each file.
\nThe second parameter, fxn
, is a function to call when the browser detects\none or more dropped files. The callback function should have one\nparameter, event
, that's a\nDragEvent.
\n"],"line":[0,3790],"params":[1,[[0,{"name":[0,"callback"],"description":[0,"called when a file loads. Called once for each file dropped.
\n"],"type":[0,"Function"]}],[0,{"name":[0,"fxn"],"description":[0,"called once when any files are dropped.
\n"],"type":[0,"Function"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\n\n// Drop an image on the canvas to view\n// this example.\nlet img;\n\nfunction setup() {\n let c = createCanvas(100, 100);\n\n background(200);\n\n // Call handleFile() when a file that's dropped on the canvas has loaded.\n c.drop(handleFile);\n\n describe('A gray square. When the user drops an image on the square, it is displayed.');\n}\n\n// Remove the existing image and display the new one.\nfunction handleFile(file) {\n // Remove the current image, if any.\n if (img) {\n img.remove();\n }\n\n // Create an
element with the\n // dropped file.\n img = createImg(file.data, '');\n img.hide();\n\n // Draw the image.\n image(img, 0, 0, width, height);\n}\n
\n\n\n\n\n// Drop an image on the canvas to view\n// this example.\nlet img;\nlet msg;\n\nfunction setup() {\n let c = createCanvas(100, 100);\n\n background(200);\n\n // Call functions when the user drops a file on the canvas\n // and when the file loads.\n c.drop(handleFile, handleDrop);\n\n 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.');\n}\n\n// Display the image when it loads.\nfunction handleFile(file) {\n // Remove the current image, if any.\n if (img) {\n img.remove();\n }\n\n // Create an img element with the dropped file.\n img = createImg(file.data, '');\n img.hide();\n\n // Draw the image.\n image(img, 0, 0, width, height);\n}\n\n// Display the file's name when it loads.\nfunction handleDrop(event) {\n // Remove current paragraph, if any.\n if (msg) {\n msg.remove();\n }\n\n // Use event to get the drop target's id.\n let id = event.target.id;\n\n // Write the canvas' id beneath it.\n msg = createP(id);\n msg.position(0, 100);\n\n // Set the font color randomly for each drop.\n let c = random(['red', 'green', 'blue']);\n msg.style('color', c);\n msg.style('font-size', '12px');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Element/drop"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Element/elt.mdx"],"slug":[0,"en/p5element/elt"],"body":[0,"\n\n# elt\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"elt"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/core/p5.Element.js"],"description":[0,"The element's underlying HTMLElement
object.
\nThe\nHTMLElement\nobject's properties and methods can be used directly.
\n"],"line":[0,56],"itemtype":[0,"property"],"class":[0,"p5.Element"],"example":[1,[[0,"\n\n\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Set the border style for the\n // canvas.\n cnv.elt.style.border = '5px dashed deeppink';\n\n describe('A gray square with a pink border drawn with dashed lines.');\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Element/elt"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Element/hasClass.mdx"],"slug":[0,"en/p5element/hasclass"],"body":[0,"\n\n# hasClass\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"hasClass()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Checks if a class is already applied to element.
\n"],"line":[0,2636],"params":[1,[[0,{"name":[0,"c"],"description":[0,"name of class to check.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,false],"return":[0,{"description":[0,"a boolean value if element has specified class."],"type":[0,"Boolean"]}],"example":[1,[[0,"\n\n\nlet div;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a div element.\n div = createDiv('div');\n\n // Add the class 'show' to the div.\n div.addClass('show');\n\n describe('A gray square.');\n}\n\n// Toggle the class 'show' when the mouse is pressed.\nfunction mousePressed() {\n if (div.hasClass('show')) {\n div.addClass('show');\n } else {\n div.removeClass('show');\n }\n}\n
\n"]]],"isConstructor":[0,false],"path":[0,"p5.Element/hasClass"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Element/height.mdx"],"slug":[0,"en/p5element/height"],"body":[0,"\n\n# height\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"height"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/core/p5.Element.js"],"description":[0,"A Number
property that stores the element's height.
\n"],"line":[0,102],"itemtype":[0,"property"],"class":[0,"p5.Element"],"isConstructor":[0,false],"path":[0,"p5.Element/height"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Element/hide.mdx"],"slug":[0,"en/p5element/hide"],"body":[0,"\n\n# hide\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"hide()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Hides the current element.
\n"],"line":[0,3529],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\nlet p;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element.\n p = createP('p5*js');\n p.position(10, 10);\n\n describe('The text \"p5*js\" at the center of a gray square. The text disappears when the user double-clicks the square.');\n}\n\n// Hide the paragraph when the user double-clicks.\nfunction doubleClicked() {\n p.hide();\n}\n
\nSets the inner HTML of the element, replacing any existing HTML.
\nThe second parameter, append
, is optional. If true
is passed, as in\nmyElement.html('hi', true)
, the HTML is appended instead of replacing\nexisting HTML.
If no arguments are passed, as in myElement.html()
, the element's inner\nHTML is returned.
the HTML to be placed inside the element
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"append"],"description":[0,"whether to append HTML to existing
\n"],"type":[0,"Boolean"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,false],"return":[0,{"description":[0,"the inner HTML of the element"],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create the div element and set its size.\n let div = createDiv('');\n div.size(100, 100);\n\n // Set the inner HTML to \"hi\".\n div.html('hi');\n\n describe('A gray square with the word \"hi\" written beneath it.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create the div element and set its size.\n let div = createDiv('Hello ');\n div.size(100, 100);\n\n // Append \"World\" to the div's HTML.\n div.html('World', true);\n\n describe('A gray square with the text \"Hello World\" written beneath it.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create the div element.\n let div = createDiv('Hello');\n\n // Prints \"Hello\" to the console.\n print(div.html());\n\n describe('A gray square with the word \"Hello!\" written beneath it.');\n}\n
\nSets the element's ID using a given string.
\nCalling myElement.id()
without an argument returns its ID as a string.
ID of the element.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Set the canvas' ID\n // to \"mycanvas\".\n cnv.id('mycanvas');\n\n // Get the canvas' ID.\n let id = cnv.id();\n text(id, 24, 54);\n\n describe('The text \"mycanvas\" written in black on a gray background.');\n}\n
\nCalls a function when the mouse is pressed and released over the element.
\nCalling myElement.mouseReleased(false)
disables the function.
Note: Some mobile browsers may also trigger this event when the element\nreceives a quick tap.
\n"],"line":[0,578],"params":[1,[[0,{"name":[0,"fxn"],"description":[0,"function to call when the mouse is\n pressed and released over the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when a\n // mouse press ends.\n cnv.mouseClicked(randomColor);\n\n describe('A gray square changes color when the user releases a mouse press.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the mouse moves over the element.
\nCalling myElement.mouseMoved(false)
disables the function.
function to call when the mouse\n moves over the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // mouse moves.\n cnv.mouseMoved(randomColor);\n\n describe('A gray square changes color when the mouse moves over the canvas.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the mouse moves off the element.
\nCalling myElement.mouseOut(false)
disables the function.
function to call when the mouse\n moves off the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // mouse moves off the canvas.\n cnv.mouseOut(randomColor);\n\n describe('A gray square changes color when the mouse moves off the canvas.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the mouse moves onto the element.
\nCalling myElement.mouseOver(false)
disables the function.
function to call when the mouse\n moves onto the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // mouse moves onto the canvas.\n cnv.mouseOver(randomColor);\n\n describe('A gray square changes color when the mouse moves onto the canvas.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the mouse is pressed over the element.
\nCalling myElement.mousePressed(false)
disables the function.
Note: Some mobile browsers may also trigger this event when the element\nreceives a quick tap.
\n"],"line":[0,350],"params":[1,[[0,{"name":[0,"fxn"],"description":[0,"function to call when the mouse is\n pressed over the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the canvas\n // is pressed.\n cnv.mousePressed(randomColor);\n\n describe('A gray square changes color when the mouse is pressed.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the mouse is released over the element.
\nCalling myElement.mouseReleased(false)
disables the function.
Note: Some mobile browsers may also trigger this event when the element\nreceives a quick tap.
\n"],"line":[0,533],"params":[1,[[0,{"name":[0,"fxn"],"description":[0,"function to call when the mouse is\n pressed over the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when a\n // mouse press ends.\n cnv.mouseReleased(randomColor);\n\n describe('A gray square changes color when the user releases a mouse press.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the mouse wheel scrolls over the element.
\nThe callback function, fxn
, is passed an event
object. event
has\ntwo numeric properties, deltaY
and deltaX
. event.deltaY
is\nnegative if the mouse wheel rotates away from the user. It's positive if\nthe mouse wheel rotates toward the user. event.deltaX
is positive if\nthe mouse wheel moves to the right. It's negative if the mouse wheel moves\nto the left.
Calling myElement.mouseWheel(false)
disables the function.
function to call when the mouse wheel is\n scrolled over the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // mouse wheel moves.\n cnv.mouseWheel(randomColor);\n\n describe('A gray square changes color when the user scrolls the mouse wheel over the canvas.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\n\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call changeBackground() when the\n // mouse wheel moves.\n cnv.mouseWheel(changeBackground);\n\n describe('A gray square. When the mouse wheel scrolls over the square, it changes color and displays shapes.');\n}\n\nfunction changeBackground(event) {\n // Change the background color\n // based on deltaY.\n if (event.deltaY > 0) {\n background('deeppink');\n } else if (event.deltaY < 0) {\n background('cornflowerblue');\n } else {\n background(200);\n }\n\n // Draw a shape based on deltaX.\n if (event.deltaX > 0) {\n circle(50, 50, 20);\n } else if (event.deltaX < 0) {\n square(40, 40, 20);\n }\n}\n
\nAttaches the element to a parent element.
\nFor example, a element may be used as a box to\nhold two pieces of text, a header and a paragraph. The\n
is the parent element of both the header and\nparagraph.
The parameter parent
can have one of three types. parent
can be a\nstring with the parent element's ID, as in\nmyElement.parent('container')
. It can also be another\np5.Element object, as in\nmyElement.parent(myDiv)
. Finally, parent
can be an HTMLElement
\nobject, as in myElement.parent(anotherElement)
.
Calling myElement.parent()
without an argument returns the element's\nparent.
ID, p5.Element,\n or HTMLElement of desired parent element.
\n"],"type":[0,"String|p5.Element|Object"]}]]]}],[0,{"params":[1,[]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n background(200);\n\n // Create a div element.\n let div = createDiv();\n\n // Place the div in the top-left corner.\n div.position(10, 20);\n\n // Set its width and height.\n div.size(80, 60);\n\n // Set its background color to white\n div.style('background-color', 'white');\n\n // Align any text to the center.\n div.style('text-align', 'center');\n\n // Set its ID to \"container\".\n div.id('container');\n\n // Create a paragraph element.\n let p = createP('p5*js');\n\n // Make the div its parent\n // using its ID \"container\".\n p.parent('container');\n\n describe('The text \"p5*js\" written in black at the center of a white rectangle. The rectangle is inside a gray square.');\n}\n
\n\nfunction setup() {\n background(200);\n\n // Create rectangular div element.\n let div = createDiv();\n\n // Place the div in the top-left corner.\n div.position(10, 20);\n\n // Set its width and height.\n div.size(80, 60);\n\n // Set its background color and align\n // any text to the center.\n div.style('background-color', 'white');\n div.style('text-align', 'center');\n\n // Create a paragraph element.\n let p = createP('p5*js');\n\n // Make the div its parent.\n p.parent(div);\n\n describe('The text \"p5*js\" written in black at the center of a white rectangle. The rectangle is inside a gray square.');\n}\n
\n\nfunction setup() {\n background(200);\n\n // Create rectangular div element.\n let div = createDiv();\n\n // Place the div in the top-left corner.\n div.position(10, 20);\n\n // Set its width and height.\n div.size(80, 60);\n\n // Set its background color and align\n // any text to the center.\n div.style('background-color', 'white');\n div.style('text-align', 'center');\n\n // Create a paragraph element.\n let p = createP('p5*js');\n\n // Make the div its parent\n // using the underlying\n // HTMLElement.\n p.parent(div.elt);\n\n describe('The text \"p5*js\" written in black at the center of a white rectangle. The rectangle is inside a gray square.');\n}\n
\nSets the element's position.
\nThe first two parameters, x
and y
, set the element's position relative\nto the top-left corner of the web page.
The third parameter, positionType
, is optional. It sets the element's\npositioning scheme.\npositionType
is a string that can be either 'static'
, 'fixed'
,\n'relative'
, 'sticky'
, 'initial'
, or 'inherit'
.
If no arguments passed, as in myElement.position()
, the method returns\nthe element's position in an object, as in { x: 0, y: 0 }
.
x-position relative to top-left of window (optional)
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"y"],"description":[0,"y-position relative to top-left of window (optional)
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"positionType"],"description":[0,"it can be static, fixed, relative, sticky, initial or inherit (optional)
\n"],"type":[0,"String"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,false],"return":[0,{"description":[0,"object of form `{ x: 0, y: 0 }` containing the element's position."],"type":[0,"Object"]}],"example":[1,[[0,"\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Positions the canvas 50px to the right and 100px\n // below the top-left corner of the window.\n cnv.position(50, 100);\n\n describe('A gray square that is 50 pixels to the right and 100 pixels down from the top-left corner of the web page.');\n}\n
\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Positions the canvas at the top-left corner\n // of the window with a 'fixed' position type.\n cnv.position(0, 0, 'fixed');\n\n describe('A gray square in the top-left corner of the web page.');\n}\n
\nRemoves the element, stops all audio/video streams, and removes all\ncallback functions.
\n"],"line":[0,3731],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,false],"example":[1,[[0,"\n\nlet p;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element.\n p = createP('p5*js');\n p.position(10, 10);\n\n describe('The text \"p5*js\" written at the center of a gray square. ');\n}\n\n// Remove the paragraph when the user double-clicks.\nfunction doubleClicked() {\n p.remove();\n}\n
\nRemoves an attribute from the element.
\nThe parameter attr
is the attribute's name as a string. For example,\ncalling myElement.removeAttribute('align')
removes its align
\nattribute if it's been set.
attribute to remove.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\nlet p;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element and place it in the center of the canvas.\n // Set its \"align\" attribute to \"center\".\n p = createP('hi');\n p.position(0, 20);\n p.attribute('align', 'center');\n\n describe('The text \"hi\" written in black at the center of a gray square. The text moves to the left edge when double-clicked.');\n}\n\n// Remove the 'align' attribute when the user double-clicks the paragraph.\nfunction doubleClicked() {\n p.removeAttribute('align');\n}\n
\nRemoves a class from the element.
\n"],"line":[0,2593],"params":[1,[[0,{"name":[0,"class"],"description":[0,"name of class to remove.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\n// In this example, a class is set when the div is created\n// and removed when mouse is pressed. This could link up\n// with a CSS style rule to toggle style properties.\n\nlet div;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a div element.\n div = createDiv('div');\n\n // Add a class to the div.\n div.addClass('myClass');\n\n describe('A gray square.');\n}\n\n// Remove 'myClass' from the div when the user presses the mouse.\nfunction mousePressed() {\n div.removeClass('myClass');\n}\n
\nShows the current element.
\n"],"line":[0,3493],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\nlet p;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element and hide it.\n p = createP('p5*js');\n p.position(10, 10);\n p.hide();\n\n describe('A gray square. The text \"p5*js\" appears when the user double-clicks the square.');\n}\n\n// Show the paragraph when the user double-clicks.\nfunction doubleClicked() {\n p.show();\n}\n
\nSets the element's width and height.
\nCalling myElement.size()
without an argument returns the element's size\nas an object with the properties width
and height
. For example,\n { width: 20, height: 10 }
.
The first parameter, width
, is optional. It's a number used to set the\nelement'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\nto 10 pixels.
The constant AUTO
can be used to adjust one dimension at a time while\nmaintaining the aspect ratio, which is width / height
. For example,\nconsider an element that's 200 pixels wide and 100 pixels tall. Calling\nmyElement.size(20, AUTO)
sets the width to 20 pixels and height to 10\npixels.
Note: In the case of elements that need to load data, such as images, wait\nto call myElement.size()
until after the data loads.
width of the element, either AUTO, or a number.
\n"],"type":[0,"Number|Constant"],"optional":[0,true]}],[0,{"name":[0,"h"],"description":[0,"height of the element, either AUTO, or a number.
\n"],"type":[0,"Number|Constant"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,false],"return":[0,{"description":[0,"width and height of the element in an object."],"type":[0,"Object"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a pink div element and place it at the top-left corner.\n let div = createDiv();\n div.position(10, 10);\n div.style('background-color', 'deeppink');\n\n // Set the div's width to 80 pixels and height to 20 pixels.\n div.size(80, 20);\n\n describe('A gray square with a pink rectangle near its top.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a pink div element and place it at the top-left corner.\n let div = createDiv();\n div.position(10, 10);\n div.style('background-color', 'deeppink');\n\n // Set the div's width to 80 pixels and height to 40 pixels.\n div.size(80, 40);\n\n // Get the div's size as an object.\n let s = div.size();\n\n // Display the div's dimensions.\n div.html(`${s.width} x ${s.height}`);\n\n describe('A gray square with a pink rectangle near its top. The text \"80 x 40\" is written within the rectangle.');\n}\n
\n\nlet img1;\nlet img2;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Load an image of an astronaut on the moon\n // and place it at the top-left of the canvas.\n img1 = createImg(\n '/assets/moonwalk.jpg',\n 'An astronaut walking on the moon',\n ''\n );\n img1.position(0, 0);\n\n // Load an image of an astronaut on the moon\n // and place it at the top-left of the canvas.\n // Resize the image once it's loaded.\n img2 = createImg(\n '/assets/moonwalk.jpg',\n 'An astronaut walking on the moon',\n '',\n resizeImage\n );\n img2.position(0, 0);\n\n describe('A gray square two copies of a space image at the top-left. The copy in front is smaller.');\n}\n\n// Resize img2 and keep its aspect ratio.\nfunction resizeImage() {\n img2.size(50, AUTO);\n}\n
\nApplies a style to the element by adding a\nCSS declaration.
\nThe first parameter, property
, is a string. If the name of a style\nproperty is passed, as in myElement.style('color')
, the method returns\nthe current value as a string or null
if it hasn't been set. If a\nproperty:style
string is passed, as in\nmyElement.style('color:deeppink')
, the method sets the style property
\nto value
.
The second parameter, value
, is optional. It sets the property's value.\nvalue
can be a string, as in\nmyElement.style('color', 'deeppink')
, or a\np5.Color object, as in\nmyElement.style('color', myColor)
.
style property to set.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"property"],"description":[0,""],"type":[0,"String"]}],[0,{"name":[0,"value"],"description":[0,"value to assign to the property.
\n"],"type":[0,"String|p5.Color"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,false],"return":[0,{"description":[0,"value of the property."],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element and set its font color to \"deeppink\".\n let p = createP('p5*js');\n p.position(25, 20);\n p.style('color', 'deeppink');\n\n describe('The text p5*js written in pink on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let c = color('deeppink');\n\n // Create a paragraph element and set its font color using a p5.Color object.\n let p = createP('p5*js');\n p.position(25, 20);\n p.style('color', c);\n\n describe('The text p5*js written in pink on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element and set its font color to \"deeppink\"\n // using property:value syntax.\n let p = createP('p5*js');\n p.position(25, 20);\n p.style('color:deeppink');\n\n describe('The text p5*js written in pink on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an empty paragraph element and set its font color to \"deeppink\".\n let p = createP();\n p.position(5, 5);\n p.style('color', 'deeppink');\n\n // Get the element's color as an RGB color string.\n let c = p.style('color');\n\n // Set the element's inner HTML using the RGB color string.\n p.html(c);\n\n describe('The text \"rgb(255, 20, 147)\" written in pink on a gray background.');\n}\n
\nToggles whether a class is applied to the element.
\n"],"line":[0,2677],"params":[1,[[0,{"name":[0,"c"],"description":[0,"class name to toggle.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\nlet div;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a div element.\n div = createDiv('div');\n\n // Add the 'show' class to the div.\n div.addClass('show');\n\n describe('A gray square.');\n}\n\n// Toggle the 'show' class when the mouse is pressed.\nfunction mousePressed() {\n div.toggleClass('show');\n}\n
\nCalls a function when the user stops touching the element.
\nCalling myElement.touchMoved(false)
disables the function.
Note: Touch functions only work on mobile devices.
\n"],"line":[0,837],"params":[1,[[0,{"name":[0,"fxn"],"description":[0,"function to call when the touch\n ends.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // user touches the canvas,\n // then lifts their finger.\n cnv.touchEnded(randomColor);\n\n describe('A gray square changes color when the user touches the canvas, then lifts their finger.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the user touches the element and moves.
\nCalling myElement.touchMoved(false)
disables the function.
Note: Touch functions only work on mobile devices.
\n"],"line":[0,793],"params":[1,[[0,{"name":[0,"fxn"],"description":[0,"function to call when the touch\n moves over the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // user touches the canvas\n // and moves.\n cnv.touchMoved(randomColor);\n\n describe('A gray square changes color when the user touches the canvas and moves.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the element is touched.
\nCalling myElement.touchStarted(false)
disables the function.
Note: Touch functions only work on mobile devices.
\n"],"line":[0,749],"params":[1,[[0,{"name":[0,"fxn"],"description":[0,"function to call when the touch\n starts.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // user touches the canvas.\n cnv.touchStarted(randomColor);\n\n describe('A gray square changes color when the user touches the canvas.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nReturns or sets the element's value.
\nCalling myElement.value()
returns the element's current value.
The parameter, value
, is an optional number or string. If provided,\nas in myElement.value(123)
, it's used to set the element's value.
\nlet input;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a text input and place it beneath the canvas.\n // Set its default value to \"hello\".\n input = createInput('hello');\n input.position(0, 100);\n\n describe('The text from an input box is displayed on a gray square.');\n}\n\nfunction draw() {\n background(200);\n\n // Use the input's value to display a message.\n let msg = input.value();\n text(msg, 0, 55);\n}\n
\n\nlet input;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a text input and place it beneath the canvas.\n // Set its default value to \"hello\".\n input = createInput('hello');\n input.position(0, 100);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Use the input's value to display a message.\n let msg = input.value();\n text(msg, 0, 55);\n}\n\n// Reset the input's value.\nfunction doubleClicked() {\n input.value('hello');\n}\n
\nA Number
property that stores the element's width.
A class to describe a file.
\np5.File
objects are used by\nmyElement.drop() and\ncreated by\ncreateFileInput.
wrapped file.
\n"],"type":[0,"File"]}]]],"chainable":[0,false],"example":[1,[[0,"\n\n// Use the file input to load a\n// file and display its info.\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a file input and place it beneath the canvas.\n // Call displayInfo() when the file loads.\n let input = createFileInput(displayInfo);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user loads a file, its info is written in black.');\n}\n\n// Display the p5.File's info once it loads.\nfunction displayInfo(file) {\n background(200);\n\n // Display the p5.File's name.\n text(file.name, 10, 10, 80, 40);\n\n // Display the p5.File's type and subtype.\n text(`${file.type}/${file.subtype}`, 10, 70);\n\n // Display the p5.File's size in bytes.\n text(file.size, 10, 90);\n}\n
\n\n// Use the file input to select an image to\n// load and display.\nlet img;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a file input and place it beneath the canvas.\n // Call handleImage() when the file image loads.\n let input = createFileInput(handleImage);\n input.position(0, 100);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw the image if it's ready.\n if (img) {\n image(img, 0, 0, width, height);\n }\n}\n\n// Use the p5.File's data once it loads.\nfunction handleImage(file) {\n // Check the p5.File's type.\n if (file.type === 'image') {\n // Create an image using using the p5.File's data.\n img = createImg(file.data, '');\n\n // Hide the image element so it doesn't appear twice.\n img.hide();\n } else {\n img = null;\n }\n}\n
\nUnderlying\nFile\nobject. All File
properties and methods are accessible.
The file\nMIME type\nas a string.
\nFor example, 'image'
and 'text'
are both MIME types.
The file subtype as a string.
\nFor example, a file with an 'image'
\nMIME type\nmay have a subtype such as png
or jpeg
.
The file name as a string.
\n"],"path":[0,"p5.File/name"]}],"size":[0,{"description":[0,"The number of bytes in the file.
\n"],"path":[0,"p5.File/size"]}],"data":[0,{"description":[0,"A string containing the file's data.
\nData can be either image data, text contents, or a parsed object in the\ncase of JSON and p5.XML objects.
\n"],"path":[0,"p5.File/data"]}]}],"isConstructor":[0,true],"path":[0,"p5/p5.File"]}],"render":[0,null]}],"entries":[1,[[0,{"id":[0,"en/p5.File/data.mdx"],"slug":[0,"en/p5file/data"],"body":[0,"\n\n# data\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"data"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"A string containing the file's data.
\nData can be either image data, text contents, or a parsed object in the\ncase of JSON and p5.XML objects.
\n"],"line":[0,5769],"itemtype":[0,"property"],"class":[0,"p5.File"],"example":[1,[[0,"\n\n// Use the file input to load a file and display its info.\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a file input and place it beneath the canvas.\n // Call displayData() when the file loads.\n let input = createFileInput(displayData);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user loads a file, its data is written in black.');\n}\n\n// Display the p5.File's data once it loads.\nfunction displayData(file) {\n background(200);\n\n // Display the p5.File's data, which looks like a random string of characters.\n text(file.data, 10, 10, 80, 80);\n}\n
\nUnderlying\nFile\nobject. All File
properties and methods are accessible.
\n// Use the file input to load a\n// file and display its info.\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a file input and place it beneath the canvas.\n // Call displayInfo() when the file loads.\n let input = createFileInput(displayInfo);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user loads a file, its info is written in black.');\n}\n\n// Use the p5.File once it loads.\nfunction displayInfo(file) {\n background(200);\n\n // Display the p5.File's name.\n text(file.name, 10, 10, 80, 40);\n\n // Display the p5.File's type and subtype.\n text(`${file.type}/${file.subtype}`, 10, 70);\n\n // Display the p5.File's size in bytes.\n text(file.size, 10, 90);\n}\n
\nThe file name as a string.
\n"],"line":[0,5699],"itemtype":[0,"property"],"class":[0,"p5.File"],"example":[1,[[0,"\n\n// Use the file input to load a\n// file and display its info.\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a file input and place it beneath the canvas.\n // Call displayName() when the file loads.\n let input = createFileInput(displayName);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user loads a file, its name is written in black.');\n}\n\n// Display the p5.File's name once it loads.\nfunction displayName(file) {\n background(200);\n\n // Display the p5.File's name.\n text(`This is file's name is: ${file.name}`, 10, 10, 80, 80);\n}\n
\nThe number of bytes in the file.
\n"],"line":[0,5734],"itemtype":[0,"property"],"class":[0,"p5.File"],"example":[1,[[0,"\n\n// Use the file input to load a file and display its info.\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a file input and place it beneath the canvas.\n // Call displaySize() when the file loads.\n let input = createFileInput(displaySize);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user loads a file, its size in bytes is written in black.');\n}\n\n// Display the p5.File's size in bytes once it loads.\nfunction displaySize(file) {\n background(200);\n\n // Display the p5.File's size.\n text(`This is file has ${file.size} bytes.`, 10, 10, 80, 80);\n}\n
\nThe file subtype as a string.
\nFor example, a file with an 'image'
\nMIME type\nmay have a subtype such as png
or jpeg
.
\n// Use the file input to load a\n// file and display its info.\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a file input and place it beneath the canvas.\n // Call displaySubtype() when the file loads.\n let input = createFileInput(displaySubtype);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user loads a file, its subtype is written in black.');\n}\n\n// Display the p5.File's type once it loads.\nfunction displaySubtype(file) {\n background(200);\n\n // Display the p5.File's subtype.\n text(`This is file's subtype is: ${file.subtype}`, 10, 10, 80, 80);\n}\n
\nThe file\nMIME type\nas a string.
\nFor example, 'image'
and 'text'
are both MIME types.
\n// Use the file input to load a file and display its info.\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a file input and place it beneath the canvas.\n // Call displayType() when the file loads.\n let input = createFileInput(displayType);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user loads a file, its type is written in black.');\n}\n\n// Display the p5.File's type once it loads.\nfunction displayType(file) {\n background(200);\n\n // Display the p5.File's type.\n text(`This is file's type is: ${file.type}`, 10, 10, 80, 80);\n}\n
\nA class to handle audio and video.
\np5.MediaElement
extends p5.Element with\nmethods to handle audio and video. p5.MediaElement
objects are created by\ncalling createVideo,\ncreateAudio, and\ncreateCapture.
DOM node that is wrapped
\n"],"type":[0,"String"]}]]],"chainable":[0,false],"example":[1,[[0,"\n\nlet capture;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createCapture().\n capture = createCapture(VIDEO);\n capture.hide();\n\n describe('A webcam feed with inverted colors.');\n}\n\nfunction draw() {\n // Display the video stream and invert the colors.\n image(capture, 0, 0, width, width * capture.height / capture.width);\n filter(INVERT);\n}\n
\nPlays audio or video from a media element.
\n"],"path":[0,"p5.MediaElement/play"]}],"stop":[0,{"description":[0,"Stops a media element and sets its current time to 0.
\nCalling media.play()
will restart playing audio/video from the beginning.
Pauses a media element.
\nCalling media.play()
will resume playing audio/video from the moment it paused.
Plays the audio/video repeatedly in a loop.
\n"],"path":[0,"p5.MediaElement/loop"]}],"noLoop":[0,{"description":[0,"Stops the audio/video from playing in a loop.
\nThe media will stop when it finishes playing.
\n"],"path":[0,"p5.MediaElement/noLoop"]}],"autoplay":[0,{"description":[0,"Sets the audio/video to play once it's loaded.
\nThe parameter, shouldAutoplay
, is optional. Calling\nmedia.autoplay()
without an argument causes the media to play\nautomatically. If true
is passed, as in media.autoplay(true)
, the\nmedia will automatically play. If false
is passed, as in\nmedia.autoPlay(false)
, it won't play automatically.
Sets the audio/video volume.
\nCalling media.volume()
without an argument returns the current volume\nas a number in the range 0 (off) to 1 (maximum).
The parameter, val
, is optional. It's a number that sets the volume\nfrom 0 (off) to 1 (maximum). For example, calling media.volume(0.5)
\nsets the volume to half of its maximum.
Sets the audio/video playback speed.
\nThe parameter, val
, is optional. It's a number that sets the playback\nspeed. 1 plays the media at normal speed, 0.5 plays it at half speed, 2\nplays it at double speed, and so on. -1 plays the media at normal speed\nin reverse.
Calling media.speed()
returns the current speed as a number.
Note: Not all browsers support backward playback. Even if they do,\nplayback might not be smooth.
\n"],"path":[0,"p5.MediaElement/speed"]}],"time":[0,{"description":[0,"Sets the media element's playback time.
\nThe parameter, time
, is optional. It's a number that specifies the\ntime, in seconds, to jump to when playback begins.
Calling media.time()
without an argument returns the number of seconds\nthe audio/video has played.
Note: Time resets to 0 when looping media restarts.
\n"],"path":[0,"p5.MediaElement/time"]}],"duration":[0,{"description":[0,"Returns the audio/video's duration in seconds.
\n"],"path":[0,"p5.MediaElement/duration"]}],"onended":[0,{"description":[0,"Calls a function when the audio/video reaches the end of its playback.
\nThe element is passed as an argument to the callback function.
\nNote: The function won't be called if the media is looping.
\n"],"path":[0,"p5.MediaElement/onended"]}],"connect":[0,{"description":[0,"Sends the element's audio to an output.
\nThe parameter, audioNode
, can be an AudioNode
or an object from the\np5.sound
library.
If no element is provided, as in myElement.connect()
, the element\nconnects to the main output. All connections are removed by the\n.disconnect()
method.
Note: This method is meant to be used with the p5.sound.js addon library.
\n"],"path":[0,"p5.MediaElement/connect"]}],"disconnect":[0,{"description":[0,"Disconnect all Web Audio routing, including to the main output.
\nThis is useful if you want to re-route the output through audio effects,\nfor example.
\n"],"path":[0,"p5.MediaElement/disconnect"]}],"showControls":[0,{"description":[0,"Show the default\nHTMLMediaElement\ncontrols.
\nNote: The controls vary between web browsers.
\n"],"path":[0,"p5.MediaElement/showControls"]}],"hideControls":[0,{"description":[0,"Hide the default\nHTMLMediaElement\ncontrols.
\n"],"path":[0,"p5.MediaElement/hideControls"]}],"addCue":[0,{"description":[0,"Schedules a function to call when the audio/video reaches a specific time\nduring its playback.
\nThe first parameter, time
, is the time, in seconds, when the function\nshould run. This value is passed to callback
as its first argument.
The second parameter, callback
, is the function to call at the specified\ncue time.
The third parameter, value
, is optional and can be any type of value.\nvalue
is passed to callback
.
Calling media.addCue()
returns an ID as a string. This is useful for\nremoving the cue later.
Removes a callback based on its ID.
\n"],"path":[0,"p5.MediaElement/removeCue"]}],"clearCues":[0,{"description":[0,"Removes all functions scheduled with media.addCue()
.
Path to the media element's source as a string.
\n"],"path":[0,"p5.MediaElement/src"]}]}],"isConstructor":[0,true],"path":[0,"p5/p5.MediaElement"]}],"render":[0,null]}],"entries":[1,[[0,{"id":[0,"en/p5.MediaElement/addCue.mdx"],"slug":[0,"en/p5mediaelement/addcue"],"body":[0,"\n\n# addCue\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"addCue()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Schedules a function to call when the audio/video reaches a specific time\nduring its playback.
\nThe first parameter, time
, is the time, in seconds, when the function\nshould run. This value is passed to callback
as its first argument.
The second parameter, callback
, is the function to call at the specified\ncue time.
The third parameter, value
, is optional and can be any type of value.\nvalue
is passed to callback
.
Calling media.addCue()
returns an ID as a string. This is useful for\nremoving the cue later.
cue time to run the callback function.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"callback"],"description":[0,"function to call at the cue time.
\n"],"type":[0,"Function"]}],[0,{"name":[0,"value"],"description":[0,"object to pass as the argument to\n callback
.
\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n let beat = createAudio('/assets/beat.mp3');\n\n // Play the beat in a loop.\n beat.loop();\n\n // Schedule a few events.\n beat.addCue(0, changeBackground, 'red');\n beat.addCue(2, changeBackground, 'deeppink');\n beat.addCue(4, changeBackground, 'orchid');\n beat.addCue(6, changeBackground, 'lavender');\n\n describe('A red square with a beat playing in the background. Its color changes every 2 seconds while the audio plays.');\n}\n\n// Change the background color.\nfunction changeBackground(c) {\n background(c);\n}\n
\nSets the audio/video to play once it's loaded.
\nThe parameter, shouldAutoplay
, is optional. Calling\nmedia.autoplay()
without an argument causes the media to play\nautomatically. If true
is passed, as in media.autoplay(true)
, the\nmedia will automatically play. If false
is passed, as in\nmedia.autoPlay(false)
, it won't play automatically.
whether the element should autoplay.
\n"],"type":[0,"Boolean"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,true],"example":[1,[[0,"\n\nlet video;\n\nfunction setup() {\n noCanvas();\n\n // Call handleVideo() once the video loads.\n video = createVideo('/assets/fingers.mov', handleVideo);\n\n describe('A video of fingers walking on a treadmill.');\n}\n\n// Set the video's size and play it.\nfunction handleVideo() {\n video.size(100, 100);\n video.autoplay();\n}\n
\n\nfunction setup() {\n noCanvas();\n\n // Load a video, but don't play it automatically.\n let video = createVideo('/assets/fingers.mov', handleVideo);\n\n // Play the video when the user clicks on it.\n video.mousePressed(handlePress);\n\n describe('An image of fingers on a treadmill. They start walking when the user double-clicks on them.');\n}\n
\nRemoves all functions scheduled with media.addCue()
.
\nlet isChanging = true;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.MediaElement using createAudio().\n let beat = createAudio('/assets/beat.mp3');\n\n // Play the beat in a loop.\n beat.loop();\n\n // Schedule a few events.\n beat.addCue(0, changeBackground, 'red');\n beat.addCue(2, changeBackground, 'deeppink');\n beat.addCue(4, changeBackground, 'orchid');\n beat.addCue(6, changeBackground, 'lavender');\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Display different instructions based on the available callbacks.\n if (isChanging === true) {\n text('Double-click to stop changing.', 10, 10, 80, 80);\n } else {\n text('No more changes.', 10, 10, 80, 80);\n }\n}\n\n// Change the background color.\nfunction changeBackground(c) {\n background(c);\n}\n\n// Remove cued functions and stop changing colors when the user\n// double-clicks.\nfunction doubleClicked() {\n if (isChanging === true) {\n beat.clearCues();\n isChanging = false;\n }\n}\n
\nSends the element's audio to an output.
\nThe parameter, audioNode
, can be an AudioNode
or an object from the\np5.sound
library.
If no element is provided, as in myElement.connect()
, the element\nconnects to the main output. All connections are removed by the\n.disconnect()
method.
Note: This method is meant to be used with the p5.sound.js addon library.
\n"],"line":[0,5095],"params":[1,[[0,{"name":[0,"audioNode"],"description":[0,"AudioNode from the Web Audio API,\nor an object from the p5.sound library
\n"],"type":[0,"AudioNode|Object"]}]]],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,false],"isConstructor":[0,false],"path":[0,"p5.MediaElement/connect"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.MediaElement/disconnect.mdx"],"slug":[0,"en/p5mediaelement/disconnect"],"body":[0,"\n\n# disconnect\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"disconnect()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Disconnect all Web Audio routing, including to the main output.
\nThis is useful if you want to re-route the output through audio effects,\nfor example.
\n"],"line":[0,5148],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,false],"isConstructor":[0,false],"path":[0,"p5.MediaElement/disconnect"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.MediaElement/duration.mdx"],"slug":[0,"en/p5mediaelement/duration"],"body":[0,"\n\n# duration\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"duration()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Returns the audio/video's duration in seconds.
\n"],"line":[0,4868],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,false],"return":[0,{"description":[0,"duration (in seconds)."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nlet dragon;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.MediaElement using createAudio().\n dragon = createAudio('/assets/lucky_dragons.mp3');\n\n // Show the default media controls.\n dragon.showControls();\n\n describe('The text \"S seconds left\" on a gray square with media controls beneath it. The number \"S\" decreases as the song plays.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the time remaining.\n let s = dragon.duration() - dragon.time();\n\n // Round s to 1 decimal place for display.\n s = round(s, 1);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the time remaining.\n text(`${s} seconds left`, 50, 50);\n}\n
\nHide the default\nHTMLMediaElement\ncontrols.
\n"],"line":[0,5207],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,false],"example":[1,[[0,"\n\nlet dragon;\nlet isHidden = false;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n dragon = createAudio('/assets/lucky_dragons.mp3');\n\n // Show the default media controls.\n dragon.showControls();\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n\n // Display a different message when controls are hidden or shown.\n if (isHidden === true) {\n text('Double-click to show controls', 10, 20, 80, 80);\n } else {\n text('Double-click to hide controls', 10, 20, 80, 80);\n }\n}\n\n// Show/hide controls based on a double-click.\nfunction doubleClicked() {\n if (isHidden === true) {\n dragon.showControls();\n isHidden = false;\n } else {\n dragon.hideControls();\n isHidden = true;\n }\n}\n
\nPlays the audio/video repeatedly in a loop.
\n"],"line":[0,4400],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,true],"example":[1,[[0,"\n\nlet beat;\nlet isLooping = false;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.MediaElement using createAudio().\n beat = createAudio('/assets/beat.mp3');\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display different instructions based on playback.\n if (isLooping === true) {\n text('Click to stop', 50, 50);\n } else {\n text('Click to loop', 50, 50);\n }\n}\n\n// Adjust playback when the user presses the mouse.\nfunction mousePressed() {\n if (isLooping === true) {\n // If the beat is looping, stop it.\n beat.stop();\n isLooping = false;\n } else {\n // If the beat is stopped, loop it.\n beat.loop();\n isLooping = true;\n }\n}\n
\nStops the audio/video from playing in a loop.
\nThe media will stop when it finishes playing.
\n"],"line":[0,4458],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,true],"example":[1,[[0,"\n\nlet beat;\nlet isPlaying = false;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.MediaElement using createAudio().\n beat = createAudio('/assets/beat.mp3');\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display different instructions based on playback.\n if (isPlaying === true) {\n text('Click to stop', 50, 50);\n } else {\n text('Click to play', 50, 50);\n }\n}\n\n// Adjust playback when the user presses the mouse.\nfunction mousePressed() {\n if (isPlaying === true) {\n // If the beat is playing, stop it.\n beat.stop();\n isPlaying = false;\n } else {\n // If the beat is stopped, play it.\n beat.play();\n isPlaying = true;\n }\n}\n
\nCalls a function when the audio/video reaches the end of its playback.
\nThe element is passed as an argument to the callback function.
\nNote: The function won't be called if the media is looping.
\n"],"line":[0,5024],"params":[1,[[0,{"name":[0,"callback"],"description":[0,"function to call when playback ends.\n The p5.MediaElement
is passed as\n the argument.
\nlet beat;\nlet isPlaying = false;\nlet isDone = false;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n beat = createAudio('/assets/beat.mp3');\n\n // Call handleEnd() when the beat finishes.\n beat.onended(handleEnd);\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display different messages based on playback.\n if (isDone === true) {\n text('Done!', 50, 50);\n } else if (isPlaying === false) {\n text('Click to play', 50, 50);\n } else {\n text('Playing...', 50, 50);\n }\n}\n\n// Play the beat when the user presses the mouse.\nfunction mousePressed() {\n if (isPlaying === false) {\n isPlaying = true;\n beat.play();\n }\n}\n\n// Set isDone when playback ends.\nfunction handleEnd() {\n isDone = false;\n}\n
\nPauses a media element.
\nCalling media.play()
will resume playing audio/video from the moment it paused.
\nlet beat;\nlet isPaused = true;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n beat = createAudio('/assets/beat.mp3');\n\n describe('The text \"Click to play\" written in black on a gray background. The beat plays or pauses when the user clicks the square.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display different instructions based on playback.\n if (isPaused === true) {\n text('Click to play', 50, 50);\n } else {\n text('Click to pause', 50, 50);\n }\n}\n\n// Adjust playback when the user presses the mouse.\nfunction mousePressed() {\n if (isPaused === true) {\n // If the beat is paused,\n // play it.\n beat.play();\n isPaused = false;\n } else {\n // If the beat is playing,\n // pause it.\n beat.pause();\n isPaused = true;\n }\n}\n
\nPlays audio or video from a media element.
\n"],"line":[0,4215],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,true],"example":[1,[[0,"\n\nlet beat;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display a message.\n text('Click to play', 50, 50);\n\n // Create a p5.MediaElement using createAudio().\n beat = createAudio('/assets/beat.mp3');\n\n describe('The text \"Click to play\" written in black on a gray background. A beat plays when the user clicks the square.');\n}\n\n// Play the beat when the user presses the mouse.\nfunction mousePressed() {\n beat.play();\n}\n
\nRemoves a callback based on its ID.
\n"],"line":[0,5328],"params":[1,[[0,{"name":[0,"id"],"description":[0,"ID of the cue, created by media.addCue()
.
\nlet lavenderID;\nlet isRemoved = false;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n let beat = createAudio('/assets/beat.mp3');\n\n // Play the beat in a loop.\n beat.loop();\n\n // Schedule a few events.\n beat.addCue(0, changeBackground, 'red');\n beat.addCue(2, changeBackground, 'deeppink');\n beat.addCue(4, changeBackground, 'orchid');\n\n // Record the ID of the \"lavender\" callback.\n lavenderID = beat.addCue(6, changeBackground, 'lavender');\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Display different instructions based on the available callbacks.\n if (isRemoved === false) {\n text('Double-click to remove lavender.', 10, 10, 80, 80);\n } else {\n text('No more lavender.', 10, 10, 80, 80);\n }\n}\n\n// Change the background color.\nfunction changeBackground(c) {\n background(c);\n}\n\n// Remove the lavender color-change cue when the user double-clicks.\nfunction doubleClicked() {\n if (isRemoved === false) {\n beat.removeCue(lavenderID);\n isRemoved = true;\n }\n}\n
\nShow the default\nHTMLMediaElement\ncontrols.
\nNote: The controls vary between web browsers.
\n"],"line":[0,5166],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background('cornflowerblue');\n\n // Style the text.\n textAlign(CENTER);\n textSize(50);\n\n // Display a dragon.\n text('🐉', 50, 50);\n\n // Create a p5.MediaElement using createAudio().\n let dragon = createAudio('/assets/lucky_dragons.mp3');\n\n // Show the default media controls.\n dragon.showControls();\n\n 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.');\n}\n
\nSets the audio/video playback speed.
\nThe parameter, val
, is optional. It's a number that sets the playback\nspeed. 1 plays the media at normal speed, 0.5 plays it at half speed, 2\nplays it at double speed, and so on. -1 plays the media at normal speed\nin reverse.
Calling media.speed()
returns the current speed as a number.
Note: Not all browsers support backward playback. Even if they do,\nplayback might not be smooth.
\n"],"line":[0,4691],"overloads":[1,[[0,{"params":[1,[]]}],[0,{"params":[1,[[0,{"name":[0,"speed"],"description":[0,"speed multiplier for playback.
\n"],"type":[0,"Number"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,false],"return":[0,{"description":[0,"current playback speed."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nlet dragon;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n dragon = createAudio('/assets/lucky_dragons.mp3');\n\n // Show the default media controls.\n dragon.showControls();\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Produce a number between 0 and 2.\n let n = sin(frameCount * 0.01) + 1;\n\n // Use n to set the playback speed.\n dragon.speed(n);\n\n // Get the current speed and display it.\n let s = dragon.speed();\n\n // Round s to 1 decimal place for display.\n s = round(s, 1);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the speed.\n text(`Speed: ${s}`, 50, 50);\n}\n
"]]],"isConstructor":[0,false],"path":[0,"p5.MediaElement/speed"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.MediaElement/src.mdx"],"slug":[0,"en/p5mediaelement/src"],"body":[0,"\n\n# src\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"src"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Path to the media element's source as a string.
\n"],"line":[0,4158],"itemtype":[0,"property"],"class":[0,"p5.MediaElement"],"example":[1,[[0,"\n\nlet beat;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n beat = createAudio('/assets/beat.mp3');\n\n describe('The text \"https://p5js.org/reference//assets/beat.mp3\" written in black on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n textWrap(CHAR);\n text(beat.src, 10, 10, 80, 80);\n}\n
\nStops a media element and sets its current time to 0.
\nCalling media.play()
will restart playing audio/video from the beginning.
\nlet beat;\nlet isStopped = true;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n beat = createAudio('/assets/beat.mp3');\n\n describe('The text \"Click to start\" written in black on a gray background. The beat starts or stops when the user presses the mouse.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display different instructions based on playback.\n if (isStopped === true) {\n text('Click to start', 50, 50);\n } else {\n text('Click to stop', 50, 50);\n }\n}\n\n// Adjust playback when the user presses the mouse.\nfunction mousePressed() {\n if (isStopped === true) {\n // If the beat is stopped, play it.\n beat.play();\n isStopped = false;\n } else {\n // If the beat is playing, stop it.\n beat.stop();\n isStopped = true;\n }\n}\n
\nSets the media element's playback time.
\nThe parameter, time
, is optional. It's a number that specifies the\ntime, in seconds, to jump to when playback begins.
Calling media.time()
without an argument returns the number of seconds\nthe audio/video has played.
Note: Time resets to 0 when looping media restarts.
\n"],"line":[0,4766],"overloads":[1,[[0,{"params":[1,[]]}],[0,{"params":[1,[[0,{"name":[0,"time"],"description":[0,"time to jump to (in seconds).
\n"],"type":[0,"Number"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,false],"return":[0,{"description":[0,"current time (in seconds)."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nlet dragon;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n dragon = createAudio('/assets/lucky_dragons.mp3');\n\n // Show the default media controls.\n dragon.showControls();\n\n describe('The text \"S seconds\" on a gray square with media controls beneath it. The number \"S\" increases as the song plays.');\n}\n\nfunction draw() {\n background(200);\n\n // Get the current playback time.\n let s = dragon.time();\n\n // Round s to 1 decimal place for display.\n s = round(s, 1);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the playback time.\n text(`${s} seconds`, 50, 50);\n}\n
\n\nlet dragon;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n dragon = createAudio('/assets/lucky_dragons.mp3');\n\n // Show the default media controls.\n dragon.showControls();\n\n // Jump to 2 seconds to start.\n dragon.time(2);\n\n describe('The text \"S seconds\" on a gray square with media controls beneath it. The number \"S\" increases as the song plays.');\n}\n\nfunction draw() {\n background(200);\n\n // Get the current playback time.\n let s = dragon.time();\n\n // Round s to 1 decimal place for display.\n s = round(s, 1);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the playback time.\n text(`${s} seconds`, 50, 50);\n}\n
\nSets the audio/video volume.
\nCalling media.volume()
without an argument returns the current volume\nas a number in the range 0 (off) to 1 (maximum).
The parameter, val
, is optional. It's a number that sets the volume\nfrom 0 (off) to 1 (maximum). For example, calling media.volume(0.5)
\nsets the volume to half of its maximum.
volume between 0.0 and 1.0.
\n"],"type":[0,"Number"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,false],"return":[0,{"description":[0,"current volume."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nlet dragon;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n dragon = createAudio('/assets/lucky_dragons.mp3');\n\n // Show the default media controls.\n dragon.showControls();\n\n 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.');\n}\n\nfunction draw() {\n background(200);\n\n // Produce a number between 0 and 1.\n let n = 0.5 * sin(frameCount * 0.01) + 0.5;\n\n // Use n to set the volume.\n dragon.volume(n);\n\n // Get the current volume and display it.\n let v = dragon.volume();\n\n // Round v to 1 decimal place for display.\n v = round(v, 1);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the volume.\n text(`Volume: ${v}`, 50, 50);\n}\n
\nAdds a value to the end of an array. Extends the length of\nthe array by one. Maps to Array.push().
\n"],"deprecated":[0,"This will be removed in a future version of p5.js."],"line":[0,10],"params":[1,[[0,{"name":[0,"array"],"description":[0,"Array to append
\n"],"type":[0,"Array"]}],[0,{"name":[0,"value"],"description":[0,"to be added to the Array
\n"],"type":[0,"Any"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"the array that was appended to"],"type":[0,"Array"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myArray = ['Mango', 'Apple', 'Papaya'];\n print(myArray); // ['Mango', 'Apple', 'Papaya']\n\n append(myArray, 'Peach');\n print(myArray); // ['Mango', 'Apple', 'Papaya', 'Peach']\n}\n
Copies an array (or part of an array) to another array. The src array is\ncopied to the dst array, beginning at the position specified by\nsrcPosition and into the position specified by dstPosition. The number of\nelements to copy is determined by length. Note that copying values\noverwrites existing values in the destination array. To append values\ninstead of overwriting them, use concat().
\nThe simplified version with only two arguments, arrayCopy(src, dst),\ncopies an entire array to another of the same size. It is equivalent to\narrayCopy(src, 0, dst, 0, src.length).
\nUsing this function is far more efficient for copying array data than\niterating through a for() loop and copying each element individually.
\n"],"deprecated":[0,"This will be removed in a future version of p5.js."],"line":[0,35],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"src"],"description":[0,"the source Array
\n"],"type":[0,"Array"]}],[0,{"name":[0,"srcPosition"],"description":[0,"starting position in the source Array
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"dst"],"description":[0,"the destination Array
\n"],"type":[0,"Array"]}],[0,{"name":[0,"dstPosition"],"description":[0,"starting position in the destination Array
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"length"],"description":[0,"number of Array elements to be copied
\n"],"type":[0,"Integer"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"src"],"description":[0,""],"type":[0,"Array"]}],[0,{"name":[0,"dst"],"description":[0,""],"type":[0,"Array"]}],[0,{"name":[0,"length"],"description":[0,""],"type":[0,"Integer"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nlet src = ['A', 'B', 'C'];\nlet dst = [1, 2, 3];\nlet srcPosition = 1;\nlet dstPosition = 0;\nlet length = 2;\n\nprint(src); // ['A', 'B', 'C']\nprint(dst); // [ 1 , 2 , 3 ]\n\narrayCopy(src, srcPosition, dst, dstPosition, length);\nprint(dst); // ['B', 'C', 3]\n
Concatenates two arrays, maps to Array.concat(). Does not modify the\ninput arrays.
\n"],"deprecated":[0,"This will be removed in a future version of p5.js."],"line":[0,112],"params":[1,[[0,{"name":[0,"a"],"description":[0,"first Array to concatenate
\n"],"type":[0,"Array"]}],[0,{"name":[0,"b"],"description":[0,"second Array to concatenate
\n"],"type":[0,"Array"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"concatenated array"],"type":[0,"Array"]}],"example":[1,[[0,"\n\nfunction setup() {\n let arr1 = ['A', 'B', 'C'];\n let arr2 = [1, 2, 3];\n\n print(arr1); // ['A','B','C']\n print(arr2); // [1,2,3]\n\n let arr3 = concat(arr1, arr2);\n\n print(arr1); // ['A','B','C']\n print(arr2); // [1, 2, 3]\n print(arr3); // ['A','B','C', 1, 2, 3]\n}\n
Reverses the order of an array, maps to Array.reverse()
\n"],"deprecated":[0,"This will be removed in a future version of p5.js."],"line":[0,141],"params":[1,[[0,{"name":[0,"list"],"description":[0,"Array to reverse
\n"],"type":[0,"Array"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"the reversed list"],"type":[0,"Array"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myArray = ['A', 'B', 'C'];\n print(myArray); // ['A','B','C']\n\n reverse(myArray);\n print(myArray); // ['C','B','A']\n}\n
Decreases an array by one element and returns the shortened array,\nmaps to Array.pop().
\n"],"deprecated":[0,"This will be removed in a future version of p5.js."],"line":[0,161],"params":[1,[[0,{"name":[0,"list"],"description":[0,"Array to shorten
\n"],"type":[0,"Array"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"shortened Array"],"type":[0,"Array"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myArray = ['A', 'B', 'C'];\n print(myArray); // ['A', 'B', 'C']\n let newArray = shorten(myArray);\n print(myArray); // ['A','B','C']\n print(newArray); // ['A','B']\n}\n
Shuffles the elements of an array.
\nThe first parameter, array
, is the array to be shuffled. For example,\ncalling shuffle(myArray)
will shuffle the elements of myArray
. By\ndefault, the original array won’t be modified. Instead, a copy will be\ncreated, shuffled, and returned.
The second parameter, modify
, is optional. If true
is passed, as in\nshuffle(myArray, true)
, then the array will be shuffled in place without\nmaking a copy.
array to shuffle.
\n"],"type":[0,"Array"]}],[0,{"name":[0,"bool"],"description":[0,"if true
, shuffle the original array in place. Defaults to false
.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of colors.\n let colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];\n\n // Create a shuffled copy of the array.\n let shuffledColors = shuffle(colors);\n\n // Draw a row of circles using the original array.\n for (let i = 0; i < colors.length; i += 1) {\n // Calculate the x-coordinate.\n let x = (i + 1) * 12.5;\n\n // Style the circle.\n let c = colors[i];\n fill(c);\n\n // Draw the circle.\n circle(x, 33, 10);\n }\n\n // Draw a row of circles using the original array.\n for (let i = 0; i < shuffledColors.length; i += 1) {\n // Calculate the x-coordinate.\n let x = (i + 1) * 12.5;\n\n // Style the circle.\n let c = shuffledColors[i];\n fill(c);\n\n // Draw the circle.\n circle(x, 67, 10);\n }\n\n describe(\n '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.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of colors.\n let colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];\n\n // Shuffle the array.\n shuffle(colors, true);\n\n // Draw a row of circles using the original array.\n for (let i = 0; i < colors.length; i += 1) {\n // Calculate the x-coordinate.\n let x = (i + 1) * 12.5;\n\n // Style the circle.\n let c = colors[i];\n fill(c);\n\n // Draw the circle.\n circle(x, 50, 10);\n }\n\n describe(\n 'A row of colorful circles on a gray background. Their sequence changes each time the sketch runs.'\n );\n}\n
\nSorts an array of numbers from smallest to largest, or puts an array of\nwords in alphabetical order. The original array is not modified; a\nre-ordered array is returned. The count parameter states the number of\nelements to sort. For example, if there are 12 elements in an array and\ncount is set to 5, only the first 5 elements in the array will be sorted.
\n"],"deprecated":[0,"This will be removed in a future version of p5.js."],"line":[0,300],"params":[1,[[0,{"name":[0,"list"],"description":[0,"Array to sort
\n"],"type":[0,"Array"]}],[0,{"name":[0,"count"],"description":[0,"number of elements to sort, starting from 0
\n"],"type":[0,"Integer"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"the sorted list"],"type":[0,"Array"]}],"example":[1,[[0,"\n\nfunction setup() {\n let words = ['banana', 'apple', 'pear', 'lime'];\n print(words); // ['banana', 'apple', 'pear', 'lime']\n let count = 4; // length of array\n\n words = sort(words, count);\n print(words); // ['apple', 'banana', 'lime', 'pear']\n}\n
\nfunction setup() {\n let numbers = [2, 6, 1, 5, 14, 9, 8, 12];\n print(numbers); // [2, 6, 1, 5, 14, 9, 8, 12]\n let count = 5; // Less than the length of the array\n\n numbers = sort(numbers, count);\n print(numbers); // [1,2,5,6,14,9,8,12]\n}\n
Inserts a value or an array of values into an existing array. The first\nparameter specifies the initial array to be modified, and the second\nparameter defines the data to be inserted. The third parameter is an index\nvalue which specifies the array position from which to insert data.\n(Remember that array index numbering starts at zero, so the first position\nis 0, the second position is 1, and so on.)
\n"],"deprecated":[0,"This will be removed in a future version of p5.js."],"line":[0,346],"params":[1,[[0,{"name":[0,"list"],"description":[0,"Array to splice into
\n"],"type":[0,"Array"]}],[0,{"name":[0,"value"],"description":[0,"value to be spliced in
\n"],"type":[0,"Any"]}],[0,{"name":[0,"position"],"description":[0,"in the array from which to insert data
\n"],"type":[0,"Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"the list"],"type":[0,"Array"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myArray = [0, 1, 2, 3, 4];\n let insArray = ['A', 'B', 'C'];\n print(myArray); // [0, 1, 2, 3, 4]\n print(insArray); // ['A','B','C']\n\n splice(myArray, insArray, 3);\n print(myArray); // [0,1,2,'A','B','C',3,4]\n}\n
Extracts an array of elements from an existing array. The list parameter\ndefines the array from which the elements will be copied, and the start\nand count parameters specify which elements to extract. If no count is\ngiven, elements will be extracted from the start to the end of the array.\nWhen specifying the start, remember that the first array element is 0.\nThis function does not change the source array.
\n"],"deprecated":[0,"This will be removed in a future version of p5.js."],"line":[0,381],"params":[1,[[0,{"name":[0,"list"],"description":[0,"Array to extract from
\n"],"type":[0,"Array"]}],[0,{"name":[0,"start"],"description":[0,"position to begin
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"count"],"description":[0,"number of values to extract
\n"],"type":[0,"Integer"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"Array of extracted elements"],"type":[0,"Array"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myArray = [1, 2, 3, 4, 5];\n print(myArray); // [1, 2, 3, 4, 5]\n\n let sub1 = subset(myArray, 0, 3);\n let sub2 = subset(myArray, 2, 2);\n print(sub1); // [1,2,3]\n print(sub2); // [3,4]\n}\n
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\nboolean('true')
will return true
and every other string value will\nreturn false
. If n
is a number, then boolean(0)
will return false
\nand every other numeric value will return true
. If an array is passed, as\nin boolean([0, 1, 'true', 'blue'])
, then an array of Boolean values will\nbe returned.
value to convert.
\n"],"type":[0,"String|Boolean|Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"ns"],"description":[0,"values to convert.
\n"],"type":[0,"Array"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"converted Boolean value."],"type":[0,"Boolean"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a number variable.\n let original = 0;\n\n // Convert the number to a Boolean value.\n let converted = boolean(original);\n\n // Style the circle based on the converted value.\n if (converted === true) {\n fill('blue');\n } else {\n fill('red');\n }\n\n // Draw the circle.\n circle(50, 50, 40);\n\n describe('A red circle on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let original = 'true';\n\n // Convert the string to a Boolean value.\n let converted = boolean(original);\n\n // Style the circle based on the converted value.\n if (converted === true) {\n fill('blue');\n } else {\n fill('red');\n }\n\n // Draw the circle.\n circle(50, 50, 40);\n\n describe('A blue circle on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of values.\n let original = [0, 'hi', 123, 'true'];\n\n // Convert the array to a Boolean values.\n let converted = boolean(original);\n\n // Iterate over the array of converted Boolean values.\n for (let i = 0; i < converted.length; i += 1) {\n\n // Style the circle based on the converted value.\n if (converted[i] === true) {\n fill('blue');\n } else {\n fill('red');\n }\n\n // Calculate the x-coordinate.\n let x = (i + 1) * 20;\n\n // Draw the circle.\n circle(x, 50, 15);\n }\n\n describe(\n 'A row of circles on a gray background. The two circles on the left are red and the two on the right are blue.'\n );\n}\n
\nConverts a Boolean
, String
, or Number
to its byte value.
byte()
converts a value to an integer (whole number) between -128 and\n127. Values greater than 127 wrap around while negative values are\nunchanged. 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\nbyte(false)
or byte(true)
, the number 0 (false
) or 1 (true
) will be\nreturned. If n
is a string or number, as in byte('256')
or byte(256)
,\nthen the byte value will be returned. Decimal values are ignored. If an\narray is passed, as in byte([true, 123, '456'])
, then an array of byte\nvalues will be returned.
Note: If a value can't be converted to a number, as in byte('giraffe')
,\nthen the value NaN
(not a number) will be returned.
value to convert.
\n"],"type":[0,"String|Boolean|Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"ns"],"description":[0,"values to convert.
\n"],"type":[0,"Array"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"converted byte value."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a Boolean variable.\n let original = true;\n\n // Convert the Boolean to its byte value.\n let converted = byte(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the original and converted values.\n text(`${original} : ${converted}`, 50, 50);\n\n describe('The text \"true : 1\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let original = '256';\n\n // Convert the string to its byte value.\n let converted = byte(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the original and converted values.\n text(`${original} : ${converted}`, 50, 50);\n\n describe('The text \"256 : 0\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a number variable.\n let original = 256;\n\n // Convert the number to its byte value.\n let converted = byte(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the original and converted values.\n text(`${original} : ${converted}`, 50, 50);\n\n describe('The text \"256 : 0\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of values.\n let original = [false, '64', 383];\n\n // Convert the array elements to their byte values.\n let converted = byte(original);\n\n // Iterate over the converted array elements.\n for (let i = 0; i < converted.length; i += 1) {\n\n // Style the circle.\n fill(converted[i]);\n\n // Calculate the x-coordinate.\n let x = (i + 1) * 25;\n\n // Draw the circle.\n circle(x, 50, 20);\n }\n\n describe(\n 'Three gray circles on a gray background. The circles get lighter from left to right.'\n );\n}\n
\nConverts 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\nchar(65)
, the corresponding single-character string is returned. If a\nstring is passed, as in char('65')
, the string is converted to an integer\n(whole number) and the corresponding single-character string is returned.\nIf an array is passed, as in char([65, 66, 67])
, an array of\nsingle-character strings is returned.
See MDN\nfor more information about conversions.
\n"],"line":[0,612],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"n"],"description":[0,"value to convert.
\n"],"type":[0,"String|Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"ns"],"description":[0,"values to convert.
\n"],"type":[0,"Array"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"converted single-character string."],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a number variable.\n let original = 65;\n\n // Convert the number to a char.\n let converted = char(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the original and converted values.\n text(`${original} : ${converted}`, 50, 50);\n\n describe('The text \"65 : A\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let original = '65';\n\n // Convert the string to a char.\n let converted = char(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the original and converted values.\n text(`${original} : ${converted}`, 50, 50);\n\n describe('The text \"65 : A\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of numbers.\n let original = ['65', 66, '67'];\n\n // Convert the string to a char.\n let converted = char(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Iterate over elements of the converted array.\n for (let i = 0; i < converted.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 25;\n\n // Display the original and converted values.\n text(`${original[i]} : ${converted[i]}`, 50, y);\n }\n\n describe(\n 'The text \"65 : A\", \"66 : B\", and \"67 : C\" written on three separate lines. The text is in black on a gray background.'\n );\n}\n
\nConverts a String
to a floating point (decimal) Number
.
float()
converts strings that resemble numbers, such as '12.34'
, into\nnumbers.
The parameter, str
, is the string value to convert. For example, calling\nfloat('12.34')
returns the number 12.34
. If an array of strings is\npassed, as in float(['12.34', '56.78'])
, then an array of numbers will be\nreturned.
Note: If a string can't be converted to a number, as in float('giraffe')
,\nthen the value NaN
(not a number) will be returned.
string to convert.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"ns"],"description":[0,"array of strings to convert.
\n"],"type":[0,"String[]"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"converted number."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let original = '12.3';\n\n // Convert the string to a number.\n let converted = float(original);\n\n // Double the converted value.\n let twice = converted * 2;\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(12);\n\n // Display the original and converted values.\n text(`${original} × 2 = ${twice}`, 50, 50);\n\n describe('The text \"12.3 × 2 = 24.6\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of strings.\n let original = ['60', '30', '15'];\n\n // Convert the strings to numbers.\n let diameters = float(original);\n\n for (let d of diameters) {\n // Draw a circle.\n circle(50, 50, d);\n }\n\n describe('Three white, concentric circles on a gray background.');\n}\n
\nConverts a Number
to a String
with its hexadecimal value.
hex()
converts a number to a string with its hexadecimal number value.\nHexadecimal (hex) numbers are base-16, which means there are 16 unique\ndigits. Hex extends the numbers 0–9 with the letters A–F. For example, the\nnumber 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)
,\nreturns the string '00000014'
. If an array is passed, as in\nhex([1, 10, 100])
, an array of hexadecimal strings is returned.
The second parameter, digits
, is optional. If a number is passed, as in\nhex(20, 2)
, it sets the number of hexadecimal digits to display. For\nexample, calling hex(20, 2)
returns the string '14'
.
value to convert.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"digits"],"description":[0,"number of digits to include.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"ns"],"description":[0,"values to convert.
\n"],"type":[0,"Number[]"]}],[0,{"name":[0,"digits"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"converted hexadecimal value."],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a number variable.\n let original = 20;\n\n // Convert the number to a hex string.\n let converted = hex(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(14);\n\n // Display the original and converted values.\n text(`${original} = ${converted}`, 50, 50);\n\n describe('The text \"20 = 00000014\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a number variable.\n let original = 20;\n\n // Convert the number to a hex string.\n // Only display two hex digits.\n let converted = hex(original, 2);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the original and converted values.\n text(`${original} = ${converted}`, 50, 50);\n\n describe('The text \"20 = 14\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of numbers.\n let original = [1, 10, 100];\n\n // Convert the numbers to hex strings.\n // Only use two hex digits.\n let converted = hex(original, 2);\n\n // Style the text.\n textAlign(RIGHT, CENTER);\n textSize(16);\n\n // Iterate over the converted values.\n for (let i = 0; i < converted.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 25;\n\n // Display the original and converted values.\n text(`${ original[i]} = ${converted[i]}`, 75, y);\n }\n\n describe(\n 'The text \"1 = 01\", \"10 = 0A\", and \"100 = 64\" written on three separate lines. The text is in black on a gray background.'\n );\n}\n
\nConverts a Boolean
, String
, or decimal Number
to an integer.
int()
converts values to integers. Integers are positive or negative\nnumbers without decimals. If the original value has decimals, as in -34.56,\nthey're removed to produce an integer such as -34.
The parameter, n
, is the value to convert. If n
is a Boolean, as in\nint(false)
or int(true)
, then the number 0 (false
) or 1 (true
) will\nbe returned. If n
is a string or number, as in int('45')
or\nint(67.89)
, then an integer will be returned. If an array is passed, as\nin 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')
,\nthen the value NaN
(not a number) will be returned.
value to convert.
\n"],"type":[0,"String|Boolean|Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"ns"],"description":[0,"values to convert.
\n"],"type":[0,"Array"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"converted number."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a Boolean variable.\n let original = false;\n\n // Convert the Boolean to an integer.\n let converted = int(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the original and converted values.\n text(`${original} : ${converted}`, 50, 50);\n\n describe('The text \"false : 0\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let original = '12.34';\n\n // Convert the string to an integer.\n let converted = int(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(14);\n\n // Display the original and converted values.\n text(`${original} ≈ ${converted}`, 50, 50);\n\n describe('The text \"12.34 ≈ 12\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a decimal number variable.\n let original = 12.34;\n\n // Convert the decimal number to an integer.\n let converted = int(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(14);\n\n // Display the original and converted values.\n text(`${original} ≈ ${converted}`, 50, 50);\n\n describe('The text \"12.34 ≈ 12\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of strings.\n let original = ['60', '30', '15'];\n\n // Convert the strings to integers.\n let diameters = int(original);\n\n for (let d of diameters) {\n // Draw a circle.\n circle(50, 50, d);\n }\n\n describe('Three white, concentric circles on a gray background.');\n}\n
\nConverts a Boolean
or Number
to String
.
str()
converts values to strings. See the\nString reference page for guidance on using\ntemplate literals instead.
The parameter, n
, is the value to convert. If n
is a Boolean, as in\nstr(false)
or str(true)
, then the value will be returned as a string,\nas in 'false'
or 'true'
. If n
is a number, as in str(123)
, then its\nvalue will be returned as a string, as in '123'
. If an array is passed,\nas in str([12.34, 56.78])
, then an array of strings will be returned.
value to convert.
\n"],"type":[0,"String|Boolean|Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"converted string."],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a Boolean variable.\n let original = false;\n\n // Convert the Boolean to a string.\n let converted = str(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the original and converted values.\n text(`${original} : ${converted}`, 50, 50);\n\n describe('The text \"false : false\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a number variable.\n let original = 123;\n\n // Convert the number to a string.\n let converted = str(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the original and converted values.\n text(`${original} = ${converted}`, 50, 50);\n\n describe('The text \"123 = 123\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of numbers.\n let original = [12, 34, 56];\n\n // Convert the numbers to strings.\n let strings = str(original);\n\n // Create an empty string variable.\n let final = '';\n\n // Concatenate all the strings.\n for (let s of strings) {\n final += s;\n }\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the concatenated string.\n text(final, 50, 50);\n\n describe('The text \"123456\" written in black on a gray background.');\n}\n
\nConverts a single-character String
to a Number
.
unchar()
converts single-character strings to their corresponding\ninteger (whole number).
The parameter, n
, is the character to convert. For example,\nunchar('A')
, returns the number 65. If an array is passed, as in\nunchar(['A', 'B', 'C'])
, an array of integers is returned.
value to convert.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"ns"],"description":[0,"values to convert.
\n"],"type":[0,"String[]"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"converted number."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let original = 'A';\n\n // Convert the string to a number.\n let converted = unchar(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the original and converted values.\n text(`${original} : ${converted}`, 50, 50);\n\n describe('The text \"A : 65\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of characters.\n let original = ['A', 'B', 'C'];\n\n // Convert the string to a number.\n let converted = unchar(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Iterate over elements of the converted array.\n for (let i = 0; i < converted.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 25;\n\n // Display the original and converted values.\n text(`${original[i]} : ${converted[i]}`, 50, y);\n }\n\n describe(\n 'The text \"A : 65\", \"B : 66\", and \"C :67\" written on three separate lines. The text is in black on a gray background.'\n );\n}\n
\nConverts a String
with a hexadecimal value to a Number
.
unhex()
converts a string with its hexadecimal number value to a number.\nHexadecimal (hex) numbers are base-16, which means there are 16 unique\ndigits. Hex extends the numbers 0–9 with the letters A–F. For example, the\nnumber 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,\nunhex('FF')
, returns the number 255. If an array is passed, as in\nunhex(['00', '80', 'FF'])
, an array of numbers is returned.
value to convert.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"ns"],"description":[0,"values to convert.
\n"],"type":[0,"String[]"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"converted number."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a a hex string variable\n let original = 'FF';\n\n // Convert the hex string to a number.\n let converted = unhex(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the original and converted values.\n text(`${original} = ${converted}`, 50, 50);\n\n describe('The text \"FF = 255\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of numbers.\n let original = ['00', '80', 'FF'];\n\n // Convert the numbers to hex strings.\n // Only use two hex digits.\n let converted = unhex(original, 2);\n\n // Style the text.\n textAlign(RIGHT, CENTER);\n textSize(16);\n\n // Iterate over the converted values.\n for (let i = 0; i < converted.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 25;\n\n // Display the original and converted values.\n text(`${ original[i]} = ${converted[i]}`, 80, y);\n }\n\n describe(\n 'The text \"00 = 0\", \"80 = 128\", and \"FF = 255\" written on three separate lines. The text is in black on a gray background.'\n );\n}\n
\nCreates a new instance of p5.NumberDict using the key-value pair\n or object you provide.
\n"],"line":[0,48],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"key"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"value"],"description":[0,""],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"object"],"description":[0,"object
\n"],"type":[0,"Object"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"p5.NumberDict"]}],"example":[1,[[0,"\n\n function setup() {\n let myDictionary = createNumberDict(100, 42);\n print(myDictionary.hasKey(100)); // logs true to console\n let anotherDictionary = createNumberDict({ 200: 84 });\n print(anotherDictionary.hasKey(200)); // logs true to console\n }\n
Creates a new instance of p5.StringDict using the key-value pair\n or the object you provide.
\n"],"line":[0,14],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"key"],"description":[0,""],"type":[0,"String"]}],[0,{"name":[0,"value"],"description":[0,""],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"object"],"description":[0,"object
\n"],"type":[0,"Object"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"p5.StringDict"]}],"example":[1,[[0,"\n\n function setup() {\n let myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // logs true to console\n let anotherDictionary = createStringDict({ happy: 'coding' });\n print(anotherDictionary.hasKey('happy')); // logs true to console\n }\n
A simple Dictionary class for Strings.
\n"],"line":[0,397],"path":[0,"p5/p5.StringDict"]}],"render":[0,null]}]]]}],[0,{"name":[0,"LocalStorage"],"entry":[0],"entries":[1,[[0,{"id":[0,"en/p5/clearStorage.mdx"],"slug":[0,"en/p5/clearstorage"],"body":[0,"\n\n# clearStorage\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"clearStorage()"],"module":[0,"Data"],"submodule":[0,"LocalStorage"],"file":[0,"src/data/local_storage.js"],"description":[0,"Removes all items in the web browser's local storage.
\nWeb browsers can save small amounts of data using the built-in\nlocalStorage object.\nData stored in localStorage
can be retrieved at any point, even after\nrefreshing a page or restarting the browser. Data are stored as key-value\npairs. Calling clearStorage()
removes all data from localStorage
.
Note: Sensitive data such as passwords or personal information shouldn't be\nstored in localStorage
.
\n// Double-click to clear localStorage.\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Store the player's name.\n storeItem('name', 'Feist');\n\n // Store the player's score.\n storeItem('score', 1234);\n\n describe(\n 'The text \"Feist: 1234\" written in black on a gray background. The text \"null: null\" appears when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(14);\n\n // Retrieve the name.\n let name = getItem('name');\n\n // Retrieve the score.\n let score = getItem('score');\n\n // Display the score.\n text(`${name}: ${score}`, 50, 50);\n}\n\n// Clear localStorage when the user double-clicks.\nfunction doubleClicked() {\n clearStorage();\n}\n
\nReturns a value in the web browser's local storage.
\nWeb browsers can save small amounts of data using the built-in\nlocalStorage object.\nData stored in localStorage
can be retrieved at any point, even after\nrefreshing a page or restarting the browser. Data are stored as key-value\npairs.
storeItem() makes it easy to store values in\nlocalStorage
and getItem()
makes it easy to retrieve them.
The first parameter, key
, is the name of the value to be stored as a\nstring.
The second parameter, value
, is the value to be retrieved a string. For\nexample, calling getItem('size')
retrieves the value with the key size
.
Note: Sensitive data such as passwords or personal information shouldn't be\nstored in localStorage
.
name of the value.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"stored item."],"type":[0,"String|Number|Boolean|Object|Array"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Store the player's name.\n storeItem('name', 'Feist');\n\n // Store the player's score.\n storeItem('score', 1234);\n\n describe('The text \"Feist: 1234\" written in black on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(14);\n\n // Retrieve the name.\n let name = getItem('name');\n\n // Retrieve the score.\n let score = getItem('score');\n\n // Display the score.\n text(`${name}: ${score}`, 50, 50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create an object.\n let p = { x: 50, y: 50 };\n\n // Store the object.\n storeItem('position', p);\n\n describe('A white circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Retrieve the object.\n let p = getItem('position');\n\n // Draw the circle.\n circle(p.x, p.y, 30);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Color object.\n let c = color('deeppink');\n\n // Store the object.\n storeItem('color', c);\n\n describe('A pink circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Retrieve the object.\n let c = getItem('color');\n\n // Style the circle.\n fill(c);\n\n // Draw the circle.\n circle(50, 50, 30);\n}\n
\nRemoves an item from the web browser's local storage.
\nWeb browsers can save small amounts of data using the built-in\nlocalStorage object.\nData stored in localStorage
can be retrieved at any point, even after\nrefreshing a page or restarting the browser. Data are stored as key-value\npairs.
storeItem() makes it easy to store values in\nlocalStorage
and removeItem()
makes it easy to delete them.
The parameter, key
, is the name of the value to remove as a string. For\nexample, calling removeItem('size')
removes the item with the key size
.
Note: Sensitive data such as passwords or personal information shouldn't be\nstored in localStorage
.
name of the value to remove.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// Double-click to remove an item from localStorage.\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Store the player's name.\n storeItem('name', 'Feist');\n\n // Store the player's score.\n storeItem('score', 1234);\n\n describe(\n 'The text \"Feist: 1234\" written in black on a gray background. The text \"Feist: null\" appears when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(14);\n\n // Retrieve the name.\n let name = getItem('name');\n\n // Retrieve the score.\n let score = getItem('score');\n\n // Display the score.\n text(`${name}: ${score}`, 50, 50);\n}\n\n// Remove the word from localStorage when the user double-clicks.\nfunction doubleClicked() {\n removeItem('score');\n}\n
\nStores a value in the web browser's local storage.
\nWeb browsers can save small amounts of data using the built-in\nlocalStorage object.\nData stored in localStorage
can be retrieved at any point, even after\nrefreshing a page or restarting the browser. Data are stored as key-value\npairs.
storeItem()
makes it easy to store values in localStorage
and\ngetItem() makes it easy to retrieve them.
The first parameter, key
, is the name of the value to be stored as a\nstring.
The second parameter, value
, is the value to be stored. Values can have\nany type.
Note: Sensitive data such as passwords or personal information shouldn't be\nstored in localStorage
.
name of the value.
\n"],"type":[0,"String"]}],[0,{"name":[0,"value"],"description":[0,"value to be stored.
\n"],"type":[0,"String|Number|Boolean|Object|Array"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Store the player's name.\n storeItem('name', 'Feist');\n\n // Store the player's score.\n storeItem('score', 1234);\n\n describe('The text \"Feist: 1234\" written in black on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(14);\n\n // Retrieve the name.\n let name = getItem('name');\n\n // Retrieve the score.\n let score = getItem('score');\n\n // Display the score.\n text(`${name}: ${score}`, 50, 50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create an object.\n let p = { x: 50, y: 50 };\n\n // Store the object.\n storeItem('position', p);\n\n describe('A white circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Retrieve the object.\n let p = getItem('position');\n\n // Draw the circle.\n circle(p.x, p.y, 30);\n}\n
\nCombines an array of strings into one string.
\nThe first parameter, list
, is the array of strings to join.
The second parameter, separator
, is the character(s) that should be used\nto separate the combined strings. For example, calling\njoin(myWords, ' : ')
would return a string of words each separated by a\ncolon and spaces.
array of strings to combine.
\n"],"type":[0,"Array"]}],[0,{"name":[0,"separator"],"description":[0,"character(s) to place between strings when they're combined.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"combined string."],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of strings.\n let myWords = ['one', 'two', 'three'];\n\n // Create a combined string\n let combined = join(myWords, ' : ');\n\n // Style the text.\n textAlign(CENTER, CENTER);\n\n // Display the combined string.\n text(combined, 50, 50);\n\n describe('The text \"one : two : three\" written in black on a gray canvas.');\n}\n
\nApplies a regular expression to a string and returns an array with the\nfirst match.
\nmatch()
uses regular expressions (regex) to match patterns in text. For\nexample, the regex abc
can be used to search a string for the exact\nsequence of characters abc
. See\nMDN.\nfor 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\napply. For example, calling match('Hello, p5*js!', '[a-z][0-9]')
would\nreturn the array ['p5']
.
Note: If no matches are found, null
is returned.
string to search.
\n"],"type":[0,"String"]}],[0,{"name":[0,"regexp"],"description":[0,"regular expression to match.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"match if found."],"type":[0,"String[]"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let string = 'Hello, p5*js!';\n\n // Match the characters that are lowercase\n // letters followed by digits.\n let matches = match(string, '[a-z][0-9]');\n\n // Print the matches array to the console:\n // ['p5']\n print(matches);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the matches.\n text(matches, 50, 50);\n\n describe('The text \"p5\" written in black on a gray canvas.');\n}\n
\nApplies a regular expression to a string and returns an array of matches.
\nmatch()
uses regular expressions (regex) to match patterns in text. For\nexample, the regex abc
can be used to search a string for the exact\nsequence of characters abc
. See\nMDN.\nfor more information about regexes. matchAll()
is different from\nmatch() because it returns every match, not just\nthe first.
The first parameter, str
, is the string to search.
The second parameter, regex
, is a string with the regular expression to\napply. For example, calling\nmatchAll('p5*js is easier than abc123', '[a-z][0-9]')
would return the\n2D array [['p5'], ['c1']]
.
Note: If no matches are found, an empty array []
is returned.
string to search.
\n"],"type":[0,"String"]}],[0,{"name":[0,"regexp"],"description":[0,"regular expression to match.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"matches found."],"type":[0,"String[]"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let string = 'p5*js is easier than abc123';\n\n // Match the character sequences that are\n // lowercase letters followed by digits.\n let matches = matchAll(string, '[a-z][0-9]');\n\n // Print the matches array to the console:\n // [['p5'], ['c1']]\n print(matches);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Iterate over the matches array.\n for (let i = 0; i < matches.length; i += 1) {\n\n // Calculate the y-coordainate.\n let y = (i + 1) * 33;\n\n // Display the match.\n text(matches[i], 50, y);\n }\n\n describe(\n 'The text \"p5\" and \"c1\" written on separate lines. The text is black on a gray background.'\n );\n}\n
\nConverts a Number
into a String
with a given number of digits.
nf()
converts numbers such as 123.45
into strings formatted with a set\nnumber of digits, as in '123.4500'
.
The first parameter, num
, is the number to convert to a string. For\nexample, calling nf(123.45)
returns the string '123.45'
. If an array of\nnumbers is passed, as in nf([123.45, 67.89])
, an array of formatted\nstrings will be returned.
The second parameter, left
, is optional. If a number is passed, as in\nnf(123.45, 4)
, it sets the minimum number of digits to include to the\nleft of the decimal place. If left
is larger than the number of digits in\nnum
, then unused digits will be set to 0. For example, calling\nnf(123.45, 4)
returns the string '0123.45'
.
The third parameter, right
, is also optional. If a number is passed, as\nin nf(123.45, 4, 1)
, it sets the minimum number of digits to include to\nthe right of the decimal place. If right
is smaller than the number of\ndecimal places in num
, then num
will be rounded to the given number of\ndecimal places. For example, calling nf(123.45, 4, 1)
returns the string\n'0123.5'
. If right is larger than the number of decimal places in num
,\nthen unused decimal places will be set to 0. For example, calling\nnf(123.45, 4, 3)
returns the string '0123.450'
.
When the number is negative, for example, calling nf(-123.45, 5, 2)
\nreturns the string '-00123.45'
.
number to format.
\n"],"type":[0,"Number|String"]}],[0,{"name":[0,"left"],"description":[0,"number of digits to include to the left of\n the decimal point.
\n"],"type":[0,"Integer|String"],"optional":[0,true]}],[0,{"name":[0,"right"],"description":[0,"number of digits to include to the right\n of the decimal point.
\n"],"type":[0,"Integer|String"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"nums"],"description":[0,"numbers to format.
\n"],"type":[0,"Number[]"]}],[0,{"name":[0,"left"],"description":[0,""],"type":[0,"Integer|String"],"optional":[0,true]}],[0,{"name":[0,"right"],"description":[0,""],"type":[0,"Integer|String"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"formatted string."],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textSize(16);\n\n // Create a number variable.\n let number = 123.45;\n\n // Display the number as a string.\n let formatted = nf(number);\n text(formatted, 20, 20);\n\n let negative = nf(-number, 4, 2);\n text(negative, 20, 40);\n\n // Display the number with four digits\n // to the left of the decimal.\n let left = nf(number, 4);\n text(left, 20, 60);\n\n // Display the number with four digits\n // to the left of the decimal and one\n // to the right.\n let right = nf(number, 4, 1);\n text(right, 20, 80);\n\n describe(\n '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.'\n );\n}\n
\nConverts a Number
into a String
with commas to mark units of 1,000.
nfc()
converts numbers such as 12345 into strings formatted with commas\nto mark the thousands place, as in '12,345'
.
The first parameter, num
, is the number to convert to a string. For\nexample, calling nfc(12345)
returns the string '12,345'
.
The second parameter, right
, is optional. If a number is passed, as in\nnfc(12345, 1)
, it sets the minimum number of digits to include to the\nright of the decimal place. If right
is smaller than the number of\ndecimal places in num
, then num
will be rounded to the given number of\ndecimal places. For example, calling nfc(12345.67, 1)
returns the string\n'12,345.7'
. If right
is larger than the number of decimal places in\nnum
, then unused decimal places will be set to 0. For example, calling\nnfc(12345.67, 3)
returns the string '12,345.670'
.
number to format.
\n"],"type":[0,"Number|String"]}],[0,{"name":[0,"right"],"description":[0,"number of digits to include to the right\n of the decimal point.
\n"],"type":[0,"Integer|String"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"nums"],"description":[0,"numbers to format.
\n"],"type":[0,"Number[]"]}],[0,{"name":[0,"right"],"description":[0,""],"type":[0,"Integer|String"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"formatted string."],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textSize(16);\n\n // Create a number variable.\n let number = 12345;\n\n // Display the number as a string.\n let commas = nfc(number);\n text(commas, 15, 33);\n\n // Display the number with four digits\n // to the left of the decimal.\n let decimals = nfc(number, 2);\n text(decimals, 15, 67);\n\n describe(\n 'The numbers \"12,345\" and \"12,345.00\" written on separate lines. The text is in black on a gray background.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of numbers.\n let numbers = [12345, 6789];\n\n // Convert the numbers to formatted strings.\n let formatted = nfc(numbers);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(14);\n\n // Iterate over the array.\n for (let i = 0; i < formatted.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 33;\n\n // Display the original and formatted numbers.\n text(`${numbers[i]} : ${formatted[i]}`, 50, y);\n }\n\n describe(\n 'The text \"12345 : 12,345\" and \"6789 : 6,789\" written on two separate lines. The text is in black on a gray background.'\n );\n}\n
\nConverts a Number
into a String
with a plus or minus sign.
nfp()
converts numbers such as 123 into strings formatted with a +
or\n-
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\nexample, calling nfp(123.45)
returns the string '+123.45'
. If an array\nof numbers is passed, as in nfp([123.45, -6.78])
, an array of formatted\nstrings will be returned.
The second parameter, left
, is optional. If a number is passed, as in\nnfp(123.45, 4)
, it sets the minimum number of digits to include to the\nleft of the decimal place. If left
is larger than the number of digits in\nnum
, then unused digits will be set to 0. For example, calling\nnfp(123.45, 4)
returns the string '+0123.45'
.
The third parameter, right
, is also optional. If a number is passed, as\nin nfp(123.45, 4, 1)
, it sets the minimum number of digits to include to\nthe right of the decimal place. If right
is smaller than the number of\ndecimal places in num
, then num
will be rounded to the given number of\ndecimal places. For example, calling nfp(123.45, 4, 1)
returns the\nstring '+0123.5'
. If right
is larger than the number of decimal places\nin num
, then unused decimal places will be set to 0. For example,\ncalling nfp(123.45, 4, 3)
returns the string '+0123.450'
.
number to format.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"left"],"description":[0,"number of digits to include to the left of the\n decimal point.
\n"],"type":[0,"Integer"],"optional":[0,true]}],[0,{"name":[0,"right"],"description":[0,"number of digits to include to the right of the\n decimal point.
\n"],"type":[0,"Integer"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"nums"],"description":[0,"numbers to format.
\n"],"type":[0,"Number[]"]}],[0,{"name":[0,"left"],"description":[0,""],"type":[0,"Integer"],"optional":[0,true]}],[0,{"name":[0,"right"],"description":[0,""],"type":[0,"Integer"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"formatted string."],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create number variables.\n let positive = 123;\n let negative = -123;\n\n // Convert the positive number to a formatted string.\n let p = nfp(positive);\n\n // Convert the negative number to a formatted string\n // with four digits to the left of the decimal\n // and two digits to the right of the decimal.\n let n = nfp(negative, 4, 2);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(14);\n\n // Display the original and formatted numbers.\n text(`${positive} : ${p}`, 50, 33);\n text(`${negative} : ${n}`, 50, 67);\n\n describe(\n 'The text \"123 : +123\" and \"-123 : -123.00\" written on separate lines. The text is in black on a gray background.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create number variables.\n let numbers = [123, -4.56];\n\n // Convert the numbers to formatted strings\n // with four digits to the left of the decimal\n // and one digit to the right of the decimal.\n let formatted = nfp(numbers, 4, 1);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(14);\n\n // Iterate over the array.\n for (let i = 0; i < formatted.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 33;\n\n // Display the original and formatted numbers.\n text(`${numbers[i]} : ${formatted[i]}`, 50, y);\n }\n\n describe(\n 'The text \"123 : +0123.0\" and \"-4.56 : 00-4.6\" written on separate lines. The text is in black on a gray background.'\n );\n}\n
\nConverts a positive Number
into a String
with an extra space in front.
nfs()
converts positive numbers such as 123.45 into strings formatted\nwith an extra space in front, as in ' 123.45'. Doing so can be helpful for\naligning positive and negative numbers.
The first parameter, num
, is the number to convert to a string. For\nexample, calling nfs(123.45)
returns the string ' 123.45'
.
The second parameter, left
, is optional. If a number is passed, as in\nnfs(123.45, 4)
, it sets the minimum number of digits to include to the\nleft of the decimal place. If left
is larger than the number of digits in\nnum
, then unused digits will be set to 0. For example, calling\nnfs(123.45, 4)
returns the string ' 0123.45'
.
The third parameter, right
, is also optional. If a number is passed, as\nin nfs(123.45, 4, 1)
, it sets the minimum number of digits to include to\nthe right of the decimal place. If right
is smaller than the number of\ndecimal places in num
, then num
will be rounded to the given number of\ndecimal places. For example, calling nfs(123.45, 4, 1)
returns the\nstring ' 0123.5'
. If right
is larger than the number of decimal places\nin num
, then unused decimal places will be set to 0. For example,\ncalling nfs(123.45, 4, 3)
returns the string ' 0123.450'
.
number to format.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"left"],"description":[0,"number of digits to include to the left of the\n decimal point.
\n"],"type":[0,"Integer"],"optional":[0,true]}],[0,{"name":[0,"right"],"description":[0,"number of digits to include to the right of the\n decimal point.
\n"],"type":[0,"Integer"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"nums"],"description":[0,"numbers to format.
\n"],"type":[0,"Array"]}],[0,{"name":[0,"left"],"description":[0,""],"type":[0,"Integer"],"optional":[0,true]}],[0,{"name":[0,"right"],"description":[0,""],"type":[0,"Integer"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"formatted string."],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create number variables.\n let positive = 123;\n let negative = -123;\n\n // Convert the positive number to a formatted string.\n let formatted = nfs(positive);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(16);\n\n // Display the negative number and the formatted positive number.\n text(negative, 50, 33);\n text(formatted, 50, 67);\n\n describe(\n 'The numbers -123 and 123 written on separate lines. The numbers align vertically. The text is in black on a gray background.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a number variable.\n let number = 123.45;\n\n // Convert the positive number to a formatted string.\n // Use four digits to the left of the decimal and\n // one digit to the right.\n let formatted = nfs(number, 4, 1);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(16);\n\n // Display a negative version of the number and\n // the formatted positive version.\n text('-0123.5', 50, 33);\n text(formatted, 50, 67);\n\n describe(\n 'The numbers \"-0123.5\" and \"0123.5\" written on separate lines. The numbers align vertically. The text is in black on a gray background.'\n );\n}\n
\nSplits 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\nsplit the string. For example, calling\nsplit('rock...paper...scissors', '...')
would return the array\n['rock', 'paper', 'scissors']
because there are three periods ...
\nbetween each word.
the String to be split
\n"],"type":[0,"String"]}],[0,{"name":[0,"delim"],"description":[0,"the String used to separate the data
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"Array of Strings"],"type":[0,"String[]"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let string = 'rock...paper...scissors';\n\n // Split the string at each ...\n let words = split(string, '...');\n\n // Print the array to the console:\n // [\"rock\", \"paper\", \"scissors\"]\n print(words);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(16);\n\n // Iterate over the words array.\n for (let i = 0; i < words.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 25;\n\n // Display the word.\n text(words[i], 50, y);\n }\n\n describe(\n 'The words \"rock\", \"paper\", and \"scissors\" written on separate lines. The text is black on a gray background.'\n );\n}\n
\nSplits a String
into pieces and returns an array containing the pieces.
splitTokens()
is an enhanced version of\nsplit(). It can split a string when any characters\nfrom 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\nshould be used to split the string. delim
can be a single string, as in\nsplitTokens('rock...paper...scissors...shoot', '...')
, or an array of\nstrings, as in\nsplitTokens('rock;paper,scissors...shoot, [';', ',', '...'])
. By default,\nif no delim
characters are specified, then any whitespace character is\nused to split. Whitespace characters include tab (\\t
), line feed (\\n
),\ncarriage return (\\r
), form feed (\\f
), and space.
string to split.
\n"],"type":[0,"String"]}],[0,{"name":[0,"delim"],"description":[0,"character(s) to use for splitting the string.
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"separated strings."],"type":[0,"String[]"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let string = 'rock paper scissors shoot';\n\n // Split the string at each space.\n let words = splitTokens(string);\n\n // Print the array to the console.\n print(words);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Iterate over the words array.\n for (let i = 0; i < words.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 20;\n\n // Display the word.\n text(words[i], 50, y);\n }\n\n describe(\n 'The words \"rock\", \"paper\", \"scissors\", and \"shoot\" written on separate lines. The text is black on a gray background.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let string = 'rock...paper...scissors...shoot';\n\n // Split the string at each ...\n let words = splitTokens(string, '...');\n\n // Print the array to the console.\n print(words);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Iterate over the words array.\n for (let i = 0; i < words.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 20;\n\n // Display the word.\n text(words[i], 50, y);\n }\n\n describe(\n 'The words \"rock\", \"paper\", \"scissors\", and \"shoot\" written on separate lines. The text is black on a gray background.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let string = 'rock;paper,scissors...shoot';\n\n // Split the string at each semicolon, comma, or ...\n let words = splitTokens(string, [';', ',', '...']);\n\n // Print the array to the console.\n print(words);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Iterate over the words array.\n for (let i = 0; i < words.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 20;\n\n // Display the word.\n text(words[i], 50, y);\n }\n\n describe(\n 'The words \"rock\", \"paper\", \"scissors\", and \"shoot\" written on separate lines. The text is black on a gray background.'\n );\n}\n
\nRemoves whitespace from the start and end of a String
without changing the middle.
trim()
trims\nwhitespace characters\nsuch as spaces, carriage returns, tabs, Unicode \"nbsp\" character.
The parameter, str
, is the string to trim. If a single string is passed,\nas in trim(' pad ')
, a single string is returned. If an array of\nstrings is passed, as in trim([' pad ', '\\n space \\n'])
, an array of\nstrings is returned.
string to trim.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"strs"],"description":[0,"strings to trim.
\n"],"type":[0,"String[]"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"trimmed string."],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let string = ' p5*js ';\n\n // Trim the whitespace.\n let trimmed = trim(string);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the text.\n text(`Hello, ${trimmed}!`, 50, 50);\n\n describe('The text \"Hello, p5*js!\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of strings.\n let strings = [' wide ', '\\n open ', '\\n spaces '];\n\n // Trim the whitespace.\n let trimmed = trim(strings);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(10);\n\n // Display the text.\n text(`${trimmed[0]} ${trimmed[1]} ${trimmed[2]}`, 50, 50);\n\n describe('The text \"wide open spaces\" written in black on a gray background.');\n}\n
\nA simple Dictionary class for Numbers.
\n"],"line":[0,415],"chainable":[0,false],"methods":[0,{"add":[0,{"description":[0,"Add the given number to the value currently stored at the given key.\nThe sum then replaces the value previously stored in the Dictionary.
\n"],"path":[0,"p5.NumberDict/add"]}],"sub":[0,{"description":[0,"Subtract the given number from the value currently stored at the given key.\nThe difference then replaces the value previously stored in the Dictionary.
\n"],"path":[0,"p5.NumberDict/sub"]}],"mult":[0,{"description":[0,"Multiply the given number with the value currently stored at the given key.\nThe product then replaces the value previously stored in the Dictionary.
\n"],"path":[0,"p5.NumberDict/mult"]}],"div":[0,{"description":[0,"Divide the given number with the value currently stored at the given key.\nThe quotient then replaces the value previously stored in the Dictionary.
\n"],"path":[0,"p5.NumberDict/div"]}],"minValue":[0,{"description":[0,"Return the lowest number currently stored in the Dictionary.
\n"],"path":[0,"p5.NumberDict/minValue"]}],"maxValue":[0,{"description":[0,"Return the highest number currently stored in the Dictionary.
\n"],"path":[0,"p5.NumberDict/maxValue"]}],"minKey":[0,{"description":[0,"Return the lowest key currently used in the Dictionary.
\n"],"path":[0,"p5.NumberDict/minKey"]}],"maxKey":[0,{"description":[0,"Return the highest key currently used in the Dictionary.
\n"],"path":[0,"p5.NumberDict/maxKey"]}]}],"isConstructor":[0,true],"path":[0,"p5/p5.NumberDict"]}],"render":[0,null]}],"entries":[1,[[0,{"id":[0,"en/p5.NumberDict/add.mdx"],"slug":[0,"en/p5numberdict/add"],"body":[0,"\n\n# add\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"add()"],"module":[0,"Data"],"submodule":[0,"Dictionary"],"file":[0,"src/data/p5.TypedDict.js"],"description":[0,"Add the given number to the value currently stored at the given key.\nThe sum then replaces the value previously stored in the Dictionary.
\n"],"line":[0,439],"params":[1,[[0,{"name":[0,"Key"],"description":[0,"for the value you wish to add to
\n"],"type":[0,"Number"]}],[0,{"name":[0,"Number"],"description":[0,"to add to the value
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.NumberDict"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createNumberDict(2, 5);\n myDictionary.add(2, 2);\n print(myDictionary.get(2)); // logs 7 to console.\n}\n
Divide the given number with the value currently stored at the given key.\nThe quotient then replaces the value previously stored in the Dictionary.
\n"],"line":[0,516],"params":[1,[[0,{"name":[0,"Key"],"description":[0,"for value you wish to divide
\n"],"type":[0,"Number"]}],[0,{"name":[0,"Amount"],"description":[0,"to divide the value by
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.NumberDict"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createNumberDict(2, 8);\n myDictionary.div(2, 2);\n print(myDictionary.get(2)); // logs 4 to console.\n}\n
Return the highest key currently used in the Dictionary.
\n"],"line":[0,649],"itemtype":[0,"method"],"class":[0,"p5.NumberDict"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });\n let highestKey = myDictionary.maxKey(); // value is 4\n print(highestKey);\n}\n
Return the highest number currently stored in the Dictionary.
\n"],"line":[0,587],"itemtype":[0,"method"],"class":[0,"p5.NumberDict"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });\n let highestValue = myDictionary.maxValue(); // value is 3\n print(highestValue);\n}\n
Return the lowest key currently used in the Dictionary.
\n"],"line":[0,629],"itemtype":[0,"method"],"class":[0,"p5.NumberDict"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });\n let lowestKey = myDictionary.minKey(); // value is 1.2\n print(lowestKey);\n}\n
Return the lowest number currently stored in the Dictionary.
\n"],"line":[0,567],"itemtype":[0,"method"],"class":[0,"p5.NumberDict"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });\n let lowestValue = myDictionary.minValue(); // value is -10\n print(lowestValue);\n}\n
Multiply the given number with the value currently stored at the given key.\nThe product then replaces the value previously stored in the Dictionary.
\n"],"line":[0,489],"params":[1,[[0,{"name":[0,"Key"],"description":[0,"for value you wish to multiply
\n"],"type":[0,"Number"]}],[0,{"name":[0,"Amount"],"description":[0,"to multiply the value by
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.NumberDict"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createNumberDict(2, 4);\n myDictionary.mult(2, 2);\n print(myDictionary.get(2)); // logs 8 to console.\n}\n
Subtract the given number from the value currently stored at the given key.\nThe difference then replaces the value previously stored in the Dictionary.
\n"],"line":[0,466],"params":[1,[[0,{"name":[0,"Key"],"description":[0,"for the value you wish to subtract from
\n"],"type":[0,"Number"]}],[0,{"name":[0,"Number"],"description":[0,"to subtract from the value
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.NumberDict"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createNumberDict(2, 5);\n myDictionary.sub(2, 2);\n print(myDictionary.get(2)); // logs 3 to console.\n}\n
Base class for all p5.Dictionary types. Specifically\n typed Dictionary classes inherit from this class.
\n"],"line":[0,82],"chainable":[0,false],"methods":[0,{"size":[0,{"description":[0,"Returns the number of key-value pairs currently stored in the Dictionary.
\n"],"path":[0,"p5.TypedDict/size"]}],"hasKey":[0,{"description":[0,"Returns true if the given key exists in the Dictionary,\notherwise returns false.
\n"],"path":[0,"p5.TypedDict/hasKey"]}],"get":[0,{"description":[0,"Returns the value stored at the given key.
\n"],"path":[0,"p5.TypedDict/get"]}],"set":[0,{"description":[0,"Updates the value associated with the given key in case it already exists\nin the Dictionary. Otherwise a new key-value pair is added.
\n"],"path":[0,"p5.TypedDict/set"]}],"create":[0,{"description":[0,"Creates a new key-value pair in the Dictionary.
\n"],"path":[0,"p5.TypedDict/create"]}],"clear":[0,{"description":[0,"Removes all previously stored key-value pairs from the Dictionary.
\n"],"path":[0,"p5.TypedDict/clear"]}],"remove":[0,{"description":[0,"Removes the key-value pair stored at the given key from the Dictionary.
\n"],"path":[0,"p5.TypedDict/remove"]}],"print":[0,{"description":[0,"Logs the set of items currently stored in the Dictionary to the console.
\n"],"path":[0,"p5.TypedDict/print"]}],"saveTable":[0,{"description":[0,"Converts the Dictionary into a CSV file for local download.
\n"],"path":[0,"p5.TypedDict/saveTable"]}],"saveJSON":[0,{"description":[0,"Converts the Dictionary into a JSON file for local download.
\n"],"path":[0,"p5.TypedDict/saveJSON"]}]}],"isConstructor":[0,true],"path":[0,"p5/p5.TypedDict"]}],"render":[0,null]}],"entries":[1,[[0,{"id":[0,"en/p5.TypedDict/clear.mdx"],"slug":[0,"en/p5typeddict/clear"],"body":[0,"\n\n# clear\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"clear()"],"module":[0,"Data"],"submodule":[0,"Dictionary"],"file":[0,"src/data/p5.TypedDict.js"],"description":[0,"Removes all previously stored key-value pairs from the Dictionary.
\n"],"line":[0,245],"itemtype":[0,"method"],"class":[0,"p5.TypedDict"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // prints 'true'\n myDictionary.clear();\n print(myDictionary.hasKey('p5')); // prints 'false'\n}\n
\nCreates a new key-value pair in the Dictionary.
\n"],"line":[0,209],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"key"],"description":[0,""],"type":[0,"Number|String"]}],[0,{"name":[0,"value"],"description":[0,""],"type":[0,"Number|String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"obj"],"description":[0,"key/value pair
\n"],"type":[0,"Object"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.TypedDict"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n}\n
Returns the value stored at the given key.
\n"],"line":[0,145],"params":[1,[[0,{"name":[0,"the"],"description":[0,"key you want to access
\n"],"type":[0,"Number|String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.TypedDict"],"chainable":[0,false],"return":[0,{"description":[0,"the value stored at that key"],"type":[0,"Number|String"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n let myValue = myDictionary.get('p5');\n print(myValue === 'js'); // logs true to console\n}\n
Returns true if the given key exists in the Dictionary,\notherwise returns false.
\n"],"line":[0,123],"params":[1,[[0,{"name":[0,"key"],"description":[0,"that you want to look up
\n"],"type":[0,"Number|String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.TypedDict"],"chainable":[0,false],"return":[0,{"description":[0,"whether that key exists in Dictionary"],"type":[0,"Boolean"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // logs true to console\n}\n
Logs the set of items currently stored in the Dictionary to the console.
\n"],"line":[0,295],"itemtype":[0,"method"],"class":[0,"p5.TypedDict"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n}\n
\nRemoves the key-value pair stored at the given key from the Dictionary.
\n"],"line":[0,266],"params":[1,[[0,{"name":[0,"key"],"description":[0,"for the pair to remove
\n"],"type":[0,"Number|String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.TypedDict"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n myDictionary.remove('p5');\n myDictionary.print();\n // above logs \"key: happy value: coding\" to console\n}\n
Converts the Dictionary into a JSON file for local download.
\n"],"line":[0,357],"itemtype":[0,"method"],"class":[0,"p5.TypedDict"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n}\n\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n createStringDict({\n john: 1940,\n paul: 1942,\n george: 1943,\n ringo: 1940\n }).saveJSON('beatles');\n }\n}\n
\nConverts the Dictionary into a CSV file for local download.
\n"],"line":[0,319],"itemtype":[0,"method"],"class":[0,"p5.TypedDict"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n}\n\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n createStringDict({\n john: 1940,\n paul: 1942,\n george: 1943,\n ringo: 1940\n }).saveTable('beatles');\n }\n}\n
\nUpdates the value associated with the given key in case it already exists\nin the Dictionary. Otherwise a new key-value pair is added.
\n"],"line":[0,171],"params":[1,[[0,{"name":[0,"key"],"description":[0,""],"type":[0,"Number|String"]}],[0,{"name":[0,"value"],"description":[0,""],"type":[0,"Number|String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.TypedDict"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.set('p5', 'JS');\n myDictionary.print(); // logs \"key: p5 - value: JS\" to console\n}\n
Returns the number of key-value pairs currently stored in the Dictionary.
\n"],"line":[0,102],"itemtype":[0,"method"],"class":[0,"p5.TypedDict"],"chainable":[0,false],"return":[0,{"description":[0,"the number of key-value pairs in the Dictionary"],"type":[0,"Integer"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createNumberDict(1, 10);\n myDictionary.create(2, 20);\n myDictionary.create(3, 30);\n print(myDictionary.size()); // logs 3 to the console\n}\n
Turns off the parts of the Friendly Error System (FES) that impact performance.
\nThe FES\ncan cause sketches to draw slowly because it does extra work behind the\nscenes. For example, the FES checks the arguments passed to functions,\nwhich takes time to process. Disabling the FES can significantly improve\nperformance by turning off these checks.
\n"],"line":[0,877],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n// Disable the FES.\np5.disableFriendlyErrors = true;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // The circle() function requires three arguments. The\n // next line would normally display a friendly error that\n // points this out. Instead, nothing happens and it fails\n // silently.\n circle(50, 50);\n\n describe('A gray square.');\n}\n
\nA function that's called repeatedly while the sketch runs.
\nDeclaring the function draw()
sets a code block to run repeatedly\nonce the sketch starts. It’s used to create animations and respond to\nuser inputs:
function draw() {\n // Code to run repeatedly.\n}\n
\nThis is often called the \"draw loop\" because p5.js calls the code in\ndraw()
in a loop behind the scenes. By default, draw()
tries to run\n60 times per second. The actual rate depends on many factors. The\ndrawing rate, called the \"frame rate\", can be controlled by calling\nframeRate(). The number of times draw()
\nhas run is stored in the system variable\nframeCount().
Code placed within draw()
begins looping after\nsetup() runs. draw()
will run until the user\ncloses the sketch. draw()
can be stopped by calling the\nnoLoop() function. draw()
can be resumed by\ncalling the loop() function.
\nfunction setup() {\n createCanvas(100, 100);\n\n // Paint the background once.\n background(200);\n\n describe(\n 'A white circle on a gray background. The circle follows the mouse as the user moves, leaving a trail.'\n );\n}\n\nfunction draw() {\n // Draw circles repeatedly.\n circle(mouseX, mouseY, 40);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A white circle on a gray background. The circle follows the mouse as the user moves.'\n );\n}\n\nfunction draw() {\n // Paint the background repeatedly.\n background(200);\n\n // Draw circles repeatedly.\n circle(mouseX, mouseY, 40);\n}\n
\n\n// Double-click the canvas to change the circle's color.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n // Paint the background repeatedly.\n background(200);\n\n // Draw circles repeatedly.\n circle(mouseX, mouseY, 40);\n}\n\n// Change the fill color when the user double-clicks.\nfunction doubleClicked() {\n fill('deeppink');\n}\n
\nReturns true
if the draw loop is running and false
if not.
By default, draw() tries to run 60 times per\nsecond. Calling noLoop() stops\ndraw() from repeating. The draw loop can be\nrestarted by calling loop().
\nThe isLooping()
function can be used to check whether a sketch is\nlooping, as in isLooping() === true
.
\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle drawn against a gray background. When the user double-clicks, the circle stops or resumes following the mouse.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw the circle at the mouse's position.\n circle(mouseX, mouseY, 20);\n}\n\n// Toggle the draw loop when the user double-clicks.\nfunction doubleClicked() {\n if (isLooping() === true) {\n noLoop();\n } else {\n loop();\n }\n}\n
\nResumes the draw loop after noLoop() has been\ncalled.
\nBy default, draw() tries to run 60 times per\nsecond. Calling noLoop() stops\ndraw() from repeating. The draw loop can be\nrestarted by calling loop()
.
The isLooping() function can be used to check\nwhether a sketch is looping, as in isLooping() === true
.
\nfunction setup() {\n createCanvas(100, 100);\n\n // Turn off the draw loop.\n noLoop();\n\n describe(\n 'A white half-circle on the left edge of a gray square. The circle starts moving to the right when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the circle's x-coordinate.\n let x = frameCount;\n\n // Draw the circle.\n circle(x, 50, 20);\n}\n\n// Resume the draw loop when the user double-clicks.\nfunction doubleClicked() {\n loop();\n}\n
\n\nlet startButton;\nlet stopButton;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create the button elements and place them\n // beneath the canvas.\n startButton = createButton('▶');\n startButton.position(0, 100);\n startButton.size(50, 20);\n stopButton = createButton('◾');\n stopButton.position(50, 100);\n stopButton.size(50, 20);\n\n // Set functions to call when the buttons are pressed.\n startButton.mousePressed(loop);\n stopButton.mousePressed(noLoop);\n\n // Slow the frame rate.\n frameRate(5);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the circle's coordinates.\n let x = random(0, 100);\n let y = random(0, 100);\n\n // Draw the circle.\n // Normally, the circle would move from left to right.\n circle(x, y, 20);\n}\n
\nStops the code in draw() from running repeatedly.
\nBy default, draw() tries to run 60 times per\nsecond. Calling noLoop()
stops draw() from\nrepeating. The draw loop can be restarted by calling\nloop(). draw() can be run\nonce by calling redraw().
The isLooping() function can be used to check\nwhether a sketch is looping, as in isLooping() === true
.
\nfunction setup() {\n createCanvas(100, 100);\n\n // Turn off the draw loop.\n noLoop();\n\n describe('A white half-circle on the left edge of a gray square.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the circle's x-coordinate.\n let x = frameCount;\n\n // Draw the circle.\n // Normally, the circle would move from left to right.\n circle(x, 50, 20);\n}\n
\n\n// Double-click to stop the draw loop.\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(5);\n\n describe('A white circle moves randomly on a gray background. It stops moving when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the circle's coordinates.\n let x = random(0, 100);\n let y = random(0, 100);\n\n // Draw the circle.\n // Normally, the circle would move from left to right.\n circle(x, y, 20);\n}\n\n// Stop the draw loop when the user double-clicks.\nfunction doubleClicked() {\n noLoop();\n}\n
\n\nlet startButton;\nlet stopButton;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create the button elements and place them\n // beneath the canvas.\n startButton = createButton('▶');\n startButton.position(0, 100);\n startButton.size(50, 20);\n stopButton = createButton('◾');\n stopButton.position(50, 100);\n stopButton.size(50, 20);\n\n // Set functions to call when the buttons are pressed.\n startButton.mousePressed(loop);\n stopButton.mousePressed(noLoop);\n\n // Slow the frame rate.\n frameRate(5);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the circle's coordinates.\n let x = random(0, 100);\n let y = random(0, 100);\n\n // Draw the circle.\n // Normally, the circle would move from left to right.\n circle(x, y, 20);\n}\n
\nEnds a drawing group that contains its own styles and transformations.
\nBy default, styles such as fill() and\ntransformations such as rotate() are applied to\nall drawing that follows. The push() and pop()
\nfunctions can limit the effect of styles and transformations to a specific\ngroup of shapes, images, and text. For example, a group of shapes could be\ntranslated to follow the mouse without affecting the rest of the sketch:
// Begin the drawing group.\npush();\n\n// Translate the origin to the mouse's position.\ntranslate(mouseX, mouseY);\n\n// Style the face.\nnoStroke();\nfill('green');\n\n// Draw the face.\ncircle(0, 0, 60);\n\n// Style the eyes.\nfill('white');\n\n// Draw the left eye.\nellipse(-20, -20, 30, 20);\n\n// Draw the right eye.\nellipse(20, -20, 30, 20);\n\n// End the drawing group.\npop();\n\n// Draw a bug.\nlet x = random(0, 100);\nlet y = random(0, 100);\ntext('🦟', x, y);\n
\nIn the code snippet above, the bug's position isn't affected by\ntranslate(mouseX, mouseY)
because that transformation is contained\nbetween push() and pop()
. The bug moves around\nthe entire canvas as expected.
Note: push() and pop()
are always called as a\npair. Both functions are required to begin and end a drawing group.
push() and pop()
can also be nested to create\nsubgroups. For example, the code snippet above could be changed to give\nmore detail to the frog’s eyes:
// Begin the drawing group.\npush();\n\n// Translate the origin to the mouse's position.\ntranslate(mouseX, mouseY);\n\n// Style the face.\nnoStroke();\nfill('green');\n\n// Draw a face.\ncircle(0, 0, 60);\n\n// Style the eyes.\nfill('white');\n\n// Draw the left eye.\npush();\ntranslate(-20, -20);\nellipse(0, 0, 30, 20);\nfill('black');\ncircle(0, 0, 8);\npop();\n\n// Draw the right eye.\npush();\ntranslate(20, -20);\nellipse(0, 0, 30, 20);\nfill('black');\ncircle(0, 0, 8);\npop();\n\n// End the drawing group.\npop();\n\n// Draw a bug.\nlet x = random(0, 100);\nlet y = random(0, 100);\ntext('🦟', x, y);\n
\nIn this version, the code to draw each eye is contained between its own\npush() and pop()
functions. Doing so makes it\neasier to add details in the correct part of a drawing.
push() and pop()
contain the effects of the\nfollowing functions:
In WebGL mode, push() and pop()
contain the\neffects of a few additional styles:
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw the left circle.\n circle(25, 50, 20);\n\n // Begin the drawing group.\n push();\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Style the circle.\n strokeWeight(5);\n stroke('royalblue');\n fill('orange');\n\n // Draw the circle.\n circle(0, 0, 20);\n\n // End the drawing group.\n pop();\n\n // Draw the right circle.\n circle(75, 50, 20);\n\n describe(\n '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.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(24);\n\n describe('A mosquito buzzes in front of a green frog. The frog follows the mouse as the user moves.');\n}\n\nfunction draw() {\n background(200);\n\n // Begin the drawing group.\n push();\n\n // Translate the origin to the mouse's position.\n translate(mouseX, mouseY);\n\n // Style the face.\n noStroke();\n fill('green');\n\n // Draw a face.\n circle(0, 0, 60);\n\n // Style the eyes.\n fill('white');\n\n // Draw the left eye.\n push();\n translate(-20, -20);\n ellipse(0, 0, 30, 20);\n fill('black');\n circle(0, 0, 8);\n pop();\n\n // Draw the right eye.\n push();\n translate(20, -20);\n ellipse(0, 0, 30, 20);\n fill('black');\n circle(0, 0, 8);\n pop();\n\n // End the drawing group.\n pop();\n\n // Draw a bug.\n let x = random(0, 100);\n let y = random(0, 100);\n text('🦟', x, y);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Draw the red sphere.\n push();\n translate(-25, 0, 0);\n noStroke();\n directionalLight(255, 0, 0, 0, 0, -1);\n sphere(20);\n pop();\n\n // Draw the blue sphere.\n push();\n translate(25, 0, 0);\n strokeWeight(0.3);\n stroke(0, 0, 255);\n noFill();\n sphere(20);\n pop();\n}\n
\nA function that's called once to load assets before the sketch runs.
\nDeclaring the function preload()
sets a code block to run once\nautomatically before setup() or\ndraw(). It's used to load assets including\nmultimedia files, fonts, data, and 3D models:
function preload() {\n // Code to run before the rest of the sketch.\n}\n
\nFunctions such as loadImage(),\nloadFont(),\nloadJSON(), and\nloadModel() are guaranteed to either\nfinish loading or raise an error if they're called within preload()
.\nDoing so ensures that assets are available when the sketch begins\nrunning.
\nlet img;\n\n// Load an image and create a p5.Image object.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Draw the image.\n image(img, 0, 0);\n\n describe('A red brick wall.');\n}\n
\nBegins a drawing group that contains its own styles and transformations.
\nBy default, styles such as fill() and\ntransformations such as rotate() are applied to\nall drawing that follows. The push()
and pop()\nfunctions can limit the effect of styles and transformations to a specific\ngroup of shapes, images, and text. For example, a group of shapes could be\ntranslated to follow the mouse without affecting the rest of the sketch:
// Begin the drawing group.\npush();\n\n// Translate the origin to the mouse's position.\ntranslate(mouseX, mouseY);\n\n// Style the face.\nnoStroke();\nfill('green');\n\n// Draw the face.\ncircle(0, 0, 60);\n\n// Style the eyes.\nfill('white');\n\n// Draw the left eye.\nellipse(-20, -20, 30, 20);\n\n// Draw the right eye.\nellipse(20, -20, 30, 20);\n\n// End the drawing group.\npop();\n\n// Draw a bug.\nlet x = random(0, 100);\nlet y = random(0, 100);\ntext('🦟', x, y);\n
\nIn the code snippet above, the bug's position isn't affected by\ntranslate(mouseX, mouseY)
because that transformation is contained\nbetween push()
and pop(). The bug moves around\nthe entire canvas as expected.
Note: push()
and pop() are always called as a\npair. Both functions are required to begin and end a drawing group.
push()
and pop() can also be nested to create\nsubgroups. For example, the code snippet above could be changed to give\nmore detail to the frog’s eyes:
// Begin the drawing group.\npush();\n\n// Translate the origin to the mouse's position.\ntranslate(mouseX, mouseY);\n\n// Style the face.\nnoStroke();\nfill('green');\n\n// Draw a face.\ncircle(0, 0, 60);\n\n// Style the eyes.\nfill('white');\n\n// Draw the left eye.\npush();\ntranslate(-20, -20);\nellipse(0, 0, 30, 20);\nfill('black');\ncircle(0, 0, 8);\npop();\n\n// Draw the right eye.\npush();\ntranslate(20, -20);\nellipse(0, 0, 30, 20);\nfill('black');\ncircle(0, 0, 8);\npop();\n\n// End the drawing group.\npop();\n\n// Draw a bug.\nlet x = random(0, 100);\nlet y = random(0, 100);\ntext('🦟', x, y);\n
\nIn this version, the code to draw each eye is contained between its own\npush()
and pop() functions. Doing so makes it\neasier to add details in the correct part of a drawing.
push()
and pop() contain the effects of the\nfollowing functions:
In WebGL mode, push()
and pop() contain the\neffects of a few additional styles:
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw the left circle.\n circle(25, 50, 20);\n\n // Begin the drawing group.\n push();\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Style the circle.\n strokeWeight(5);\n stroke('royalblue');\n fill('orange');\n\n // Draw the circle.\n circle(0, 0, 20);\n\n // End the drawing group.\n pop();\n\n // Draw the right circle.\n circle(75, 50, 20);\n\n describe(\n '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.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(24);\n\n describe('A mosquito buzzes in front of a green frog. The frog follows the mouse as the user moves.');\n}\n\nfunction draw() {\n background(200);\n\n // Begin the drawing group.\n push();\n\n // Translate the origin to the mouse's position.\n translate(mouseX, mouseY);\n\n // Style the face.\n noStroke();\n fill('green');\n\n // Draw a face.\n circle(0, 0, 60);\n\n // Style the eyes.\n fill('white');\n\n // Draw the left eye.\n push();\n translate(-20, -20);\n ellipse(0, 0, 30, 20);\n fill('black');\n circle(0, 0, 8);\n pop();\n\n // Draw the right eye.\n push();\n translate(20, -20);\n ellipse(0, 0, 30, 20);\n fill('black');\n circle(0, 0, 8);\n pop();\n\n // End the drawing group.\n pop();\n\n // Draw a bug.\n let x = random(0, 100);\n let y = random(0, 100);\n text('🦟', x, y);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Draw the red sphere.\n push();\n translate(-25, 0, 0);\n noStroke();\n directionalLight(255, 0, 0, 0, 0, -1);\n sphere(20);\n pop();\n\n // Draw the blue sphere.\n push();\n translate(25, 0, 0);\n strokeWeight(0.3);\n stroke(0, 0, 255);\n noFill();\n sphere(20);\n pop();\n}\n
\nRuns the code in draw() once.
\nBy default, draw() tries to run 60 times per\nsecond. Calling noLoop() stops\ndraw() from repeating. Calling redraw()
will\nexecute the code in the draw() function a set\nnumber of times.
The parameter, n
, is optional. If a number is passed, as in redraw(5)
,\nthen the draw loop will run the given number of times. By default, n
is\n1.
number of times to run draw(). Defaults to 1.
\n"],"type":[0,"Integer"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// Double-click the canvas to move the circle.\n\nlet x = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Turn off the draw loop.\n noLoop();\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Draw the circle.\n circle(x, 50, 20);\n\n // Increment x.\n x += 5;\n}\n\n// Run the draw loop when the user double-clicks.\nfunction doubleClicked() {\n redraw();\n}\n
\n\n// Double-click the canvas to move the circle.\n\nlet x = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Turn off the draw loop.\n noLoop();\n\n describe(\n 'A white half-circle on the left edge of a gray square. The circle hops to the right when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Draw the circle.\n circle(x, 50, 20);\n\n // Increment x.\n x += 5;\n}\n\n// Run the draw loop three times when the user double-clicks.\nfunction doubleClicked() {\n redraw(3);\n}\n
\nRemoves the sketch from the web page.
\nCalling remove()
stops the draw loop and removes any HTML elements\ncreated by the sketch, including the canvas. A new sketch can be\ncreated by using the p5() constructor, as in\nnew p5()
.
\n// Double-click to remove the canvas.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A white circle on a gray background. The circle follows the mouse as the user moves. The sketch disappears when the user double-clicks.'\n );\n}\n\nfunction draw() {\n // Paint the background repeatedly.\n background(200);\n\n // Draw circles repeatedly.\n circle(mouseX, mouseY, 40);\n}\n\n// Remove the sketch when the user double-clicks.\nfunction doubleClicked() {\n remove();\n}\n
\nA function that's called once when the sketch begins running.
\nDeclaring the function setup()
sets a code block to run once\nautomatically when the sketch starts running. It's used to perform\nsetup tasks such as creating the canvas and initializing variables:
function setup() {\n // Code to run once at the start of the sketch.\n}\n
\nCode placed in setup()
will run once before code placed in\ndraw() begins looping. If the\npreload() is declared, then setup()
will\nrun immediately after preload() finishes\nloading assets.
Note: setup()
doesn’t have to be declared, but it’s common practice to do so.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw the circle.\n circle(50, 50, 40);\n\n describe('A white circle on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Paint the background once.\n background(200);\n\n describe(\n 'A white circle on a gray background. The circle follows the mouse as the user moves, leaving a trail.'\n );\n}\n\nfunction draw() {\n // Draw circles repeatedly.\n circle(mouseX, mouseY, 40);\n}\n
\n\nlet img;\n\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Draw the image.\n image(img, 0, 0);\n\n describe(\n 'A white circle on a brick wall. The circle follows the mouse as the user moves, leaving a trail.'\n );\n}\n\nfunction draw() {\n // Style the circle.\n noStroke();\n\n // Draw the circle.\n circle(mouseX, mouseY, 10);\n}\n
\nAUTO allows us to automatically set the width or height of an element (but not both),\nbased on the current height and width of the element. Only one parameter can\nbe passed to the size function as AUTO, at a time.
\n"],"line":[0,810],"itemtype":[0,"property"],"class":[0,"p5"],"isConstructor":[0,false],"path":[0,"p5/AUTO"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/constants/DEGREES.mdx"],"slug":[0,"en/p5/constants/degrees"],"body":[0,"\n\n# DEGREES\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"DEGREES"],"module":[0,"Constants"],"submodule":[0,"Constants"],"file":[0,"src/core/constants.js"],"description":[0,"A String
constant that's used to set the\nangleMode().
By default, functions such as rotate() and\nsin() expect angles measured in units of radians.\nCalling angleMode(DEGREES)
ensures that angles are measured in units of\ndegrees.
Note: TWO_PI
radians equals 360˚.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw a red arc from 0 to HALF_PI radians.\n fill(255, 0, 0);\n arc(50, 50, 80, 80, 0, HALF_PI);\n\n // Use degrees.\n angleMode(DEGREES);\n\n // Draw a blue arc from 90˚ to 180˚.\n fill(0, 0, 255);\n arc(50, 50, 80, 80, 90, 180);\n\n describe('The bottom half of a circle drawn on a gray background. The bottom-right quarter is red. The bottom-left quarter is blue.');\n}\n
\nA Number
constant that's approximately 1.5708.
HALF_PI
is half the value of the mathematical constant π. It's useful for\nmany tasks that involve rotation and oscillation. For example, calling\nrotate(HALF_PI)
rotates the coordinate system HALF_PI
radians, which is\na quarter turn (90˚).
Note: TWO_PI
radians equals 360˚, PI
radians equals 180˚, HALF_PI
\nradians equals 90˚, and QUARTER_PI
radians equals 45˚.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw an arc from 0 to HALF_PI.\n arc(50, 50, 80, 80, 0, HALF_PI);\n\n describe('The bottom-right quarter of a circle drawn in white on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Draw a line.\n line(0, 0, 40, 0);\n\n // Rotate a quarter turn.\n rotate(HALF_PI);\n\n // Draw the same line, rotated.\n line(0, 0, 40, 0);\n\n 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.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Calculate the x-coordinates.\n let x1 = 40 * sin(frameCount * 0.05);\n let x2 = 40 * sin(frameCount * 0.05 + HALF_PI);\n\n // Style the oscillators.\n noStroke();\n\n // Draw the red oscillator.\n fill(255, 0, 0);\n circle(x1, 0, 20);\n\n // Draw the blue oscillator.\n fill(0, 0, 255);\n circle(x2, 0, 20);\n}\n
\nHSB (hue, saturation, brightness) is a type of color model.\nYou can learn more about it at\nHSB.
\n"],"line":[0,794],"itemtype":[0,"property"],"class":[0,"p5"],"isConstructor":[0,false],"path":[0,"p5/HSB"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/constants/P2D.mdx"],"slug":[0,"en/p5/constants/p2d"],"body":[0,"\n\n# P2D\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"P2D"],"module":[0,"Constants"],"submodule":[0,"Constants"],"file":[0,"src/core/constants.js"],"description":[0,"The default, two-dimensional renderer.
\n"],"line":[0,18],"itemtype":[0,"property"],"class":[0,"p5"],"isConstructor":[0,false],"path":[0,"p5/P2D"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/constants/PI.mdx"],"slug":[0,"en/p5/constants/pi"],"body":[0,"\n\n# PI\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"PI"],"module":[0,"Constants"],"submodule":[0,"Constants"],"file":[0,"src/core/constants.js"],"description":[0,"A Number
constant that's approximately 3.1416.
PI
is the mathematical constant π. It's useful for many tasks that\ninvolve rotation and oscillation. For example, calling rotate(PI)
rotates\nthe coordinate system PI
radians, which is a half turn (180˚).
Note: TWO_PI
radians equals 360˚, PI
radians equals 180˚, HALF_PI
\nradians equals 90˚, and QUARTER_PI
radians equals 45˚.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw an arc from 0 to PI.\n arc(50, 50, 80, 80, 0, PI);\n\n describe('The bottom half of a circle drawn in white on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Draw a line.\n line(0, 0, 40, 0);\n\n // Rotate a half turn.\n rotate(PI);\n\n // Draw the same line, rotated.\n line(0, 0, 40, 0);\n\n describe('A horizontal black line on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Calculate the x-coordinates.\n let x1 = 40 * sin(frameCount * 0.05);\n let x2 = 40 * sin(frameCount * 0.05 + PI);\n\n // Style the oscillators.\n noStroke();\n\n // Draw the red oscillator.\n fill(255, 0, 0);\n circle(x1, 0, 20);\n\n // Draw the blue oscillator.\n fill(0, 0, 255);\n circle(x2, 0, 20);\n}\n
\nA Number
constant that's approximately 0.7854.
QUARTER_PI
is one-fourth the value of the mathematical constant π. It's\nuseful for many tasks that involve rotation and oscillation. For example,\ncalling rotate(QUARTER_PI)
rotates the coordinate system QUARTER_PI
\nradians, which is an eighth of a turn (45˚).
Note: TWO_PI
radians equals 360˚, PI
radians equals 180˚, HALF_PI
\nradians equals 90˚, and QUARTER_PI
radians equals 45˚.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw an arc from 0 to QUARTER_PI.\n arc(50, 50, 80, 80, 0, QUARTER_PI);\n\n describe('A one-eighth slice of a circle drawn in white on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Draw a line.\n line(0, 0, 40, 0);\n\n // Rotate an eighth turn.\n rotate(QUARTER_PI);\n\n // Draw the same line, rotated.\n line(0, 0, 40, 0);\n\n describe('Two black lines that form a \"V\" opening towards the bottom-right corner of a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n '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.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Calculate the x-coordinates.\n let x1 = 40 * sin(frameCount * 0.05);\n let x2 = 40 * sin(frameCount * 0.05 + QUARTER_PI);\n\n // Style the oscillators.\n noStroke();\n\n // Draw the red oscillator.\n fill(255, 0, 0);\n circle(x1, 0, 20);\n\n // Draw the blue oscillator.\n fill(0, 0, 255);\n circle(x2, 0, 20);\n}\n
\nA String
constant that's used to set the\nangleMode().
By default, functions such as rotate() and\nsin() expect angles measured in units of radians.\nCalling angleMode(RADIANS)
ensures that angles are measured in units of\nradians. Doing so can be useful if the\nangleMode() has been set to\nDEGREES.
Note: TWO_PI
radians equals 360˚.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use degrees.\n angleMode(DEGREES);\n\n // Draw a red arc from 0˚ to 90˚.\n fill(255, 0, 0);\n arc(50, 50, 80, 80, 0, 90);\n\n // Use radians.\n angleMode(RADIANS);\n\n // Draw a blue arc from HALF_PI to PI.\n fill(0, 0, 255);\n arc(50, 50, 80, 80, HALF_PI, PI);\n\n describe('The bottom half of a circle drawn on a gray background. The bottom-right quarter is red. The bottom-left quarter is blue.');\n}\n
\nA Number
constant that's approximately 6.2382.
TAU
is twice the value of the mathematical constant π. It's useful for\nmany tasks that involve rotation and oscillation. For example, calling\nrotate(TAU)
rotates the coordinate system TAU
radians, which is one\nfull turn (360˚). TAU
and TWO_PI
are equal.
Note: TAU
radians equals 360˚, PI
radians equals 180˚, HALF_PI
\nradians equals 90˚, and QUARTER_PI
radians equals 45˚.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw an arc from 0 to TAU.\n arc(50, 50, 80, 80, 0, TAU);\n\n describe('A white circle drawn on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Draw a line.\n line(0, 0, 40, 0);\n\n // Rotate a full turn.\n rotate(TAU);\n\n // Style the second line.\n strokeWeight(5);\n\n // Draw the same line, shorter and rotated.\n line(0, 0, 20, 0);\n\n describe(\n '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.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A red circle with a blue center oscillates from left to right on a gray background.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Calculate the x-coordinates.\n let x1 = 40 * sin(frameCount * 0.05);\n let x2 = 40 * sin(frameCount * 0.05 + TAU);\n\n // Style the oscillators.\n noStroke();\n\n // Draw the red oscillator.\n fill(255, 0, 0);\n circle(x1, 0, 20);\n\n // Draw the blue oscillator, smaller.\n fill(0, 0, 255);\n circle(x2, 0, 10);\n}\n
\nA Number
constant that's approximately 6.2382.
TWO_PI
is twice the value of the mathematical constant π. It's useful for\nmany tasks that involve rotation and oscillation. For example, calling\nrotate(TWO_PI)
rotates the coordinate system TWO_PI
radians, which is\none full turn (360˚). TWO_PI
and TAU
are equal.
Note: TWO_PI
radians equals 360˚, PI
radians equals 180˚, HALF_PI
\nradians equals 90˚, and QUARTER_PI
radians equals 45˚.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw an arc from 0 to TWO_PI.\n arc(50, 50, 80, 80, 0, TWO_PI);\n\n describe('A white circle drawn on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Draw a line.\n line(0, 0, 40, 0);\n\n // Rotate a full turn.\n rotate(TWO_PI);\n\n // Style the second line.\n strokeWeight(5);\n\n // Draw the same line, shorter and rotated.\n line(0, 0, 20, 0);\n\n describe(\n '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.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A red circle with a blue center oscillates from left to right on a gray background.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Calculate the x-coordinates.\n let x1 = 40 * sin(frameCount * 0.05);\n let x2 = 40 * sin(frameCount * 0.05 + TWO_PI);\n\n // Style the oscillators.\n noStroke();\n\n // Draw the red oscillator.\n fill(255, 0, 0);\n circle(x1, 0, 20);\n\n // Draw the blue oscillator, smaller.\n fill(0, 0, 255);\n circle(x2, 0, 10);\n}\n
\nVersion of this p5.js.
\n"],"line":[0,9],"itemtype":[0,"property"],"class":[0,"p5"],"isConstructor":[0,false],"path":[0,"p5/VERSION"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/constants/WEBGL.mdx"],"slug":[0,"en/p5/constants/webgl"],"body":[0,"\n\n# WEBGL\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"WEBGL"],"module":[0,"Constants"],"submodule":[0,"Constants"],"file":[0,"src/core/constants.js"],"description":[0,"One of the two render modes in p5.js, used for computationally intensive tasks like 3D rendering and shaders.
\nWEBGL
differs from the default P2D
renderer in the following ways:
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.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.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.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.WEBGL
sketch can be adjusted by changing camera attributes. See the tutorial page section about cameras for an explanation of camera controls.WEBGL
requires opentype/truetype font files to be preloaded using loadFont(). See the wiki section about text for details, along with a workaround.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\".
\n"],"line":[0,24],"itemtype":[0,"property"],"class":[0,"p5"],"isConstructor":[0,false],"path":[0,"p5/WEBGL"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/constants/WEBGL2.mdx"],"slug":[0,"en/p5/constants/webgl2"],"body":[0,"\n\n# WEBGL2\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"WEBGL2"],"module":[0,"Constants"],"submodule":[0,"Constants"],"file":[0,"src/core/constants.js"],"description":[0,"One of the two possible values of a WebGL canvas (either WEBGL or WEBGL2),\nwhich can be used to determine what capabilities the rendering environment\nhas.
\n"],"line":[0,45],"itemtype":[0,"property"],"class":[0,"p5"],"isConstructor":[0,false],"path":[0,"p5/WEBGL2"]}],"render":[0,null]}]]]}]]]}],[0,{"name":[0,"Foundation"],"subcats":[1,[[0,{"name":[0],"entry":[0],"entries":[1,[]]}],[0,{"name":[0],"entry":[0],"entries":[1,[[0,{"id":[0,"en/p5/class.mdx"],"slug":[0,"en/p5/class"],"body":[0,"\n\n# class\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"class"],"module":[0,"Foundation"],"submodule":[0,"Foundation"],"file":[0,"src/core/reference.js"],"description":[0,"A template for creating objects of a particular type.
\nClasses can make it easier to program with objects. For example, a Frog
\nclass could create objects that behave like frogs. Each object created\nusing a class is called an instance of that class. All instances of a class\nare the same type. Here's an example of creating an instance of a Frog
\nclass:
let fifi = new Frog(50, 50, 20);\n
\nThe variable fifi
refers to an instance of the Frog
class. The keyword\nnew
is used to call the Frog
class' constructor in the statement\nnew Frog()
. Altogether, a new Frog
object was created and assigned to\nthe variable fifi
. Classes are templates, so they can be used to create\nmore than one instance:
// First Frog instance.\nlet frog1 = new Frog(25, 50, 10);\n\n// Second Frog instance.\nlet frog2 = new Frog(75, 50, 10);\n
\nA simple Frog
class could be declared as follows:
class Frog {\n constructor(x, y, size) {\n // This code runs once when an instance is created.\n this.x = x;\n this.y = y;\n this.size = size;\n }\n\n show() {\n // This code runs once when myFrog.show() is called.\n textAlign(CENTER, CENTER);\n textSize(this.size);\n text('🐸', this.x, this.y);\n }\n\n hop() {\n // This code runs once when myFrog.hop() is called.\n this.x += random(-10, 10);\n this.y += random(-10, 10);\n }\n}\n
\nClass declarations begin with the keyword class
followed by the class\nname, such as Frog
, and curly braces {}
. Class names should use\nPascalCase
and can't have spaces in their names. For example, naming a\nclass Kermit The Frog
with spaces between each word would throw a\nSyntaxError
. The code between the curly braces {}
defines the class.
Functions that belong to a class are called methods. constructor()
,\nshow()
, and hop()
are methods in the Frog
class. Methods define an\nobject's behavior. Methods can accept parameters and return values, just\nlike functions. Note that methods don't use the function
keyword.
constructor()
is a special method that's called once when an instance of\nthe class is created. The statement new Frog()
calls the Frog
class'\nconstructor()
method.
A class definition is a template for instances. The keyword this
refers\nto an instance's data and methods. For example, each Frog
instance has\nunique coordinates stored in this.x
and this.y
. The show()
method\nuses those coordinates to draw the frog. The hop()
method updates those\ncoordinates when called. Once a Frog
instance is created, its data and\nmethods can be accessed using the dot operator .
as follows:
// Draw a lily pad.\nfill('green');\nstroke('green');\ncircle(fifi.x, fifi.y, 2 * fifi.size);\n\n// Show the Frog.\nfifi.show();\n\n// Hop.\nfifi.hop();\n
\n"],"line":[0,1329],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n// Declare a frog variable.\nlet fifi;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Assign the frog variable a new Frog object.\n fifi = new Frog(50, 50, 20);\n\n describe('A frog face drawn on a blue background.');\n}\n\nfunction draw() {\n background('cornflowerblue');\n\n // Show the frog.\n fifi.show();\n}\n\nclass Frog {\n constructor(x, y, size) {\n this.x = x;\n this.y = y;\n this.size = size;\n }\n\n show() {\n textAlign(CENTER, CENTER);\n textSize(this.size);\n text('🐸', this.x, this.y);\n }\n}\n
\n\n// Declare two frog variables.\nlet frog1;\nlet frog2;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Assign the frog variables a new Frog object.\n frog1 = new Frog(25, 50, 10);\n frog2 = new Frog(75, 50, 20);\n\n describe('Two frog faces drawn next to each other on a blue background.');\n}\n\nfunction draw() {\n background('cornflowerblue');\n\n // Show the frogs.\n frog1.show();\n frog2.show();\n}\n\nclass Frog {\n constructor(x, y, size) {\n this.x = x;\n this.y = y;\n this.size = size;\n }\n\n show() {\n textAlign(CENTER, CENTER);\n textSize(this.size);\n text('🐸', this.x, this.y);\n }\n}\n
\n\n// Declare two frog variables.\nlet frog1;\nlet frog2;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Assign the frog variables a new Frog object.\n frog1 = new Frog(25, 50, 10);\n frog2 = new Frog(75, 50, 20);\n\n // Slow the frame rate.\n frameRate(1);\n\n describe('Two frog faces on a blue background. The frogs hop around randomly.');\n}\n\nfunction draw() {\n background('cornflowerblue');\n\n // Show the frogs.\n frog1.show();\n frog2.show();\n\n // Move the frogs.\n frog1.hop();\n frog2.hop();\n\n // Wrap around if they've hopped off the edge.\n frog1.checkEdges();\n frog2.checkEdges();\n}\n\nclass Frog {\n constructor(x, y, size) {\n this.x = x;\n this.y = y;\n this.size = size;\n }\n\n show() {\n textAlign(CENTER, CENTER);\n textSize(this.size);\n text('🐸', this.x, this.y);\n }\n\n hop() {\n this.x += random(-10, 10);\n this.y += random(-10, 10);\n }\n\n checkEdges() {\n if (this.x > width) {\n this.x = this.x - width;\n } else if (this.x < 0) {\n this.x = width - this.x;\n }\n\n if (this.y > height) {\n this.y = this.y - height;\n } else if (this.y < 0) {\n this.y = height - this.y;\n }\n }\n}\n
\n\n// Create an array that will hold frogs.\nlet frogs = [];\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Add Frog objects to the array.\n for (let i = 0; i < 5; i += 1) {\n // Calculate random coordinates and size.\n let x = random(0, 100);\n let y = random(0, 100);\n let s = random(2, 20);\n\n // Create a new Frog object.\n let frog = new Frog(x, y, s);\n\n // Add the Frog to the array.\n frogs.push(frog);\n }\n\n // Slow the frame rate.\n frameRate(1);\n\n describe(\n 'Five frog faces on a blue background. The frogs hop around randomly.'\n );\n}\n\nfunction draw() {\n background('cornflowerblue');\n\n for (let frog of frogs) {\n // Show the frog.\n frog.show();\n\n // Move the frog.\n frog.hop();\n\n // Wrap around if they've hopped off the edge.\n frog.checkEdges();\n }\n}\n\nclass Frog {\n constructor(x, y, size) {\n this.x = x;\n this.y = y;\n this.size = size;\n }\n\n show() {\n textAlign(CENTER, CENTER);\n textSize(this.size);\n text('🐸', this.x, this.y);\n }\n\n hop() {\n this.x += random(-10, 10);\n this.y += random(-10, 10);\n }\n\n checkEdges() {\n if (this.x > width) {\n this.x = this.x - width;\n } else if (this.x < 0) {\n this.x = width - this.x;\n }\n\n if (this.y > height) {\n this.y = this.y - height;\n } else if (this.y < 0) {\n this.y = height - this.y;\n }\n }\n}\n
\nPrints a message to the web browser's console.
\nThe console\nobject is helpful for printing messages while debugging. For example, it's\ncommon to add a console.log()
statement while studying how a section of\ncode works:
if (isPlaying === true) {\n // Add a console.log() statement to make sure this block of code runs.\n console.log('Got here!');\n\n // Game logic.\n}\n
\nconsole.error()
is helpful for tracking errors because it prints\nformatted messages. For example, it's common to encounter errors when\nloading media assets:
// Logs an error message with special formatting.\nfunction handleFailure(error) {\n console.error('Oops!', error);\n}\n\n// Try to load an image and call handleError() if it fails.\nloadImage('https://example.com/cat.jpg', handleImage, handleError);\n
\n"],"line":[0,1988],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n noCanvas();\n\n // Prints \"Hello!\" to the console.\n console.log('Hello!');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Try to load an image from a fake URL.\n // Call handleError() if the image fails to load.\n loadImage('https://example.com/cat.jpg', handleImage, handleError);\n}\n\n// Displays the image.\nfunction handleImage(img) {\n image(img, 0, 0);\n\n describe('A cat on a gray background.');\n}\n\n// Prints the error.\nfunction handleError(error) {\n console.error('Oops!', error);\n\n describe('A gray square.');\n}\n
\nA way to repeat a block of code when the number of iterations is known.
\nfor
loops are helpful for repeating statements a certain number of times.\nFor example, a for
loop makes it easy to express the idea\n\"draw five lines\" like so:
for (let x = 10; x < 100; x += 20) {\n line(x, 25, x, 75);\n}\n
\nThe loop's header begins with the keyword for
. Loops generally count up\nor count down as they repeat, or iterate. The statements in parentheses\nlet 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\nloop body are repeated during each iteration of the loop.
It's common to create infinite loops accidentally. When this happens,\nsketches may become unresponsive and the web browser may display a warning.\nFor example, the following loop never stops iterating because it doesn't\ncount up:
\nfor (let x = 10; x < 100; x = 20) {\n line(x, 25, x, 75);\n}\n
\nThe statement x = 20
keeps the variable x
stuck at 20
, which is\nalways less than 100
.
for
loops can also count down:
for (let d = 100; d > 0; d -= 10) {\n circle(50, 50, d);\n}\n
\nfor
loops can also contain other loops. The following nested loop draws a\ngrid of points:
// Loop from left to right.\nfor (let x = 10; x < 100; x += 10) {\n\n // Loop from top to bottom.\n for (let y = 10; y < 100; y += 10) {\n point(x, y);\n }\n\n}\n
\nfor
loops are also helpful for iterating through the elements of an\narray. For example, it's common to iterate through an array that contains\ninformation about where or what to draw:
// Create an array of x-coordinates.\nlet xCoordinates = [20, 40, 60];\n\nfor (let i = 0; i < xCoordinates.length; i += 1) {\n // Update the element.\n xCoordinates[i] += random(-1, 1);\n\n // Draw a circle.\n circle(xCoordinates[i], 50, 20);\n}\n
\nIf the array's values aren't modified, the for...of
statement can\nsimplify the code. They're similar to for
loops in Python and for-each
\nloops in C++ and Java. The following loops have the same effect:
// Draw circles with a for loop.\nlet xCoordinates = [20, 40, 60];\n\nfor (let i = 0; i < xCoordinates.length; i += 1) {\n circle(xCoordinates[i], 50, 20);\n}\n
\n// Draw circles with a for...of statement.\nlet xCoordinates = [20, 40, 60];\n\nfor (let x of xCoordinates) {\n circle(x, 50, 20);\n}\n
\nIn 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\nxCoordinates.length
. i
is used to access the element in xCoordinates
\nat index i
.
In the second code snippet, x
isn't keeping track of the loop's progress\nor an index. During each iteration, x
contains the next element of\nxCoordinates
. x
starts from the beginning of xCoordinates
(20
) and\nupdates its value to 40
and then 60
during the next iterations.
\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Five black vertical lines on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw vertical lines using a loop.\n for (let x = 10; x < 100; x += 20) {\n line(x, 25, x, 75);\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Five white concentric circles drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw concentric circles using a loop.\n for (let d = 100; d > 0; d -= 20) {\n circle(50, 50, d);\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A grid of black dots on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Set the spacing for points on the grid.\n let space = 10;\n\n // Increase the stroke weight.\n strokeWeight(3);\n\n // Loop from the left to the right.\n for (let x = space; x < 100; x += space) {\n // Loop from the top to the bottom.\n for (let y = space; y < 100; y += space) {\n point(x, y);\n }\n }\n}\n
\n\n// Declare the variable xCoordinates and assign it an array of numbers.\nlet xCoordinates = [20, 40, 60, 80];\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Four white circles drawn in a horizontal line on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the element at index i and use it to draw a circle.\n for (let i = 0; i < xCoordinates.length; i += 1) {\n circle(xCoordinates[i], 50, 20);\n }\n}\n
\n\n// Declare the variable xCoordinates and assign it an array of numbers.\nlet xCoordinates = [20, 40, 60, 80];\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Four white circles drawn in a horizontal line on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access each element of the array and use it to draw a circle.\n for (let x of xCoordinates) {\n circle(x, 50, 20);\n }\n}\n
\nA named group of statements.
\nFunctions\nhelp with organizing and reusing code. For example, functions make it easy\nto express the idea \"Draw a flower.\":
\nfunction drawFlower() {\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(20);\n\n // Draw a flower emoji.\n text('🌸', 50, 50);\n}\n
\nThe function header begins with the keyword function
. The function's\nname, drawFlower
, is followed by parentheses ()
and curly braces {}
.\nThe code between the curly braces is called the function's body. The\nfunction's body runs when the function is called like so:
drawFlower();\n
\nFunctions can accept inputs by adding parameters to their headers.\nParameters are placeholders for values that will be provided when the\nfunction is called. For example, the drawFlower()
function could include\na parameter for the flower's size:
function drawFlower(size) {\n // Style the text.\n textAlign(CENTER, CENTER);\n\n // Use the size parameter.\n textSize(size);\n\n // Draw a flower emoji.\n text('🌸', 50, 50);\n}\n
\nParameters are part of the function's declaration. Arguments are provided\nby the code that calls a function. When a function is called, arguments are\nassigned to parameters:
\n// The argument 20 is assigned to the parameter size.\ndrawFlower(20);\n
\nFunctions can have multiple parameters separated by commas. Parameters\ncan have any type. For example, the drawFlower()
function could accept\nNumber
parameters for the flower's x- and y-coordinates along with its\nsize:
function drawFlower(x, y, size) {\n // Style the text.\n textAlign(CENTER, CENTER);\n\n // Use the size parameter.\n textSize(size);\n\n // Draw a flower emoji.\n // Use the x and y parameters.\n text('🌸', x, y);\n}\n
\nFunctions can also produce outputs by adding a return
statement:
function double(x) {\n let answer = 2 * x;\n return answer;\n}\n
\nThe expression following return
can produce an output that's used\nelsewhere. For example, the output of the double()
function can be\nassigned to a variable:
let six = double(3);\ntext(`3 x 2 = ${six}`, 50, 50);\n
\n"],"line":[0,317],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A pink flower on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Call the drawFlower() function.\n drawFlower();\n}\n\n// Declare a function that draws a flower at the\n// center of the canvas.\nfunction drawFlower() {\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(20);\n\n // Draw a flower emoji.\n text('🌸', 50, 50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A pink flower on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Call the drawFlower() function and pass values for\n // its position and size.\n drawFlower(50, 50, 20);\n}\n\n// Declare a function that draws a flower at the\n// center of the canvas.\nfunction drawFlower(x, y, size) {\n // Style the text.\n textAlign(CENTER, CENTER);\n\n // Use the size parameter.\n textSize(size);\n\n // Draw a flower emoji.\n // Use the x and y parameters.\n text('🌸', x, y);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('The message \"Hello, 🌍!\" written on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Create a greeting.\n let greeting = createGreeting('🌍');\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the greeting.\n text(greeting, 50, 50);\n}\n\n// Return a string with a personalized greeting.\nfunction createGreeting(name) {\n let message = `Hello, ${name}!`;\n return message;\n}\n
\nA way to choose whether to run a block of code.
\nif
statements are helpful for running a block of code based on a\ncondition. For example, an if
statement makes it easy to express the\nidea \"Draw a circle if the mouse is pressed.\":
if (mouseIsPressed === true) {\n circle(mouseX, mouseY, 20);\n}\n
\nThe statement header begins with the keyword if
. The expression in\nparentheses mouseIsPressed === true
is a Boolean
expression that's\neither true
or false
. The code between the curly braces {}
is the if\nstatement's body. The body only runs if the Boolean
expression is true
.
The mouseIsPressed system variable is\nalways true
or false
, so the code snippet above could also be written\nas follows:
if (mouseIsPressed) {\n circle(mouseX, mouseY, 20);\n}\n
\nAn if
-else
statement adds a block of code that runs if the Boolean
\nexpression is false
. For example, here's an if
-else
statement that\nexpresses the idea \"Draw a circle if the mouse is pressed. Otherwise,\ndisplay a message.\":
if (mouseIsPressed === true) {\n // When true.\n circle(mouseX, mouseY, 20);\n} else {\n // When false.\n text('Click me!', 50, 50);\n}\n
\nThere are two possible paths, or branches, in this code snippet. The\nprogram must follow one branch or the other.
\nAn else
-if
statement makes it possible to add more branches.\nelse
-if
statements run different blocks of code under different\nconditions. For example, an else
-if
statement makes it easy to express\nthe idea \"If the mouse is on the left, paint the canvas white. If the mouse\nis in the middle, paint the canvas gray. Otherwise, paint the canvas\nblack.\":
if (mouseX < 33) {\n background(255);\n} else if (mouseX < 67) {\n background(200);\n} else {\n background(0);\n}\n
\nif
statements can add as many else
-if
statements as needed. However,\nthere can only be one else
statement and it must be last.
if
statements can also check for multiple conditions at once. For\nexample, the Boolean
operator &&
(AND) checks whether two expressions\nare both true
:
if (keyIsPressed === true && key === 'p') {\n text('You pressed the \"p\" key!', 50, 50);\n}\n
\nIf the user is pressing a key AND that key is 'p'
, then a message will\ndisplay.
The Boolean
operator ||
(OR) checks whether at least one of two\nexpressions is true
:
if (keyIsPressed === true || mouseIsPressed === true) {\n text('You did something!', 50, 50);\n}\n
\nIf the user presses a key, or presses a mouse button, or both, then a\nmessage will display.
\nThe body of an if
statement can contain another if
statement. This is\ncalled a \"nested if
statement.\" For example, nested if
statements make\nit easy to express the idea \"If a key is pressed, then check if the key is\n'r'
. If it is, then set the fill to red.\":
if (keyIsPressed === true) {\n if (key === 'r') {\n fill('red');\n }\n}\n
\nSee Boolean and Number\nto learn more about these data types and the operations they support.
\n"],"line":[0,110],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n// Click the mouse to show the circle.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A white circle on a gray background. The circle follows the mouse user clicks on the canvas.'\n );\n}\n\nfunction draw() {\n background(200);\n\n if (mouseIsPressed === true) {\n circle(mouseX, mouseY, 20);\n }\n}\n
\n\n// Click the mouse to show different shapes.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A white ellipse on a gray background. The ellipse becomes a circle when the user presses the mouse.'\n );\n}\n\nfunction draw() {\n background(200);\n\n if (mouseIsPressed === true) {\n circle(50, 50, 20);\n } else {\n ellipse(50, 50, 20, 50);\n }\n}\n
\n\n// Move the mouse to change the background color.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A square changes color from white to black as the user moves the mouse from left to right.'\n );\n}\n\nfunction draw() {\n if (mouseX < 33) {\n background(255);\n } else if (mouseX < 67) {\n background(200);\n } else {\n background(0);\n }\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A white circle drawn on a gray background. The circle changes color to red when the user presses the \"r\" key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n if (keyIsPressed === true) {\n if (key === 'r') {\n fill('red');\n }\n }\n\n circle(50, 50, 40);\n}\n
\nDeclares a new variable.
\nA variable is a container for a value. For example, a variable might\ncontain a creature's x-coordinate as a Number
or its name as a\nString
. Variables can change value by reassigning them as follows:
// Declare the variable x and assign it the value 10.\nlet x = 10;\n\n// Reassign x to 50.\nx = 50;\n
\nVariables have block scope. When a variable is declared between curly\nbraces {}
, it only exists within the block defined by those braces. For\nexample, the following code would throw a ReferenceError
because x
is\ndeclared within the setup()
function's block:
function setup() {\n createCanvas(100, 100);\n\n let x = 50;\n}\n\nfunction draw() {\n background(200);\n\n // x was declared in setup(), so it can't be referenced here.\n circle(x, 50, 20);\n}\n
\nVariables declared outside of all curly braces {}
are in the global\nscope. A variable that's in the global scope can be used and changed\nanywhere in a sketch:
let x = 50;\n\nfunction setup() {\n createCanvas(100, 100);\n}\n\nfunction draw() {\n background(200);\n\n // Change the value of x.\n x += 10;\n\n circle(x, 50, 20);\n}\n
\n"],"line":[0,7],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(220);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Create the message variable.\n let message = 'Hello, 🌍!';\n\n // Display the message.\n text(message, 50, 50);\n\n describe('The text \"Hello, 🌍!\" written on a gray background.');\n}\n
\n\nlet x = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle moves from left to right against a gray background.');\n}\n\nfunction draw() {\n background(220);\n\n // Change the value of x.\n x += 1;\n\n circle(x, 50, 20);\n}\n
\nA list that keeps several pieces of data in order.
\nArrays are helpful for storing related data. They can contain data of any\ntype. For example, an array could contain a list of someone's favorite\ncolors as strings. Arrays are created as follows:
\nlet myArray = ['deeppink', 'darkorchid', 'magenta'];\n
\nEach piece of data in an array is called an element. Each element has an\naddress, or index, within its array. The variable myArray
refers to an\narray with three String elements, 'deeppink'
,\n'darkorchid'
, and 'magenta'
. Arrays are zero-indexed, which means\nthat 'deeppink'
is at index 0, 'darkorchid'
is at index 1, and\n'magenta'
is at index 2. Array elements can be accessed using their\nindices as follows:
let zeroth = myArray[0]; // 'deeppink'\nlet first = myArray[1]; // 'darkorchid'\nlet second = myArray[2]; // 'magenta'\n
\nElements can be added to the end of an array by calling the\npush()\nmethod as follows:
\nmyArray.push('lavender');\n\nlet third = myArray[3]; // 'lavender'\n
\nSee MDN\nfor more information about arrays.
\n"],"line":[0,1140],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n// Declare the variable xCoordinates and assign it an array\n// with three numeric elements.\nlet xCoordinates = [25, 50, 75];\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'Three white circles drawn in a horizontal line on a gray background.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Access the element at index 0, which is 25.\n circle(xCoordinates[0], 50, 20);\n\n // Access the element at index 1, which is 50.\n circle(xCoordinates[1], 50, 20);\n\n // Access the element at index 2, which is 75.\n circle(xCoordinates[2], 50, 20);\n}\n
\n\n// Declare the variable xCoordinates and assign it an array with three numeric elements.\nlet xCoordinates = [20, 40, 60];\n\n// Add another element to the end of the array.\nxCoordinates.push(80);\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Four white circles drawn in a horizontal line on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the element at index 0, which is 20.\n circle(xCoordinates[0], 50, 20);\n\n // Access the element at index 1, which is 40.\n circle(xCoordinates[1], 50, 20);\n\n // Access the element at index 2, which is 60.\n circle(xCoordinates[2], 50, 20);\n\n // Access the element at index 3, which is 80.\n circle(xCoordinates[3], 50, 20);\n}\n
\n\n// Declare the variable xCoordinates and assign it an empty array.\nlet xCoordinates = [];\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Add elements to the array using a loop.\n for (let x = 20; x < 100; x += 20) {\n xCoordinates.push(x);\n }\n\n describe('Four white circles drawn in a horizontal line on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the element at index i and use it to draw a circle.\n for (let i = 0; i < xCoordinates.length; i += 1) {\n circle(xCoordinates[i], 50, 20);\n }\n}\n
\n\n// Declare the variable xCoordinates and assign it an empty array.\nlet xCoordinates = [];\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Add elements to the array using a loop.\n for (let x = 20; x < 100; x += 20) {\n xCoordinates.push(x);\n }\n\n describe('Four white circles drawn in a horizontal line on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access each element of the array and use it to draw a circle.\n for (let x of xCoordinates) {\n circle(x, 50, 20);\n }\n}\n
\n\n// Declare the variable xCoordinates and assign it an empty array.\nlet xCoordinates = [];\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Add elements to the array using a loop.\n for (let x = 20; x < 100; x += 20) {\n xCoordinates.push(x);\n }\n\n describe(\n 'Four white circles in a horizontal line on a gray background. The circles move randomly.'\n );\n}\n\nfunction draw() {\n background(200);\n\n for (let i = 0; i < xCoordinates.length; i += 1) {\n // Update the element at index i.\n xCoordinates[i] += random(-1, 1);\n\n // Use the element at index i to draw a circle.\n circle(xCoordinates[i], 50, 20);\n }\n}\n
\nA value that's either true
or false
.
Boolean
values help to make decisions in code. They appear any time a\nlogical condition is checked. For example, the condition\n\"Is a mouse button being pressed?\" must be either true
or\nfalse
:
// If the user presses the mouse, draw a circle at\n// the mouse's location.\nif (mouseIsPressed === true) {\n circle(mouseX, mouseY, 20);\n}\n
\nThe if
statement checks whether\nmouseIsPressed is true
and draws a\ncircle if it is. Boolean
expressions such as mouseIsPressed === true
\nevaluate to one of the two possible Boolean
values: true
or false
.
The ===
operator (EQUAL) checks whether two values are equal. If they\nare, the expression evaluates to true
. Otherwise, it evaluates to\nfalse
.
Note: There's also a ==
operator with two =
instead of three. Don't use\nit.
The mouseIsPressed system variable is\nalways true
or false
, so the code snippet above could also be written\nas follows:
if (mouseIsPressed) {\n circle(mouseX, mouseY, 20);\n}\n
\nThe !==
operator (NOT EQUAL) checks whether two values are not equal, as\nin the following example:
if (2 + 2 !== 4) {\n text('War is peace.', 50, 50);\n}\n
\nStarting from the left, the arithmetic expression 2 + 2
produces the\nvalue 4
. The Boolean
expression 4 !== 4
evaluates to false
because\n4
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\nit.
The Boolean
operator &&
(AND) checks whether two expressions are both\ntrue
:
if (keyIsPressed === true && key === 'p') {\n text('You pressed the \"p\" key!', 50, 50);\n}\n
\nIf the user is pressing a key AND that key is 'p'
, then a message will\ndisplay.
The Boolean
operator ||
(OR) checks whether at least one of two\nexpressions is true
:
if (keyIsPressed === true || mouseIsPressed === true) {\n text('You did something!', 50, 50);\n}\n
\nIf the user presses a key, or presses a mouse button, or both, then a\nmessage will display.
\nThe following truth table summarizes a few common scenarios with &&
and\n||
:
true && true // true\ntrue && false // false\nfalse && false // false\ntrue || true // true\ntrue || false // true\nfalse || false // false\n
\nThe relational operators >
, << code=\"\">,
>=
, and <=< code=\"\"> also produce
<>Boolean
\nvalues:=<>
2 > 1 // true\n2 < 1 // false\n2 >= 2 // true\n2 <= 2=\"\" true=\"\" <=\"\" code=\"\"/>
\nSee if for more information about if
statements and\nNumber for more information about Number
s.
\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A gray square. When the user presses the mouse, a circle appears at that location.');\n}\n\nfunction draw() {\n background(200);\n\n // If the user presses the mouse, draw a circle at that location.\n if (mouseIsPressed) {\n circle(mouseX, mouseY, 20);\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A gray square. When the user presses the mouse, a circle appears at that location.');\n}\n\nfunction draw() {\n background(200);\n\n // If the user presses the mouse, draw a circle at that location.\n if (mouseIsPressed === true) {\n circle(mouseX, mouseY, 20);\n }\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A gray square that turns pink when the user presses the mouse or a key.');\n}\n\nfunction draw() {\n background(200);\n\n // If the user presses the mouse, change the background color.\n if (mouseIsPressed === true || keyIsPressed === true) {\n background('deeppink');\n }\n}\n
\n\n// Click the canvas to begin detecting key presses.\n\n// Create a Boolean variable.\nlet isPlaying = false;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'The message \"Begin?\\nY or N\" written in green on a black background. The message \"Good luck!\" appears when they press the \"y\" key.'\n );\n}\n\nfunction draw() {\n background(0);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(16);\n fill(0, 255, 0);\n\n // Display a different message when the user begins playing.\n if (isPlaying === false) {\n text('Begin?', 50, 40);\n text('Y or N', 50, 60);\n } else {\n text('Good luck!', 50, 50);\n }\n}\n\n// Start playing when the user presses the 'y' key.\nfunction keyPressed() {\n if (key === 'y') {\n isPlaying = true;\n }\n}\n
\nA number that can be positive, negative, or zero.
\nThe Number
data type is useful for describing values such as position,\nsize, and color. A number can be an integer such as 20 or a decimal number\nsuch as 12.34. For example, a circle's position and size can be described\nby three numbers:
circle(50, 50, 20);\n
\ncircle(50, 50, 12.34);\n
\nNumbers support basic arithmetic and follow the standard order of\noperations: Parentheses, Exponents, Multiplication, Division, Addition,\nand Subtraction (PEMDAS). For example, it's common to use arithmetic\noperators with p5.js' system variables that are numbers:
\n// Draw a circle at the center.\ncircle(width / 2, height / 2, 20);\n
\n// Draw a circle that moves from left to right.\ncircle(frameCount * 0.01, 50, 20);\n
\nHere's a quick overview of the arithmetic operators:
\n1 + 2 // Add\n1 - 2 // Subtract\n1 * 2 // Multiply\n1 / 2 // Divide\n1 % 2 // Remainder\n1 ** 2 // Exponentiate\n
\nIt's common to update a number variable using arithmetic. For example, an\nobject's location can be updated like so:
\nx = x + 1;\n
\nThe statement above adds 1 to a variable x
using the +
operator. The\naddition assignment operator +=
expresses the same idea:
x += 1;\n
\nHere's a quick overview of the assignment operators:
\nx += 2 // Addition assignment\nx -= 2 // Subtraction assignment\nx *= 2 // Multiplication assignment\nx /= 2 // Division assignment\nx %= 2 // Remainder assignment\n
\nNumbers can be compared using the\nrelational operators\n>
, << code=\"\">,
>=
, <=< code=\"\">,
<>===
, and !==
. For example, a sketch's\nframeCount can be used as a timer:=<>
if (frameCount > 1000) {\n text('Game over!', 50, 50);\n}\n
\nAn expression such as frameCount > 1000
evaluates to a Boolean
value\nthat's either true
or false
. The relational operators all produce\nBoolean
values:
2 > 1 // true\n2 < 1 // false\n2 >= 2 // true\n2 <= 2=\"\" true=\"\" !=\"=\" false=\"\" <=\"\" code=\"\"/>
\nSee Boolean for more information about comparisons and conditions.
\nNote: There are also ==
and !=
operators with one fewer =
. Don't use them.
Expressions with numbers can also produce special values when something\ngoes wrong:
\nsqrt(-1) // NaN\n1 / 0 // Infinity\n
\nThe value NaN
stands for\nNot-A-Number.\nNaN
appears when calculations or conversions don't work. Infinity
is a\nvalue that's larger than any number. It appears during certain\ncalculations.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw a circle at the center.\n circle(50, 50, 70);\n\n // Draw a smaller circle at the center.\n circle(width / 2, height / 2, 30);\n\n describe('Two concentric, white circles drawn on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle travels from left to right on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n circle(frameCount * 0.05, 50, 20);\n}\n
\nA container for data that's stored as key-value pairs.
\nObjects help to organize related data of any type, including other objects.\nA value stored in an object can be accessed by name, called its key. Each\nkey-value pair is called a \"property.\" Objects are similar to dictionaries\nin Python and maps in Java and Ruby.
\nFor example, an object could contain the location, size, and appearance of\na dog:
\n// Declare the dog variable and assign it an object.\nlet dog = { x: 50, y: 50, size: 20, emoji: '🐶' };\n\n// Style the text.\ntextAlign(CENTER, CENTER);\ntextSize(dog.size);\n\n// Draw the dog.\ntext(dog.emoji, dog.x, dog.y);\n
\nThe variable dog
is assigned an object with four properties. Objects\nare declared with curly braces {}
. Values can be accessed using the dot\noperator, as in dog.size
. In the example above, the key size
\ncorresponds to the value 20
. Objects can also be empty to start:
// Declare a cat variable and assign it an empty object.\nlet cat = {};\n\n// Add properties to the object.\ncat.x = 50;\ncat.y = 50;\ncat.size = 20;\ncat.emoji = '🐱';\n\n// Style the text.\ntextAlign(CENTER, CENTER);\ntextSize(cat.size);\n\n// Draw the cat.\ntext(cat.emoji, cat.x, cat.y);\n
\nAn object's data can be updated while a sketch runs. For example, the cat
\ncould run away from the dog
by updating its location:
// Run to the right.\ncat.x += 5;\n
\nIf needed, an object's values can be accessed using square brackets []
\nand strings instead of dot notation:
// Run to the right.\ncat[\"x\"] += 5;\n
\nThis syntax can be helpful when the key's name has spaces, as in\ncat['height (m)']
.
\n// Declare the variable data and assign it an object with three properties.\nlet data = { x: 50, y: 50, d: 20 };\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the object's values using the . operator.\n circle(data.x, data.y, data.d);\n}\n
\n\n// Declare the variable data and assign it an object with three properties.\nlet data = { x: 50, y: 50, d: 20 };\n\n// Add another property for color.\ndata.color = 'deeppink';\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A pink circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the object's values using the . operator.\n fill(data.color);\n circle(data.x, data.y, data.d);\n}\n
\n\n// Declare the variable data and assign it an object with three properties.\nlet data = { x: 50, y: 50, d: 20 };\n\n// Add another property for color.\ndata.color = 'deeppink';\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the object's values using the . operator.\n fill(data.color);\n circle(data.x, data.y, data.d);\n\n // Update the object's x and y properties.\n data.x += random(-1, 1);\n data.y += random(-1, 1);\n}\n
\nA sequence of text characters.
\nThe String
data type is helpful for working with text. For example, a\nstring could contain a welcome message:
// Use a string literal.\ntext('Hello!', 10, 10);\n
\n// Create a string variable.\nlet message = 'Hello!';\n\n// Use the string variable.\ntext(message, 10, 10);\n
\nThe most common way to create strings is to use some form of quotations as\nfollows:
\ntext(\"hi\", 50, 50);\n
\ntext('hi', 50, 50);\n
\ntext(`hi`, 50, 50);\n
\n\"hi\"
, 'hi'
, and hi
are all string literals. A \"literal\" means a\nvalue was actually written, as in text('hi', 50, 50)
. By contrast,\ntext(message, 50, 50)
uses the variable message
, so it isn't a string\nliteral.
Single quotes ''
and double quotes \"\"
mean the same thing. It's nice to\nhave the option for cases when a string contains one type of quote:
text(\"What's up?\", 50, 50);\n
\ntext('Air quotes make you look \"cool.\"', 50, 50);\n
\nBackticks ``
create template literals. Template literals have many uses.\nFor example, they can contain both single and double quotes as needed:
text(`\"Don't you forget about me\"`, 10, 10);\n
\nTemplate literals are helpful when strings are created from variables like\nso:
\nlet size = random(10, 20);\ncircle(50, 50, size);\n\ntext(`The circle's diameter is ${size} pixels.`, 10, 10);\n
\nThe size
variable's value will replace ${size}
when the string is\ncreated. ${}
is a placeholder for any value. That means an expression can\nbe used, as in ${round(PI, 3)}
. All of the following are valid template\nliterals:
text(`π is about ${round(PI, 2)} pixels.`, 10, 10);\ntext(`It's ${mouseX < width / 2} that I'm on the left half of the canvas.`, 10, 30);\n
\nTemplate literals can include several variables:
\nlet x = random(0, 100);\nlet y = random(0, 100);\nlet size = random(10, 20);\ncircle(x, y, size);\n\ntext(`The circle at (${x}, ${y}) has a diameter of ${size} pixels.`, 10, 10);\n
\nTemplate literals are also helpful for creating multi-line text like so:
\nlet poem = `My sketch doesn't run;\nit waits for me patiently\nwhile bugs point the way.`;\n\ntext(poem, 10, 10);\n
\n"],"line":[0,710],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(20);\n\n // Display a welcome message.\n text('Hello!', 50, 50);\n\n describe('The text \"Hello!\" written on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(20);\n\n // Create a string variable.\n let world = '🌍';\n\n // Display a welcome message using a template string.\n text(`Hello, ${world}!`, 50, 50);\n\n describe('The text \"Hello, 🌍!\" written on a gray background.');\n}\n
\nA way to repeat a block of code.
\nwhile
loops are helpful for repeating statements while a condition is\ntrue
. They're like if
statements that repeat. For example, a while
\nloop makes it easy to express the idea \"draw several lines\" like so:
// Declare a variable to keep track of iteration.\nlet x = 10;\n\n// Repeat as long as x < 100\nwhile (x < 100) {\n line(x, 25, x, 75);\n\n // Increment by 20.\n x += 20;\n}\n
\nThe loop's header begins with the keyword while
. Loops generally count up\nor count down as they repeat, or iterate. The statement in parentheses\nx < 100
is a condition the loop checks each time it iterates. If the\ncondition is true
, the loop runs the code between the curly braces {}
,\nThe code between the curly braces is called the loop's body. If the\ncondition is false
, the body is skipped and the loop is stopped.
It's common to create infinite loops accidentally. For example, the\nfollowing loop never stops iterating because it doesn't count up:
\n// Declare a variable to keep track of iteration.\nlet x = 10;\n\n// Repeat as long as x < 100\nwhile (x < 100) {\n line(x, 25, x, 75);\n}\n\n// This should be in the loop's body!\nx += 20;\n
\nThe statement x += 20
appears after the loop's body. That means the\nvariable x
is stuck at 10
, which is always less than 100
.
while
loops are useful when the number of iterations isn't known in\nadvance. For example, concentric circles could be drawn at random\nincrements:
let d = 100;\nlet minSize = 5;\n\nwhile (d > minSize) {\n circle(50, 50, d);\n d -= random(10);\n}\n
\n"],"line":[0,1872],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Five black vertical lines on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Declare a variable to keep track of iteration.\n let x = 10;\n\n // Repeat as long as x < 100\n while (x < 100) {\n line(x, 25, x, 75);\n\n // Increment by 20.\n x += 20;\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(5);\n\n describe(\n \"A gray square with several concentric circles at the center. The circles' sizes decrease at random increments.\"\n );\n}\n\nfunction draw() {\n background(200);\n\n let d = 100;\n let minSize = 5;\n\n while (d > minSize) {\n circle(50, 50, d);\n d -= random(5, 15);\n }\n}\n
\n