// This file is auto-generated from JSDoc documentation declare const RGB: 'rgb'; declare const __RGB: typeof RGB; declare const RGBHDR: 'rgbhdr'; declare const __RGBHDR: typeof RGBHDR; /** * HSB (hue, saturation, brightness) is a type of color model. * You can learn more about it at * HSB. */ declare const HSB: 'hsb'; declare const __HSB: typeof HSB; declare const HSL: 'hsl'; declare const __HSL: typeof HSL; declare const HWB: 'hwb'; declare const __HWB: typeof HWB; declare const LAB: 'lab'; declare const __LAB: typeof LAB; declare const LCH: 'lch'; declare const __LCH: typeof LCH; declare const OKLAB: 'oklab'; declare const __OKLAB: typeof OKLAB; declare const OKLCH: 'oklch'; declare const __OKLCH: typeof OKLCH; declare const RGBA: 'rgba'; declare const __RGBA: typeof RGBA; /** * Version of this p5.js. */ declare const VERSION: string; declare const __VERSION: typeof VERSION; /** * The default, two-dimensional renderer in p5.js. * * Use this when calling (for example, * `createCanvas(400, 400, P2D)`) to specify a 2D context. */ declare const P2D: 'p2d'; declare const __P2D: typeof P2D; /** * A high-dynamic-range (HDR) variant of the default, two-dimensional renderer. * * When available, this mode can allow for extended color ranges and more * dynamic color representation. Use it similarly to `P2D`: * `createCanvas(400, 400, P2DHDR)`. */ declare const P2DHDR: 'p2d-hdr'; declare const __P2DHDR: typeof P2DHDR; /** * One of the two render modes in p5.js, used for computationally intensive tasks like 3D rendering and shaders. * * `WEBGL` differs from the default `P2D` renderer in the following ways: * * - Coordinate System - When drawing in `WEBGL` mode, the origin point (0,0,0) is located at the center of the screen, not the top-left corner. See the tutorial page about coordinates and transformations. * * - 3D Shapes - `WEBGL` mode can be used to draw 3-dimensional shapes like box(), sphere(), cone(), and more. See the tutorial page about custom geometry to make more complex objects. * * - Shape Detail - When drawing in `WEBGL` mode, you can specify how smooth curves should be drawn by using a `detail` parameter. See the wiki section about shapes for a more information and an example. * * - Textures - A texture is like a skin that wraps onto a shape. See the wiki section about textures for examples of mapping images onto surfaces with textures. * * - Materials and Lighting - `WEBGL` offers different types of lights like ambientLight() to place around a scene. Materials like specularMaterial() reflect the lighting to convey shape and depth. See the tutorial page for styling and appearance to experiment with different combinations. * * - Camera - The viewport of a `WEBGL` sketch can be adjusted by changing camera attributes. See the tutorial page section about cameras for an explanation of camera controls. * * - Text - `WEBGL` requires opentype/truetype font files to be preloaded using loadFont(). See the wiki section about text for details, along with a workaround. * * - Shaders - Shaders are hardware accelerated programs that can be used for a variety of effects and graphics. See the introduction to shaders to get started with shaders in p5.js. * * - Graphics Acceleration - `WEBGL` mode uses the graphics card instead of the CPU, so it may help boost the performance of your sketch (example: drawing more shapes on the screen at once). * * To learn more about WEBGL mode, check out all the interactive WEBGL tutorials in the "Tutorials" section of this website, or read the wiki article "Getting started with WebGL in p5". */ declare const WEBGL: 'webgl'; declare const __WEBGL: typeof WEBGL; /** * One of the two possible values of a WebGL canvas (either WEBGL or WEBGL2), * which can be used to determine what capabilities the rendering environment * has. */ declare const WEBGL2: 'webgl2'; declare const __WEBGL2: typeof WEBGL2; declare const ARROW: 'default'; declare const __ARROW: typeof ARROW; declare const SIMPLE: string; declare const __SIMPLE: typeof SIMPLE; declare const FULL: string; declare const __FULL: typeof FULL; declare const CROSS: 'crosshair'; declare const __CROSS: typeof CROSS; declare const HAND: 'pointer'; declare const __HAND: typeof HAND; declare const MOVE: 'move'; declare const __MOVE: typeof MOVE; declare const TEXT: 'text'; declare const __TEXT: typeof TEXT; declare const WAIT: 'wait'; declare const __WAIT: typeof WAIT; /** * A `Number` constant that's approximately 1.5708. * * `HALF_PI` is half the value of the mathematical constant π. It's useful for * many tasks that involve rotation and oscillation. For example, calling * `rotate(HALF_PI)` rotates the coordinate system `HALF_PI` radians, which is * a quarter turn (90˚). * * Note: `TWO_PI` radians equals 360˚, `PI` radians equals 180˚, `HALF_PI` * radians equals 90˚, and `QUARTER_PI` radians equals 45˚. */ declare const HALF_PI: number; declare const __HALF_PI: typeof HALF_PI; /** * A `Number` constant that's approximately 3.1416. * * `PI` is the mathematical constant π. It's useful for many tasks that * involve rotation and oscillation. For example, calling `rotate(PI)` rotates * the coordinate system `PI` radians, which is a half turn (180˚). * * Note: `TWO_PI` radians equals 360˚, `PI` radians equals 180˚, `HALF_PI` * radians equals 90˚, and `QUARTER_PI` radians equals 45˚. */ declare const PI: number; declare const __PI: typeof PI; /** * A `Number` constant that's approximately 0.7854. * * `QUARTER_PI` is one-fourth the value of the mathematical constant π. It's * useful for many tasks that involve rotation and oscillation. For example, * calling `rotate(QUARTER_PI)` rotates the coordinate system `QUARTER_PI` * radians, which is an eighth of a turn (45˚). * * Note: `TWO_PI` radians equals 360˚, `PI` radians equals 180˚, `HALF_PI` * radians equals 90˚, and `QUARTER_PI` radians equals 45˚. */ declare const QUARTER_PI: number; declare const __QUARTER_PI: typeof QUARTER_PI; /** * A `Number` constant that's approximately 6.2382. * * `TAU` is twice the value of the mathematical constant π. It's useful for * many tasks that involve rotation and oscillation. For example, calling * `rotate(TAU)` rotates the coordinate system `TAU` radians, which is one * full turn (360˚). `TAU` and `TWO_PI` are equal. * * Note: `TAU` radians equals 360˚, `PI` radians equals 180˚, `HALF_PI` * radians equals 90˚, and `QUARTER_PI` radians equals 45˚. */ declare const TAU: number; declare const __TAU: typeof TAU; /** * A `Number` constant that's approximately 6.2382. * * `TWO_PI` is twice the value of the mathematical constant π. It's useful for * many tasks that involve rotation and oscillation. For example, calling * `rotate(TWO_PI)` rotates the coordinate system `TWO_PI` radians, which is * one full turn (360˚). `TWO_PI` and `TAU` are equal. * * Note: `TWO_PI` radians equals 360˚, `PI` radians equals 180˚, `HALF_PI` * radians equals 90˚, and `QUARTER_PI` radians equals 45˚. */ declare const TWO_PI: number; declare const __TWO_PI: typeof TWO_PI; declare const DEG_TO_RAD: number; declare const __DEG_TO_RAD: typeof DEG_TO_RAD; declare const RAD_TO_DEG: number; declare const __RAD_TO_DEG: typeof RAD_TO_DEG; declare const CORNER: 'corner'; declare const __CORNER: typeof CORNER; declare const CORNERS: 'corners'; declare const __CORNERS: typeof CORNERS; declare const RADIUS: 'radius'; declare const __RADIUS: typeof RADIUS; declare const RIGHT: 'right'; declare const __RIGHT: typeof RIGHT; declare const LEFT: 'left'; declare const __LEFT: typeof LEFT; declare const CENTER: 'center'; declare const __CENTER: typeof CENTER; declare const TOP: 'top'; declare const __TOP: typeof TOP; declare const BOTTOM: 'bottom'; declare const __BOTTOM: typeof BOTTOM; declare const BASELINE: 'alphabetic'; declare const __BASELINE: typeof BASELINE; declare const POINTS: 0; declare const __POINTS: typeof POINTS; declare const LINES: 1; declare const __LINES: typeof LINES; declare const LINE_STRIP: 3; declare const __LINE_STRIP: typeof LINE_STRIP; declare const LINE_LOOP: 2; declare const __LINE_LOOP: typeof LINE_LOOP; declare const TRIANGLES: 4; declare const __TRIANGLES: typeof TRIANGLES; declare const TRIANGLE_FAN: 6; declare const __TRIANGLE_FAN: typeof TRIANGLE_FAN; declare const TRIANGLE_STRIP: 5; declare const __TRIANGLE_STRIP: typeof TRIANGLE_STRIP; declare const QUADS: 'quads'; declare const __QUADS: typeof QUADS; declare const QUAD_STRIP: 'quad_strip'; declare const __QUAD_STRIP: typeof QUAD_STRIP; declare const TESS: 'tess'; declare const __TESS: typeof TESS; declare const EMPTY_PATH: 7; declare const __EMPTY_PATH: typeof EMPTY_PATH; declare const PATH: 8; declare const __PATH: typeof PATH; declare const CLOSE: 'close'; declare const __CLOSE: typeof CLOSE; declare const OPEN: 'open'; declare const __OPEN: typeof OPEN; declare const CHORD: 'chord'; declare const __CHORD: typeof CHORD; declare const PIE: 'pie'; declare const __PIE: typeof PIE; declare const PROJECT: 'square'; declare const __PROJECT: typeof PROJECT; declare const SQUARE: 'butt'; declare const __SQUARE: typeof SQUARE; declare const ROUND: 'round'; declare const __ROUND: typeof ROUND; declare const BEVEL: 'bevel'; declare const __BEVEL: typeof BEVEL; declare const MITER: 'miter'; declare const __MITER: typeof MITER; /** * AUTO allows us to automatically set the width or height of an element (but not both), * based on the current height and width of the element. Only one parameter can * be passed to the size function as AUTO, at a time. */ declare const AUTO: 'auto'; declare const __AUTO: typeof AUTO; declare const ALT: 'Alt'; declare const __ALT: typeof ALT; declare const BACKSPACE: 'Backspace'; declare const __BACKSPACE: typeof BACKSPACE; declare const CONTROL: 'Control' | 'Control'; declare const __CONTROL: typeof CONTROL; declare const DELETE: 'Delete'; declare const __DELETE: typeof DELETE; declare const DOWN_ARROW: 'ArrowDown'; declare const __DOWN_ARROW: typeof DOWN_ARROW; declare const ENTER: 'Enter'; declare const __ENTER: typeof ENTER; declare const ESCAPE: 'Escape'; declare const __ESCAPE: typeof ESCAPE; declare const LEFT_ARROW: 'ArrowLeft'; declare const __LEFT_ARROW: typeof LEFT_ARROW; declare const OPTION: 'Alt'; declare const __OPTION: typeof OPTION; declare const RETURN: 'Enter'; declare const __RETURN: typeof RETURN; declare const RIGHT_ARROW: 'ArrowRight'; declare const __RIGHT_ARROW: typeof RIGHT_ARROW; declare const SHIFT: 'Shift'; declare const __SHIFT: typeof SHIFT; declare const TAB: 'Tab'; declare const __TAB: typeof TAB; declare const UP_ARROW: 'ArrowUp'; declare const __UP_ARROW: typeof UP_ARROW; declare const BLEND: 'source-over'; declare const __BLEND: typeof BLEND; declare const REMOVE: 'destination-out'; declare const __REMOVE: typeof REMOVE; declare const ADD: 'lighter'; declare const __ADD: typeof ADD; declare const DARKEST: 'darken'; declare const __DARKEST: typeof DARKEST; declare const LIGHTEST: 'lighten'; declare const __LIGHTEST: typeof LIGHTEST; declare const DIFFERENCE: 'difference'; declare const __DIFFERENCE: typeof DIFFERENCE; declare const SUBTRACT: 'subtract'; declare const __SUBTRACT: typeof SUBTRACT; declare const EXCLUSION: 'exclusion'; declare const __EXCLUSION: typeof EXCLUSION; declare const MULTIPLY: 'multiply'; declare const __MULTIPLY: typeof MULTIPLY; declare const SCREEN: 'screen'; declare const __SCREEN: typeof SCREEN; declare const REPLACE: 'copy'; declare const __REPLACE: typeof REPLACE; declare const OVERLAY: 'overlay'; declare const __OVERLAY: typeof OVERLAY; declare const HARD_LIGHT: 'hard-light'; declare const __HARD_LIGHT: typeof HARD_LIGHT; declare const SOFT_LIGHT: 'soft-light'; declare const __SOFT_LIGHT: typeof SOFT_LIGHT; declare const DODGE: 'color-dodge'; declare const __DODGE: typeof DODGE; declare const BURN: 'color-burn'; declare const __BURN: typeof BURN; declare const THRESHOLD: 'threshold'; declare const __THRESHOLD: typeof THRESHOLD; declare const GRAY: 'gray'; declare const __GRAY: typeof GRAY; declare const OPAQUE: 'opaque'; declare const __OPAQUE: typeof OPAQUE; declare const INVERT: 'invert'; declare const __INVERT: typeof INVERT; declare const POSTERIZE: 'posterize'; declare const __POSTERIZE: typeof POSTERIZE; declare const DILATE: 'dilate'; declare const __DILATE: typeof DILATE; declare const ERODE: 'erode'; declare const __ERODE: typeof ERODE; declare const BLUR: 'blur'; declare const __BLUR: typeof BLUR; declare const NORMAL: 'normal'; declare const __NORMAL: typeof NORMAL; declare const ITALIC: 'italic'; declare const __ITALIC: typeof ITALIC; declare const BOLD: 'bold'; declare const __BOLD: typeof BOLD; declare const BOLDITALIC: 'bold italic'; declare const __BOLDITALIC: typeof BOLDITALIC; declare const CHAR: 'CHAR'; declare const __CHAR: typeof CHAR; declare const WORD: 'WORD'; declare const __WORD: typeof WORD; declare const LINEAR: 'linear'; declare const __LINEAR: typeof LINEAR; declare const QUADRATIC: 'quadratic'; declare const __QUADRATIC: typeof QUADRATIC; declare const BEZIER: 'bezier'; declare const __BEZIER: typeof BEZIER; declare const CURVE: 'curve'; declare const __CURVE: typeof CURVE; declare const STROKE: 'stroke'; declare const __STROKE: typeof STROKE; declare const FILL: 'fill'; declare const __FILL: typeof FILL; declare const TEXTURE: 'texture'; declare const __TEXTURE: typeof TEXTURE; declare const IMMEDIATE: 'immediate'; declare const __IMMEDIATE: typeof IMMEDIATE; declare const IMAGE: 'image'; declare const __IMAGE: typeof IMAGE; declare const NEAREST: 'nearest'; declare const __NEAREST: typeof NEAREST; declare const REPEAT: 'repeat'; declare const __REPEAT: typeof REPEAT; declare const CLAMP: 'clamp'; declare const __CLAMP: typeof CLAMP; declare const MIRROR: 'mirror'; declare const __MIRROR: typeof MIRROR; declare const FLAT: 'flat'; declare const __FLAT: typeof FLAT; declare const SMOOTH: 'smooth'; declare const __SMOOTH: typeof SMOOTH; declare const LANDSCAPE: 'landscape'; declare const __LANDSCAPE: typeof LANDSCAPE; declare const PORTRAIT: 'portrait'; declare const __PORTRAIT: typeof PORTRAIT; declare const GRID: 'grid'; declare const __GRID: typeof GRID; declare const AXES: 'axes'; declare const __AXES: typeof AXES; declare const LABEL: 'label'; declare const __LABEL: typeof LABEL; declare const FALLBACK: 'fallback'; declare const __FALLBACK: typeof FALLBACK; declare const CONTAIN: 'contain'; declare const __CONTAIN: typeof CONTAIN; declare const COVER: 'cover'; declare const __COVER: typeof COVER; declare const UNSIGNED_BYTE: 'unsigned-byte'; declare const __UNSIGNED_BYTE: typeof UNSIGNED_BYTE; declare const UNSIGNED_INT: 'unsigned-int'; declare const __UNSIGNED_INT: typeof UNSIGNED_INT; declare const FLOAT: 'float'; declare const __FLOAT: typeof FLOAT; declare const HALF_FLOAT: 'half-float'; declare const __HALF_FLOAT: typeof HALF_FLOAT; /** * The `splineProperty('ends')` mode where splines curve through * their first and last points. */ declare const INCLUDE: Symbol; declare const __INCLUDE: typeof INCLUDE; /** * The `splineProperty('ends')` mode where the first and last points in a spline * affect the direction of the curve, but are not rendered. */ declare const EXCLUDE: Symbol; declare const __EXCLUDE: typeof EXCLUDE; /** * A `Number` variable that tracks the number of frames drawn since the sketch * started. * * `frameCount`'s value is 0 inside setup(). It * increments by 1 each time the code in draw() * finishes executing. */ declare const frameCount: number; declare const __frameCount: typeof frameCount; /** * A `Number` variable that tracks the number of milliseconds it took to draw * the last frame. * * `deltaTime` contains the amount of time it took * draw() to execute during the previous frame. It's * useful for simulating physics. */ declare const deltaTime: number; declare const __deltaTime: typeof deltaTime; /** * A `Boolean` variable that's `true` if the browser is focused and `false` if * not. * * Note: The browser window can only receive input if it's focused. */ declare const focused: boolean; declare const __focused: typeof focused; /** * A `String` variable with the WebGL version in use. * * `webglVersion`'s value equals one of the following string constants: * * - `WEBGL2` whose value is `'webgl2'`, * * - `WEBGL` whose value is `'webgl'`, or * * - `P2D` whose value is `'p2d'`. This is the default for 2D sketches. * * - `P2DHDR` whose value is `'p2d-hdr'` (used for HDR 2D sketches, if available). * * See setAttributes() for ways to set the * WebGL version. */ declare const webglVersion: 'webgl' | 'webgl2'; declare const __webglVersion: typeof webglVersion; /** * A `Number` variable that stores the width of the screen display. * * `displayWidth` is useful for running full-screen programs. Its value * depends on the current pixelDensity(). * * Note: The actual screen width can be computed as * `displayWidth * pixelDensity()`. */ declare const displayWidth: number; declare const __displayWidth: typeof displayWidth; /** * A `Number` variable that stores the height of the screen display. * * `displayHeight` is useful for running full-screen programs. Its value * depends on the current pixelDensity(). * * Note: The actual screen height can be computed as * `displayHeight * pixelDensity()`. */ declare const displayHeight: number; declare const __displayHeight: typeof displayHeight; /** * A `Number` variable that stores the width of the browser's viewport. * * The layout viewport * is the area within the browser that's available for drawing. */ declare const windowWidth: number; declare const __windowWidth: typeof windowWidth; /** * A `Number` variable that stores the height of the browser's viewport. * * The layout viewport * is the area within the browser that's available for drawing. */ declare const windowHeight: number; declare const __windowHeight: typeof windowHeight; /** * The system variable deviceOrientation always contains the orientation of * the device. The value of this variable will either be set 'landscape' * or 'portrait'. If no data is available it will be set to 'undefined'. * either LANDSCAPE or PORTRAIT. */ declare const deviceOrientation: 'landscape' | 'portrait'; declare const __deviceOrientation: typeof deviceOrientation; /** * The system variable accelerationX always contains the acceleration of the * device along the x axis. Value is represented as meters per second squared. */ declare const accelerationX: number; declare const __accelerationX: typeof accelerationX; /** * The system variable accelerationY always contains the acceleration of the * device along the y axis. Value is represented as meters per second squared. */ declare const accelerationY: number; declare const __accelerationY: typeof accelerationY; /** * The system variable accelerationZ always contains the acceleration of the * device along the z axis. Value is represented as meters per second squared. */ declare const accelerationZ: number; declare const __accelerationZ: typeof accelerationZ; /** * The system variable pAccelerationX always contains the acceleration of the * device along the x axis in the frame previous to the current frame. Value * is represented as meters per second squared. */ declare const pAccelerationX: number; declare const __pAccelerationX: typeof pAccelerationX; /** * The system variable pAccelerationY always contains the acceleration of the * device along the y axis in the frame previous to the current frame. Value * is represented as meters per second squared. */ declare const pAccelerationY: number; declare const __pAccelerationY: typeof pAccelerationY; /** * The system variable pAccelerationZ always contains the acceleration of the * device along the z axis in the frame previous to the current frame. Value * is represented as meters per second squared. */ declare const pAccelerationZ: number; declare const __pAccelerationZ: typeof pAccelerationZ; /** * The system variable rotationX always contains the rotation of the * device along the x axis. If the sketch * angleMode() is set to DEGREES, the value will be -180 to 180. If * it is set to RADIANS, the value will be -PI to PI. * * Note: The order the rotations are called is important, ie. if used * together, it must be called in the order Z-X-Y or there might be * unexpected behaviour. */ declare const rotationX: number; declare const __rotationX: typeof rotationX; /** * The system variable rotationY always contains the rotation of the * device along the y axis. If the sketch * angleMode() is set to DEGREES, the value will be -90 to 90. If * it is set to RADIANS, the value will be -PI/2 to PI/2. * * Note: The order the rotations are called is important, ie. if used * together, it must be called in the order Z-X-Y or there might be * unexpected behaviour. */ declare const rotationY: number; declare const __rotationY: typeof rotationY; /** * The system variable rotationZ always contains the rotation of the * device along the z axis. If the sketch * angleMode() is set to DEGREES, the value will be 0 to 360. If * it is set to RADIANS, the value will be 0 to 2*PI. * * Unlike rotationX and rotationY, this variable is available for devices * with a built-in compass only. * * Note: The order the rotations are called is important, ie. if used * together, it must be called in the order Z-X-Y or there might be * unexpected behaviour. */ declare const rotationZ: number; declare const __rotationZ: typeof rotationZ; /** * The system variable pRotationX always contains the rotation of the * device along the x axis in the frame previous to the current frame. * If the sketch angleMode() is set to DEGREES, * the value will be -180 to 180. If it is set to RADIANS, the value will * be -PI to PI. * * pRotationX can also be used with rotationX to determine the rotate * direction of the device along the X-axis. */ declare const pRotationX: number; declare const __pRotationX: typeof pRotationX; /** * The system variable pRotationY always contains the rotation of the * device along the y axis in the frame previous to the current frame. * If the sketch angleMode() is set to DEGREES, * the value will be -90 to 90. If it is set to RADIANS, the value will * be -PI/2 to PI/2. * * pRotationY can also be used with rotationY to determine the rotate * direction of the device along the Y-axis. */ declare const pRotationY: number; declare const __pRotationY: typeof pRotationY; /** * The system variable pRotationZ always contains the rotation of the * device along the z axis in the frame previous to the current frame. * If the sketch angleMode() is set to DEGREES, * the value will be 0 to 360. If it is set to RADIANS, the value will * be 0 to 2*PI. * * pRotationZ can also be used with rotationZ to determine the rotate * direction of the device along the Z-axis. */ declare const pRotationZ: number; declare const __pRotationZ: typeof pRotationZ; /** * When a device is rotated, the axis that triggers the deviceTurned() * method is stored in the turnAxis variable. The turnAxis variable is only defined within * the scope of deviceTurned(). */ declare const turnAxis: string; declare const __turnAxis: typeof turnAxis; /** * A `Boolean` system variable that's `true` if any key is currently pressed * and `false` if not. */ declare const keyIsPressed: boolean; declare const __keyIsPressed: typeof keyIsPressed; /** * A `String` system variable that contains the value of the last key typed. * * The key variable is helpful for checking whether an * ASCII * key has been typed. For example, the expression `key === "a"` evaluates to * `true` if the `a` key was typed and `false` if not. `key` doesn’t update * for special keys such as `LEFT_ARROW` and `ENTER`. Use keyCode instead for * special keys. The keyIsDown() function should * be used to check for multiple different key presses at the same time. */ declare const key: string; declare const __key: typeof key; /** * The `code` property represents a physical key on the keyboard (as opposed * to the character generated by pressing the key). In other words, this * property returns a value that isn't altered by keyboard layout or the state * of the modifier keys. * * This property is useful when you want to handle keys based on their * physical positions on the input device rather than the characters associated * with those keys; * * Unlike key, the `code` property differentiates between * physical keys that generate the same character—for example, `CtrlLeft` and * `CtrlRight`—so each can be handled independently. * Here's the MDN docs for KeyboardEvent.code * * Pressing the key physically labeled “A” always yields `KeyA`, regardless * of the current keyboard layout (QWERTY, Dvorak, AZERTY, etc.) or the character * that appears in a text field. * * The code property returns a plain string (e.g., 'ArrowRight'). You can * compare it directly with string literals: * * `if (keyIsDown(RIGHT_ARROW)) { * // … * } * // The line above is equivalent to: * if (code === 'ArrowRight') { * // … * } * if (key === 'ArrowRight') { * // … * }`The system variables `BACKSPACE`, `DELETE`, `ENTER`, `RETURN`, `TAB`, * `ESCAPE`, `SHIFT`, `CONTROL`, `OPTION`, `ALT`, `UP_ARROW`, `DOWN_ARROW`, * `LEFT_ARROW`, and `RIGHT_ARROW` are all helpful shorthands the key codes of * special keys. * These are simply shorthands for the same string values: * * `if (code === RIGHT_ARROW) { * // .. * }`

The table below summarizes how the main keyboard-related system variables changed between p5.js 1.x and 2.x.

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Variablep5.js 1.x p5.js 2.x
keyText string (e.g., "ArrowUp").Text string (e.g., "ArrowUp", "f" or "F").
codeNot supported.Text String (e.g., "ArrowUp", "KeyF").
keyCodeNumber (e.g., 70).Number (unchanged; e.g., 70).
System variables (BACKSPACE, UP_ARROW, …)NumberText String (e.g., "ArrowUp").
*/ declare const code: string; declare const __code: typeof code; /** * A `Number` system variable that contains the code of the last key pressed. * * Every key has a numeric key code. For example, the letter `a` key has the key code 65. * Use this key code to determine which key was pressed by comparing it to the numeric value * of the desired key. * * For example, to detect when the Enter key is pressed: * * `if (keyCode === 13) { // Enter key * // Code to run if the Enter key was pressed. * }`Alternatively, you can use the key function to directly compare the key value: * * `if (key === 'Enter') { // Enter key * // Code to run if the Enter key was pressed. * }`Use the following numeric codes for the arrow keys: * * Up Arrow: 38 * Down Arrow: 40 * Left Arrow: 37 * Right Arrow: 39 * * More key codes can be found at websites such as * keycode.info. */ declare const keyCode: number; declare const __keyCode: typeof keyCode; /** * A `Number` system variable that tracks the mouse's horizontal movement. * * `movedX` tracks how many pixels the mouse moves left or right between * frames. `movedX` will have a negative value if the mouse moves left between * frames and a positive value if it moves right. `movedX` can be calculated * as `mouseX - pmouseX`. * * Note: `movedX` continues updating even when * requestPointerLock() is active. */ declare const movedX: number; declare const __movedX: typeof movedX; /** * A `Number` system variable that tracks the mouse's vertical movement. * * `movedY` tracks how many pixels the mouse moves up or down between * frames. `movedY` will have a negative value if the mouse moves up between * frames and a positive value if it moves down. `movedY` can be calculated * as `mouseY - pmouseY`. * * Note: `movedY` continues updating even when * requestPointerLock() is active. */ declare const movedY: number; declare const __movedY: typeof movedY; /** * A `Number` system variable that tracks the mouse's horizontal position. * * `mouseX` keeps track of the mouse's position relative to the * top-left corner of the canvas. For example, if the mouse is 50 pixels from * the left edge of the canvas, then `mouseX` will be 50. * * If touch is used instead of the mouse, then `mouseX` will hold the * x-coordinate of the most recent touch point. */ declare const mouseX: number; declare const __mouseX: typeof mouseX; /** * A `Number` system variable that tracks the mouse's vertical position. * * `mouseY` keeps track of the mouse's position relative to the * top-left corner of the canvas. For example, if the mouse is 50 pixels from * the top edge of the canvas, then `mouseY` will be 50. * * If touch is used instead of the mouse, then `mouseY` will hold the * y-coordinate of the most recent touch point. */ declare const mouseY: number; declare const __mouseY: typeof mouseY; /** * A `Number` system variable that tracks the mouse's previous horizontal * position. * * `pmouseX` keeps track of the mouse's position relative to the * top-left corner of the canvas. Its value is * mouseX from the previous frame. For example, if * the mouse was 50 pixels from the left edge of the canvas during the last * frame, then `pmouseX` will be 50. * * If touch is used instead of the mouse, then `pmouseX` will hold the * x-coordinate of the last touch point. * * Note: `pmouseX` is reset to the current mouseX * value at the start of each touch event. */ declare const pmouseX: number; declare const __pmouseX: typeof pmouseX; /** * A `Number` system variable that tracks the mouse's previous vertical * position. * * `pmouseY` keeps track of the mouse's position relative to the * top-left corner of the canvas. Its value is * mouseY from the previous frame. For example, if * the mouse was 50 pixels from the top edge of the canvas during the last * frame, then `pmouseY` will be 50. * * If touch is used instead of the mouse, then `pmouseY` will hold the * y-coordinate of the last touch point. * * Note: `pmouseY` is reset to the current mouseY * value at the start of each touch event. */ declare const pmouseY: number; declare const __pmouseY: typeof pmouseY; /** * A `Number` variable that tracks the mouse's horizontal position within the * browser. * * `winMouseX` keeps track of the mouse's position relative to the top-left * corner of the browser window. For example, if the mouse is 50 pixels from * the left edge of the browser, then `winMouseX` will be 50. * * On a touchscreen device, `winMouseX` will hold the x-coordinate of the most * recent touch point. * * Note: Use mouseX to track the mouse’s * x-coordinate within the canvas. */ declare const winMouseX: number; declare const __winMouseX: typeof winMouseX; /** * A `Number` variable that tracks the mouse's vertical position within the * browser. * * `winMouseY` keeps track of the mouse's position relative to the top-left * corner of the browser window. For example, if the mouse is 50 pixels from * the top edge of the browser, then `winMouseY` will be 50. * * On a touchscreen device, `winMouseY` will hold the y-coordinate of the most * recent touch point. * * Note: Use mouseY to track the mouse’s * y-coordinate within the canvas. */ declare const winMouseY: number; declare const __winMouseY: typeof winMouseY; /** * A `Number` variable that tracks the mouse's previous horizontal position * within the browser. * * `pwinMouseX` keeps track of the mouse's position relative to the top-left * corner of the browser window. Its value is * winMouseX from the previous frame. For * example, if the mouse was 50 pixels from * the left edge of the browser during the last frame, then `pwinMouseX` will * be 50. * * On a touchscreen device, `pwinMouseX` will hold the x-coordinate of the most * recent touch point. `pwinMouseX` is reset to the current * winMouseX value at the start of each touch * event. * * Note: Use pmouseX to track the mouse’s previous * x-coordinate within the canvas. */ declare const pwinMouseX: number; declare const __pwinMouseX: typeof pwinMouseX; /** * A `Number` variable that tracks the mouse's previous vertical position * within the browser. * * `pwinMouseY` keeps track of the mouse's position relative to the top-left * corner of the browser window. Its value is * winMouseY from the previous frame. For * example, if the mouse was 50 pixels from * the top edge of the browser during the last frame, then `pwinMouseY` will * be 50. * * On a touchscreen device, `pwinMouseY` will hold the y-coordinate of the most * recent touch point. `pwinMouseY` is reset to the current * winMouseY value at the start of each touch * event. * * Note: Use pmouseY to track the mouse’s previous * y-coordinate within the canvas. */ declare const pwinMouseY: number; declare const __pwinMouseY: typeof pwinMouseY; /** * An object that tracks the current state of mouse buttons, showing which * buttons are pressed at any given moment. * * The `mouseButton` object has three properties: * * - `left`: A boolean indicating whether the left mouse button is pressed. * * - `right`: A boolean indicating whether the right mouse button is pressed. * * - `center`: A boolean indicating whether the middle mouse button (scroll wheel button) is pressed. * * Note: Different browsers may track `mouseButton` differently. See * MDN * for more information. */ declare const mouseButton: object; declare const __mouseButton: typeof mouseButton; /** * An `Array` of all the current touch points on a touchscreen device. * * The `touches` array is empty by default. When the user touches their * screen, a new touch point is tracked and added to the array. Touch points * are `Objects` with the following properties: * * `// Iterate over the touches array. * for (let touch of touches) { * // x-coordinate relative to the top-left * // corner of the canvas. * console.log(touch.x); * * // y-coordinate relative to the top-left * // corner of the canvas. * console.log(touch.y); * * // x-coordinate relative to the top-left * // corner of the browser. * console.log(touch.winX); * * // y-coordinate relative to the top-left * // corner of the browser. * console.log(touch.winY); * * // ID number * console.log(touch.id); * }` */ declare const touches: object[]; declare const __touches: typeof touches; /** * A `Boolean` system variable that's `true` if the mouse is pressed and * `false` if not. */ declare const mouseIsPressed: boolean; declare const __mouseIsPressed: typeof mouseIsPressed; /** * A `Number` variable that stores the width of the canvas in pixels. * * `width`'s default value is 100. Calling * createCanvas() or * resizeCanvas() changes the value of * `width`. Calling noCanvas() sets its value to * 0. */ declare const width: number; declare const __width: typeof width; /** * A `Number` variable that stores the height of the canvas in pixels. * * `height`'s default value is 100. Calling * createCanvas() or * resizeCanvas() changes the value of * `height`. Calling noCanvas() sets its value to * 0. */ declare const height: number; declare const __height: typeof height; /** * Turns off the parts of the Friendly Error System (FES) that impact performance. * * The FES * can cause sketches to draw slowly because it does extra work behind the * scenes. For example, the FES checks the arguments passed to functions, * which takes time to process. Disabling the FES can significantly improve * performance by turning off these checks. */ declare let disableFriendlyErrors: boolean; declare let __disableFriendlyErrors: typeof disableFriendlyErrors; /** * A system variable that provides direct access to the sketch's * `<canvas>` element. * * The `<canvas>` element provides many specialized features that aren't * included in the p5.js library. The `drawingContext` system variable * provides access to these features by exposing the sketch's * CanvasRenderingContext2D * object. */ declare const drawingContext: CanvasRenderingContext2D | WebGLRenderingContext | WebGL2RenderingContext; declare const __drawingContext: typeof drawingContext; declare const VIDEO: 'video'; declare const __VIDEO: typeof VIDEO; declare const AUDIO: 'audio'; declare const __AUDIO: typeof AUDIO; /** * An array containing the color of each pixel on the canvas. * * Colors are stored as numbers representing red, green, blue, and alpha * (RGBA) values. `pixels` is a one-dimensional array for performance reasons. * * Each pixel occupies four elements in the `pixels` array, one for each RGBA * value. For example, the pixel at coordinates (0, 0) stores its RGBA values * at `pixels[0]`, `pixels[1]`, `pixels[2]`, and `pixels[3]`, respectively. * The next pixel at coordinates (1, 0) stores its RGBA values at `pixels[4]`, * `pixels[5]`, `pixels[6]`, and `pixels[7]`. And so on. The `pixels` array * for a 100×100 canvas has 100 × 100 × 4 = 40,000 elements. * * Some displays use several smaller pixels to set the color at a single * point. The pixelDensity() function returns * the pixel density of the canvas. High density displays often have a * pixelDensity() of 2. On such a display, the * `pixels` array for a 100×100 canvas has 200 × 200 × 4 = * 160,000 elements. * * Accessing the RGBA values for a point on the canvas requires a little math * as shown below. The loadPixels() function * must be called before accessing the `pixels` array. The * updatePixels() function must be called * after any changes are made. */ declare const pixels: number[]; declare const __pixels: typeof pixels; /** * A `String` constant that's used to set the * angleMode(). * * By default, functions such as rotate() and * sin() expect angles measured in units of radians. * Calling `angleMode(DEGREES)` ensures that angles are measured in units of * degrees. * * Note: `TWO_PI` radians equals 360˚. */ declare const DEGREES: 'degrees'; declare const __DEGREES: typeof DEGREES; /** * A `String` constant that's used to set the * angleMode(). * * By default, functions such as rotate() and * sin() expect angles measured in units of radians. * Calling `angleMode(RADIANS)` ensures that angles are measured in units of * radians. Doing so can be useful if the * angleMode() has been set to * DEGREES. * * Note: `TWO_PI` radians equals 360˚. */ declare const RADIANS: 'radians'; declare const __RADIANS: typeof RADIANS; declare class p5 { constructor(sketch?: (p: p5) => void, node?: HTMLElement, sync?: boolean); /** * Loads a p5.js library. * * A library is a function that adds functionality to p5.js by adding methods * and properties for sketches to use, or for automatically running code at * different stages of the p5.js lifecycle. Take a look at the * contributor docs for creating libraries * to learn more about creating libraries. * @param library The library function to register */ static registerAddon(library: Function): void; /** * Creates a screen reader-accessible description of the canvas. * * The first parameter, `text`, is the description of the canvas. * * The second parameter, `display`, is optional. It determines how the * description is displayed. If `LABEL` is passed, as in * `describe('A description.', LABEL)`, the description will be visible in * a div element next to the canvas. If `FALLBACK` is passed, as in * `describe('A description.', FALLBACK)`, the description will only be * visible to screen readers. This is the default mode. * * Read * Writing accessible canvas descriptions * to learn more about making sketches accessible. * @param text description of the canvas. * @param display either LABEL or FALLBACK. */ describe(text: string, display?: typeof p5.FALLBACK | typeof p5.LABEL): void; /** * Creates a screen reader-accessible description of elements in the canvas. * * Elements are shapes or groups of shapes that create meaning together. For * example, a few overlapping circles could make an "eye" element. * * The first parameter, `name`, is the name of the element. * * The second parameter, `text`, is the description of the element. * * The third parameter, `display`, is optional. It determines how the * description is displayed. If `LABEL` is passed, as in * `describe('A description.', LABEL)`, the description will be visible in * a div element next to the canvas. Using `LABEL` creates unhelpful * duplicates for screen readers. Only use `LABEL` during development. If * `FALLBACK` is passed, as in `describe('A description.', FALLBACK)`, the * description will only be visible to screen readers. This is the default * mode. * * Read * Writing accessible canvas descriptions * to learn more about making sketches accessible. * @param name name of the element. * @param text description of the element. * @param display either LABEL or FALLBACK. */ describeElement(name: string, text: string, display?: typeof p5.FALLBACK | typeof p5.LABEL): void; /** * Creates a screen reader-accessible description of shapes on the canvas. * * `textOutput()` adds a general description, list of shapes, and * table of shapes to the web page. The general description includes the * canvas size, canvas color, and number of shapes. For example, * `Your output is a, 100 by 100 pixels, gray canvas containing the following 2 shapes:`. * * A list of shapes follows the general description. The list describes the * color, location, and area of each shape. For example, * `a red circle at middle covering 3% of the canvas`. Each shape can be * selected to get more details. * * `textOutput()` uses its table of shapes as a list. The table describes the * shape, color, location, coordinates and area. For example, * `red circle location = middle area = 3%`. This is different from * gridOutput(), which uses its table as a grid. * * The `display` parameter is optional. It determines how the description is * displayed. If `LABEL` is passed, as in `textOutput(LABEL)`, the description * will be visible in a div element next to the canvas. Using `LABEL` creates * unhelpful duplicates for screen readers. Only use `LABEL` during * development. If `FALLBACK` is passed, as in `textOutput(FALLBACK)`, the * description will only be visible to screen readers. This is the default * mode. * * Read * Writing accessible canvas descriptions * to learn more about making sketches accessible. * @param display either FALLBACK or LABEL. */ textOutput(display?: typeof p5.FALLBACK | typeof p5.LABEL): void; /** * Creates a screen reader-accessible description of shapes on the canvas. * * `gridOutput()` adds a general description, table of shapes, and list of * shapes to the web page. The general description includes the canvas size, * canvas color, and number of shapes. For example, * `gray canvas, 100 by 100 pixels, contains 2 shapes: 1 circle 1 square`. * * `gridOutput()` uses its table of shapes as a grid. Each shape in the grid * is placed in a cell whose row and column correspond to the shape's location * on the canvas. The grid cells describe the color and type of shape at that * location. For example, `red circle`. These descriptions can be selected * individually to get more details. This is different from * textOutput(), which uses its table as a list. * * A list of shapes follows the table. The list describes the color, type, * location, and area of each shape. For example, * `red circle, location = middle, area = 3 %`. * * The `display` parameter is optional. It determines how the description is * displayed. If `LABEL` is passed, as in `gridOutput(LABEL)`, the description * will be visible in a div element next to the canvas. Using `LABEL` creates * unhelpful duplicates for screen readers. Only use `LABEL` during * development. If `FALLBACK` is passed, as in `gridOutput(FALLBACK)`, the * description will only be visible to screen readers. This is the default * mode. * * Read * Writing accessible canvas descriptions * to learn more about making sketches accessible. * @param display either FALLBACK or LABEL. */ gridOutput(display?: typeof p5.FALLBACK | typeof p5.LABEL): void; /** * Removes the sketch from the web page. * * Calling `remove()` stops the draw loop and removes any HTML elements * created by the sketch, including the canvas. A new sketch can be * created by using the p5() constructor, as in * `new p5()`. */ remove(): void; remove(): void; remove(): void; remove(): void; /** * Creates a new sketch in "instance" mode. * * All p5.js sketches are instances of the `p5` class. Put another way, all * p5.js sketches are objects with methods including `pInst.setup()`, * `pInst.draw()`, `pInst.circle()`, and `pInst.fill()`. By default, sketches * run in "global mode" to hide some of this complexity. * * In global mode, a default instance of the `p5` class is created * automatically. The default `p5` instance searches the web page's source * code for declarations of system functions such as `setup()`, `draw()`, * and `mousePressed()`, then attaches those functions to itself as methods. * Calling a function such as `circle()` in global mode actually calls the * default `p5` object's `pInst.circle()` method. * * It's often helpful to isolate the code within sketches from the rest of the * code on a web page. Two common use cases are web pages that use other * JavaScript libraries and web pages with multiple sketches. "Instance mode" * makes it easy to support both of these scenarios. * * Instance mode sketches support the same API as global mode sketches. They * use a function to bundle, or encapsulate, an entire sketch. The function * containing the sketch is then passed to the `p5()` constructor. * * The first parameter, `sketch`, is a function that contains the sketch. For * example, the statement `new p5(mySketch)` would create a new instance mode * sketch from a function named `mySketch`. The function should have one * parameter, `p`, that's a `p5` object. * * The second parameter, `node`, is optional. If a string is passed, as in * `new p5(mySketch, 'sketch-one')` the new instance mode sketch will become a * child of the HTML element with the id `sketch-one`. If an HTML element is * passed, as in `new p5(mySketch, myElement)`, then the new instance mode * sketch will become a child of the `Element` object called `myElement`. * @param sketch function containing the sketch. * @param node ID or reference to the HTML element that will contain the sketch. */ p5(sketch: object, node: string | HTMLElement): void; /** * Creates a p5.Color object. * * By default, the parameters are interpreted as RGB values. Calling * `color(255, 204, 0)` will return a bright yellow color. The way these * parameters are interpreted may be changed with the * colorMode() function. * * The version of `color()` with one parameter interprets the value one of two * ways. If the parameter is a number, it's interpreted as a grayscale value. * If the parameter is a string, it's interpreted as a CSS color string. * * The version of `color()` with two parameters interprets the first one as a * grayscale value. The second parameter sets the alpha (transparency) value. * * The version of `color()` with three parameters interprets them as RGB, HSB, * or HSL colors, depending on the current `colorMode()`. * * The version of `color()` with four parameters interprets them as RGBA, HSBA, * or HSLA colors, depending on the current `colorMode()`. The last parameter * sets the alpha (transparency) value. * @param gray number specifying value between white and black. * @param alpha alpha value relative to current color range * (default is 0-255). * @returns resulting color. */ color(gray: number, alpha?: number): p5.Color; color(v1: number, v2: number, v3: number, alpha?: number): p5.Color; color(value: string): p5.Color; color(values: number[]): p5.Color; color(color: p5.Color): p5.Color; /** * Gets the red value of a color. * * `red()` extracts the red value from a * p5.Color object, an array of color components, or * a CSS color string. * * By default, `red()` returns a color's red value in the range 0 * to 255. If the colorMode() is set to RGB, it * returns the red value in the given range. * @param color p5.Color object, array of * color components, or CSS color string. * @returns the red value. */ red(color: p5.Color | number[] | string): number; /** * Gets the green value of a color. * * `green()` extracts the green value from a * p5.Color object, an array of color components, or * a CSS color string. * * By default, `green()` returns a color's green value in the range 0 * to 255. If the colorMode() is set to RGB, it * returns the green value in the given range. * @param color p5.Color object, array of * color components, or CSS color string. * @returns the green value. */ green(color: p5.Color | number[] | string): number; /** * Gets the blue value of a color. * * `blue()` extracts the blue value from a * p5.Color object, an array of color components, or * a CSS color string. * * By default, `blue()` returns a color's blue value in the range 0 * to 255. If the colorMode() is set to RGB, it * returns the blue value in the given range. * @param color p5.Color object, array of * color components, or CSS color string. * @returns the blue value. */ blue(color: p5.Color | number[] | string): number; /** * Gets the alpha (transparency) value of a color. * * `alpha()` extracts the alpha value from a * p5.Color object, an array of color components, or * a CSS color string. * @param color p5.Color object, array of * color components, or CSS color string. * @returns the alpha value. */ alpha(color: p5.Color | number[] | string): number; /** * Gets the hue value of a color. * * `hue()` extracts the hue value from a * p5.Color object, an array of color components, or * a CSS color string. * * Hue describes a color's position on the color wheel. By default, `hue()` * returns a color's HSL hue in the range 0 to 360. If the * colorMode() is set to HSB or HSL, it returns the hue * value in the given mode. * @param color p5.Color object, array of * color components, or CSS color string. * @returns the hue value. */ hue(color: p5.Color | number[] | string): number; /** * Gets the saturation value of a color. * * `saturation()` extracts the saturation value from a * p5.Color object, an array of color components, or * a CSS color string. * * Saturation is scaled differently in HSB and HSL. By default, `saturation()` * returns a color's HSL saturation in the range 0 to 100. If the * colorMode() is set to HSB or HSL, it returns the * saturation value in the given mode. * @param color p5.Color object, array of * color components, or CSS color string. * @returns the saturation value */ saturation(color: p5.Color | number[] | string): number; /** * Gets the brightness value of a color. * * `brightness()` extracts the HSB brightness value from a * p5.Color object, an array of color components, or * a CSS color string. * * By default, `brightness()` returns a color's HSB brightness in the range 0 * to 100. If the colorMode() is set to HSB, it * returns the brightness value in the given range. * @param color p5.Color object, array of * color components, or CSS color string. * @returns the brightness value. */ brightness(color: p5.Color | number[] | string): number; /** * Gets the lightness value of a color. * * `lightness()` extracts the HSL lightness value from a * p5.Color object, an array of color components, or * a CSS color string. * * By default, `lightness()` returns a color's HSL lightness in the range 0 * to 100. If the colorMode() is set to HSL, it * returns the lightness value in the given range. * @param color p5.Color object, array of * color components, or CSS color string. * @returns the lightness value. */ lightness(color: p5.Color | number[] | string): number; /** * Blends two colors to find a third color between them. * * The `amt` parameter specifies the amount to interpolate between the two * values. 0 is equal to the first color, 0.1 is very near the first color, * 0.5 is halfway between the two colors, and so on. Negative numbers are set * to 0. Numbers greater than 1 are set to 1. This differs from the behavior of * lerp. It's necessary because numbers outside of the * interval [0, 1] will produce strange and unexpected colors. * * The way that colors are interpolated depends on the current * colorMode(). * @param c1 interpolate from this color. * @param c2 interpolate to this color. * @param amt number between 0 and 1. * @returns interpolated color. */ lerpColor(c1: p5.Color, c2: p5.Color, amt: number): p5.Color; /** * Blends multiple colors to find a color between them. * * The `amt` parameter specifies the amount to interpolate between the color * stops which are colors at each `amt` value "location" with `amt` values * that are between 2 color stops interpolating between them based on its relative * distance to both. * * The way that colors are interpolated depends on the current * colorMode(). * @param colors_stops color stops to interpolate from * @param amt number to use to interpolate relative to color stops * @returns interpolated color. */ paletteLerp(colors_stops: [p5.Color | string | number | number[], number][], amt: number): p5.Color; /** * Starts defining a shape that will mask any shapes drawn afterward. * * Any shapes drawn between `beginClip()` and * endClip() will add to the mask shape. The mask * will apply to anything drawn after endClip(). * * The parameter, `options`, is optional. If an object with an `invert` * property is passed, as in `beginClip({ invert: true })`, it will be used to * set the masking mode. `{ invert: true }` inverts the mask, creating holes * in shapes that are masked. `invert` is `false` by default. * * Masks can be contained between the * push() and pop() functions. * Doing so allows unmasked shapes to be drawn after masked shapes. * * Masks can also be defined in a callback function that's passed to * clip(). * @param options an object containing clip settings. */ beginClip(options?: { invert?: boolean }): void; /** * Ends defining a mask that was started with * beginClip(). */ endClip(): void; /** * Defines a shape that will mask any shapes drawn afterward. * * The first parameter, `callback`, is a function that defines the mask. * Any shapes drawn in `callback` will add to the mask shape. The mask * will apply to anything drawn after `clip()` is called. * * The second parameter, `options`, is optional. If an object with an `invert` * property is passed, as in `beginClip({ invert: true })`, it will be used to * set the masking mode. `{ invert: true }` inverts the mask, creating holes * in shapes that are masked. `invert` is `false` by default. * * Masks can be contained between the * push() and pop() functions. * Doing so allows unmasked shapes to be drawn after masked shapes. * * Masks can also be defined with beginClip() * and endClip(). * @param callback a function that draws the mask shape. * @param options an object containing clip settings. */ clip(callback: Function, options?: { invert?: boolean }): void; /** * Sets the color used for the background of the canvas. * * By default, the background is transparent. `background()` is typically used * within draw() to clear the display window at the * beginning of each frame. It can also be used inside * setup() to set the background on the first frame * of animation. * * The version of `background()` with one parameter interprets the value one * of four ways. If the parameter is a `Number`, it's interpreted as a grayscale * value. If the parameter is a `String`, it's interpreted as a CSS color string. * RGB, RGBA, HSL, HSLA, hex, and named color strings are supported. If the * parameter is a p5.Color object, it will be used as * the background color. If the parameter is a * p5.Image object, it will be used as the background * image. * * The version of `background()` with two parameters interprets the first one * as a grayscale value. The second parameter sets the alpha (transparency) * value. * * The version of `background()` with three parameters interprets them as RGB, * HSB, or HSL colors, depending on the current * colorMode(). By default, colors are specified * in RGB values. Calling `background(255, 204, 0)` sets the background a bright * yellow color. * * The version of `background()` with four parameters interprets them as RGBA, * HSBA, or HSLA colors, depending on the current * colorMode(). The last parameter sets the alpha * (transparency) value. * @param color any value created by the color() function */ background(color: p5.Color): void; background(colorstring: string, a?: number): void; background(gray: number, a?: number): void; background(v1: number, v2: number, v3: number, a?: number): void; background(values: number[]): void; background(image: p5.Image, a?: number): void; /** * Clears the pixels on the canvas. * * `clear()` makes every pixel 100% transparent. Calling `clear()` doesn't * clear objects created by `createX()` functions such as * createGraphics(), * createVideo(), and * createImg(). These objects will remain * unchanged after calling `clear()` and can be redrawn. * * In WebGL mode, this function can clear the screen to a specific color. It * interprets four numeric parameters as normalized RGBA color values. It also * clears the depth buffer. If you are not using the WebGL renderer, these * parameters will have no effect. * @param r normalized red value. * @param g normalized green value. * @param b normalized blue value. * @param a normalized alpha value. */ clear(r?: number, g?: number, b?: number, a?: number): void; clear(): void; /** * Changes the way color values are interpreted. * * By default, the `Number` parameters for fill(), * stroke(), * background(), and * color() are defined by values between 0 and 255 * using the RGB color model. This is equivalent to calling * `colorMode(RGB, 255)`. Pure red is `color(255, 0, 0)` in this model. * * Calling `colorMode(RGB, 100)` sets colors to use RGB color values * between 0 and 100. Pure red is `color(100, 0, 0)` in this model. * * Calling `colorMode(HSB)` or `colorMode(HSL)` changes to HSB or HSL systems instead of RGB. * Pure red is `color(0, 100, 100)` in HSB and `color(0, 100, 50)` in HSL. * * Some additional color modes that p5.js supports are: * * `RGBHDR` - High Dynamic Range RGB defined within the Display P3 color space. * Colors are expressed with an extended dynamic range. To render these colors * accurately, you must use the HDR canvas. * * `HWB` - Hue, Whiteness, Blackness. * Similar to HSB and HSL, this mode uses a hue angle. * Instead of saturation and lightness, HWB defines colors based on the percentage * of whiteness and blackness. This is the color model used by Chrome's GUI color picker. * Pure red in HWB is represented as `color(0, 0, 0)` (i.e., hue 0 with 0% whiteness and 0% blackness). * * ` ``LAB` - Also known as CIE Lab, this color mode defines colors with Lightness, Alpha, and Beta. * It is widely used in professional color measurement contexts due to its perceptual uniformity. * * `LCH` - A more intuitive representation of the CIE Lab color space using Lightness, Chroma, and Hue. * This mode separates the color's chromatic intensity (chroma) from its lightness, * simplifying color selection and manipulation. * * `OKLAB` - A variant of the CIE Lab color space that corrects for non-uniformities inherent in LAB. * The adjustment provides a more perceptually accurate and uniform representation, * which is particularly beneficial for smooth color transitions. * * `OKLCH` - An easier-to-use representation of OKLAB, expressing colors in terms of Lightness, Chroma, and Hue. * This mode retains the perceptual benefits of OKLAB while offering a more intuitive format for color manipulation. * * p5.Color objects remember the mode that they were * created in. Changing modes doesn't affect their appearance. * * `Single-value (Grayscale) Colors`: * When a color is specified with only one parameter (e.g., `color(g)`), p5.js will interpret it * as a grayscale color. However, how that single parameter translates into a grayscale value * depends on the color mode: * * - `RGB, HSB, and HSL`: In RGB, the single value is interpreted using the “blue” maximum * (i.e., the single parameter is mapped to the blue channel's max). * In HSB and HSL, the single value is mapped to Brightness and Lightness max respectively with hue=0 . * and saturation=0. * * - `LAB, LCH, OKLAB, and OKLCH`: The single value is taken to be the `lightness (L)` component, * with the specified max range for that channel. * * - `HWB`: Grayscale relies on both the `whiteness (W)` and `blackness (B)` channels. Since * a single value cannot directly account for two distinct channels, the library uses an * average of their max values to interpret the single grayscale parameter. For instance, * if W has a max of 50 and B has a max of 100, then the single grayscale parameter * is mapped using (50 + 100) / 2 = 75 as its effective maximum. More complex or negative * ranges are currently not handled, so results in those cases may be ambiguous. * @param mode either RGB, HSB, HSL, * or one of the extended modes described above. * @param max range for all values. * @returns The current color mode. */ colorMode(mode: typeof p5.RGB | typeof p5.HSB | typeof p5.HSL | typeof p5.RGBHDR | typeof p5.HWB | typeof p5.LAB | typeof p5.LCH | typeof p5.OKLAB | typeof p5.OKLCH, max?: number): typeof p5.RGB | typeof p5.HSB | typeof p5.HSL | typeof p5.RGBHDR | typeof p5.HWB | typeof p5.LAB | typeof p5.LCH | typeof p5.OKLAB | typeof p5.OKLCH; colorMode(mode: typeof p5.RGB | typeof p5.HSB | typeof p5.HSL | typeof p5.RGBHDR | typeof p5.HWB | typeof p5.LAB | typeof p5.LCH | typeof p5.OKLAB | typeof p5.OKLCH, max1: number, max2: number, max3: number, maxA?: number): typeof p5.RGB | typeof p5.HSB | typeof p5.HSL | typeof p5.RGBHDR | typeof p5.HWB | typeof p5.LAB | typeof p5.LCH | typeof p5.OKLAB | typeof p5.OKLCH; colorMode(): typeof p5.RGB | typeof p5.HSB | typeof p5.HSL | typeof p5.RGBHDR | typeof p5.HWB | typeof p5.LAB | typeof p5.LCH | typeof p5.OKLAB | typeof p5.OKLCH; /** * Sets the color used to fill shapes. * * Calling `fill(255, 165, 0)` or `fill('orange')` means all shapes drawn * after the fill command will be filled with the color orange. * * The version of `fill()` with one parameter interprets the value one of * three ways. If the parameter is a `Number`, it's interpreted as a grayscale * value. If the parameter is a `String`, it's interpreted as a CSS color * string. A p5.Color object can also be provided to * set the fill color. * * The version of `fill()` with three parameters interprets them as RGB, HSB, * or HSL colors, depending on the current * colorMode(). The default color space is RGB, * with each value in the range from 0 to 255. * * The version of `fill()` with four parameters interprets them as `RGBA`, `HSBA`, * or `HSLA` colors, depending on the current colorMode(). The last parameter * sets the alpha (transparency) value. * @param v1 red value if color mode is RGB or hue value if color mode is HSB. * @param v2 green value if color mode is RGB or saturation value if color mode is HSB. * @param v3 blue value if color mode is RGB or brightness value if color mode is HSB. * @param alpha alpha value, controls transparency (0 - transparent, 255 - opaque). */ fill(v1: number, v2: number, v3: number, alpha?: number): void; fill(value: string): void; fill(gray: number, alpha?: number): void; fill(values: number[]): void; fill(color: p5.Color): void; /** * Disables setting the fill color for shapes. * * Calling `noFill()` is the same as making the fill completely transparent, * as in `fill(0, 0)`. If both noStroke() and * `noFill()` are called, nothing will be drawn to the screen. */ noFill(): void; /** * Disables drawing points, lines, and the outlines of shapes. * * Calling `noStroke()` is the same as making the stroke completely transparent, * as in `stroke(0, 0)`. If both `noStroke()` and * noFill() are called, nothing will be drawn to the * screen. */ noStroke(): void; /** * Sets the color used to draw points, lines, and the outlines of shapes. * * Calling `stroke(255, 165, 0)` or `stroke('orange')` means all shapes drawn * after calling `stroke()` will be outlined with the color orange. The way * these parameters are interpreted may be changed with the * colorMode() function. * * The version of `stroke()` with one parameter interprets the value one of * three ways. If the parameter is a `Number`, it's interpreted as a grayscale * value. If the parameter is a `String`, it's interpreted as a CSS color * string. A p5.Color object can also be provided to * set the stroke color. * * The version of `stroke()` with two parameters interprets the first one as a * grayscale value. The second parameter sets the alpha (transparency) value. * * The version of `stroke()` with three parameters interprets them as RGB, HSB, * or HSL colors, depending on the current `colorMode()`. * * The version of `stroke()` with four parameters interprets them as RGBA, HSBA, * or HSLA colors, depending on the current `colorMode()`. The last parameter * sets the alpha (transparency) value. * @param v1 red value if color mode is RGB or hue value if color mode is HSB. * @param v2 green value if color mode is RGB or saturation value if color mode is HSB. * @param v3 blue value if color mode is RGB or brightness value if color mode is HSB. * @param alpha alpha value, controls transparency (0 - transparent, 255 - opaque). */ stroke(v1: number, v2: number, v3: number, alpha?: number): void; stroke(value: string): void; stroke(gray: number, alpha?: number): void; stroke(values: number[]): void; stroke(color: p5.Color): void; /** * Starts using shapes to erase parts of the canvas. * * All drawing that follows `erase()` will subtract from the canvas, revealing * the web page underneath. The erased areas will become transparent, allowing * the content behind the canvas to show through. The * fill(), stroke(), and * blendMode() have no effect once `erase()` is * called. * * The `erase()` function has two optional parameters. The first parameter * sets the strength of erasing by the shape's interior. A value of 0 means * that no erasing will occur. A value of 255 means that the shape's interior * will fully erase the content underneath. The default value is 255 * (full strength). * * The second parameter sets the strength of erasing by the shape's edge. A * value of 0 means that no erasing will occur. A value of 255 means that the * shape's edge will fully erase the content underneath. The default value is * 255 (full strength). * * To cancel the erasing effect, use the noErase() * function. * * `erase()` has no effect on drawing done with the * image() and * background() functions. * @param strengthFill a number (0-255) for the strength of erasing under a shape's interior. * Defaults to 255, which is full strength. * @param strengthStroke a number (0-255) for the strength of erasing under a shape's edge. * Defaults to 255, which is full strength. */ erase(strengthFill?: number, strengthStroke?: number): void; /** * Ends erasing that was started with erase(). * * The fill(), stroke(), and * blendMode() settings will return to what they * were prior to calling erase(). */ noErase(): void; /** * Sets the way colors blend when added to the canvas. * * By default, drawing with a solid color paints over the current pixel values * on the canvas. `blendMode()` offers many options for blending colors. * * Shapes, images, and text can be used as sources for drawing to the canvas. * A source pixel changes the color of the canvas pixel where it's drawn. The * final color results from blending the source pixel's color with the canvas * pixel's color. RGB color values from the source and canvas pixels are * compared, added, subtracted, multiplied, and divided to create different * effects. Red values with red values, greens with greens, and blues with * blues. * * The parameter, `mode`, sets the blend mode. For example, calling * `blendMode(ADD)` sets the blend mode to `ADD`. The following blend modes * are available in both 2D and WebGL mode: * * - `BLEND`: color values from the source overwrite the canvas. This is the default mode. * * - `ADD`: color values from the source are added to values from the canvas. * * - `DARKEST`: keeps the darkest color value. * * - `LIGHTEST`: keeps the lightest color value. * * - `EXCLUSION`: similar to `DIFFERENCE` but with less contrast. * * - `MULTIPLY`: color values from the source are multiplied with values from the canvas. The result is always darker. * * - `SCREEN`: all color values are inverted, then multiplied, then inverted again. The result is always lighter. (Opposite of `MULTIPLY`) * * - `REPLACE`: the last source drawn completely replaces the rest of the canvas. * * - `REMOVE`: overlapping pixels are removed by making them completely transparent. * * The following blend modes are only available in 2D mode: * * - `DIFFERENCE`: color values from the source are subtracted from the values from the canvas. If the difference is a negative number, it's made positive. * * - `OVERLAY`: combines `MULTIPLY` and `SCREEN`. Dark values in the canvas get darker and light values get lighter. * * - `HARD_LIGHT`: combines `MULTIPLY` and `SCREEN`. Dark values in the source get darker and light values get lighter. * * - `SOFT_LIGHT`: a softer version of `HARD_LIGHT`. * * - `DODGE`: lightens light tones and increases contrast. Divides the canvas color values by the inverted color values from the source. * * - `BURN`: darkens dark tones and increases contrast. Divides the source color values by the inverted color values from the canvas, then inverts the result. * * The following blend modes are only available in WebGL mode: * * - `SUBTRACT`: RGB values from the source are subtracted from the values from the canvas. If the difference is a negative number, it's made positive. Alpha (transparency) values from the source and canvas are added. * @param mode blend mode to set. * either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY, * EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT, * SOFT_LIGHT, DODGE, BURN, ADD, REMOVE or SUBTRACT */ blendMode(mode: typeof p5.BLEND | typeof p5.DARKEST | typeof p5.LIGHTEST | typeof p5.DIFFERENCE | typeof p5.MULTIPLY | typeof p5.EXCLUSION | typeof p5.SCREEN | typeof p5.REPLACE | typeof p5.OVERLAY | typeof p5.HARD_LIGHT | typeof p5.SOFT_LIGHT | typeof p5.DODGE | typeof p5.BURN | typeof p5.ADD | typeof p5.REMOVE | typeof p5.SUBTRACT): void; /** * Displays text in the web browser's console. * * `print()` is helpful for printing values while debugging. Each call to * `print()` creates a new line of text. * * Note: Call `print('\n')` to print a blank line. Calling `print()` without * an argument opens the browser's dialog for printing documents. * @param contents content to print to the console. */ print(contents: any): void; print(data: string | number | any[]): void; /** * Changes the cursor's appearance. * * The first parameter, `type`, sets the type of cursor to display. The * built-in options are `ARROW`, `CROSS`, `HAND`, `MOVE`, `TEXT`, and `WAIT`. * `cursor()` also recognizes standard CSS cursor properties passed as * strings: `'help'`, `'wait'`, `'crosshair'`, `'not-allowed'`, `'zoom-in'`, * and `'grab'`. If the path to an image is passed, as in * `cursor('assets/target.png')`, then the image will be used as the cursor. * Images must be in .cur, .gif, .jpg, .jpeg, or .png format and should be at most 32 by 32 pixels large. * * The parameters `x` and `y` are optional. If an image is used for the * cursor, `x` and `y` set the location pointed to within the image. They are * both 0 by default, so the cursor points to the image's top-left corner. `x` * and `y` must be less than the image's width and height, respectively. * @param type Built-in: either ARROW, CROSS, HAND, MOVE, TEXT, or WAIT. * Native CSS properties: 'grab', 'progress', and so on. * Path to cursor image. * @param x horizontal active spot of the cursor. * @param y vertical active spot of the cursor. */ cursor(type: typeof p5.ARROW | typeof p5.CROSS | typeof p5.HAND | typeof p5.MOVE | typeof p5.TEXT | typeof p5.WAIT | string, x?: number, y?: number): void; /** * Sets the number of frames to draw per second. * * Calling `frameRate()` with one numeric argument, as in `frameRate(30)`, * attempts to draw 30 frames per second (FPS). The target frame rate may not * be achieved depending on the sketch's processing needs. Most computers * default to a frame rate of 60 FPS. Frame rates of 24 FPS and above are * fast enough for smooth animations. * * Calling `frameRate()` without an argument returns the current frame rate. * The value returned is an approximation. * @param fps number of frames to draw per second. * @returns current frame rate. */ frameRate(fps: number): number; frameRate(): number; /** * Returns the target frame rate. * * The value is either the system frame rate or the last value passed to * frameRate(). * @returns _targetFrameRate */ getTargetFrameRate(): number; /** * Hides the cursor from view. */ noCursor(): void; /** * A function that's called when the browser window is resized. * * Code placed in the body of `windowResized()` will run when the * browser window's size changes. It's a good place to call * resizeCanvas() or make other * adjustments to accommodate the new window size. * * The `event` parameter is optional. If added to the function declaration, it * can be used for debugging or other purposes. * @param event optional resize Event. */ windowResized(event?: Event): void; /** * Toggles full-screen mode or returns the current mode. * * Calling `fullscreen(true)` makes the sketch full-screen. Calling * `fullscreen(false)` makes the sketch its original size. * * Calling `fullscreen()` without an argument returns `true` if the sketch * is in full-screen mode and `false` if not. * * Note: Due to browser restrictions, `fullscreen()` can only be called with * user input such as a mouse press. * @param val whether the sketch should be in fullscreen mode. * @returns current fullscreen state. */ fullscreen(val?: boolean): boolean; /** * Sets the pixel density or returns the current density. * * Computer displays are grids of little lights called pixels. A * display's pixel density describes how many pixels it packs into an * area. Displays with smaller pixels have a higher pixel density and create * sharper images. * * `pixelDensity()` sets the pixel scaling for high pixel density displays. * By default, the pixel density is set to match the display's density. * Calling `pixelDensity(1)` turn this off. * * Calling `pixelDensity()` without an argument returns the current pixel * density. * @param val desired pixel density. * @returns current pixel density of the sketch. */ pixelDensity(val?: number): number; pixelDensity(): number; /** * Returns the display's current pixel density. * @returns current pixel density of the display. */ displayDensity(): number; /** * Returns the sketch's current * URL * as a `String`. * @returns url */ getURL(): string; /** * Returns the current * URL * path as an `Array` of `String`s. * * For example, consider a sketch hosted at the URL * `https://example.com/sketchbook`. Calling `getURLPath()` returns * `['sketchbook']`. For a sketch hosted at the URL * `https://example.com/sketchbook/monday`, `getURLPath()` returns * `['sketchbook', 'monday']`. * @returns path components. */ getURLPath(): string[]; /** * Returns the current * URL parameters * in an `Object`. * * For example, calling `getURLParams()` in a sketch hosted at the URL * `https://p5js.org?year=2014&month=May&day=15` returns * `{ year: 2014, month: 'May', day: 15 }`. * @returns URL params */ getURLParams(): object; /** * Converts 3D world coordinates to 2D screen coordinates. * * This function takes a 3D vector and converts its coordinates * from the world space to screen space. This can be useful for placing * 2D elements in a 3D scene or for determining the screen position * of 3D objects. * @param x The x coordinate in world space. (Or a vector for all three coordinates.) * @param y The y coordinate in world space. * @param z The z coordinate in world space. * @returns A vector containing the 2D screen coordinates. */ worldToScreen(x: number | p5.Vector, y: number, z?: number): p5.Vector; /** * Converts 2D screen coordinates to 3D world coordinates. * * This function takes a vector and converts its coordinates from coordinates * on the screen to coordinates in the currently drawn object. This can be * useful for determining the mouse position relative to a 2D or 3D object. * * If given, the Z component of the input coordinates is treated as "depth", * or distance from the camera. * @param x The x coordinate in screen space. (Or a vector for all three coordinates.) * @param y The y coordinate in screen space. * @param z The z coordinate in screen space. * @returns A vector containing the 3D world space coordinates. */ screenToWorld(x: number | p5.Vector, y: number, z?: number): p5.Vector; /** * A function that's called once when the sketch begins running. * * Declaring the function `setup()` sets a code block to run once * automatically when the sketch starts running. It's used to perform * setup tasks such as creating the canvas and initializing variables: * * `function setup() { * // Code to run once at the start of the sketch. * }`Code placed in `setup()` will run once before code placed in * draw() begins looping. * If `setup()` is declared `async` (e.g. `async function setup()`), * execution pauses at each `await` until its promise resolves. * For example, `font = await loadFont(...)` waits for the font asset * to load because `loadFont()` function returns a promise, and the await * keyword means the program will wait for the promise to resolve. * This ensures that all assets are fully loaded before the sketch continues. * * loading assets. * * Note: `setup()` doesn’t have to be declared, but it’s common practice to do so. */ setup(): void; /** * A function that's called repeatedly while the sketch runs. * * Declaring the function `draw()` sets a code block to run repeatedly * once the sketch starts. It’s used to create animations and respond to * user inputs: * * `function draw() { * // Code to run repeatedly. * }`This is often called the "draw loop" because p5.js calls the code in * `draw()` in a loop behind the scenes. By default, `draw()` tries to run * 60 times per second. The actual rate depends on many factors. The * drawing rate, called the "frame rate", can be controlled by calling * frameRate(). The number of times `draw()` * has run is stored in the system variable * frameCount(). * * Code placed within `draw()` begins looping after * setup() runs. `draw()` will run until the user * closes the sketch. `draw()` can be stopped by calling the * noLoop() function. `draw()` can be resumed by * calling the loop() function. */ draw(): void; /** * Creates a canvas element on the web page. * * `createCanvas()` creates the main drawing canvas for a sketch. It should * only be called once at the beginning of setup(). * Calling `createCanvas()` more than once causes unpredictable behavior. * * The first two parameters, `width` and `height`, are optional. They set the * dimensions of the canvas and the values of the * width and height system * variables. For example, calling `createCanvas(900, 500)` creates a canvas * that's 900×500 pixels. By default, `width` and `height` are both 100. * * The third parameter is also optional. If either of the constants `P2D` or * `WEBGL` is passed, as in `createCanvas(900, 500, WEBGL)`, then it will set * the sketch's rendering mode. If an existing * HTMLCanvasElement * is passed, as in `createCanvas(900, 500, myCanvas)`, then it will be used * by the sketch. * * The fourth parameter is also optional. If an existing * HTMLCanvasElement * is passed, as in `createCanvas(900, 500, WEBGL, myCanvas)`, then it will be * used by the sketch. * * Note: In WebGL mode, the canvas will use a WebGL2 context if it's supported * by the browser. Check the webglVersion * system variable to check what version is being used, or call * `setAttributes({ version: 1 })` to create a WebGL1 context. * @param width width of the canvas. Defaults to 100. * @param height height of the canvas. Defaults to 100. * @param renderer either P2D or WEBGL. Defaults to `P2D`. * @param canvas existing canvas element that should be used for the sketch. * @returns new `p5.Renderer` that holds the canvas. */ createCanvas(width?: number, height?: number, renderer?: typeof p5.P2D | typeof p5.WEBGL | typeof p5.P2DHDR, canvas?: HTMLCanvasElement): p5.Renderer; createCanvas(width?: number, height?: number, canvas?: HTMLCanvasElement): p5.Renderer; /** * Resizes the canvas to a given width and height. * * `resizeCanvas()` immediately clears the canvas and calls * redraw(). It's common to call `resizeCanvas()` * within the body of windowResized() like * so: * * `function windowResized() { * resizeCanvas(windowWidth, windowHeight); * }`The first two parameters, `width` and `height`, set the dimensions of the * canvas. They also the values of the width and * height system variables. For example, calling * `resizeCanvas(300, 500)` resizes the canvas to 300×500 pixels, then sets * width to 300 and * height 500. * * The third parameter, `noRedraw`, is optional. If `true` is passed, as in * `resizeCanvas(300, 500, true)`, then the canvas will be canvas to 300×500 * pixels but the redraw() function won't be called * immediately. By default, redraw() is called * immediately when `resizeCanvas()` finishes executing. * @param width width of the canvas. * @param height height of the canvas. * @param noRedraw whether to delay calling * redraw(). Defaults * to `false`. */ resizeCanvas(width: number, height: number, noRedraw?: boolean): void; /** * Removes the default canvas. * * By default, a 100×100 pixels canvas is created without needing to call * createCanvas(). `noCanvas()` removes the * default canvas for sketches that don't need it. */ noCanvas(): void; /** * Creates a p5.Graphics object. * * `createGraphics()` creates an offscreen drawing canvas (graphics buffer) * and returns it as a p5.Graphics object. Drawing * to a separate graphics buffer can be helpful for performance and for * organizing code. * * The first two parameters, `width` and `height`, are optional. They set the * dimensions of the p5.Graphics object. For * example, calling `createGraphics(900, 500)` creates a graphics buffer * that's 900×500 pixels. * * The third parameter is also optional. If either of the constants `P2D` or * `WEBGL` is passed, as in `createGraphics(900, 500, WEBGL)`, then it will set * the p5.Graphics object's rendering mode. If an * existing * HTMLCanvasElement * is passed, as in `createGraphics(900, 500, myCanvas)`, then it will be used * by the graphics buffer. * * The fourth parameter is also optional. If an existing * HTMLCanvasElement * is passed, as in `createGraphics(900, 500, WEBGL, myCanvas)`, then it will be * used by the graphics buffer. * * Note: In WebGL mode, the p5.Graphics object * will use a WebGL2 context if it's supported by the browser. Check the * webglVersion system variable to check what * version is being used, or call `setAttributes({ version: 1 })` to create a * WebGL1 context. * @param width width of the graphics buffer. * @param height height of the graphics buffer. * @param renderer either P2D or WEBGL. Defaults to P2D. * @param canvas existing canvas element that should be * used for the graphics buffer.. * @returns new graphics buffer. */ createGraphics(width: number, height: number, renderer?: typeof p5.P2D | typeof p5.WEBGL, canvas?: HTMLCanvasElement): p5.Graphics; createGraphics(width: number, height: number, canvas?: HTMLCanvasElement): p5.Graphics; /** * Creates and a new p5.Framebuffer object. * * p5.Framebuffer objects are separate drawing * surfaces that can be used as textures in WebGL mode. They're similar to * p5.Graphics objects and generally run much * faster when used as textures. * * The parameter, `options`, is optional. An object can be passed to configure * the p5.Framebuffer object. The available * properties are: * * - `format`: data format of the texture, either `UNSIGNED_BYTE`, `FLOAT`, or `HALF_FLOAT`. Default is `UNSIGNED_BYTE`. * * - `channels`: whether to store `RGB` or `RGBA` color channels. Default is to match the main canvas which is `RGBA`. * * - `depth`: whether to include a depth buffer. Default is `true`. * * - `depthFormat`: data format of depth information, either `UNSIGNED_INT` or `FLOAT`. Default is `FLOAT`. * * - `stencil`: whether to include a stencil buffer for masking. `depth` must be `true` for this feature to work. Defaults to the value of `depth` which is `true`. * * - `antialias`: whether to perform anti-aliasing. If set to `true`, as in `{ antialias: true }`, 2 samples will be used by default. The number of samples can also be set, as in `{ antialias: 4 }`. Default is to match setAttributes() which is `false` (`true` in Safari). * * - `width`: width of the p5.Framebuffer object. Default is to always match the main canvas width. * * - `height`: height of the p5.Framebuffer object. Default is to always match the main canvas height. * * - `density`: pixel density of the p5.Framebuffer object. Default is to always match the main canvas pixel density. * * - `textureFiltering`: how to read values from the p5.Framebuffer object. Either `LINEAR` (nearby pixels will be interpolated) or `NEAREST` (no interpolation). Generally, use `LINEAR` when using the texture as an image and `NEAREST` if reading the texture as data. Default is `LINEAR`. * * If the `width`, `height`, or `density` attributes are set, they won't automatically match the main canvas and must be changed manually. * * Note: `createFramebuffer()` can only be used in WebGL mode. * @param options configuration options. * @returns new framebuffer. */ createFramebuffer(options?: { format?: typeof p5.UNSIGNED_BYTE | typeof p5.FLOAT | typeof p5.HALF_FLOAT; channels?: typeof p5.RGB | typeof p5.RGBA; depth?: boolean; depthFormat?: typeof p5.UNSIGNED_INT | typeof p5.FLOAT; stencil?: boolean; antialias?: boolean | number; width?: number; height?: number; density?: number; textureFiltering?: typeof p5.LINEAR | typeof p5.NEAREST }): p5.Framebuffer; /** * Clears the depth buffer in WebGL mode. * * `clearDepth()` clears information about how far objects are from the camera * in 3D space. This information is stored in an object called the * depth buffer. Clearing the depth buffer ensures new objects aren't drawn * behind old ones. Doing so can be useful for feedback effects in which the * previous frame serves as the background for the current frame. * * The parameter, `depth`, is optional. If a number is passed, as in * `clearDepth(0.5)`, it determines the range of objects to clear from the * depth buffer. 0 doesn't clear any depth information, 0.5 clears depth * information halfway between the near and far clipping planes, and 1 clears * depth information all the way to the far clipping plane. By default, * `depth` is 1. * * Note: `clearDepth()` can only be used in WebGL mode. * @param depth amount of the depth buffer to clear between 0 * (none) and 1 (far clipping plane). Defaults to 1. */ clearDepth(depth?: number): void; /** * Stops the code in draw() from running repeatedly. * * By default, draw() tries to run 60 times per * second. Calling `noLoop()` stops draw() from * repeating. The draw loop can be restarted by calling * loop(). draw() can be run * once by calling redraw(). * * The isLooping() function can be used to check * whether a sketch is looping, as in `isLooping() === true`. */ noLoop(): void; /** * Resumes the draw loop after noLoop() has been * called. * * By default, draw() tries to run 60 times per * second. Calling noLoop() stops * draw() from repeating. The draw loop can be * restarted by calling `loop()`. * * The isLooping() function can be used to check * whether a sketch is looping, as in `isLooping() === true`. */ loop(): void; /** * Returns `true` if the draw loop is running and `false` if not. * * By default, draw() tries to run 60 times per * second. Calling noLoop() stops * draw() from repeating. The draw loop can be * restarted by calling loop(). * * The `isLooping()` function can be used to check whether a sketch is * looping, as in `isLooping() === true`. */ isLooping(): boolean; /** * Runs the code in draw() once. * * By default, draw() tries to run 60 times per * second. Calling noLoop() stops * draw() from repeating. Calling `redraw()` will * execute the code in the draw() function a set * number of times. `await` the result of `redraw` to make sure it has finished. * * The parameter, `n`, is optional. If a number is passed, as in `redraw(5)`, * then the draw loop will run the given number of times. By default, `n` is * 1. * @param n number of times to run draw(). Defaults to 1. */ redraw(n?: number): Promise; /** * Applies a transformation matrix to the coordinate system. * * Transformations such as * translate(), * rotate(), and * scale() * use matrix-vector multiplication behind the scenes. A table of numbers, * called a matrix, encodes each transformation. The values in the matrix * then multiply each point on the canvas, which is represented by a vector. * * `applyMatrix()` allows for many transformations to be applied at once. See * Wikipedia * and MDN * for more details about transformations. * * There are two ways to call `applyMatrix()` in two and three dimensions. * * In 2D mode, the parameters `a`, `b`, `c`, `d`, `e`, and `f`, correspond to * elements in the following transformation matrix: * * The transformation matrix used when applyMatrix is called in 2D mode. * * The numbers can be passed individually, as in * `applyMatrix(2, 0, 0, 0, 2, 0)`. They can also be passed in an array, as in * `applyMatrix([2, 0, 0, 0, 2, 0])`. * * In 3D mode, the parameters `a`, `b`, `c`, `d`, `e`, `f`, `g`, `h`, `i`, * `j`, `k`, `l`, `m`, `n`, `o`, and `p` correspond to elements in the * following transformation matrix: * * The transformation matrix used when applyMatrix is called in 3D mode. * * The numbers can be passed individually, as in * `applyMatrix(2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1)`. They can * also be passed in an array, as in * `applyMatrix([2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1])`. * * By default, transformations accumulate. The * push() and pop() functions * can be used to isolate transformations within distinct drawing groups. * * Note: Transformations are reset at the beginning of the draw loop. Calling * `applyMatrix()` inside the draw() function won't * cause shapes to transform continuously. * @param arr an array containing the elements of the transformation matrix. Its length should be either 6 (2D) or 16 (3D). */ applyMatrix(arr: number[]): void; applyMatrix(a: number, b: number, c: number, d: number, e: number, f: number): void; applyMatrix(a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number, k: number, l: number, m: number, n: number, o: number, p: number): void; /** * Clears all transformations applied to the coordinate system. */ resetMatrix(): void; /** * Rotates the coordinate system. * * By default, the positive x-axis points to the right and the positive y-axis * points downward. The `rotate()` function changes this orientation by * rotating the coordinate system about the origin. Everything drawn after * `rotate()` is called will appear to be rotated. * * The first parameter, `angle`, is the amount to rotate. For example, calling * `rotate(1)` rotates the coordinate system clockwise 1 radian which is * nearly 57˚. `rotate()` interprets angle values using the current * angleMode(). * * The second parameter, `axis`, is optional. It's used to orient 3D rotations * in WebGL mode. If a p5.Vector is passed, as in * `rotate(QUARTER_PI, myVector)`, then the coordinate system will rotate * `QUARTER_PI` radians about `myVector`. If an array of vector components is * passed, as in `rotate(QUARTER_PI, [1, 0, 0])`, then the coordinate system * will rotate `QUARTER_PI` radians about a vector with the components * `[1, 0, 0]`. * * By default, transformations accumulate. For example, calling `rotate(1)` * twice has the same effect as calling `rotate(2)` once. The * push() and pop() functions * can be used to isolate transformations within distinct drawing groups. * * Note: Transformations are reset at the beginning of the draw loop. Calling * `rotate(1)` inside the draw() function won't cause * shapes to spin. * @param angle angle of rotation in the current angleMode(). * @param axis axis to rotate about in 3D. */ rotate(angle: number, axis?: p5.Vector | number[]): void; /** * Rotates the coordinate system about the x-axis in WebGL mode. * * The parameter, `angle`, is the amount to rotate. For example, calling * `rotateX(1)` rotates the coordinate system about the x-axis by 1 radian. * `rotateX()` interprets angle values using the current * angleMode(). * * By default, transformations accumulate. For example, calling `rotateX(1)` * twice has the same effect as calling `rotateX(2)` once. The * push() and pop() functions * can be used to isolate transformations within distinct drawing groups. * * Note: Transformations are reset at the beginning of the draw loop. Calling * `rotateX(1)` inside the draw() function won't cause * shapes to spin. * @param angle angle of rotation in the current angleMode(). */ rotateX(angle: number): void; /** * Rotates the coordinate system about the y-axis in WebGL mode. * * The parameter, `angle`, is the amount to rotate. For example, calling * `rotateY(1)` rotates the coordinate system about the y-axis by 1 radian. * `rotateY()` interprets angle values using the current * angleMode(). * * By default, transformations accumulate. For example, calling `rotateY(1)` * twice has the same effect as calling `rotateY(2)` once. The * push() and pop() functions * can be used to isolate transformations within distinct drawing groups. * * Note: Transformations are reset at the beginning of the draw loop. Calling * `rotateY(1)` inside the draw() function won't cause * shapes to spin. * @param angle angle of rotation in the current angleMode(). */ rotateY(angle: number): void; /** * Rotates the coordinate system about the z-axis in WebGL mode. * * The parameter, `angle`, is the amount to rotate. For example, calling * `rotateZ(1)` rotates the coordinate system about the z-axis by 1 radian. * `rotateZ()` interprets angle values using the current * angleMode(). * * By default, transformations accumulate. For example, calling `rotateZ(1)` * twice has the same effect as calling `rotateZ(2)` once. The * push() and pop() functions * can be used to isolate transformations within distinct drawing groups. * * Note: Transformations are reset at the beginning of the draw loop. Calling * `rotateZ(1)` inside the draw() function won't cause * shapes to spin. * @param angle angle of rotation in the current angleMode(). */ rotateZ(angle: number): void; /** * Scales the coordinate system. * * By default, shapes are drawn at their original scale. A rectangle that's 50 * pixels wide appears to take up half the width of a 100 pixel-wide canvas. * The `scale()` function can shrink or stretch the coordinate system so that * shapes appear at different sizes. There are two ways to call `scale()` with * parameters that set the scale factor(s). * * The first way to call `scale()` uses numbers to set the amount of scaling. * The first parameter, `s`, sets the amount to scale each axis. For example, * calling `scale(2)` stretches the x-, y-, and z-axes by a factor of 2. The * next two parameters, `y` and `z`, are optional. They set the amount to * scale the y- and z-axes. For example, calling `scale(2, 0.5, 1)` stretches * the x-axis by a factor of 2, shrinks the y-axis by a factor of 0.5, and * leaves the z-axis unchanged. * * The second way to call `scale()` uses a p5.Vector * object to set the scale factors. For example, calling `scale(myVector)` * uses the x-, y-, and z-components of `myVector` to set the amount of * scaling along the x-, y-, and z-axes. Doing so is the same as calling * `scale(myVector.x, myVector.y, myVector.z)`. * * By default, transformations accumulate. For example, calling `scale(1)` * twice has the same effect as calling `scale(2)` once. The * push() and pop() functions * can be used to isolate transformations within distinct drawing groups. * * Note: Transformations are reset at the beginning of the draw loop. Calling * `scale(2)` inside the draw() function won't cause * shapes to grow continuously. * @param s amount to scale along the positive x-axis. * @param y amount to scale along the positive y-axis. Defaults to `s`. * @param z amount to scale along the positive z-axis. Defaults to `y`. */ scale(s: number | p5.Vector | number[], y?: number, z?: number): void; scale(scales: p5.Vector | number[]): void; /** * Shears the x-axis so that shapes appear skewed. * * By default, the x- and y-axes are perpendicular. The `shearX()` function * transforms the coordinate system so that x-coordinates are translated while * y-coordinates are fixed. * * The first parameter, `angle`, is the amount to shear. For example, calling * `shearX(1)` transforms all x-coordinates using the formula * `x = x + y * tan(angle)`. `shearX()` interprets angle values using the * current angleMode(). * * By default, transformations accumulate. For example, calling * `shearX(1)` twice has the same effect as calling `shearX(2)` once. The * push() and * pop() functions can be used to isolate * transformations within distinct drawing groups. * * Note: Transformations are reset at the beginning of the draw loop. Calling * `shearX(1)` inside the draw() function won't * cause shapes to shear continuously. * @param angle angle to shear by in the current angleMode(). */ shearX(angle: number): void; /** * Shears the y-axis so that shapes appear skewed. * * By default, the x- and y-axes are perpendicular. The `shearY()` function * transforms the coordinate system so that y-coordinates are translated while * x-coordinates are fixed. * * The first parameter, `angle`, is the amount to shear. For example, calling * `shearY(1)` transforms all y-coordinates using the formula * `y = y + x * tan(angle)`. `shearY()` interprets angle values using the * current angleMode(). * * By default, transformations accumulate. For example, calling * `shearY(1)` twice has the same effect as calling `shearY(2)` once. The * push() and * pop() functions can be used to isolate * transformations within distinct drawing groups. * * Note: Transformations are reset at the beginning of the draw loop. Calling * `shearY(1)` inside the draw() function won't * cause shapes to shear continuously. * @param angle angle to shear by in the current angleMode(). */ shearY(angle: number): void; /** * Translates the coordinate system. * * By default, the origin `(0, 0)` is at the sketch's top-left corner in 2D * mode and center in WebGL mode. The `translate()` function shifts the origin * to a different position. Everything drawn after `translate()` is called * will appear to be shifted. There are two ways to call `translate()` with * parameters that set the origin's position. * * The first way to call `translate()` uses numbers to set the amount of * translation. The first two parameters, `x` and `y`, set the amount to * translate along the positive x- and y-axes. For example, calling * `translate(20, 30)` translates the origin 20 pixels along the x-axis and 30 * pixels along the y-axis. The third parameter, `z`, is optional. It sets the * amount to translate along the positive z-axis. For example, calling * `translate(20, 30, 40)` translates the origin 20 pixels along the x-axis, * 30 pixels along the y-axis, and 40 pixels along the z-axis. * * The second way to call `translate()` uses a * p5.Vector object to set the amount of * translation. For example, calling `translate(myVector)` uses the x-, y-, * and z-components of `myVector` to set the amount to translate along the x-, * y-, and z-axes. Doing so is the same as calling * `translate(myVector.x, myVector.y, myVector.z)`. * * By default, transformations accumulate. For example, calling * `translate(10, 0)` twice has the same effect as calling * `translate(20, 0)` once. The push() and * pop() functions can be used to isolate * transformations within distinct drawing groups. * * Note: Transformations are reset at the beginning of the draw loop. Calling * `translate(10, 0)` inside the draw() function won't * cause shapes to move continuously. * @param x amount to translate along the positive x-axis. * @param y amount to translate along the positive y-axis. * @param z amount to translate along the positive z-axis. */ translate(x: number, y: number, z?: number): void; translate(vector: p5.Vector): void; /** * Begins a drawing group that contains its own styles and transformations. * * By default, styles such as fill() and * transformations such as rotate() are applied to * all drawing that follows. The `push()` and pop() * functions can limit the effect of styles and transformations to a specific * group of shapes, images, and text. For example, a group of shapes could be * translated to follow the mouse without affecting the rest of the sketch: * * `// Begin the drawing group. * push(); * * // Translate the origin to the mouse's position. * translate(mouseX, mouseY); * * // Style the face. * noStroke(); * fill('green'); * * // Draw the face. * circle(0, 0, 60); * * // Style the eyes. * fill('white'); * * // Draw the left eye. * ellipse(-20, -20, 30, 20); * * // Draw the right eye. * ellipse(20, -20, 30, 20); * * // End the drawing group. * pop(); * * // Draw a bug. * let x = random(0, 100); * let y = random(0, 100); * text('🦟', x, y);`In the code snippet above, the bug's position isn't affected by * `translate(mouseX, mouseY)` because that transformation is contained * between `push()` and pop(). The bug moves around * the entire canvas as expected. * * Note: `push()` and pop() are always called as a * pair. Both functions are required to begin and end a drawing group. * * `push()` and pop() can also be nested to create * subgroups. For example, the code snippet above could be changed to give * more detail to the frog’s eyes: * * `// Begin the drawing group. * push(); * * // Translate the origin to the mouse's position. * translate(mouseX, mouseY); * * // Style the face. * noStroke(); * fill('green'); * * // Draw a face. * circle(0, 0, 60); * * // Style the eyes. * fill('white'); * * // Draw the left eye. * push(); * translate(-20, -20); * ellipse(0, 0, 30, 20); * fill('black'); * circle(0, 0, 8); * pop(); * * // Draw the right eye. * push(); * translate(20, -20); * ellipse(0, 0, 30, 20); * fill('black'); * circle(0, 0, 8); * pop(); * * // End the drawing group. * pop(); * * // Draw a bug. * let x = random(0, 100); * let y = random(0, 100); * text('🦟', x, y);`In this version, the code to draw each eye is contained between its own * `push()` and pop() functions. Doing so makes it * easier to add details in the correct part of a drawing. * * `push()` and pop() contain the effects of the * following functions: * * - fill() * * - noFill() * * - noStroke() * * - stroke() * * - tint() * * - noTint() * * - strokeWeight() * * - strokeCap() * * - strokeJoin() * * - imageMode() * * - rectMode() * * - ellipseMode() * * - colorMode() * * - textAlign() * * - textFont() * * - textSize() * * - textLeading() * * - applyMatrix() * * - resetMatrix() * * - rotate() * * - scale() * * - shearX() * * - shearY() * * - translate() * * In WebGL mode, `push()` and pop() contain the * effects of a few additional styles: * * - setCamera() * * - ambientLight() * * - directionalLight() * * - pointLight() texture() * * - specularMaterial() * * - shininess() * * - normalMaterial() * * - shader() */ push(): void; /** * Ends a drawing group that contains its own styles and transformations. * * By default, styles such as fill() and * transformations such as rotate() are applied to * all drawing that follows. The push() and `pop()` * functions can limit the effect of styles and transformations to a specific * group of shapes, images, and text. For example, a group of shapes could be * translated to follow the mouse without affecting the rest of the sketch: * * `// Begin the drawing group. * push(); * * // Translate the origin to the mouse's position. * translate(mouseX, mouseY); * * // Style the face. * noStroke(); * fill('green'); * * // Draw the face. * circle(0, 0, 60); * * // Style the eyes. * fill('white'); * * // Draw the left eye. * ellipse(-20, -20, 30, 20); * * // Draw the right eye. * ellipse(20, -20, 30, 20); * * // End the drawing group. * pop(); * * // Draw a bug. * let x = random(0, 100); * let y = random(0, 100); * text('🦟', x, y);`In the code snippet above, the bug's position isn't affected by * `translate(mouseX, mouseY)` because that transformation is contained * between push() and `pop()`. The bug moves around * the entire canvas as expected. * * Note: push() and `pop()` are always called as a * pair. Both functions are required to begin and end a drawing group. * * push() and `pop()` can also be nested to create * subgroups. For example, the code snippet above could be changed to give * more detail to the frog’s eyes: * * `// Begin the drawing group. * push(); * * // Translate the origin to the mouse's position. * translate(mouseX, mouseY); * * // Style the face. * noStroke(); * fill('green'); * * // Draw a face. * circle(0, 0, 60); * * // Style the eyes. * fill('white'); * * // Draw the left eye. * push(); * translate(-20, -20); * ellipse(0, 0, 30, 20); * fill('black'); * circle(0, 0, 8); * pop(); * * // Draw the right eye. * push(); * translate(20, -20); * ellipse(0, 0, 30, 20); * fill('black'); * circle(0, 0, 8); * pop(); * * // End the drawing group. * pop(); * * // Draw a bug. * let x = random(0, 100); * let y = random(0, 100); * text('🦟', x, y);`In this version, the code to draw each eye is contained between its own * push() and `pop()` functions. Doing so makes it * easier to add details in the correct part of a drawing. * * push() and `pop()` contain the effects of the * following functions: * * - fill() * * - noFill() * * - noStroke() * * - stroke() * * - tint() * * - noTint() * * - strokeWeight() * * - strokeCap() * * - strokeJoin() * * - imageMode() * * - rectMode() * * - ellipseMode() * * - colorMode() * * - textAlign() * * - textFont() * * - textSize() * * - textLeading() * * - applyMatrix() * * - resetMatrix() * * - rotate() * * - scale() * * - shearX() * * - shearY() * * - translate() * * In WebGL mode, push() and `pop()` contain the * effects of a few additional styles: * * - setCamera() * * - ambientLight() * * - directionalLight() * * - pointLight() texture() * * - specularMaterial() * * - shininess() * * - normalMaterial() * * - shader() */ pop(): void; /** * Stores a value in the web browser's local storage. * * Web browsers can save small amounts of data using the built-in * localStorage object. * Data stored in `localStorage` can be retrieved at any point, even after * refreshing a page or restarting the browser. Data are stored as key-value * pairs. * * `storeItem()` makes it easy to store values in `localStorage` and * getItem() makes it easy to retrieve them. * * The first parameter, `key`, is the name of the value to be stored as a * string. * * The second parameter, `value`, is the value to be stored. Values can have * any type. * * Note: Sensitive data such as passwords or personal information shouldn't be * stored in `localStorage`. * @param key name of the value. * @param value value to be stored. */ storeItem(key: string, value: string | number | boolean | object | any[]): void; /** * Returns a value in the web browser's local storage. * * Web browsers can save small amounts of data using the built-in * localStorage object. * Data stored in `localStorage` can be retrieved at any point, even after * refreshing a page or restarting the browser. Data are stored as key-value * pairs. * * storeItem() makes it easy to store values in * `localStorage` and `getItem()` makes it easy to retrieve them. * * The first parameter, `key`, is the name of the value to be stored as a * string. * * The second parameter, `value`, is the value to be retrieved a string. For * example, calling `getItem('size')` retrieves the value with the key `size`. * * Note: Sensitive data such as passwords or personal information shouldn't be * stored in `localStorage`. * @param key name of the value. * @returns stored item. */ getItem(key: string): string | number | boolean | object | any[]; /** * Removes all items in the web browser's local storage. * * Web browsers can save small amounts of data using the built-in * localStorage object. * Data stored in `localStorage` can be retrieved at any point, even after * refreshing a page or restarting the browser. Data are stored as key-value * pairs. Calling `clearStorage()` removes all data from `localStorage`. * * Note: Sensitive data such as passwords or personal information shouldn't be * stored in `localStorage`. */ clearStorage(): void; /** * Removes an item from the web browser's local storage. * * Web browsers can save small amounts of data using the built-in * localStorage object. * Data stored in `localStorage` can be retrieved at any point, even after * refreshing a page or restarting the browser. Data are stored as key-value * pairs. * * storeItem() makes it easy to store values in * `localStorage` and `removeItem()` makes it easy to delete them. * * The parameter, `key`, is the name of the value to remove as a string. For * example, calling `removeItem('size')` removes the item with the key `size`. * * Note: Sensitive data such as passwords or personal information shouldn't be * stored in `localStorage`. * @param key name of the value to remove. */ removeItem(key: string): void; /** * Searches the page for the first element that matches the given * CSS selector string. * * The selector string can be an ID, class, tag name, or a combination. * `select()` returns a p5.Element object if it * finds a match and `null` if not. * * The second parameter, `container`, is optional. It specifies a container to * search within. `container` can be CSS selector string, a * p5.Element object, or an * HTMLElement object. * @param selectors CSS selector string of element to search for. * @param container CSS selector string, p5.Element, or * HTMLElement to search within. * @returns p5.Element containing the element. */ select(selectors: string, container?: string | p5.Element | HTMLElement): p5.Element | null; /** * Searches the page for all elements that matches the given * CSS selector string. * * The selector string can be an ID, class, tag name, or a combination. * `selectAll()` returns an array of p5.Element * objects if it finds any matches and an empty array if none are found. * * The second parameter, `container`, is optional. It specifies a container to * search within. `container` can be CSS selector string, a * p5.Element object, or an * HTMLElement object. * @param selectors CSS selector string of element to search for. * @param container CSS selector string, p5.Element, or * HTMLElement to search within. * @returns array of p5.Elements containing any elements found. */ selectAll(selectors: string, container?: string | p5.Element | HTMLElement): p5.Element[]; /** * Creates a new p5.Element object. * * The first parameter, `tag`, is a string an HTML tag such as `'h5'`. * * The second parameter, `content`, is optional. It's a string that sets the * HTML content to insert into the new element. New elements have no content * by default. * @param tag tag for the new element. * @param content HTML content to insert into the element. * @returns new p5.Element object. */ createElement(tag: string, content?: string): p5.Element; /** * Removes all elements created by p5.js, including any event handlers. * * There are two exceptions: * canvas elements created by createCanvas() * and p5.Render objects created by * createGraphics(). */ removeElements(): void; /** * Helpers for create methods. */ addElement(): void; addElement(): void; /** * Creates a `<div></div>` element. * * `<div></div>` elements are commonly used as containers for * other elements. * * The parameter `html` is optional. It accepts a string that sets the * inner HTML of the new `<div></div>`. * @param html inner HTML for the new `<div></div>` element. * @returns new p5.Element object. */ createDiv(html?: string): p5.Element; /** * Creates a paragraph element. * * `<p></p>` elements are commonly used for paragraph-length text. * * The parameter `html` is optional. It accepts a string that sets the * inner HTML of the new `<p></p>`. * @param html inner HTML for the new `<p></p>` element. * @returns new p5.Element object. */ createP(html?: string): p5.Element; /** * Creates a `<span></span>` element. * * `<span></span>` elements are commonly used as containers * for inline elements. For example, a `<span></span>` * can hold part of a sentence that's a * different style. * * The parameter `html` is optional. It accepts a string that sets the * inner HTML of the new `<span></span>`. * @param html inner HTML for the new `<span></span>` element. * @returns new p5.Element object. */ createSpan(html?: string): p5.Element; /** * Creates an `<img>` element that can appear outside of the canvas. * * The first parameter, `src`, is a string with the path to the image file. * `src` should be a relative path, as in `'assets/image.png'`, or a URL, as * in `'https://example.com/image.png'`. * * The second parameter, `alt`, is a string with the * alternate text * for the image. An empty string `''` can be used for images that aren't displayed. * * The third parameter, `crossOrigin`, is optional. It's a string that sets the * crossOrigin property * of the image. Use `'anonymous'` or `'use-credentials'` to fetch the image * with cross-origin access. * * The fourth parameter, `callback`, is also optional. It sets a function to * call after the image loads. The new image is passed to the callback * function as a p5.Element object. * @param src relative path or URL for the image. * @param alt alternate text for the image. * @returns new p5.Element object. */ createImg(src: string, alt: string): p5.Element; createImg(src: string, alt: string, crossOrigin?: string, successCallback?: Function): p5.Element; /** * Creates an `<a></a>` element that links to another web page. * * The first parmeter, `href`, is a string that sets the URL of the linked * page. * * The second parameter, `html`, is a string that sets the inner HTML of the * link. It's common to use text, images, or buttons as links. * * The third parameter, `target`, is optional. It's a string that tells the * web browser where to open the link. By default, links open in the current * browser tab. Passing `'_blank'` will cause the link to open in a new * browser tab. MDN describes a few * other options. * @param href URL of linked page. * @param html inner HTML of link element to display. * @param target target where the new link should open, * either `'_blank'`, `'_self'`, `'_parent'`, or `'_top'`. * @returns new p5.Element object. */ createA(href: string, html: string, target?: string): p5.Element; /** * Creates a slider `<input></input>` element. * * Range sliders are useful for quickly selecting numbers from a given range. * * The first two parameters, `min` and `max`, are numbers that set the * slider's minimum and maximum. * * The third parameter, `value`, is optional. It's a number that sets the * slider's default value. * * The fourth parameter, `step`, is also optional. It's a number that sets the * spacing between each value in the slider's range. Setting `step` to 0 * allows the slider to move smoothly from `min` to `max`. * @param min minimum value of the slider. * @param max maximum value of the slider. * @param value default value of the slider. * @param step size for each step in the slider's range. * @returns new p5.Element object. */ createSlider(min: number, max: number, value?: number, step?: number): p5.Element; /** * Creates a `<button></button>` element. * * The first parameter, `label`, is a string that sets the label displayed on * the button. * * The second parameter, `value`, is optional. It's a string that sets the * button's value. See * MDN * for more details. * @param label label displayed on the button. * @param value value of the button. * @returns new p5.Element object. */ createButton(label: string, value?: string): p5.Element; /** * Creates a checkbox `<input></input>` element. * * Checkboxes extend the p5.Element class with a * `checked()` method. Calling `myBox.checked()` returns `true` if it the box * is checked and `false` if not. * * The first parameter, `label`, is optional. It's a string that sets the label * to display next to the checkbox. * * The second parameter, `value`, is also optional. It's a boolean that sets the * checkbox's value. * @param label label displayed after the checkbox. * @param value value of the checkbox. Checked is `true` and unchecked is `false`. * @returns new p5.Element object. */ createCheckbox(label?: string, value?: boolean): p5.Element; /** * Creates a dropdown menu `<select></select>` element. * * The parameter is optional. If `true` is passed, as in * `let mySelect = createSelect(true)`, then the dropdown will support * multiple selections. If an existing `<select></select>` element * is passed, as in `let mySelect = createSelect(otherSelect)`, the existing * element will be wrapped in a new p5.Element * object. * * Dropdowns extend the p5.Element class with a few * helpful methods for managing options: * * - `mySelect.option(name, [value])` adds an option to the menu. The first paremeter, `name`, is a string that sets the option's name and value. The second parameter, `value`, is optional. If provided, it sets the value that corresponds to the key `name`. If an option with `name` already exists, its value is changed to `value`. * * - `mySelect.value()` returns the currently-selected option's value. * * - `mySelect.selected()` returns the currently-selected option. * * - `mySelect.selected(option)` selects the given option by default. * * - `mySelect.disable()` marks the whole dropdown element as disabled. * * - `mySelect.disable(option)` marks a given option as disabled. * * - `mySelect.enable()` marks the whole dropdown element as enabled. * * - `mySelect.enable(option)` marks a given option as enabled. * @param multiple support multiple selections. * @returns new p5.Element object. */ createSelect(multiple?: boolean): p5.Element; createSelect(existing: object): p5.Element; /** * Creates a radio button element. * * The parameter is optional. If a string is passed, as in * `let myRadio = createSelect('food')`, then each radio option will * have `"food"` as its `name` parameter: `<input name="food"></input>`. * If an existing `<div></div>` or `<span></span>` * element is passed, as in `let myRadio = createSelect(container)`, it will * become the radio button's parent element. * * Radio buttons extend the p5.Element class with a few * helpful methods for managing options: * * - `myRadio.option(value, [label])` adds an option to the menu. The first paremeter, `value`, is a string that sets the option's value and label. The second parameter, `label`, is optional. If provided, it sets the label displayed for the `value`. If an option with `value` already exists, its label is changed and its value is returned. * * - `myRadio.value()` returns the currently-selected option's value. * * - `myRadio.selected()` returns the currently-selected option. * * - `myRadio.selected(value)` selects the given option and returns it as an `HTMLInputElement`. * * - `myRadio.disable(shouldDisable)` enables the entire radio button if `true` is passed and disables it if `false` is passed. * @param containerElement container HTML Element, either a `<div></div>` * or `<span></span>`. * @returns new p5.Element object. */ createRadio(containerElement?: object): p5.Element; createRadio(name?: string): p5.Element; createRadio(): p5.Element; /** * Creates a color picker element. * * The parameter, `value`, is optional. If a color string or * p5.Color object is passed, it will set the default * color. * * Color pickers extend the p5.Element class with a * couple of helpful methods for managing colors: * * - `myPicker.value()` returns the current color as a hex string in the format `'#rrggbb'`. * * - `myPicker.color()` returns the current color as a p5.Color object. * @param value default color as a CSS color string. * @returns new p5.Element object. */ createColorPicker(value?: string | p5.Color): p5.Element; /** * Creates a text `<input></input>` element. * * Call `myInput.size()` to set the length of the text box. * * The first parameter, `value`, is optional. It's a string that sets the * input's default value. The input is blank by default. * * The second parameter, `type`, is also optional. It's a string that * specifies the type of text being input. See MDN for a full * list of options. * The default is `'text'`. * @param value default value of the input box. Defaults to an empty string `''`. * @param type type of input. Defaults to `'text'`. * @returns new p5.Element object. */ createInput(value?: string, type?: string): p5.Element; createInput(value?: string): p5.Element; /** * Creates an `<input></input>` element of type `'file'`. * * `createFileInput()` allows users to select local files for use in a sketch. * It returns a p5.File object. * * The first parameter, `callback`, is a function that's called when the file * loads. The callback function should have one parameter, `file`, that's a * p5.File object. * * The second parameter, `multiple`, is optional. It's a boolean value that * allows loading multiple files if set to `true`. If `true`, `callback` * will be called once per file. * @param callback function to call once the file loads. * @param multiple allow multiple files to be selected. * @returns The new input element. */ createFileInput(callback: (input: p5.File) => any, multiple?: boolean): p5.Element; /** * Creates a `<video>` element for simple audio/video playback. * * `createVideo()` returns a new * p5.MediaElement object. Videos are shown by * default. They can be hidden by calling `video.hide()` and drawn to the * canvas using image(). * * The first parameter, `src`, is the path the video. If a single string is * passed, as in `'assets/topsecret.mp4'`, a single video is loaded. An array * of strings can be used to load the same video in different formats. For * example, `['assets/topsecret.mp4', 'assets/topsecret.ogv', 'assets/topsecret.webm']`. * This is useful for ensuring that the video can play across different browsers with * different capabilities. See * MDN * for more information about supported formats. * * The second parameter, `callback`, is optional. It's a function to call once * the video is ready to play. * @param src path to a video file, or an array of paths for * supporting different browsers. * @param callback function to call once the video is ready to play. * @returns new p5.MediaElement object. */ createVideo(src?: string | string[], callback?: (video: p5.MediaElement) => any): p5.MediaElement; /** * Creates a hidden `<audio>` element for simple audio playback. * * `createAudio()` returns a new * p5.MediaElement object. * * The first parameter, `src`, is the path the audio. If a single string is * passed, as in `'assets/audio.mp3'`, a single audio is loaded. An array * of strings can be used to load the same audio in different formats. For * example, `['assets/audio.mp3', 'assets/video.wav']`. * This is useful for ensuring that the audio can play across different * browsers with different capabilities. See * MDN * for more information about supported formats. * * The second parameter, `callback`, is optional. It's a function to call once * the audio is ready to play. * @param src path to an audio file, or an array of paths * for supporting different browsers. * @param callback function to call once the audio is ready to play. * @returns new p5.MediaElement object. */ createAudio(src?: string | string[], callback?: (video: p5.MediaElement) => any): p5.MediaElement; /** * Creates a `<video>` element that "captures" the audio/video stream from * the webcam and microphone. * * `createCapture()` returns a new * p5.MediaElement object. Videos are shown by * default. They can be hidden by calling `capture.hide()` and drawn to the * canvas using image(). * * The first parameter, `type`, is optional. It sets the type of capture to * use. By default, `createCapture()` captures both audio and video. If `VIDEO` * is passed, as in `createCapture(VIDEO)`, only video will be captured. * If `AUDIO` is passed, as in `createCapture(AUDIO)`, only audio will be * captured. A constraints object can also be passed to customize the stream. * See the * W3C documentation for possible properties. Different browsers support different * properties. * * The 'flipped' property is an optional property which can be set to `{flipped:true}` * to mirror the video output.If it is true then it means that video will be mirrored * or flipped and if nothing is mentioned then by default it will be `false`. * * The second parameter,`callback`, is optional. It's a function to call once * the capture is ready for use. The callback function should have one * parameter, `stream`, that's a * MediaStream object. * * Note: `createCapture()` only works when running a sketch locally or using HTTPS. Learn more * here * and here. * @param type type of capture, either AUDIO or VIDEO, * or a constraints object. Both video and audio * audio streams are captured by default. * @param flipped flip the capturing video and mirror the output with `{flipped:true}`. By * default it is false. * @param callback function to call once the stream * has loaded. * @returns new p5.MediaElement object. */ createCapture(type?: typeof p5.AUDIO | typeof p5.VIDEO | object, flipped?: object, callback?: Function): p5.MediaElement; /** * The setMoveThreshold() function is used to set the movement threshold for * the deviceMoved() function. The default threshold is set to 0.5. * @param value The threshold value */ setMoveThreshold(value: number): void; /** * The setShakeThreshold() function is used to set the movement threshold for * the deviceShaken() function. The default threshold is set to 30. * @param value The threshold value */ setShakeThreshold(value: number): void; /** * The deviceMoved() function is called when the device is moved by more than * the threshold value along X, Y or Z axis. The default threshold is set to 0.5. * The threshold value can be changed using setMoveThreshold(). */ deviceMoved(): void; /** * The deviceTurned() function is called when the device rotates by * more than 90 degrees continuously. * * The axis that triggers the deviceTurned() method is stored in the turnAxis * variable. The deviceTurned() method can be locked to trigger on any axis: * X, Y or Z by comparing the turnAxis variable to 'X', 'Y' or 'Z'. */ deviceTurned(): void; /** * The deviceShaken() function is called when the device total acceleration * changes of accelerationX and accelerationY values is more than * the threshold value. The default threshold is set to 30. * The threshold value can be changed using setShakeThreshold(). */ deviceShaken(): void; /** * A function that's called once when any key is pressed. * * Declaring the function `keyPressed()` sets a code block to run once * automatically when the user presses any key: * * `function keyPressed() { * // Code to run. * }`The key and keyCode * variables will be updated with the most recently typed value when * `keyPressed()` is called by p5.js: * * `function keyPressed() { * if (key === 'c') { * // Code to run. * } * * if (keyCode === 13) { // Enter key * // Code to run. * } * }`The parameter, `event`, is optional. `keyPressed()` is always passed a * KeyboardEvent * object with properties that describe the key press event: * * `function keyPressed(event) { * // Code to run that uses the event. * console.log(event); * }`Browsers may have default behaviors attached to various key events. For * example, some browsers may jump to the bottom of a web page when the * `SPACE` key is pressed. To prevent any default behavior for this event, add * `return false;` to the end of the function. * @param event optional `KeyboardEvent` callback argument. */ keyPressed(event?: KeyboardEvent): void; /** * A function that's called once when any key is released. * * Declaring the function `keyReleased()` sets a code block to run once * automatically when the user releases any key: * * `function keyReleased() { * // Code to run. * }`The key and keyCode * variables will be updated with the most recently released value when * `keyReleased()` is called by p5.js: * * `function keyReleased() { * if (key === 'c') { * // Code to run. * } * * if (keyCode === 13) { // Enter key * // Code to run. * } * }`The parameter, `event`, is optional. `keyReleased()` is always passed a * KeyboardEvent * object with properties that describe the key press event: * * `function keyReleased(event) { * // Code to run that uses the event. * console.log(event); * }`Browsers may have default behaviors attached to various key events. To * prevent any default behavior for this event, add `return false;` to the end * of the function. * @param event optional `KeyboardEvent` callback argument. */ keyReleased(event?: KeyboardEvent): void; /** * A function that's called once when keys with printable characters are pressed. * * Declaring the function `keyTyped()` sets a code block to run once * automatically when the user presses any key with a printable character such * as `a` or 1. Modifier keys such as `SHIFT`, `CONTROL`, and the arrow keys * will be ignored: * * `function keyTyped() { * // Code to run. * }`The key and keyCode * variables will be updated with the most recently released value when * `keyTyped()` is called by p5.js: * * `function keyTyped() { * // Check for the "c" character using key. * if (key === 'c') { * // Code to run. * } * * // Check for "c" using keyCode. * if (keyCode === 67) { // 67 is the ASCII code for 'c' * // Code to run. * } * }`The parameter, `event`, is optional. `keyTyped()` is always passed a * KeyboardEvent * object with properties that describe the key press event: * * `function keyReleased(event) { * // Code to run that uses the event. * console.log(event); * }`Note: Use the keyPressed() function and * keyCode system variable to respond to modifier * keys such as `ALT`. * * Browsers may have default behaviors attached to various key events. To * prevent any default behavior for this event, add `return false;` to the end * of the function. * @param event optional `KeyboardEvent` callback argument. */ keyTyped(event?: KeyboardEvent): void; /** * Returns `true` if the key it’s checking is pressed and `false` if not. * * `keyIsDown()` is helpful when checking for multiple different key presses. * For example, `keyIsDown()` can be used to check if both `LEFT_ARROW` and * `UP_ARROW` are pressed: * * `if (keyIsDown(LEFT_ARROW) && keyIsDown(UP_ARROW)) { * // Move diagonally. * }``keyIsDown()` can check for key presses using strings based on * KeyboardEvent.key * or KeyboardEvent.code values, * such as `keyIsDown('x')` or `keyIsDown('ArrowLeft')`. * * Note: In p5.js 2.0 and newer, numeric keycodes (such as 88 for 'X') are no longer supported. * This is a breaking change from previous versions. * * You can still use the p5 constants like `LEFT_ARROW` which now map to string values * internally rather than numeric codes. * @param code key to check. * @returns whether the key is down or not. */ keyIsDown(code: number | string): boolean; /** * A function that's called when the mouse moves. * * Declaring the function `mouseMoved()` sets a code block to run * automatically when the user moves the mouse without clicking any mouse * buttons: * * `function mouseMoved() { * // Code to run. * }`The mouse system variables, such as mouseX and * mouseY, will be updated with their most recent * value when `mouseMoved()` is called by p5.js: * * `function mouseMoved() { * if (mouseX < 50) { * // Code to run if the mouse is on the left. * } * * if (mouseY > 50) { * // Code to run if the mouse is near the bottom. * } * }`The parameter, `event`, is optional. `mouseMoved()` is always passed a * MouseEvent * object with properties that describe the mouse move event: * * `function mouseMoved(event) { * // Code to run that uses the event. * console.log(event); * }`Browsers may have default behaviors attached to various mouse events. For * example, some browsers highlight text when the user moves the mouse while * pressing a mouse button. To prevent any default behavior for this event, * add `return false;` to the end of the function. * @param event optional `MouseEvent` argument. */ mouseMoved(event?: MouseEvent): void; /** * A function that's called when the mouse moves while a button is pressed. * * Declaring the function `mouseDragged()` sets a code block to run * automatically when the user clicks and drags the mouse: * * `function mouseDragged() { * // Code to run. * }`The mouse system variables, such as mouseX and * mouseY, will be updated with their most recent * value when `mouseDragged()` is called by p5.js: * * `function mouseDragged() { * if (mouseX < 50) { * // Code to run if the mouse is on the left. * } * * if (mouseY > 50) { * // Code to run if the mouse is near the bottom. * } * }`The parameter, `event`, is optional. `mouseDragged()` is always passed a * MouseEvent * object with properties that describe the mouse drag event: * * `function mouseDragged(event) { * // Code to run that uses the event. * console.log(event); * }`On touchscreen devices, `mouseDragged()` will run when a user moves a touch * point. * * Browsers may have default behaviors attached to various mouse events. For * example, some browsers highlight text when the user moves the mouse while * pressing a mouse button. To prevent any default behavior for this event, * add `return false;` to the end of the function. * @param event optional `MouseEvent` argument. */ mouseDragged(event?: MouseEvent): void; /** * A function that's called once when a mouse button is pressed. * * Declaring the function `mousePressed()` sets a code block to run * automatically when the user presses a mouse button: * * `function mousePressed() { * // Code to run. * }`The mouse system variables, such as mouseX and * mouseY, will be updated with their most recent * value when `mousePressed()` is called by p5.js: * * `function mousePressed() { * if (mouseX < 50) { * // Code to run if the mouse is on the left. * } * * if (mouseY > 50) { * // Code to run if the mouse is near the bottom. * } * }`The parameter, `event`, is optional. `mousePressed()` is always passed a * MouseEvent * object with properties that describe the mouse press event: * * `function mousePressed(event) { * // Code to run that uses the event. * console.log(event); * }`On touchscreen devices, `mousePressed()` will run when a user’s touch * begins. * * Browsers may have default behaviors attached to various mouse events. For * example, some browsers highlight text when the user moves the mouse while * pressing a mouse button. To prevent any default behavior for this event, * add `return false;` to the end of the function. * * Note: `mousePressed()`, mouseReleased(), * and mouseClicked() are all related. * `mousePressed()` runs as soon as the user clicks the mouse. * mouseReleased() runs as soon as the user * releases the mouse click. mouseClicked() * runs immediately after mouseReleased(). * @param event optional `MouseEvent` argument. */ mousePressed(event?: MouseEvent): void; /** * A function that's called once when a mouse button is released. * * Declaring the function `mouseReleased()` sets a code block to run * automatically when the user releases a mouse button after having pressed * it: * * `function mouseReleased() { * // Code to run. * }`The mouse system variables, such as mouseX and * mouseY, will be updated with their most recent * value when `mouseReleased()` is called by p5.js: * * `function mouseReleased() { * if (mouseX < 50) { * // Code to run if the mouse is on the left. * } * * if (mouseY > 50) { * // Code to run if the mouse is near the bottom. * } * }`The parameter, `event`, is optional. `mouseReleased()` is always passed a * MouseEvent * object with properties that describe the mouse release event: * * `function mouseReleased(event) { * // Code to run that uses the event. * console.log(event); * }`On touchscreen devices, `mouseReleased()` will run when a user’s touch * ends. * * Browsers may have default behaviors attached to various mouse events. For * example, some browsers highlight text when the user moves the mouse while * pressing a mouse button. To prevent any default behavior for this event, * add `return false;` to the end of the function. * * Note: mousePressed(), `mouseReleased()`, * and mouseClicked() are all related. * mousePressed() runs as soon as the user * clicks the mouse. `mouseReleased()` runs as soon as the user releases the * mouse click. mouseClicked() runs * immediately after `mouseReleased()`. * @param event optional `MouseEvent` argument. */ mouseReleased(event?: MouseEvent): void; /** * A function that's called once after a mouse button is pressed and released. * * Declaring the function `mouseClicked()` sets a code block to run * automatically when the user releases a mouse button after having pressed * it: * * `function mouseClicked() { * // Code to run. * }`The mouse system variables, such as mouseX and * mouseY, will be updated with their most recent * value when `mouseClicked()` is called by p5.js: * * `function mouseClicked() { * if (mouseX < 50) { * // Code to run if the mouse is on the left. * } * * if (mouseY > 50) { * // Code to run if the mouse is near the bottom. * } * }`The parameter, `event`, is optional. `mouseClicked()` is always passed a * MouseEvent * object with properties that describe the mouse click event: * * `function mouseClicked(event) { * // Code to run that uses the event. * console.log(event); * }`On touchscreen devices, `mouseClicked()` will run when a user’s touch * ends. * * Browsers may have default behaviors attached to various mouse events. For * example, some browsers highlight text when the user moves the mouse while * pressing a mouse button. To prevent any default behavior for this event, * add `return false;` to the end of the function. * * Note: mousePressed(), * mouseReleased(), * and `mouseClicked()` are all related. * mousePressed() runs as soon as the user * clicks the mouse. mouseReleased() runs as * soon as the user releases the mouse click. `mouseClicked()` runs * immediately after mouseReleased(). * @param event optional `MouseEvent` argument. */ mouseClicked(event?: MouseEvent): void; /** * A function that's called once when a mouse button is clicked twice quickly. * * Declaring the function `doubleClicked()` sets a code block to run * automatically when the user presses and releases the mouse button twice * quickly: * * `function doubleClicked() { * // Code to run. * }`The mouse system variables, such as mouseX and * mouseY, will be updated with their most recent * value when `doubleClicked()` is called by p5.js: * * `function doubleClicked() { * if (mouseX < 50) { * // Code to run if the mouse is on the left. * } * * if (mouseY > 50) { * // Code to run if the mouse is near the bottom. * } * }`The parameter, `event`, is optional. `doubleClicked()` is always passed a * MouseEvent * object with properties that describe the double-click event: * * `function doubleClicked(event) { * // Code to run that uses the event. * console.log(event); * }`On touchscreen devices, code placed in `doubleClicked()` will run after two * touches that occur within a short time. * * Browsers may have default behaviors attached to various mouse events. For * example, some browsers highlight text when the user moves the mouse while * pressing a mouse button. To prevent any default behavior for this event, * add `return false;` to the end of the function. * @param event optional `MouseEvent` argument. */ doubleClicked(event?: MouseEvent): void; /** * A function that's called once when the mouse wheel moves. * * Declaring the function `mouseWheel()` sets a code block to run * automatically when the user scrolls with the mouse wheel: * * `function mouseWheel() { * // Code to run. * }`The mouse system variables, such as mouseX and * mouseY, will be updated with their most recent * value when `mouseWheel()` is called by p5.js: * * `function mouseWheel() { * if (mouseX < 50) { * // Code to run if the mouse is on the left. * } * * if (mouseY > 50) { * // Code to run if the mouse is near the bottom. * } * }`The parameter, `event`, is optional. `mouseWheel()` is always passed a * MouseEvent * object with properties that describe the mouse scroll event: * * `function mouseWheel(event) { * // Code to run that uses the event. * console.log(event); * }`The `event` object has many properties including `delta`, a `Number` * containing the distance that the user scrolled. For example, `event.delta` * might have the value 5 when the user scrolls up. `event.delta` is positive * if the user scrolls up and negative if they scroll down. The signs are * opposite on macOS with "natural" scrolling enabled. * * Browsers may have default behaviors attached to various mouse events. For * example, some browsers highlight text when the user moves the mouse while * pressing a mouse button. To prevent any default behavior for this event, * add `return false;` to the end of the function. * * Note: On Safari, `mouseWheel()` may only work as expected if * `return false;` is added at the end of the function. * @param event optional `WheelEvent` argument. */ mouseWheel(event?: WheelEvent): void; /** * Locks the mouse pointer to its current position and makes it invisible. * * `requestPointerLock()` allows the mouse to move forever without leaving the * screen. Calling `requestPointerLock()` locks the values of * mouseX, mouseY, * pmouseX, and pmouseY. * movedX and movedY * continue updating and can be used to get the distance the mouse moved since * the last frame was drawn. Calling * exitPointerLock() resumes updating the * mouse system variables. * * Note: Most browsers require an input, such as a click, before calling * `requestPointerLock()`. It’s recommended to call `requestPointerLock()` in * an event function such as doubleClicked(). */ requestPointerLock(): void; /** * Exits a pointer lock started with * requestPointerLock. * * Calling `requestPointerLock()` locks the values of * mouseX, mouseY, * pmouseX, and pmouseY. * Calling `exitPointerLock()` resumes updating the mouse system variables. * * Note: Most browsers require an input, such as a click, before calling * `requestPointerLock()`. It’s recommended to call `requestPointerLock()` in * an event function such as doubleClicked(). */ exitPointerLock(): void; /** * Creates a new p5.Image object. * * `createImage()` uses the `width` and `height` parameters to set the new * p5.Image object's dimensions in pixels. The new * p5.Image can be modified by updating its * pixels array or by calling its * get() and * set() methods. The * loadPixels() method must be called * before reading or modifying pixel values. The * updatePixels() method must be called * for updates to take effect. * * Note: The new p5.Image object is transparent by * default. * @param width width in pixels. * @param height height in pixels. * @returns new p5.Image object. */ createImage(width: number, height: number): p5.Image; /** * Saves the current canvas as an image. * * By default, `saveCanvas()` saves the canvas as a PNG image called * `untitled.png`. * * The first parameter, `filename`, is optional. It's a string that sets the * file's name. If a file extension is included, as in * `saveCanvas('drawing.png')`, then the image will be saved using that * format. * * The second parameter, `extension`, is also optional. It sets the files format. * Either `'png'`, `'webp'`, or `'jpg'` can be used. For example, `saveCanvas('drawing', 'jpg')` * saves the canvas to a file called `drawing.jpg`. * * Note: The browser will either save the file immediately or prompt the user * with a dialogue window. * @param selectedCanvas reference to a * specific HTML5 canvas element. * @param filename file name. Defaults to 'untitled'. * @param extension file extension, either 'png', 'webp', or 'jpg'. Defaults to 'png'. */ saveCanvas(selectedCanvas: p5.Framebuffer | p5.Element | HTMLCanvasElement, filename?: string, extension?: string): void; saveCanvas(filename?: string, extension?: string): void; /** * Captures a sequence of frames from the canvas that can be saved as images. * * `saveFrames()` creates an array of frame objects. Each frame is stored as * an object with its file type, file name, and image data as a string. For * example, the first saved frame might have the following properties: * * `{ ext: 'png', filenmame: 'frame0', imageData: 'data:image/octet-stream;base64, abc123' }`. * * The first parameter, `filename`, sets the prefix for the file names. For * example, setting the prefix to `'frame'` would generate the image files * `frame0.png`, `frame1.png`, and so on. * * The second parameter, `extension`, sets the file type to either `'png'` or * `'jpg'`. * * The third parameter, `duration`, sets the duration to record in seconds. * The maximum duration is 15 seconds. * * The fourth parameter, `framerate`, sets the number of frames to record per * second. The maximum frame rate value is 22. Limits are placed on `duration` * and `framerate` to avoid using too much memory. Recording large canvases * can easily crash sketches or even web browsers. * * The fifth parameter, `callback`, is optional. If a function is passed, * image files won't be saved by default. The callback function can be used * to process an array containing the data for each captured frame. The array * of image data contains a sequence of objects with three properties for each * frame: `imageData`, `filename`, and `extension`. * * Note: Frames are downloaded as individual image files by default. * @param filename prefix of file name. * @param extension file extension, either 'jpg' or 'png'. * @param duration duration in seconds to record. This parameter will be constrained to be less or equal to 15. * @param framerate number of frames to save per second. This parameter will be constrained to be less or equal to 22. * @param callback callback function that will be executed * to handle the image data. This function * should accept an array as argument. The * array will contain the specified number of * frames of objects. Each object has three * properties: `imageData`, `filename`, and `extension`. */ saveFrames(filename: string, extension: string, duration: number, framerate: number, callback?: (arg0: any[]) => void): void; /** * Loads an image to create a p5.Image object. * * `loadImage()` interprets the first parameter one of three ways. If the path * to an image file is provided, `loadImage()` will load it. Paths to local * files should be relative, such as `'assets/thundercat.jpg'`. URLs such as * `'https://example.com/thundercat.jpg'` may be blocked due to browser * security. Raw image data can also be passed as a base64 encoded image in * the form `'data:image/png;base64,arandomsequenceofcharacters'`. The `path` * parameter can also be defined as a `Request` * object for more advanced usage. * * The second parameter is optional. If a function is passed, it will be * called once the image has loaded. The callback function can optionally use * the new p5.Image object. The return value of the * function will be used as the final return value of `loadImage()`. * * The third parameter is also optional. If a function is passed, it will be * called if the image fails to load. The callback function can optionally use * the event error. The return value of the function will be used as the final * return value of `loadImage()`. * * This function returns a `Promise` and should be used in an `async` setup with * `await`. See the examples for the usage syntax. * @param path path of the image to be loaded or base64 encoded image. * @param successCallback function called with * p5.Image once it * loads. * @param failureCallback function called with event * error if the image fails to load. * @returns the p5.Image object. */ loadImage(path: string | Request, successCallback?: (arg0: p5.Image) => void, failureCallback?: (arg0: Event) => void): Promise; /** * Generates a gif from a sketch and saves it to a file. * * `saveGif()` may be called in setup() or at any * point while a sketch is running. * * The first parameter, `fileName`, sets the gif's file name. * * The second parameter, `duration`, sets the gif's duration in seconds. * * The third parameter, `options`, is optional. If an object is passed, * `saveGif()` will use its properties to customize the gif. `saveGif()` * recognizes the properties `delay`, `units`, `silent`, * `notificationDuration`, and `notificationID`. * @param filename file name of gif. * @param duration duration in seconds to capture from the sketch. * @param options an object that can contain five more properties: */ saveGif(filename: string, duration: number, options?: { delay?: number; units?: 'seconds' | 'frames'; silent?: boolean; notificationDuration?: number; notificationID?: string }): void; /** * Draws an image to the canvas. * * The first parameter, `img`, is the source image to be drawn. `img` can be * any of the following objects: * * - p5.Image * * - p5.Element * * - p5.Texture * * - p5.Framebuffer * * - p5.FramebufferTexture * * The second and third parameters, `dx` and `dy`, set the coordinates of the * destination image's top left corner. See * imageMode() for other ways to position images. * * `let img; * * async function setup() { * // Load the image. * img = await loadImage('assets/laDefense.jpg'); * * createCanvas(100, 100); * * background(50); * * // Draw the image. * image(img, 0, 0); * * describe('An image of the underside of a white umbrella with a gridded ceiling above.'); * }`Here's a diagram that explains how optional parameters work in `image()`: * * * * The fourth and fifth parameters, `dw` and `dh`, are optional. They set the * the width and height to draw the destination image. By default, `image()` * draws the full source image at its original size. * * The sixth and seventh parameters, `sx` and `sy`, are also optional. * These coordinates define the top left corner of a subsection to draw from * the source image. * * The eighth and ninth parameters, `sw` and `sh`, are also optional. * They define the width and height of a subsection to draw from the source * image. By default, `image()` draws the full subsection that begins at * `(sx, sy)` and extends to the edges of the source image. * * The ninth parameter, `fit`, is also optional. It enables a subsection of * the source image to be drawn without affecting its aspect ratio. If * `CONTAIN` is passed, the full subsection will appear within the destination * rectangle. If `COVER` is passed, the subsection will completely cover the * destination rectangle. This may have the effect of zooming into the * subsection. * * The tenth and eleventh paremeters, `xAlign` and `yAlign`, are also * optional. They determine how to align the fitted subsection. `xAlign` can * be set to either `LEFT`, `RIGHT`, or `CENTER`. `yAlign` can be set to * either `TOP`, `BOTTOM`, or `CENTER`. By default, both `xAlign` and `yAlign` * are set to `CENTER`. * @param img image to display. * @param x x-coordinate of the top-left corner of the image. * @param y y-coordinate of the top-left corner of the image. * @param width width to draw the image. * @param height height to draw the image. */ image(img: p5.Image | p5.Element | p5.Texture | p5.Framebuffer | p5.FramebufferTexture | p5.Renderer | p5.Graphics, x: number, y: number, width?: number, height?: number): void; image(img: p5.Image | p5.Element | p5.Texture | p5.Framebuffer | p5.FramebufferTexture, dx: number, dy: number, dWidth: number, dHeight: number, sx: number, sy: number, sWidth?: number, sHeight?: number, fit?: typeof p5.CONTAIN | typeof p5.COVER, xAlign?: typeof p5.LEFT | typeof p5.RIGHT | typeof p5.CENTER, yAlign?: typeof p5.TOP | typeof p5.BOTTOM | typeof p5.CENTER): void; /** * Tints images using a color. * * The version of `tint()` with one parameter interprets it one of four ways. * If the parameter is a number, it's interpreted as a grayscale value. If the * parameter is a string, it's interpreted as a CSS color string. An array of * `[R, G, B, A]` values or a p5.Color object can * also be used to set the tint color. * * The version of `tint()` with two parameters uses the first one as a * grayscale value and the second as an alpha value. For example, calling * `tint(255, 128)` will make an image 50% transparent. * * The version of `tint()` with three parameters interprets them as RGB or * HSB values, depending on the current * colorMode(). The optional fourth parameter * sets the alpha value. For example, `tint(255, 0, 0, 100)` will give images * a red tint and make them transparent. * @param v1 red or hue value. * @param v2 green or saturation value. * @param v3 blue or brightness. */ tint(v1: number, v2: number, v3: number, alpha?: number): void; tint(value: string): void; tint(gray: number, alpha?: number): void; tint(values: number[]): void; tint(color: p5.Color): void; /** * Removes the current tint set by tint(). * * `noTint()` restores images to their original colors. */ noTint(): void; /** * Changes the location from which images are drawn when * image() is called. * * By default, the first * two parameters of image() are the x- and * y-coordinates of the image's upper-left corner. The next parameters are * its width and height. This is the same as calling `imageMode(CORNER)`. * * `imageMode(CORNERS)` also uses the first two parameters of * image() as the x- and y-coordinates of the image's * top-left corner. The third and fourth parameters are the coordinates of its * bottom-right corner. * * `imageMode(CENTER)` uses the first two parameters of * image() as the x- and y-coordinates of the image's * center. The next parameters are its width and height. * @param mode either CORNER, CORNERS, or CENTER. */ imageMode(mode: typeof p5.CORNER | typeof p5.CORNERS | typeof p5.CENTER): void; /** * Copies a region of pixels from one image to another. * * The first parameter, `srcImage`, is the * p5.Image object to blend. * * The next four parameters, `sx`, `sy`, `sw`, and `sh` determine the region * to blend from the source image. `(sx, sy)` is the top-left corner of the * region. `sw` and `sh` are the regions width and height. * * The next four parameters, `dx`, `dy`, `dw`, and `dh` determine the region * of the canvas to blend into. `(dx, dy)` is the top-left corner of the * region. `dw` and `dh` are the regions width and height. * * The tenth parameter, `blendMode`, sets the effect used to blend the images' * colors. The options are `BLEND`, `DARKEST`, `LIGHTEST`, `DIFFERENCE`, * `MULTIPLY`, `EXCLUSION`, `SCREEN`, `REPLACE`, `OVERLAY`, `HARD_LIGHT`, * `SOFT_LIGHT`, `DODGE`, `BURN`, `ADD`, or `NORMAL` * @param srcImage source image. * @param sx x-coordinate of the source's upper-left corner. * @param sy y-coordinate of the source's upper-left corner. * @param sw source image width. * @param sh source image height. * @param dx x-coordinate of the destination's upper-left corner. * @param dy y-coordinate of the destination's upper-left corner. * @param dw destination image width. * @param dh destination image height. * @param blendMode the blend mode. either * BLEND, DARKEST, LIGHTEST, DIFFERENCE, * MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT, * SOFT_LIGHT, DODGE, BURN, ADD or NORMAL. */ blend(srcImage: p5.Image, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number, blendMode: typeof p5.BLEND | typeof p5.DARKEST | typeof p5.LIGHTEST | typeof p5.DIFFERENCE | typeof p5.MULTIPLY | typeof p5.EXCLUSION | typeof p5.SCREEN | typeof p5.REPLACE | typeof p5.OVERLAY | typeof p5.HARD_LIGHT | typeof p5.SOFT_LIGHT | typeof p5.DODGE | typeof p5.BURN | typeof p5.ADD | typeof p5.NORMAL): void; blend(sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number, blendMode: typeof p5.BLEND | typeof p5.DARKEST | typeof p5.LIGHTEST | typeof p5.DIFFERENCE | typeof p5.MULTIPLY | typeof p5.EXCLUSION | typeof p5.SCREEN | typeof p5.REPLACE | typeof p5.OVERLAY | typeof p5.HARD_LIGHT | typeof p5.SOFT_LIGHT | typeof p5.DODGE | typeof p5.BURN | typeof p5.ADD | typeof p5.NORMAL): void; /** * Copies pixels from a source image to a region of the canvas. * * The first parameter, `srcImage`, is the * p5.Image object to blend. The source image can be * the canvas itself or a * p5.Image object. `copy()` will scale pixels from * the source region if it isn't the same size as the destination region. * * The next four parameters, `sx`, `sy`, `sw`, and `sh` determine the region * to copy from the source image. `(sx, sy)` is the top-left corner of the * region. `sw` and `sh` are the region's width and height. * * The next four parameters, `dx`, `dy`, `dw`, and `dh` determine the region * of the canvas to copy into. `(dx, dy)` is the top-left corner of the * region. `dw` and `dh` are the region's width and height. * @param srcImage source image. * @param sx x-coordinate of the source's upper-left corner. * @param sy y-coordinate of the source's upper-left corner. * @param sw source image width. * @param sh source image height. * @param dx x-coordinate of the destination's upper-left corner. * @param dy y-coordinate of the destination's upper-left corner. * @param dw destination image width. * @param dh destination image height. */ copy(srcImage: p5.Image | p5.Element, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void; copy(sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void; /** * Applies an image filter to the canvas. * * The preset options are: * * `INVERT` * Inverts the colors in the image. No parameter is used. * * `GRAY` * Converts the image to grayscale. No parameter is used. * * `THRESHOLD` * Converts the image to black and white. Pixels with a grayscale value * above a given threshold are converted to white. The rest are converted to * black. The threshold must be between 0.0 (black) and 1.0 (white). If no * value is specified, 0.5 is used. * * `OPAQUE` * Sets the alpha channel to entirely opaque. No parameter is used. * * `POSTERIZE` * Limits the number of colors in the image. Each color channel is limited to * the number of colors specified. Values between 2 and 255 are valid, but * results are most noticeable with lower values. The default value is 4. * * `BLUR` * Blurs the image. The level of blurring is specified by a blur radius. Larger * values increase the blur. The default value is 4. A gaussian blur is used * in `P2D` mode. A box blur is used in `WEBGL` mode. * * `ERODE` * Reduces the light areas. No parameter is used. * * `DILATE` * Increases the light areas. No parameter is used. * * `filter()` uses WebGL in the background by default because it's faster. * This can be disabled in `P2D` mode by adding a `false` argument, as in * `filter(BLUR, false)`. This may be useful to keep computation off the GPU * or to work around a lack of WebGL support. * * In WebgL mode, `filter()` can also use custom shaders. See * createFilterShader() for more * information. * @param filterType either THRESHOLD, GRAY, OPAQUE, INVERT, * POSTERIZE, BLUR, ERODE, DILATE or BLUR. * @param filterParam parameter unique to each filter. * @param useWebGL flag to control whether to use fast * WebGL filters (GPU) or original image * filters (CPU); defaults to `true`. */ filter(filterType: typeof p5.THRESHOLD | typeof p5.GRAY | typeof p5.OPAQUE | typeof p5.INVERT | typeof p5.POSTERIZE | typeof p5.BLUR | typeof p5.ERODE | typeof p5.DILATE | typeof p5.BLUR, filterParam?: number, useWebGL?: boolean): void; filter(filterType: typeof p5.THRESHOLD | typeof p5.GRAY | typeof p5.OPAQUE | typeof p5.INVERT | typeof p5.POSTERIZE | typeof p5.BLUR | typeof p5.ERODE | typeof p5.DILATE | typeof p5.BLUR, filterParam?: number, useWebGL?: boolean): void; filter(shaderFilter: p5.Shader): void; /** * Gets a pixel or a region of pixels from the canvas. * * `get()` is easy to use but it's not as fast as * pixels. Use pixels * to read many pixel values. * * The version of `get()` with no parameters returns the entire canvas. * * The version of `get()` with two parameters interprets them as * coordinates. It returns an array with the `[R, G, B, A]` values of the * pixel at the given point. * * The version of `get()` with four parameters interprets them as coordinates * and dimensions. It returns a subsection of the canvas as a * p5.Image object. The first two parameters are the * coordinates for the upper-left corner of the subsection. The last two * parameters are the width and height of the subsection. * * Use p5.Image.get() to work directly with * p5.Image objects. * @param x x-coordinate of the pixel. * @param y y-coordinate of the pixel. * @param w width of the subsection to be returned. * @param h height of the subsection to be returned. * @returns subsection as a p5.Image object. */ get(x: number, y: number, w: number, h: number): p5.Image; get(): p5.Image; get(x: number, y: number): number[]; /** * Loads the current value of each pixel on the canvas into the * pixels array. * * `loadPixels()` must be called before reading from or writing to * pixels. */ loadPixels(): void; /** * Sets the color of a pixel or draws an image to the canvas. * * `set()` is easy to use but it's not as fast as * pixels. Use pixels * to set many pixel values. * * `set()` interprets the first two parameters as x- and y-coordinates. It * interprets the last parameter as a grayscale value, a `[R, G, B, A]` pixel * array, a p5.Color object, or a * p5.Image object. If an image is passed, the first * two parameters set the coordinates for the image's upper-left corner, * regardless of the current imageMode(). * * updatePixels() must be called after using * `set()` for changes to appear. * @param x x-coordinate of the pixel. * @param y y-coordinate of the pixel. * @param c grayscale value | pixel array | * p5.Color object | p5.Image to copy. */ set(x: number, y: number, c: number | number[] | object): void; /** * Updates the canvas with the RGBA values in the * pixels array. * * `updatePixels()` only needs to be called after changing values in the * pixels array. Such changes can be made directly * after calling loadPixels() or by calling * set(). * @param x x-coordinate of the upper-left corner of region * to update. * @param y y-coordinate of the upper-left corner of region * to update. * @param w width of region to update. * @param h height of region to update. */ updatePixels(x?: number, y?: number, w?: number, h?: number): void; updatePixels(): void; /** * Loads a JSON file to create an `Object`. * * JavaScript Object Notation * (JSON) * is a standard format for sending data between applications. The format is * based on JavaScript objects which have keys and values. JSON files store * data in an object with strings as keys. Values can be strings, numbers, * Booleans, arrays, `null`, or other objects. * * The first parameter, `path`, is a string with the path to the file. * Paths to local files should be relative, as in * `loadJSON('assets/data.json')`. URLs such as * `'https://example.com/data.json'` may be blocked due to browser security. * The `path` parameter can also be defined as a `Request` * object for more advanced usage. * * The second parameter, `successCallback`, is optional. If a function is * passed, as in `loadJSON('assets/data.json', handleData)`, then the * `handleData()` function will be called once the data loads. The object * created from the JSON data will be passed to `handleData()` as its only argument. * The return value of the `handleData()` function will be used as the final return * value of `loadJSON('assets/data.json', handleData)`. * * The third parameter, `failureCallback`, is also optional. If a function is * passed, as in `loadJSON('assets/data.json', handleData, handleFailure)`, * then the `handleFailure()` function will be called if an error occurs while * loading. The `Error` object will be passed to `handleFailure()` as its only * argument. The return value of the `handleFailure()` function will be used as the * final return value of `loadJSON('assets/data.json', handleData, handleFailure)`. * * This function returns a `Promise` and should be used in an `async` setup with * `await`. See the examples for the usage syntax. * @param path path of the JSON file to be loaded. * @param successCallback function to call once the data is loaded. Will be passed the object. * @param errorCallback function to call if the data fails to load. Will be passed an `Error` event object. * @returns object containing the loaded data. */ loadJSON(path: string | Request, successCallback?: Function, errorCallback?: Function): Promise; /** * Loads a text file to create an `Array`. * * The first parameter, `path`, is always a string with the path to the file. * Paths to local files should be relative, as in * `loadStrings('assets/data.txt')`. URLs such as * `'https://example.com/data.txt'` may be blocked due to browser security. * The `path` parameter can also be defined as a `Request` * object for more advanced usage. * * The second parameter, `successCallback`, is optional. If a function is * passed, as in `loadStrings('assets/data.txt', handleData)`, then the * `handleData()` function will be called once the data loads. The array * created from the text data will be passed to `handleData()` as its only * argument. The return value of the `handleData()` function will be used as * the final return value of `loadStrings('assets/data.txt', handleData)`. * * The third parameter, `failureCallback`, is also optional. If a function is * passed, as in `loadStrings('assets/data.txt', handleData, handleFailure)`, * then the `handleFailure()` function will be called if an error occurs while * loading. The `Error` object will be passed to `handleFailure()` as its only * argument. The return value of the `handleFailure()` function will be used as * the final return value of `loadStrings('assets/data.txt', handleData, handleFailure)`. * * This function returns a `Promise` and should be used in an `async` setup with * `await`. See the examples for the usage syntax. * @param path path of the text file to be loaded. * @param successCallback function to call once the data is * loaded. Will be passed the array. * @param errorCallback function to call if the data fails to * load. Will be passed an `Error` event * object. * @returns new array containing the loaded text. */ loadStrings(path: string | Request, successCallback?: Function, errorCallback?: Function): Promise; /** * Reads the contents of a file or URL and creates a p5.Table object with * its values. If a file is specified, it must be located in the sketch's * "data" folder. The filename parameter can also be a URL to a file found * online. By default, the file is assumed to be comma-separated (in CSV * format). Table only looks for a header row if the 'header' option is * included. * * This function returns a `Promise` and should be used in an `async` setup with * `await`. See the examples for the usage syntax. * * All files loaded and saved use UTF-8 encoding. This method is suitable for fetching files up to size of 64MB. * @param filename name of the file or URL to load * @param separator the separator character used by the file, defaults to `','` * @param header "header" to indicate table has header row * @param callback function to be executed after * loadTable() completes. On success, the * Table object is passed in as the * first argument. * @param errorCallback function to be executed if * there is an error, response is passed * in as first argument * @returns Table object containing data */ loadTable(filename: string | Request, separator?: string, header?: string, callback?: Function, errorCallback?: Function): Promise; /** * Loads an XML file to create a p5.XML object. * * Extensible Markup Language * (XML) * is a standard format for sending data between applications. Like HTML, the * XML format is based on tags and attributes, as in * `<time units="s">1234</time>`. * * The first parameter, `path`, is always a string with the path to the file. * Paths to local files should be relative, as in * `loadXML('assets/data.xml')`. URLs such as `'https://example.com/data.xml'` * may be blocked due to browser security. The `path` parameter can also be defined * as a `Request` * object for more advanced usage. * * The second parameter, `successCallback`, is optional. If a function is * passed, as in `loadXML('assets/data.xml', handleData)`, then the * `handleData()` function will be called once the data loads. The * p5.XML object created from the data will be passed * to `handleData()` as its only argument. The return value of the `handleData()` * function will be used as the final return value of `loadXML('assets/data.xml', handleData)`. * * The third parameter, `failureCallback`, is also optional. If a function is * passed, as in `loadXML('assets/data.xml', handleData, handleFailure)`, then * the `handleFailure()` function will be called if an error occurs while * loading. The `Error` object will be passed to `handleFailure()` as its only * argument. The return value of the `handleFailure()` function will be used as the * final return value of `loadXML('assets/data.xml', handleData, handleFailure)`. * * This function returns a `Promise` and should be used in an `async` setup with * `await`. See the examples for the usage syntax. * @param path path of the XML file to be loaded. * @param successCallback function to call once the data is * loaded. Will be passed the * p5.XML object. * @param errorCallback function to call if the data fails to * load. Will be passed an `Error` event * object. * @returns XML data loaded into a p5.XML * object. */ loadXML(path: string | Request, successCallback?: Function, errorCallback?: Function): Promise; /** * This method is suitable for fetching files up to size of 64MB. * @param file name of the file or URL to load * @param callback function to be executed after loadBytes() * completes * @param errorCallback function to be executed if there * is an error * @returns a Uint8Array containing the loaded buffer */ loadBytes(file: string | Request, callback?: Function, errorCallback?: Function): Promise; /** * Loads a file at the given path as a Blob, then returns the resulting data or * passes it to a success callback function, if provided. On load, this function * returns a `Promise` that resolves to a Blob containing the file data. * @param path The path or Request object pointing to the file * you want to load. * @param successCallback Optional. A function to be called if the * file successfully loads, receiving the * resulting Blob as its only argument. * @param errorCallback Optional. A function to be called if an * error occurs during loading; receives the * error object as its only argument. * @returns A promise that resolves with the loaded Blob. */ loadBlob(path: string | Request, successCallback?: Function, errorCallback?: Function): Promise; /** * Method for executing an HTTP GET request. If data type is not specified, * it will default to `'text'`. This is equivalent to * calling httpDo(path, 'GET'). The 'binary' datatype will return * a Blob object, and the 'arrayBuffer' datatype will return an ArrayBuffer * which can be used to initialize typed arrays (such as Uint8Array). * @param path name of the file or url to load * @param datatype "json", "jsonp", "binary", "arrayBuffer", * "xml", or "text" * @param callback function to be executed after * httpGet() completes, data is passed in * as first argument * @param errorCallback function to be executed if * there is an error, response is passed * in as first argument * @returns A promise that resolves with the data when the operation * completes successfully or rejects with the error after * one occurs. */ httpGet(path: string | Request, datatype?: string, callback?: Function, errorCallback?: Function): Promise; httpGet(path: string | Request, callback: Function, errorCallback?: Function): Promise; /** * Method for executing an HTTP POST request. If data type is not specified, * it will default to `'text'`. This is equivalent to * calling httpDo(path, 'POST'). * @param path name of the file or url to load * @param data param data passed sent with request * @param datatype "json", "jsonp", "xml", or "text". * If omitted, httpPost() will guess. * @param callback function to be executed after * httpPost() completes, data is passed in * as first argument * @param errorCallback function to be executed if * there is an error, response is passed * in as first argument * @returns A promise that resolves with the data when the operation * completes successfully or rejects with the error after * one occurs. */ httpPost(path: string | Request, data?: object | boolean, datatype?: string, callback?: Function, errorCallback?: Function): Promise; httpPost(path: string | Request, data: object | boolean, callback?: Function, errorCallback?: Function): Promise; httpPost(path: string | Request, callback?: Function, errorCallback?: Function): Promise; /** * Method for executing an HTTP request. If data type is not specified, * it will default to `'text'`. * * This function is meant for more advanced usage of HTTP requests in p5.js. It is * best used when a `Request` * object is passed to the `path` parameter. * * This method is suitable for fetching files up to size of 64MB when "GET" is used. * @param path name of the file or url to load * @param method either "GET", "POST", "PUT", "DELETE", * or other HTTP request methods * @param datatype "json", "jsonp", "xml", or "text" * @param data param data passed sent with request * @param callback function to be executed after * httpGet() completes, data is passed in * as first argument * @param errorCallback function to be executed if * there is an error, response is passed * in as first argument * @returns A promise that resolves with the data when the operation * completes successfully or rejects with the error after * one occurs. */ httpDo(path: string | Request, method?: string, datatype?: string, data?: object, callback?: Function, errorCallback?: Function): Promise; httpDo(path: string | Request, callback?: Function, errorCallback?: Function): Promise; /** * Creates a new p5.PrintWriter object. * * p5.PrintWriter objects provide a way to * save a sequence of text data, called the print stream, to the user's * computer. They're low-level objects that enable precise control of text * output. Functions such as * saveStrings() and * saveJSON() are easier to use for simple file * saving. * * The first parameter, `filename`, is the name of the file to be written. If * a string is passed, as in `createWriter('words.txt')`, a new * p5.PrintWriter object will be created that * writes to a file named `words.txt`. * * The second parameter, `extension`, is optional. If a string is passed, as * in `createWriter('words', 'csv')`, the first parameter will be interpreted * as the file name and the second parameter as the extension. * @param name name of the file to create. * @param extension format to use for the file. * @returns stream for writing data. */ createWriter(name: string, extension?: string): p5.PrintWriter; /** * Writes data to the print stream without adding new lines. * * The parameter, `data`, is the data to write. `data` can be a number or * string, as in `myWriter.write('hi')`, or an array of numbers and strings, * as in `myWriter.write([1, 2, 3])`. A comma will be inserted between array * array elements when they're added to the print stream. * @param data data to be written as a string, number, * or array of strings and numbers. */ write(data: string | number | any[]): void; /** * Saves the file and closes the print stream. */ close(): void; /** * Saves a given element(image, text, json, csv, wav, or html) to the client's * computer. The first parameter can be a pointer to element we want to save. * The element can be one of p5.Element,an Array of * Strings, an Array of JSON, a JSON object, a p5.Table * , a p5.Image, or a p5.SoundFile (requires * p5.sound). The second parameter is a filename (including extension).The * third parameter is for options specific to this type of object. This method * will save a file that fits the given parameters. * If it is called without specifying an element, by default it will save the * whole canvas as an image file. You can optionally specify a filename as * the first parameter in such a case. * Note that it is not recommended to * call this method within draw, as it will open a new save dialog on every * render. * @param objectOrFilename If filename is provided, will * save canvas as an image with * either png or jpg extension * depending on the filename. * If object is provided, will * save depending on the object * and filename (see examples * above). * @param filename If an object is provided as the first * parameter, then the second parameter * indicates the filename, * and should include an appropriate * file extension (see examples above). * @param options Additional options depend on * filetype. For example, when saving JSON, * true indicates that the * output will be optimized for filesize, * rather than readability. */ save(objectOrFilename?: object | string, filename?: string, options?: boolean | string): void; /** * Saves an `Object` or `Array` to a JSON file. * * JavaScript Object Notation * (JSON) * is a standard format for sending data between applications. The format is * based on JavaScript objects which have keys and values. JSON files store * data in an object with strings as keys. Values can be strings, numbers, * Booleans, arrays, `null`, or other objects. * * The first parameter, `json`, is the data to save. The data can be an array, * as in `[1, 2, 3]`, or an object, as in * `{ x: 50, y: 50, color: 'deeppink' }`. * * The second parameter, `filename`, is a string that sets the file's name. * For example, calling `saveJSON([1, 2, 3], 'data.json')` saves the array * `[1, 2, 3]` to a file called `data.json` on the user's computer. * * The third parameter, `optimize`, is optional. If `true` is passed, as in * `saveJSON([1, 2, 3], 'data.json', true)`, then all unneeded whitespace will * be removed to reduce the file size. * * Note: The browser will either save the file immediately or prompt the user * with a dialogue window. * @param json data to save. * @param filename name of the file to be saved. * @param optimize whether to trim unneeded whitespace. Defaults * to `true`. */ saveJSON(json: any[] | object, filename: string, optimize?: boolean): void; /** * Saves an `Array` of `String`s to a file, one per line. * * The first parameter, `list`, is an array with the strings to save. * * The second parameter, `filename`, is a string that sets the file's name. * For example, calling `saveStrings(['0', '01', '011'], 'data.txt')` saves * the array `['0', '01', '011']` to a file called `data.txt` on the user's * computer. * * The third parameter, `extension`, is optional. If a string is passed, as in * `saveStrings(['0', '01', '0`1'], 'data', 'txt')`, the second parameter will * be interpreted as the file name and the third parameter as the extension. * * The fourth parameter, `isCRLF`, is also optional, If `true` is passed, as * in `saveStrings(['0', '01', '011'], 'data', 'txt', true)`, then two * characters, `\r\n` , will be added to the end of each string to create new * lines in the saved file. `\r` is a carriage return (CR) and `\n` is a line * feed (LF). By default, only `\n` (line feed) is added to each string in * order to create new lines. * * Note: The browser will either save the file immediately or prompt the user * with a dialogue window. * @param list data to save. * @param filename name of file to be saved. * @param extension format to use for the file. * @param isCRLF whether to add `\r\n` to the end of each * string. Defaults to `false`. */ saveStrings(list: string[], filename: string, extension?: string, isCRLF?: boolean): void; /** * Writes the contents of a Table object to a file. Defaults to a * text file with comma-separated-values ('csv') but can also * use tab separation ('tsv'), or generate an HTML table ('html'). * The file saving process and location of the saved file will * vary between web browsers. * @param Table the Table object to save to a file * @param filename the filename to which the Table should be saved * @param options can be one of "tsv", "csv", or "html" */ saveTable(Table: p5.Table, filename: string, options?: string): void; /** * Sets the element's content. * * An element's content is the text between its tags. For example, the element * `<language>JavaScript</language>` has the content `JavaScript`. * * The parameter, `content`, is a string with the element's new content. * @param content new content for the element. */ setContent(content: string): void; /** * Calculates the absolute value of a number. * * A number's absolute value is its distance from zero on the number line. * -5 and 5 are both five units away from zero, so calling `abs(-5)` and * `abs(5)` both return 5. The absolute value of a number is always positive. * @param n number to compute. * @returns absolute value of given number. */ abs(n: number): number; /** * Calculates the closest integer value that is greater than or equal to a * number. * * For example, calling `ceil(9.03)` and `ceil(9.97)` both return the value * 10. * @param n number to round up. * @returns rounded up number. */ ceil(n: number): number; /** * Constrains a number between a minimum and maximum value. * @param n number to constrain. * @param low minimum limit. * @param high maximum limit. * @returns constrained number. */ constrain(n: number, low: number, high: number): number; /** * Calculates the distance between two points. * * The version of `dist()` with four parameters calculates distance in two * dimensions. * * The version of `dist()` with six parameters calculates distance in three * dimensions. * * Use p5.Vector.dist() to calculate the * distance between two p5.Vector objects. * @param x1 x-coordinate of the first point. * @param y1 y-coordinate of the first point. * @param x2 x-coordinate of the second point. * @param y2 y-coordinate of the second point. * @returns distance between the two points. */ dist(x1: number, y1: number, x2: number, y2: number): number; dist(x1: number, y1: number, z1: number, x2: number, y2: number, z2: number): number; /** * Calculates the value of Euler's number e (2.71828...) raised to the power * of a number. * @param n exponent to raise. * @returns e^n */ exp(n: number): number; /** * Calculates the closest integer value that is less than or equal to the * value of a number. * @param n number to round down. * @returns rounded down number. */ floor(n: number): number; /** * Calculates a number between two numbers at a specific increment. * * The `amt` parameter is the amount to interpolate between the two numbers. * 0.0 is equal to the first number, 0.1 is very near the first number, 0.5 is * half-way in between, and 1.0 is equal to the second number. The `lerp()` * function is convenient for creating motion along a straight path and for * drawing dotted lines. * * If the value of `amt` is less than 0 or more than 1, `lerp()` will return a * number outside of the original interval. For example, calling * `lerp(0, 10, 1.5)` will return 15. * @param start first value. * @param stop second value. * @param amt number. * @returns lerped value. */ lerp(start: number, stop: number, amt: number): number; /** * Calculates the natural logarithm (the base-e logarithm) of a number. * * `log()` expects the `n` parameter to be a value greater than 0 because * the natural logarithm is defined that way. * @param n number greater than 0. * @returns natural logarithm of n. */ log(n: number): number; /** * Calculates the magnitude, or length, of a vector. * * A vector can be thought of in different ways. In one view, a vector is a * point in space. The vector's components, `x` and `y`, are the point's * coordinates `(x, y)`. A vector's magnitude is the distance from the origin * `(0, 0)` to `(x, y)`. `mag(x, y)` is a shortcut for calling * `dist(0, 0, x, y)`. * * A vector can also be thought of as an arrow pointing in space. This view is * helpful for programming motion. See p5.Vector for * more details. * * Use p5.Vector.mag() to calculate the * magnitude of a p5.Vector object. * @param x first component. * @param y second component. * @returns magnitude of vector. */ mag(x: number, y: number): number; /** * Re-maps a number from one range to another. * * For example, calling `map(2, 0, 10, 0, 100)` returns 20. The first three * arguments set the original value to 2 and the original range from 0 to 10. * The last two arguments set the target range from 0 to 100. 20's position * in the target range [0, 100] is proportional to 2's position in the * original range [0, 10]. * * The sixth parameter, `withinBounds`, is optional. By default, `map()` can * return values outside of the target range. For example, * `map(11, 0, 10, 0, 100)` returns 110. Passing `true` as the sixth parameter * constrains the remapped value to the target range. For example, * `map(11, 0, 10, 0, 100, true)` returns 100. * @param value the value to be remapped. * @param start1 lower bound of the value's current range. * @param stop1 upper bound of the value's current range. * @param start2 lower bound of the value's target range. * @param stop2 upper bound of the value's target range. * @param withinBounds constrain the value to the newly mapped range. * @returns remapped number. */ map(value: number, start1: number, stop1: number, start2: number, stop2: number, withinBounds?: boolean): number; /** * Returns the largest value in a sequence of numbers. * * The version of `max()` with one parameter interprets it as an array of * numbers and returns the largest number. * * The version of `max()` with two or more parameters interprets them as * individual numbers and returns the largest number. * @param n0 first number to compare. * @param n1 second number to compare. * @returns maximum number. */ max(n0: number, n1: number): number; max(nums: number[]): number; /** * Returns the smallest value in a sequence of numbers. * * The version of `min()` with one parameter interprets it as an array of * numbers and returns the smallest number. * * The version of `min()` with two or more parameters interprets them as * individual numbers and returns the smallest number. * @param n0 first number to compare. * @param n1 second number to compare. * @returns minimum number. */ min(n0: number, n1: number): number; min(nums: number[]): number; /** * Maps a number from one range to a value between 0 and 1. * * For example, `norm(2, 0, 10)` returns 0.2. 2's position in the original * range [0, 10] is proportional to 0.2's position in the range [0, 1]. This * is the same as calling `map(2, 0, 10, 0, 1)`. * * Numbers outside of the original range are not constrained between 0 and 1. * Out-of-range values are often intentional and useful. * @param value incoming value to be normalized. * @param start lower bound of the value's current range. * @param stop upper bound of the value's current range. * @returns normalized number. */ norm(value: number, start: number, stop: number): number; /** * Calculates exponential expressions such as 23. * * For example, `pow(2, 3)` evaluates the expression * 2 × 2 × 2. `pow(2, -3)` evaluates 1 ÷ * (2 × 2 × 2). * @param n base of the exponential expression. * @param e power by which to raise the base. * @returns n^e. */ pow(n: number, e: number): number; /** * Calculates the integer closest to a number. * * For example, `round(133.8)` returns the value 134. * * The second parameter, `decimals`, is optional. It sets the number of * decimal places to use when rounding. For example, `round(12.34, 1)` returns * 12.3. `decimals` is 0 by default. * @param n number to round. * @param decimals number of decimal places to round to, default is 0. * @returns rounded number. */ round(n: number, decimals?: number): number; /** * Calculates the square of a number. * * Squaring a number means multiplying the number by itself. For example, * `sq(3)` evaluates 3 × 3 which is 9. `sq(-3)` evaluates -3 × -3 * which is also 9. Multiplying two negative numbers produces a positive * number. The value returned by `sq()` is always positive. * @param n number to square. * @returns squared number. */ sq(n: number): number; /** * Calculates the square root of a number. * * A number's square root can be multiplied by itself to produce the original * number. For example, `sqrt(9)` returns 3 because 3 × 3 = 9. `sqrt()` * always returns a positive value. `sqrt()` doesn't work with negative arguments * such as `sqrt(-9)`. * @param n non-negative number to square root. * @returns square root of number. */ sqrt(n: number): number; /** * Calculates the fractional part of a number. * * A number's fractional part includes its decimal values. For example, * `fract(12.34)` returns 0.34. * @param n number whose fractional part will be found. * @returns fractional part of n. */ fract(n: number): number; /** * Creates a new p5.Vector object. * * A vector can be thought of in different ways. In one view, a vector is like * an arrow pointing in space. Vectors have both magnitude (length) and * direction. This view is helpful for programming motion. * * A vector's components determine its magnitude and direction. For example, * calling `createVector(3, 4)` creates a new * p5.Vector object with an x-component of 3 and a * y-component of 4. From the origin, this vector's tip is 3 units to the * right and 4 units down. * * You can also pass N dimensions to the `createVector` function. For example, * calling `createVector(1, 2, 3, 4)` creates a vector with four components. * This allows for flexibility in representing vectors in higher-dimensional * spaces. * * p5.Vector objects are often used to program * motion because they simplify the math. For example, a moving ball has a * position and a velocity. Position describes where the ball is in space. The * ball's position vector extends from the origin to the ball's center. * Velocity describes the ball's speed and the direction it's moving. If the * ball is moving straight up, its velocity vector points straight up. Adding * the ball's velocity vector to its position vector moves it, as in * `pos.add(vel)`. Vector math relies on methods inside the * p5.Vector class. * @param x Zero or more numbers, representing each component of the vector. * @returns new p5.Vector object. */ createVector(...x: number[]): p5.Vector; /** * Returns random numbers that can be tuned to feel organic. * * Values returned by random() and * randomGaussian() can change by large * amounts between function calls. By contrast, values returned by `noise()` * can be made "smooth". Calls to `noise()` with similar inputs will produce * similar outputs. `noise()` is used to create textures, motion, shapes, * terrains, and so on. Ken Perlin invented `noise()` while animating the * original Tron film in the 1980s. * * `noise()` always returns values between 0 and 1. It returns the same value * for a given input while a sketch is running. `noise()` produces different * results each time a sketch runs. The * noiseSeed() function can be used to generate * the same sequence of Perlin noise values each time a sketch runs. * * The character of the noise can be adjusted in two ways. The first way is to * scale the inputs. `noise()` interprets inputs as coordinates. The sequence * of noise values will be smoother when the input coordinates are closer. The * second way is to use the noiseDetail() * function. * * The version of `noise()` with one parameter computes noise values in one * dimension. This dimension can be thought of as space, as in `noise(x)`, or * time, as in `noise(t)`. * * The version of `noise()` with two parameters computes noise values in two * dimensions. These dimensions can be thought of as space, as in * `noise(x, y)`, or space and time, as in `noise(x, t)`. * * The version of `noise()` with three parameters computes noise values in * three dimensions. These dimensions can be thought of as space, as in * `noise(x, y, z)`, or space and time, as in `noise(x, y, t)`. * @param x x-coordinate in noise space. * @param y y-coordinate in noise space. * @param z z-coordinate in noise space. * @returns Perlin noise value at specified coordinates. */ noise(x: number, y?: number, z?: number): number; /** * Adjusts the character of the noise produced by the * noise() function. * * Perlin noise values are created by adding layers of noise together. The * noise layers, called octaves, are similar to harmonics in music. Lower * octaves contribute more to the output signal. They define the overall * intensity of the noise. Higher octaves create finer-grained details. * * By default, noise values are created by combining four octaves. Each higher * octave contributes half as much (50% less) compared to its predecessor. * `noiseDetail()` changes the number of octaves and the falloff amount. For * example, calling `noiseDetail(6, 0.25)` ensures that * noise() will use six octaves. Each higher octave * will contribute 25% as much (75% less) compared to its predecessor. Falloff * values between 0 and 1 are valid. However, falloff values greater than 0.5 * might result in noise values greater than 1. * @param lod number of octaves to be used by the noise. * @param falloff falloff factor for each octave. */ noiseDetail(lod: number, falloff: number): void; /** * Sets the seed value for the noise() function. * * By default, noise() produces different results * each time a sketch is run. Calling `noiseSeed()` with a constant argument, * such as `noiseSeed(99)`, makes noise() produce the * same results each time a sketch is run. * @param seed seed value. */ noiseSeed(seed: number): void; /** * Sets the seed value for the random() and * randomGaussian() functions. * * By default, random() and * randomGaussian() produce different * results each time a sketch is run. Calling `randomSeed()` with a constant * argument, such as `randomSeed(99)`, makes these functions produce the same * results each time a sketch is run. * @param seed seed value. */ randomSeed(seed: number): void; /** * Returns a random number or a random element from an array. * * `random()` follows uniform distribution, which means that all outcomes are * equally likely. When `random()` is used to generate numbers, all * numbers in the output range are equally likely to be returned. When * `random()` is used to select elements from an array, all elements are * equally likely to be chosen. * * By default, `random()` produces different results each time a sketch runs. * The randomSeed() function can be used to * generate the same sequence of numbers or choices each time a sketch runs. * * The version of `random()` with no parameters returns a random number from 0 * up to but not including 1. * * The version of `random()` with one parameter works one of two ways. If the * argument passed is a number, `random()` returns a random number from 0 up * to but not including the number. For example, calling `random(5)` returns * values between 0 and 5. If the argument passed is an array, `random()` * returns a random element from that array. For example, calling * `random(['🦁', '🐯', '🐻'])` returns either a lion, tiger, or bear emoji. * * The version of `random()` with two parameters returns a random number from * a given range. The arguments passed set the range's lower and upper bounds. * For example, calling `random(-5, 10.2)` returns values from -5 up to but * not including 10.2. * @param min lower bound (inclusive). * @param max upper bound (exclusive). * @returns random number. */ random(min?: number, max?: number): number; random(choices: readonly T[]): T; /** * Returns a random number fitting a Gaussian, or normal, distribution. * * Normal distributions look like bell curves when plotted. Values from a * normal distribution cluster around a central value called the mean. The * cluster's standard deviation describes its spread. * * By default, `randomGaussian()` produces different results each time a * sketch runs. The randomSeed() function can be * used to generate the same sequence of numbers each time a sketch runs. * * There's no minimum or maximum value that `randomGaussian()` might return. * Values far from the mean are very unlikely and values near the mean are * very likely. * * The version of `randomGaussian()` with no parameters returns values with a * mean of 0 and standard deviation of 1. * * The version of `randomGaussian()` with one parameter interprets the * argument passed as the mean. The standard deviation is 1. * * The version of `randomGaussian()` with two parameters interprets the first * argument passed as the mean and the second as the standard deviation. * @param mean mean. * @param sd standard deviation. * @returns random number. */ randomGaussian(mean?: number, sd?: number): number; /** * Calculates the arc cosine of a number. * * `acos()` is the inverse of cos(). It expects * arguments in the range -1 to 1. By default, `acos()` returns values in the * range 0 to π (about 3.14). If the * angleMode() is `DEGREES`, then values are * returned in the range 0 to 180. * @param value value whose arc cosine is to be returned. * @returns arc cosine of the given value. */ acos(value: number): number; /** * Calculates the arc sine of a number. * * `asin()` is the inverse of sin(). It expects input * values in the range of -1 to 1. By default, `asin()` returns values in the * range -π ÷ 2 (about -1.57) to π ÷ 2 (about 1.57). If * the angleMode() is `DEGREES` then values are * returned in the range -90 to 90. * @param value value whose arc sine is to be returned. * @returns arc sine of the given value. */ asin(value: number): number; /** * Calculates the arc tangent of a number. * * `atan()` is the inverse of tan(). It expects input * values in the range of -Infinity to Infinity. By default, `atan()` returns * values in the range -π ÷ 2 (about -1.57) to π ÷ 2 * (about 1.57). If the angleMode() is `DEGREES` * then values are returned in the range -90 to 90. * @param value value whose arc tangent is to be returned. * @returns arc tangent of the given value. */ atan(value: number): number; /** * Calculates the angle formed by a point, the origin, and the positive * x-axis. * * `atan2()` is most often used for orienting geometry to the mouse's * position, as in `atan2(mouseY, mouseX)`. The first parameter is the point's * y-coordinate and the second parameter is its x-coordinate. * * By default, `atan2()` returns values in the range * -π (about -3.14) to π (3.14). If the * angleMode() is `DEGREES`, then values are * returned in the range -180 to 180. * @param y y-coordinate of the point. * @param x x-coordinate of the point. * @returns arc tangent of the given point. */ atan2(y: number, x: number): number; /** * Calculates the cosine of an angle. * * `cos()` is useful for many geometric tasks in creative coding. The values * returned oscillate between -1 and 1 as the input angle increases. `cos()` * calculates the cosine of an angle, using radians by default, or according * to if angleMode() setting (RADIANS or DEGREES). * @param angle the angle, in radians by default, or according to if angleMode() setting (RADIANS or DEGREES). * @returns cosine of the angle. */ cos(angle: number): number; /** * Calculates the sine of an angle. * * `sin()` is useful for many geometric tasks in creative coding. The values * returned oscillate between -1 and 1 as the input angle increases. `sin()` * calculates the sine of an angle, using radians by default, or according to * if angleMode() setting (RADIANS or DEGREES). * @param angle the angle, in radians by default, or according to if angleMode() setting (RADIANS or DEGREES). * @returns sine of the angle. */ sin(angle: number): number; /** * Calculates the tangent of an angle. * * `tan()` is useful for many geometric tasks in creative coding. The values * returned range from -Infinity to Infinity and repeat periodically as the * input angle increases. `tan()` calculates the tan of an angle, using radians * by default, or according to * if angleMode() setting (RADIANS or DEGREES). * @param angle the angle, in radians by default, or according to if angleMode() setting (RADIANS or DEGREES). * @returns tangent of the angle. */ tan(angle: number): number; /** * Converts an angle measured in radians to its value in degrees. * * Degrees and radians are both units for measuring angles. There are 360˚ in * one full rotation. A full rotation is 2 × π (about 6.28) radians. * * The same angle can be expressed in with either unit. For example, 90° is a * quarter of a full rotation. The same angle is 2 × π ÷ 4 * (about 1.57) radians. * @param radians radians value to convert to degrees. * @returns converted angle. */ degrees(radians: number): number; /** * Converts an angle measured in degrees to its value in radians. * * Degrees and radians are both units for measuring angles. There are 360˚ in * one full rotation. A full rotation is 2 × π (about 6.28) radians. * * The same angle can be expressed in with either unit. For example, 90° is a * quarter of a full rotation. The same angle is 2 × π ÷ 4 * (about 1.57) radians. * @param degrees degree value to convert to radians. * @returns converted angle. */ radians(degrees: number): number; /** * Changes the unit system used to measure angles. * * Degrees and radians are both units for measuring angles. There are 360˚ in * one full rotation. A full rotation is 2 × π (about 6.28) radians. * * Functions such as rotate() and * sin() expect angles measured radians by default. * Calling `angleMode(DEGREES)` switches to degrees. Calling * `angleMode(RADIANS)` switches back to radians. * * Calling `angleMode()` with no arguments returns current angle mode, which * is either `RADIANS` or `DEGREES`. * @param mode either RADIANS or DEGREES. * @returns mode either RADIANS or DEGREES */ angleMode(mode: typeof p5.RADIANS | typeof p5.DEGREES): typeof p5.RADIANS | typeof p5.DEGREES; angleMode(): typeof p5.RADIANS | typeof p5.DEGREES; /** * Draws an arc. * * An arc is a section of an ellipse defined by the `x`, `y`, `w`, and * `h` parameters. `x` and `y` set the location of the arc's center. `w` and * `h` set the arc's width and height. See * ellipse() and * ellipseMode() for more details. * * The fifth and sixth parameters, `start` and `stop`, set the angles * between which to draw the arc. Arcs are always drawn clockwise from * `start` to `stop`. Angles are always given in radians. * * The seventh parameter, `mode`, is optional. It determines the arc's fill * style. The fill modes are a semi-circle (`OPEN`), a closed semi-circle * (`CHORD`), or a closed pie segment (`PIE`). * * The eighth parameter, `detail`, is also optional. It determines how many * vertices are used to draw the arc in WebGL mode. The default value is 25. * @param x x-coordinate of the arc's ellipse. * @param y y-coordinate of the arc's ellipse. * @param w width of the arc's ellipse by default. * @param h height of the arc's ellipse by default. * @param start angle to start the arc, specified in radians. * @param stop angle to stop the arc, specified in radians. * @param mode optional parameter to determine the way of drawing * the arc. either CHORD, PIE, or OPEN. * @param detail optional parameter for WebGL mode only. This is to * specify the number of vertices that makes up the * perimeter of the arc. Default value is 25. Won't * draw a stroke for a detail of more than 50. */ arc(x: number, y: number, w: number, h: number, start: number, stop: number, mode?: typeof p5.CHORD | typeof p5.PIE | typeof p5.OPEN, detail?: number): void; /** * Draws an ellipse (oval). * * An ellipse is a round shape defined by the `x`, `y`, `w`, and * `h` parameters. `x` and `y` set the location of its center. `w` and * `h` set its width and height. See * ellipseMode() for other ways to set * its position. * * If no height is set, the value of width is used for both the width and * height. If a negative height or width is specified, the absolute value is * taken. * * The fifth parameter, `detail`, is also optional. It determines how many * vertices are used to draw the ellipse in WebGL mode. The default value is * 25. * @param x x-coordinate of the center of the ellipse. * @param y y-coordinate of the center of the ellipse. * @param w width of the ellipse. * @param h height of the ellipse. */ ellipse(x: number, y: number, w: number, h?: number): void; ellipse(x: number, y: number, w: number, h: number, detail?: number): void; /** * Draws a circle. * * A circle is a round shape defined by the `x`, `y`, and `d` parameters. * `x` and `y` set the location of its center. `d` sets its width and height (diameter). * Every point on the circle's edge is the same distance, `0.5 * d`, from its center. * `0.5 * d` (half the diameter) is the circle's radius. * See ellipseMode() for other ways to set its position. * @param x x-coordinate of the center of the circle. * @param y y-coordinate of the center of the circle. * @param d diameter of the circle. */ circle(x: number, y: number, d: number): void; /** * Draws a straight line between two points. * * A line's default width is one pixel. The version of `line()` with four * parameters draws the line in 2D. To color a line, use the * stroke() function. To change its width, use the * strokeWeight() function. A line * can't be filled, so the fill() function won't * affect the line's color. * * The version of `line()` with six parameters allows the line to be drawn in * 3D space. Doing so requires adding the `WEBGL` argument to * createCanvas(). * @param x1 the x-coordinate of the first point. * @param y1 the y-coordinate of the first point. * @param x2 the x-coordinate of the second point. * @param y2 the y-coordinate of the second point. */ line(x1: number, y1: number, x2: number, y2: number): void; line(x1: number, y1: number, z1: number, x2: number, y2: number, z2: number): void; /** * Draws a single point in space. * * A point's default width is one pixel. To color a point, use the * stroke() function. To change its width, use the * strokeWeight() function. A point * can't be filled, so the fill() function won't * affect the point's color. * * The version of `point()` with two parameters allows the point's location to * be set with its x- and y-coordinates, as in `point(10, 20)`. * * The version of `point()` with three parameters allows the point to be drawn * in 3D space with x-, y-, and z-coordinates, as in `point(10, 20, 30)`. * Doing so requires adding the `WEBGL` argument to * createCanvas(). * * The version of `point()` with one parameter allows the point's location to * be set with a p5.Vector object. * @param x the x-coordinate. * @param y the y-coordinate. * @param z the z-coordinate (for WebGL mode). */ point(x: number, y: number, z?: number): void; point(coordinateVector: p5.Vector): void; /** * Draws a quadrilateral (four-sided shape). * * Quadrilaterals include rectangles, squares, rhombuses, and trapezoids. The * first pair of parameters `(x1, y1)` sets the quad's first point. The next * three pairs of parameters set the coordinates for its next three points * `(x2, y2)`, `(x3, y3)`, and `(x4, y4)`. Points should be added in either * clockwise or counter-clockwise order. * * The version of `quad()` with twelve parameters allows the quad to be drawn * in 3D space. Doing so requires adding the `WEBGL` argument to * createCanvas(). * * The thirteenth and fourteenth parameters are optional. In WebGL mode, they * set the number of segments used to draw the quadrilateral in the x- and * y-directions. They're both 2 by default. * @param x1 the x-coordinate of the first point. * @param y1 the y-coordinate of the first point. * @param x2 the x-coordinate of the second point. * @param y2 the y-coordinate of the second point. * @param x3 the x-coordinate of the third point. * @param y3 the y-coordinate of the third point. * @param x4 the x-coordinate of the fourth point. * @param y4 the y-coordinate of the fourth point. * @param detailX number of segments in the x-direction. * @param detailY number of segments in the y-direction. */ quad(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, x4: number, y4: number, detailX?: number, detailY?: number): void; quad(x1: number, y1: number, z1: number, x2: number, y2: number, z2: number, x3: number, y3: number, z3: number, x4: number, y4: number, z4: number, detailX?: number, detailY?: number): void; /** * Draws a rectangle. * * A rectangle is a four-sided shape defined by the `x`, `y`, `w`, and `h` * parameters. `x` and `y` set the location of its top-left corner. `w` sets * its width and `h` sets its height. Every angle in the rectangle measures * 90˚. See rectMode() for other ways to define * rectangles. * * The version of `rect()` with five parameters creates a rounded rectangle. The * fifth parameter sets the radius for all four corners. * * The version of `rect()` with eight parameters also creates a rounded * rectangle. Each of the last four parameters set the radius of a corner. The * radii start with the top-left corner and move clockwise around the * rectangle. If any of these parameters are omitted, they are set to the * value of the last radius that was set. * @param x x-coordinate of the rectangle. * @param y y-coordinate of the rectangle. * @param w width of the rectangle. * @param h height of the rectangle. * @param tl optional radius of top-left corner. * @param tr optional radius of top-right corner. * @param br optional radius of bottom-right corner. * @param bl optional radius of bottom-left corner. */ rect(x: number, y: number, w: number, h?: number, tl?: number, tr?: number, br?: number, bl?: number): void; rect(x: number, y: number, w: number, h: number, detailX?: number, detailY?: number): void; /** * Draws a square. * * A square is a four-sided shape defined by the `x`, `y`, and `s` * parameters. `x` and `y` set the location of its top-left corner. `s` sets * its width and height. Every angle in the square measures 90˚ and all its * sides are the same length. See rectMode() for * other ways to define squares. * * The version of `square()` with four parameters creates a rounded square. * The fourth parameter sets the radius for all four corners. * * The version of `square()` with seven parameters also creates a rounded * square. Each of the last four parameters set the radius of a corner. The * radii start with the top-left corner and move clockwise around the * square. If any of these parameters are omitted, they are set to the * value of the last radius that was set. * @param x x-coordinate of the square. * @param y y-coordinate of the square. * @param s side size of the square. * @param tl optional radius of top-left corner. * @param tr optional radius of top-right corner. * @param br optional radius of bottom-right corner. * @param bl optional radius of bottom-left corner. */ square(x: number, y: number, s: number, tl?: number, tr?: number, br?: number, bl?: number): void; /** * Draws a triangle. * * A triangle is a three-sided shape defined by three points. The * first two parameters specify the triangle's first point `(x1, y1)`. The * middle two parameters specify its second point `(x2, y2)`. And the last two * parameters specify its third point `(x3, y3)`. * @param x1 x-coordinate of the first point. * @param y1 y-coordinate of the first point. * @param x2 x-coordinate of the second point. * @param y2 y-coordinate of the second point. * @param x3 x-coordinate of the third point. * @param y3 y-coordinate of the third point. */ triangle(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number): void; /** * Changes where ellipses, circles, and arcs are drawn. * * By default, the first two parameters of * ellipse(), circle(), * and arc() * are the x- and y-coordinates of the shape's center. The next parameters set * the shape's width and height. This is the same as calling * `ellipseMode(CENTER)`. * * `ellipseMode(RADIUS)` also uses the first two parameters to set the x- and * y-coordinates of the shape's center. The next parameters are half of the * shapes's width and height. Calling `ellipse(0, 0, 10, 15)` draws a shape * with a width of 20 and height of 30. * * `ellipseMode(CORNER)` uses the first two parameters as the upper-left * corner of the shape. The next parameters are its width and height. * * `ellipseMode(CORNERS)` uses the first two parameters as the location of one * corner of the ellipse's bounding box. The next parameters are the location * of the opposite corner. * * The argument passed to `ellipseMode()` must be written in ALL CAPS because * the constants `CENTER`, `RADIUS`, `CORNER`, and `CORNERS` are defined this * way. JavaScript is a case-sensitive language. * @param mode either CENTER, RADIUS, CORNER, or CORNERS */ ellipseMode(mode: typeof p5.CENTER | typeof p5.RADIUS | typeof p5.CORNER | typeof p5.CORNERS): void; /** * Draws certain features with jagged (aliased) edges. * * smooth() is active by default. In 2D mode, * `noSmooth()` is helpful for scaling up images without blurring. The * functions don't affect shapes or fonts. * * In WebGL mode, `noSmooth()` causes all shapes to be drawn with jagged * (aliased) edges. The functions don't affect images or fonts. */ noSmooth(): void; /** * Changes where rectangles and squares are drawn. * * By default, the first two parameters of * rect() and square(), * are the x- and y-coordinates of the shape's upper left corner. The next parameters set * the shape's width and height. This is the same as calling * `rectMode(CORNER)`. * * `rectMode(CORNERS)` also uses the first two parameters as the location of * one of the corners. The next parameters are the location of the opposite * corner. This mode only works for rect(). * * `rectMode(CENTER)` uses the first two parameters as the x- and * y-coordinates of the shape's center. The next parameters are its width and * height. * * `rectMode(RADIUS)` also uses the first two parameters as the x- and * y-coordinates of the shape's center. The next parameters are * half of the shape's width and height. * * The argument passed to `rectMode()` must be written in ALL CAPS because the * constants `CENTER`, `RADIUS`, `CORNER`, and `CORNERS` are defined this way. * JavaScript is a case-sensitive language. * @param mode either CORNER, CORNERS, CENTER, or RADIUS */ rectMode(mode: typeof p5.CENTER | typeof p5.RADIUS | typeof p5.CORNER | typeof p5.CORNERS): void; /** * Draws certain features with smooth (antialiased) edges. * * `smooth()` is active by default. In 2D mode, * noSmooth() is helpful for scaling up images * without blurring. The functions don't affect shapes or fonts. * * In WebGL mode, noSmooth() causes all shapes to * be drawn with jagged (aliased) edges. The functions don't affect images or * fonts. */ smooth(): void; /** * Sets the style for rendering the ends of lines. * * The caps for line endings are either rounded (`ROUND`), squared * (`SQUARE`), or extended (`PROJECT`). The default cap is `ROUND`. * * The argument passed to `strokeCap()` must be written in ALL CAPS because * the constants `ROUND`, `SQUARE`, and `PROJECT` are defined this way. * JavaScript is a case-sensitive language. * @param cap either ROUND, SQUARE, or PROJECT */ strokeCap(cap: typeof p5.ROUND | typeof p5.SQUARE | typeof p5.PROJECT): void; /** * Sets the style of the joints that connect line segments. * * Joints are either mitered (`MITER`), beveled (`BEVEL`), or rounded * (`ROUND`). The default joint is `MITER` in 2D mode and `ROUND` in WebGL * mode. * * The argument passed to `strokeJoin()` must be written in ALL CAPS because * the constants `MITER`, `BEVEL`, and `ROUND` are defined this way. * JavaScript is a case-sensitive language. * @param join either MITER, BEVEL, or ROUND */ strokeJoin(join: typeof p5.MITER | typeof p5.BEVEL | typeof p5.ROUND): void; /** * Sets the width of the stroke used for points, lines, and the outlines of * shapes. * * Note: `strokeWeight()` is affected by transformations, especially calls to * scale(). * @param weight the weight of the stroke (in pixels). */ strokeWeight(weight: number): void; /** * Draws a Bézier curve. * * Bézier curves can form shapes and curves that slope gently. They're defined * by two anchor points and two control points. Bézier curves provide more * control than the spline curves created with the * spline() function. * * The first two parameters, `x1` and `y1`, set the first anchor point. The * first anchor point is where the curve starts. * * The next four parameters, `x2`, `y2`, `x3`, and `y3`, set the two control * points. The control points "pull" the curve towards them. * * The seventh and eighth parameters, `x4` and `y4`, set the last anchor * point. The last anchor point is where the curve ends. * * Bézier curves can also be drawn in 3D using WebGL mode. The 3D version of * `bezier()` has twelve arguments because each point has x-, y-, * and z-coordinates. * @param x1 x-coordinate of the first anchor point. * @param y1 y-coordinate of the first anchor point. * @param x2 x-coordinate of the first control point. * @param y2 y-coordinate of the first control point. * @param x3 x-coordinate of the second control point. * @param y3 y-coordinate of the second control point. * @param x4 x-coordinate of the second anchor point. * @param y4 y-coordinate of the second anchor point. */ bezier(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, x4: number, y4: number): void; bezier(x1: number, y1: number, z1: number, x2: number, y2: number, z2: number, x3: number, y3: number, z3: number, x4: number, y4: number, z4: number): void; /** * Calculates coordinates along a Bézier curve using interpolation. * * `bezierPoint()` calculates coordinates along a Bézier curve using the * anchor and control points. It expects points in the same order as the * bezier() function. `bezierPoint()` works one axis * at a time. Passing the anchor and control points' x-coordinates will * calculate the x-coordinate of a point on the curve. Passing the anchor and * control points' y-coordinates will calculate the y-coordinate of a point on * the curve. * * The first parameter, `a`, is the coordinate of the first anchor point. * * The second and third parameters, `b` and `c`, are the coordinates of the * control points. * * The fourth parameter, `d`, is the coordinate of the last anchor point. * * The fifth parameter, `t`, is the amount to interpolate along the curve. 0 * is the first anchor point, 1 is the second anchor point, and 0.5 is halfway * between them. * @param a coordinate of first anchor point. * @param b coordinate of first control point. * @param c coordinate of second control point. * @param d coordinate of second anchor point. * @param t amount to interpolate between 0 and 1. * @returns coordinate of the point on the curve. */ bezierPoint(a: number, b: number, c: number, d: number, t: number): number; /** * Calculates coordinates along a line that's tangent to a Bézier curve. * * Tangent lines skim the surface of a curve. A tangent line's slope equals * the curve's slope at the point where it intersects. * * `bezierTangent()` calculates coordinates along a tangent line using the * Bézier curve's anchor and control points. It expects points in the same * order as the bezier() function. `bezierTangent()` * works one axis at a time. Passing the anchor and control points' * x-coordinates will calculate the x-coordinate of a point on the tangent * line. Passing the anchor and control points' y-coordinates will calculate * the y-coordinate of a point on the tangent line. * * The first parameter, `a`, is the coordinate of the first anchor point. * * The second and third parameters, `b` and `c`, are the coordinates of the * control points. * * The fourth parameter, `d`, is the coordinate of the last anchor point. * * The fifth parameter, `t`, is the amount to interpolate along the curve. 0 * is the first anchor point, 1 is the second anchor point, and 0.5 is halfway * between them. * @param a coordinate of first anchor point. * @param b coordinate of first control point. * @param c coordinate of second control point. * @param d coordinate of second anchor point. * @param t amount to interpolate between 0 and 1. * @returns coordinate of a point on the tangent line. */ bezierTangent(a: number, b: number, c: number, d: number, t: number): number; /** * Draws a curve using a Catmull-Rom spline. * * Spline curves can form shapes and curves that slope gently. They’re like * cables that are attached to a set of points. By default (`ends: INCLUDE`), * the curve passes through all four points you provide, in order * `p0(x1,y1)` -> `p1(x2,y2)` -> `p2(x3,y3)` -> `p3(x4,y4)`. Think of them as * points on a curve. If you switch to `ends: EXCLUDE`, p0 and p3 act * like control points and only the middle span `p1->p2` is drawn. * * Spline curves can also be drawn in 3D using WebGL mode. The 3D version of * `spline()` has twelve arguments because each point has x-, y-, and * z-coordinates. * @param x1 x-coordinate of point p0. * @param y1 y-coordinate of point p0. * @param x2 x-coordinate of point p1. * @param y2 y-coordinate of point p1. * @param x3 x-coordinate of point p2. * @param y3 y-coordinate of point p2. * @param x4 x-coordinate of point p3. * @param y4 y-coordinate of point p3. */ spline(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, x4: number, y4: number): void; spline(x1: number, y1: number, z1: number, x2: number, y2: number, z2: number, x3: number, y3: number, z3: number, x4: number, y4: number, z4: number): void; /** * Calculates coordinates along a spline curve using interpolation. * * `splinePoint()` calculates coordinates along a spline curve using four * points p0, p1, p2, p3. It expects points in the same order as the * spline() function. `splinePoint()` works one axis * at a time. Passing the points' x-coordinates will * calculate the x-coordinate of a point on the curve. Passing the * points' y-coordinates will calculate the y-coordinate of a point on * the curve. * * The first parameter, `a`, is the coordinate of point p0. * * The second and third parameters, `b` and `c`, are the coordinates of * points p1 and p2. * * The fourth parameter, `d`, is the coordinate of point p3. * * The fifth parameter, `t`, is the amount to interpolate along the span * from p1 to p2. `t = 0` is p1, `t = 1` is p2, and `t = 0.5` is halfway * between them. * @param a coordinate of point p0. * @param b coordinate of point p1. * @param c coordinate of point p2. * @param d coordinate of point p3. * @param t amount to interpolate between 0 and 1. * @returns coordinate of a point on the curve. */ splinePoint(a: number, b: number, c: number, d: number, t: number): number; /** * Calculates coordinates along a line that's tangent to a spline curve. * * Tangent lines skim the surface of a curve. A tangent line's slope equals * the curve's slope at the point where it intersects. * * `splineTangent()` calculates coordinates along a tangent line using four * points p0, p1, p2, p3. It expects points in the same order as the * spline() function. `splineTangent()` works one * axis at a time. Passing the points' x-coordinates returns the x-component of * the tangent vector; passing the points' y-coordinates returns the y-component. * The first parameter, `a`, is the coordinate of point p0. * * The second and third parameters, `b` and `c`, are the coordinates of * points p1 and p2. * * The fourth parameter, `d`, is the coordinate of point p3. * * The fifth parameter, `t`, is the amount to interpolate along the span * from p1 to p2. `t = 0` is p1, `t = 1` is p2, and `t = 0.5` is halfway * between them. * @param a coordinate of point p0. * @param b coordinate of point p1. * @param c coordinate of point p2. * @param d coordinate of point p3. * @param t amount to interpolate between 0 and 1. * @returns coordinate of a point on the tangent line. */ splineTangent(a: number, b: number, c: number, d: number, t: number): number; /** * Influences the shape of the Bézier curve segment in a custom shape. * By default, this is 3; the other possible parameter is 2. This * results in quadratic Bézier curves. * * `bezierVertex()` adds a curved segment to custom shapes. The Bézier curves * it creates are defined like those made by the * bezier() function. `bezierVertex()` must be * called between the * beginShape() and * endShape() functions. There must be at least * one call to bezierVertex(), before * a number of `bezierVertex()` calls that is a multiple of the parameter * set by bezierOrder(...) (default 3). * * Each curve of order 3 requires three calls to `bezierVertex`, so * 2 curves would need 7 calls to `bezierVertex()`: * (1 one initial anchor point, two sets of 3 curves describing the curves) * With `bezierOrder(2)`, two curves would need 5 calls: 1 + 2 + 2. * * Bézier curves can also be drawn in 3D using WebGL mode. * * Note: `bezierVertex()` won’t work when an argument is passed to * beginShape(). * @param order The new order to set. Can be either 2 or 3, by default 3 * @returns The current Bézier order. */ bezierOrder(order: number): number; bezierOrder(): number; /** * Connects points with a smooth curve (a spline). * * `splineVertex()` adds a curved segment to custom shapes. * The curve it creates follows the same rules as the ones * made with the spline() function. * `splineVertex()` must be called between the * beginShape() and * endShape() functions. * * Spline curves can form shapes and curves that slope gently. They’re like * cables that are attached to a set of points. `splineVertex()` draws a smooth * curve through the points you give it. * beginShape() and * endShape() in order to draw a curve: * * If you provide three points, the spline will pass through them. * It works the same way with any number of points. * * `beginShape(); * * // Add the first point. * splineVertex(25, 80); * * // Add the second point. * splineVertex(20, 30); * * // Add the last point. * splineVertex(85, 60); * * endShape();` * * Passing in `CLOSE` to `endShape()` closes the spline smoothly. * * `beginShape(); * * // Add the first point. * splineVertex(25, 80); * * // Add the second point. * splineVertex(20, 30); * * // Add the second point. * splineVertex(85, 60); * * endShape(CLOSE);` * * By default (`ends: INCLUDE`), the curve passes through * all the points you add with `splineVertex()`, similar to * the spline() function. To draw only * the middle span p1->p2 (skipping p0->p1 and p2->p3), set * `splineProperty('ends', EXCLUDE)`. You don’t need to duplicate * vertices to draw those spans. * * Spline curves can also be drawn in 3D using WebGL mode. The 3D version of * `splineVertex()` has three arguments because each point has x-, y-, and * z-coordinates. By default, the vertex’s z-coordinate is set to 0. * * Note: `splineVertex()` won’t work when an argument is passed to * beginShape(). * @param x x-coordinate of the vertex * @param y y-coordinate of the vertex */ splineVertex(x: number, y: number): void; splineVertex(x: number, y: number, z?: number): void; splineVertex(x: number, y: number, u?: number, v?: number): void; splineVertex(x: number, y: number, z: number, u?: number, v?: number): void; /** * Gets or sets a given spline property. * * Use `splineProperty()` to adjust the behavior of splines * created with `splineVertex()` or `spline()`. You can control * two key aspects of a spline: its end behavior (`ends`) and * its curvature (`tightness`). * * By default, the ends property is set to `INCLUDE`, which means * the spline passes through every point, including the endpoints. * You can also set it to `EXCLUDE` i.e. `splineProperty('ends', EXCLUDE)`, * which makes the spline pass through all points except the endpoints. * * `INCLUDE` case will have the spline passing through * all points, like this: * * `splineProperty('ends', INCLUDE); // no need to set this, as it is the default * spline(25, 46, 93, 44, 93, 81, 35, 85); * * point(25, 46); * point(93, 44); * point(93, 81); * point(35, 85);` * * EXCLUDE case will have the spline passing through * the middle points, like this: * * `splineProperty('ends', EXCLUDE); * spline(25, 46, 93, 44, 93, 81, 35, 85); * * point(25, 46); * point(93, 44); * point(93, 81); * point(35, 85);` * * By default, the tightness property is set to `0`, * producing a smooth curve that passes evenly through * the vertices. Negative values make the curve looser, * while positive values make it tighter. Common values * range between -1 and 1, though values outside this * range can also be used for different effects. * * For example, To set tightness, use `splineProperty('tightness', t)`, * (default: t = 0). * * Here's the example showing negetive value of tightness, * which creates a rounder bulge: * * `splineProperty('tightness', -5) * stroke(0); * strokeWeight(2); * spline(25, 46, 93, 44, 93, 81, 35, 85);` * Here's the example showing positive value of tightness, * which makes the curve tighter and more angular: * * `splineProperty('tightness', 5) * stroke(0); * strokeWeight(2); * spline(25, 46, 93, 44, 93, 81, 35, 85);` * * In all cases, the splines in p5.js are cardinal splines. * When tightness is 0, these splines are often known as * Catmull-Rom splines * @param value Value to set the given property to. * @returns The current value for the given property. */ splineProperty(property: string, value: any): void; splineProperty(property: string): void; /** * Get or set multiple spline properties at once. * * Similar to splineProperty(): * `splineProperty('tightness', t)` is the same as * `splineProperties({'tightness': t})` * @param properties An object containing key-value pairs to set. * @returns The current spline properties. */ splineProperties(properties: object): object; splineProperties(): object; /** * Adds a vertex to a custom shape. * * `vertex()` sets the coordinates of vertices drawn between the * beginShape() and * endShape() functions. * * The first two parameters, `x` and `y`, set the x- and y-coordinates of the * vertex. * * The third parameter, `z`, is optional. It sets the z-coordinate of the * vertex in WebGL mode. By default, `z` is 0. * * The fourth and fifth parameters, `u` and `v`, are also optional. They set * the u- and v-coordinates for the vertex’s texture when used with * endShape(). By default, `u` and `v` are both 0. * @param x x-coordinate of the vertex. * @param y y-coordinate of the vertex. */ vertex(x: number, y: number): void; vertex(x: number, y: number, u?: number, v?: number): void; vertex(x: number, y: number, z: number, u?: number, v?: number): void; /** * Begins creating a hole within a flat shape. * * The `beginContour()` and endContour() * functions allow for creating negative space within custom shapes that are * flat. `beginContour()` begins adding vertices to a negative space and * endContour() stops adding them. * `beginContour()` and endContour() must be * called between beginShape() and * endShape(). * * Transformations such as translate(), * rotate(), and scale() * don't work between `beginContour()` and * endContour(). It's also not possible to use * other shapes, such as ellipse() or * rect(), between `beginContour()` and * endContour(). * * Note: The vertices that define a negative space must "wind" in the opposite * direction from the outer shape. First, draw vertices for the outer shape * clockwise order. Then, draw vertices for the negative space in * counter-clockwise order. */ beginContour(): void; /** * Stops creating a hole within a flat shape. * * The beginContour() and `endContour()` * functions allow for creating negative space within custom shapes that are * flat. beginContour() begins adding vertices * to a negative space and `endContour()` stops adding them. * beginContour() and `endContour()` must be * called between beginShape() and * endShape(). * * By default, * the controur has an `OPEN` end, and to close it, * call `endContour(CLOSE)`. The CLOSE contour mode closes splines smoothly. * * Transformations such as translate(), * rotate(), and scale() * don't work between beginContour() and * `endContour()`. It's also not possible to use other shapes, such as * ellipse() or rect(), * between beginContour() and `endContour()`. * * Note: The vertices that define a negative space must "wind" in the opposite * direction from the outer shape. First, draw vertices for the outer shape * clockwise order. Then, draw vertices for the negative space in * counter-clockwise order. * @param mode By default, the value is OPEN */ endContour(mode?: typeof p5.OPEN | typeof p5.CLOSE): void; /** * Begins adding vertices to a custom shape. * * The `beginShape()` and endShape() functions * allow for creating custom shapes in 2D or 3D. `beginShape()` begins adding * vertices to a custom shape and endShape() stops * adding them. * * The parameter, `kind`, sets the kind of shape to make. The available kinds are: * * - `PATH` (the default) to draw shapes by tracing out the path along their edges. * * - `POINTS` to draw a series of points. * * - `LINES` to draw a series of unconnected line segments. * * - `TRIANGLES` to draw a series of separate triangles. * * - `TRIANGLE_FAN` to draw a series of connected triangles sharing the first vertex in a fan-like fashion. * * - `TRIANGLE_STRIP` to draw a series of connected triangles in strip fashion. * * - `QUADS` to draw a series of separate quadrilaterals (quads). * * - `QUAD_STRIP` to draw quad strip using adjacent edges to form the next quad. * * After calling `beginShape()`, shapes can be built by calling * vertex(), * bezierVertex(), and/or * splineVertex(). Calling * endShape() will stop adding vertices to the * shape. Each shape will be outlined with the current stroke color and filled * with the current fill color. * * Transformations such as translate(), * rotate(), and * scale() don't work between `beginShape()` and * endShape(). It's also not possible to use * other shapes, such as ellipse() or * rect(), between `beginShape()` and * endShape(). * @param kind either POINTS, LINES, TRIANGLES, TRIANGLE_FAN * TRIANGLE_STRIP, QUADS, QUAD_STRIP or PATH. Defaults to PATH. */ beginShape(kind?: typeof p5.POINTS | typeof p5.LINES | typeof p5.TRIANGLES | typeof p5.TRIANGLE_FAN | typeof p5.TRIANGLE_STRIP | typeof p5.QUADS | typeof p5.QUAD_STRIP | typeof p5.PATH): void; /** * Adds a Bézier curve segment to a custom shape. * * `bezierVertex()` adds a curved segment to custom shapes. The Bézier curves * it creates are defined like those made by the * bezier() function. `bezierVertex()` must be * called between the * beginShape() and * endShape() functions. * Bézier need a starting point. Building a shape * only with Bézier curves needs one initial * call to bezierVertex(), before * a number of `bezierVertex()` calls that is a multiple of the parameter * set by bezierOrder(...) (default 3). * But shapes can mix different types of vertices, so if there * are some previous vertices, then the initial anchor is not needed, * only the multiples of 3 (or the Bézier order) calls to * `bezierVertex` for each curve. * * Each curve of order 3 requires three calls to `bezierVertex`, so * 2 curves would need 7 calls to `bezierVertex()`: * (1 one initial anchor point, two sets of 3 curves describing the curves) * With `bezierOrder(2)`, two curves would need 5 calls: 1 + 2 + 2. * * Bézier curves can also be drawn in 3D using WebGL mode. * * Note: `bezierVertex()` won’t work when an argument is passed to * beginShape(). * @param x x-coordinate of the first control point. * @param y y-coordinate of the first control point. */ bezierVertex(x: number, y: number, u?: number, v?: number): void; bezierVertex(x: number, y: number, z: number, u?: number, v?: number): void; /** * Concludes the vertices of a custom shape. * * The beginShape() and `endShape()` functions * allow for creating custom shapes in 2D or 3D. * beginShape() begins adding vertices to a * custom shape and `endShape()` stops adding them. * * The first parameter, `mode`, is optional. By default, the first and last * vertices of a shape aren't connected. If the constant `CLOSE` is passed, as * in `endShape(CLOSE)`, then the first and last vertices will be connected. * When CLOSE mode is used for splines (with `splineVeertex()`), the shape is ended smoothly. * * The second parameter, `count`, is also optional. In WebGL mode, it’s more * efficient to draw many copies of the same shape using a technique called * instancing. * The `count` parameter tells WebGL mode how many copies to draw. For * example, calling `endShape(CLOSE, 400)` after drawing a custom shape will * make it efficient to draw 400 copies. This feature requires * writing a custom shader. * * After calling beginShape(), shapes can be * built by calling vertex(), * bezierVertex() and/or * splineVertex(). Calling * `endShape()` will stop adding vertices to the * shape. Each shape will be outlined with the current stroke color and filled * with the current fill color. * * Transformations such as translate(), * rotate(), and * scale() don't work between * beginShape() and `endShape()`. It's also not * possible to use other shapes, such as ellipse() or * rect(), between * beginShape() and `endShape()`. * @param mode use CLOSE to close the shape * @param count number of times you want to draw/instance the shape (for WebGL mode). */ endShape(mode?: typeof p5.CLOSE, count?: number): void; /** * Sets the normal vector for vertices in a custom 3D shape. * * 3D shapes created with beginShape() and * endShape() are made by connecting sets of * points called vertices. Each vertex added with * vertex() has a normal vector that points away * from it. The normal vector controls how light reflects off the shape. * * `normal()` can be called two ways with different parameters to define the * normal vector's components. * * The first way to call `normal()` has three parameters, `x`, `y`, and `z`. * If `Number`s are passed, as in `normal(1, 2, 3)`, they set the x-, y-, and * z-components of the normal vector. * * The second way to call `normal()` has one parameter, `vector`. If a * p5.Vector object is passed, as in * `normal(myVector)`, its components will be used to set the normal vector. * * `normal()` changes the normal vector of vertices added to a custom shape * with vertex(). `normal()` must be called between * the beginShape() and * endShape() functions, just like * vertex(). The normal vector set by calling * `normal()` will affect all following vertices until `normal()` is called * again: * * `beginShape(); * * // Set the vertex normal. * normal(-0.4, -0.4, 0.8); * * // Add a vertex. * vertex(-30, -30, 0); * * // Set the vertex normal. * normal(0, 0, 1); * * // Add vertices. * vertex(30, -30, 0); * vertex(30, 30, 0); * * // Set the vertex normal. * normal(0.4, -0.4, 0.8); * * // Add a vertex. * vertex(-30, 30, 0); * * endShape();` * @param vector vertex normal as a p5.Vector object. */ normal(vector: p5.Vector): void; normal(x: number, y: number, z: number): void; /** * Sets the shader's vertex property or attribute variables. * * A vertex property, or vertex attribute, is a variable belonging to a vertex in a shader. p5.js provides some * default properties, such as `aPosition`, `aNormal`, `aVertexColor`, etc. These are * set using vertex(), normal() * and fill() respectively. Custom properties can also * be defined within beginShape() and * endShape(). * * The first parameter, `propertyName`, is a string with the property's name. * This is the same variable name which should be declared in the shader, such as * `in vec3 aProperty`, similar to .`setUniform()`. * * The second parameter, `data`, is the value assigned to the shader variable. This * value will be applied to subsequent vertices created with * vertex(). It can be a Number or an array of numbers, * and in the shader program the type can be declared according to the WebGL * specification. Common types include `float`, `vec2`, `vec3`, `vec4` or matrices. * * See also the vertexProperty() method on * Geometry objects. * @param attributeName the name of the vertex attribute. * @param data the data tied to the vertex attribute. */ vertexProperty(attributeName: string, data: number | number[]): void; /** * Registers a callback to modify the world-space properties of each vertex in a shader. This hook can be used inside baseColorShader().modify() and similar shader modify() calls to customize vertex positions, normals, texture coordinates, and colors before rendering. "World space" refers to the coordinate system of the 3D scene, before any camera or projection transformations are applied. * * The callback receives a vertex object with the following properties: * * - `position`: a three-component vector representing the original position of the vertex. * * - `normal`: a three-component vector representing the direction the surface is facing. * * - `texCoord`: a two-component vector representing the texture coordinates. * * - `color`: a four-component vector representing the color of the vertex (red, green, blue, alpha). * * This hook is available in: * * - baseMaterialShader() * * - baseNormalShader() * * - baseColorShader() * * - baseStrokeShader() * @param callback A callback function which receives a vertex object containing position (vec3), normal (vec3), texCoord (vec2), and color (vec4) properties. The function should return the modified vertex object. */ getWorldInputs(callback: Function): void; /** * Registers a callback to customize how color components are combined in the fragment shader. This hook can be used inside baseMaterialShader().modify() and similar shader modify() calls to control the final color output of a material. The callback receives an object with the following properties: * * - `baseColor`: a three-component vector representing the base color (red, green, blue). * * - `diffuse`: a single number representing the diffuse reflection. * * - `ambientColor`: a three-component vector representing the ambient color. * * - `ambient`: a single number representing the ambient reflection. * * - `specularColor`: a three-component vector representing the specular color. * * - `specular`: a single number representing the specular reflection. * * - `emissive`: a three-component vector representing the emissive color. * * - `opacity`: a single number representing the opacity. * * The callback should return a vector with four components (red, green, blue, alpha) for the final color. * * This hook is available in: * * - baseMaterialShader() * @param callback A callback function which receives the object described above and returns a vector with four components for the final color. */ combineColors(callback: Function): void; /** * Registers a callback to modify the properties of each fragment (pixel) before the final color is calculated in the fragment shader. This hook can be used inside baseMaterialShader().modify() and similar shader modify() calls to adjust per-pixel data before lighting/mixing. * * The callback receives an `Inputs` object. Available fields depend on the shader: * * - In baseMaterialShader(): * * - `normal`: a three-component vector representing the surface normal. * * - `texCoord`: a two-component vector representing the texture coordinates (u, v). * * - `ambientLight`: a three-component vector representing the ambient light color. * * - `ambientMaterial`: a three-component vector representing the material's ambient color. * * - `specularMaterial`: a three-component vector representing the material's specular color. * * - `emissiveMaterial`: a three-component vector representing the material's emissive color. * * - `color`: a four-component vector representing the base color (red, green, blue, alpha). * * - `shininess`: a number controlling specular highlights. * * - `metalness`: a number controlling the metalness factor. * * - In baseStrokeShader(): * * - `color`: a four-component vector representing the stroke color (red, green, blue, alpha). * * - `tangent`: a two-component vector representing the stroke tangent. * * - `center`: a two-component vector representing the cap/join center. * * - `position`: a two-component vector representing the current fragment position. * * - `strokeWeight`: a number representing the stroke weight in pixels. * * Return the modified object to update the fragment. * * This hook is available in: * * - baseMaterialShader() * * - baseStrokeShader() * @param callback A callback function which receives the fragment inputs object and should return it after making any changes. */ getPixelInputs(callback: Function): void; /** * Registers a callback to change the final color of each pixel after all lighting and mixing is done in the fragment shader. This hook can be used inside baseColorShader().modify() and similar shader modify() calls to adjust the color before it appears on the screen. The callback receives a four component vector representing red, green, blue, and alpha. * * Return a new color array to change the output color. * * This hook is available in: * * - baseColorShader() * * - baseMaterialShader() * * - baseNormalShader() * * - baseStrokeShader() * @param callback A callback function which receives the color array and should return a color array. */ getFinalColor(callback: Function): void; /** * Registers a callback to set the final color for each pixel in a filter shader. This hook can be used inside baseFilterShader().modify() and similar shader modify() calls to control the output color for each pixel. The callback receives the following arguments: * * - `inputs`: an object with the following properties: * * - `texCoord`: a two-component vector representing the texture coordinates (u, v). * * - `canvasSize`: a two-component vector representing the canvas size in pixels (width, height). * * - `texelSize`: a two-component vector representing the size of a single texel in texture space. * * - `canvasContent`: a texture containing the sketch's contents before the filter is applied. * * Return a four-component vector `[r, g, b, a]` for the pixel. * * This hook is available in: * * - baseFilterShader() * @param callback A callback function which receives the inputs object and canvasContent, and should return a color array. */ getColor(callback: Function): void; /** * Registers a callback to modify the properties of each vertex before any transformations are applied in the vertex shader. This hook can be used inside baseColorShader().modify() and similar shader modify() calls to move, color, or otherwise modify the raw model data. The callback receives an object with the following properties: * * - `position`: a three-component vector representing the original position of the vertex. * * - `normal`: a three-component vector representing the direction the surface is facing. * * - `texCoord`: a two-component vector representing the texture coordinates. * * - `color`: a four-component vector representing the color of the vertex (red, green, blue, alpha). * * Return the modified object to update the vertex. * * This hook is available in: * * - baseColorShader() * * - baseMaterialShader() * * - baseNormalShader() * * - baseStrokeShader() * @param callback A callback function which receives the vertex object and should return it after making any changes. */ getObjectInputs(callback: Function): void; /** * Registers a callback to adjust vertex properties after the model has been transformed by the camera, but before projection, in the vertex shader. This hook can be used inside baseColorShader().modify() and similar shader modify() calls to create effects that depend on the camera's view. The callback receives an object with the following properties: * * - `position`: a three-component vector representing the position after camera transformation. * * - `normal`: a three-component vector representing the normal after camera transformation. * * - `texCoord`: a two-component vector representing the texture coordinates. * * - `color`: a four-component vector representing the color of the vertex (red, green, blue, alpha). * * Return the modified object to update the vertex. * * This hook is available in: * * - baseColorShader() * * - baseMaterialShader() * * - baseNormalShader() * * - baseStrokeShader() * @param callback A callback function which receives the vertex object and should return it after making any changes. */ getCameraInputs(callback: Function): void; /** * Loads a font and creates a p5.Font object. * `loadFont()` can load fonts in either .otf or .ttf format. Loaded fonts can * be used to style text on the canvas and in HTML elements. * * The first parameter, `path`, is the path to a font file. * Paths to local files should be relative. For example, * `'assets/inconsolata.otf'`. The Inconsolata font used in the following * examples can be downloaded for free * here. * Paths to remote files should be URLs. For example, * `'https://example.com/inconsolata.otf'`. URLs may be blocked due to browser * security. * * In 2D mode, `path` can take on a few other forms. It could be a path to a CSS file, * such as one from Google Fonts. It could also * be a string with a CSS `@font-face` declaration. * * The second parameter, `successCallback`, is optional. If a function is * passed, it will be called once the font has loaded. The callback function * may use the new p5.Font object if needed. * * The third parameter, `failureCallback`, is also optional. If a function is * passed, it will be called if the font fails to load. The callback function * may use the error * Event * object if needed. * * Fonts can take time to load. `await` the result of `loadFont()` in * setup() before using the result. * @param path path of the font or CSS file to be loaded, or a CSS `@font-face` string. * @param name An alias that can be used for this font in `textFont()`. Defaults to the name in the font's metadata. * @param options An optional object with extra CSS font face descriptors, or p5.js font settings. * @param successCallback function called with the * p5.Font object after it * loads. * @param failureCallback function called with the error * Event * object if the font fails to load. * @returns p5.Font object. */ loadFont(path: string, name?: string, options?: { sets?: string | string[] }, successCallback?: (font: p5.Font) => any, failureCallback?: Function): Promise; loadFont(path: string, successCallback?: (font: p5.Font) => any, failureCallback?: Function): Promise; /** * Draws text to the canvas. * * The first parameter, `str`, is the text to be drawn. The second and third * parameters, `x` and `y`, set the coordinates of the text's bottom-left * corner. See textAlign() for other ways to * align text. * * The fourth and fifth parameters, `maxWidth` and `maxHeight`, are optional. * They set the dimensions of the invisible rectangle containing the text. By * default, they set its maximum width and height. See * rectMode() for other ways to define the * rectangular text box. Text will wrap to fit within the text box. Text * outside of the box won't be drawn. * * Text can be styled a few ways. Call the fill() * function to set the text's fill color. Call * stroke() and * strokeWeight() to set the text's outline. * Call textSize() and * textFont() to set the text's size and font, * respectively. * * Note: `WEBGL` mode only supports fonts loaded with * loadFont(). Calling * stroke() has no effect in `WEBGL` mode. * @param str text to be displayed. * @param x x-coordinate of the text box. * @param y y-coordinate of the text box. * @param maxWidth maximum width of the text box. See * rectMode() for * other options. * @param maxHeight maximum height of the text box. See * rectMode() for * other options. */ text(str: string | object | any[] | number | boolean, x: number, y: number, maxWidth?: number, maxHeight?: number): void; /** * Sets the way text is aligned when text() is called. * * By default, calling `text('hi', 10, 20)` places the bottom-left corner of * the text's bounding box at (10, 20). * * The first parameter, `horizAlign`, changes the way * text() interprets x-coordinates. By default, the * x-coordinate sets the left edge of the bounding box. `textAlign()` accepts * the following values for `horizAlign`: `LEFT`, `CENTER`, or `RIGHT`. * * The second parameter, `vertAlign`, is optional. It changes the way * text() interprets y-coordinates. By default, the * y-coordinate sets the bottom edge of the bounding box. `textAlign()` * accepts the following values for `vertAlign`: `TOP`, `BOTTOM`, `CENTER`, * or `BASELINE`. * * Calling `textAlign()` without arguments returns the current alignment settings. * @param horizAlign horizontal alignment * @param vertAlign vertical alignment * @returns If no arguments are provided, returns an object with current horizontal and vertical alignment */ textAlign(horizAlign?: typeof p5.LEFT | typeof p5.CENTER | typeof p5.RIGHT, vertAlign?: typeof p5.TOP | typeof p5.BOTTOM | typeof p5.CENTER | typeof p5.BASELINE): object; /** * Returns the ascent of the text. * * The `textAscent()` function calculates the distance from the baseline to the * highest point of the current font. This value represents the ascent, which is essential * for determining the overall height of the text along with `textDescent()`. If * a text string is provided as an argument, the ascent is calculated based on that specific * string; otherwise, the ascent of the current font is returned. * @param txt (Optional) The text string for which to calculate the ascent. * If omitted, the function returns the ascent for the current font. * @returns The ascent value in pixels. */ textAscent(txt?: string): number; /** * Returns the descent of the text. * * The `textDescent()` function calculates the distance from the baseline to the * lowest point of the current font. This value represents the descent, which, when combined * with the ascent (from `textAscent()`), determines the overall vertical span of the text. * If a text string is provided as an argument, the descent is calculated based on that specific string; * otherwise, the descent of the current font is returned. * @param txt (Optional) The text string for which to calculate the descent. * If omitted, the function returns the descent for the current font. * @returns The descent value in pixels. */ textDescent(txt?: string): number; /** * Sets the spacing between lines of text when * text() is called. * * Note: Spacing is measured in pixels. * * Calling `textLeading()` without an argument returns the current spacing. * @param leading The new text leading to apply, in pixels * @returns If no arguments are provided, the current text leading */ textLeading(leading?: number): number; /** * Sets the font used by the text() function. * * The first parameter, `font`, sets the font. `textFont()` recognizes either * a p5.Font object or a string with the name of a * system font. For example, `'Courier New'`. * * The second parameter, `size`, is optional. It sets the font size in pixels. * This has the same effect as calling textSize(). * * Calling `textFont()` without arguments returns the current font. * * Note: `WEBGL` mode only supports fonts loaded with * loadFont(). * @param font The font to apply * @param size An optional text size to apply. * @returns If no arguments are provided, returns the current font */ textFont(font?: p5.Font | string | object, size?: number): string | p5.Font; /** * Sets or gets the current text size. * * The `textSize()` function is used to specify the size of the text * that will be rendered on the canvas. When called with an argument, it sets the * text size to the specified value (which can be a number representing pixels or a * CSS-style string, e.g., '32px', '2em'). When called without an argument, it * returns the current text size in pixels. * @param size The size to set for the text. * @returns If no arguments are provided, the current text size in pixels. */ textSize(size: number): number; textSize(): number; /** * Sets the style for system fonts when * text() is called. * * The parameter, `style`, can be either `NORMAL`, `ITALIC`, `BOLD`, or * `BOLDITALIC`. * * `textStyle()` may be overridden by CSS styling. This function doesn't * affect fonts loaded with loadFont(). * @param style The style to use * @returns If no arguments are provided, the current style */ textStyle(style: typeof p5.NORMAL | typeof p5.ITALIC | typeof p5.BOLD | typeof p5.BOLDITALIC): typeof p5.NORMAL | typeof p5.ITALIC | typeof p5.BOLD | typeof p5.BOLDITALIC; textStyle(): typeof p5.NORMAL | typeof p5.BOLD | typeof p5.ITALIC | typeof p5.BOLDITALIC; /** * Calculates the width of the given text string in pixels. * * The `textWidth()` function processes the provided text string to determine its tight bounding box * based on the current text properties such as font, textSize, and textStyle. Internally, it splits * the text into individual lines (if line breaks are present) and computes the bounding box for each * line using the renderer’s measurement functions. The final width is determined as the maximum width * among all these lines. * * For example, if the text contains multiple lines due to wrapping or explicit line breaks, textWidth() * will return the width of the longest line. * * Note: In p5.js 2.0+, leading and trailing spaces are ignored. * `textWidth(" Hello ")` returns the same width as `textWidth("Hello")`. * @param text The text to measure * @returns The width of the text */ textWidth(text: string): number; /** * Sets the style for wrapping text when * text() is called. * * The parameter, `style`, can be one of the following values: * * `WORD` starts new lines of text at spaces. If a string of text doesn't * have spaces, it may overflow the text box and the canvas. This is the * default style. * * `CHAR` starts new lines as needed to stay within the text box. * * `textWrap()` only works when the maximum width is set for a text box. For * example, calling `text('Have a wonderful day', 0, 10, 100)` sets the * maximum width to 100 pixels. * * Calling `textWrap()` without an argument returns the current style. * @param style The wrapping style to use * @returns If no arguments are provided, the current wrapping style */ textWrap(style: typeof p5.WORD | typeof p5.CHAR): typeof p5.CHAR | typeof p5.WORD; textWrap(): typeof p5.CHAR | typeof p5.WORD; /** * Computes the tight bounding box for a block of text. * * The `textBounds()` function calculates the precise pixel boundaries that enclose * the rendered text based on the current text properties (such as font, textSize, textStyle, and * alignment). If the text spans multiple lines (due to line breaks or wrapping), the function * measures each line individually and then aggregates these measurements into a single bounding box. * The resulting object contains the x and y coordinates along with the width (w) and height (h) * of the text block. * @param str The text string to measure. * @param x The x-coordinate where the text is drawn. * @param y The y-coordinate where the text is drawn. * @param width (Optional) The maximum width available for the text block. * When specified, the text may be wrapped to fit within this width. * @param height (Optional) The maximum height available for the text block. * Any lines exceeding this height will be truncated. * @returns An object with properties `x`, `y`, `w`, and `h` that represent the tight * bounding box of the rendered text. */ textBounds(str: string, x: number, y: number, width?: number, height?: number): { x: number; y: number; w: number; h: number }; /** * Sets or gets the text drawing direction. * * The textDirection() function allows you to specify the direction in which text is * rendered on the canvas. When provided with a direction parameter (such as "ltr" for * left-to-right, "rtl" for right-to-left, or "inherit"), it updates the renderer's state with that * value and applies the new setting. When called without any arguments, it returns the current text * direction. This function is particularly useful for rendering text in languages with different * writing directions. * @param direction The text direction to set ("ltr", "rtl", or "inherit"). * @returns If no arguments are provided, the current text direction, either "ltr", "rtl", or "inherit" */ textDirection(direction: string): string; textDirection(): string; /** * Sets or gets a single text property for the renderer. * * The `textProperty()` function allows you to set or retrieve a single text-related property, * such as `textAlign`, `textBaseline`, `fontStyle`, or any other property * that may be part of the renderer's state, its drawing context, or the canvas style. * * When called with a `prop` and a `value`, the function sets the property by checking * for its existence in the renderer's state, the drawing context, or the canvas style. If the property is * successfully modified, the function applies the updated text properties. If called with only the * `prop` parameter, the function returns the current value of that property. * @param prop The name of the text property to set or get. * @param value The value to set for the specified text property. If omitted, the current * value of the property is returned * @returns If no arguments are provided, the current value of the specified text property */ textProperty(prop: string, value: any): void; textProperty(prop: string): void; /** * Gets or sets text properties in batch, similar to calling `textProperty()` * multiple times. * * If an object is passed in, `textProperty(key, value)` will be called for you * on every key/value pair in the object. * * If no arguments are passed in, an object will be returned with all the current * properties. * @param properties An object whose keys are properties to set, and whose * values are what they should be set to. * @returns An object with all the possible properties and their current values. */ textProperties(properties: object): object; textProperties(): object; /** * Computes a generic (non-tight) bounding box for a block of text. * * The `fontBounds()` function calculates the bounding box for the text based on the * font's intrinsic metrics (such as `fontBoundingBoxAscent` and * `fontBoundingBoxDescent`). Unlike `textBounds()`, which measures the exact * pixel boundaries of the rendered text, `fontBounds()` provides a looser measurement * derived from the font’s default spacing. This measurement is useful for layout purposes where * a consistent approximation of the text's dimensions is desired. * @param str The text string to measure. * @param x The x-coordinate where the text is drawn. * @param y The y-coordinate where the text is drawn. * @param width (Optional) The maximum width available for the text block. * When specified, the text may be wrapped to fit within this width. * @param height (Optional) The maximum height available for the text block. * Any lines exceeding this height will be truncated. * @returns An object with properties `x`, `y`, `w`, and `h` representing the loose * bounding box of the text based on the font's intrinsic metrics. */ fontBounds(str: string, x: number, y: number, width?: number, height?: number): { x: number; y: number; w: number; h: number }; /** * Returns the loose width of a text string based on the current font. * * The `fontWidth()` function measures the width of the provided text string using * the font's default measurement (i.e., the width property from the text metrics returned by * the browser). Unlike `textWidth()`, which calculates the tight pixel boundaries * of the text glyphs, `fontWidth()` uses the font's intrinsic spacing, which may include * additional space for character spacing and kerning. This makes it useful for scenarios where * an approximate width is sufficient for layout and positioning. * @param theText The text string to measure. * @returns The loose width of the text in pixels. */ fontWidth(theText: string): number; /** * Returns the loose ascent of the text based on the font's intrinsic metrics. * * The `fontAscent()` function calculates the ascent of the text using the font's * intrinsic metrics (e.g., `fontBoundingBoxAscent`). This value represents the space * above the baseline that the font inherently occupies, and is useful for layout purposes when * an approximate vertical measurement is required. * @returns The loose ascent value in pixels. */ fontAscent(): number; /** * Returns the loose descent of the text based on the font's intrinsic metrics. * * The `fontDescent()` function calculates the descent of the text using the font's * intrinsic metrics (e.g., `fontBoundingBoxDescent`). This value represents the space * below the baseline that the font inherently occupies, and is useful for layout purposes when * an approximate vertical measurement is required. * @returns The loose descent value in pixels. */ fontDescent(): number; /** * Sets or gets the current font weight. * * The textWeight() function is used to specify the weight (thickness) of the text. * When a numeric value is provided, it sets the font weight to that value and updates the * rendering properties accordingly (including the "font-variation-settings" on the canvas style). * When called without an argument, it returns the current font weight setting. * @param weight The numeric weight value to set for the text. * @returns If no arguments are provided, the current font weight */ textWeight(weight: number): number; textWeight(): number; /** * Converts a `String` to a floating point (decimal) `Number`. * * `float()` converts strings that resemble numbers, such as `'12.34'`, into * numbers. * * The parameter, `str`, is the string value to convert. For example, calling * `float('12.34')` returns the number `12.34`. If an array of strings is * passed, as in `float(['12.34', '56.78'])`, then an array of numbers will be * returned. * * Note: If a string can't be converted to a number, as in `float('giraffe')`, * then the value `NaN` (not a number) will be returned. * @param str string to convert. * @returns converted number. */ float(str: string): number; float(ns: string[]): number[]; /** * Converts a `Boolean`, `String`, or decimal `Number` to an integer. * * `int()` converts values to integers. Integers are positive or negative * numbers without decimals. If the original value has decimals, as in -34.56, * they're removed to produce an integer such as -34. * * The parameter, `n`, is the value to convert. If `n` is a Boolean, as in * `int(false)` or `int(true)`, then the number 0 (`false`) or 1 (`true`) will * be returned. If `n` is a string or number, as in `int('45')` or * `int(67.89)`, then an integer will be returned. If an array is passed, as * in `int([12.34, 56.78])`, then an array of integers will be returned. * * Note: If a value can't be converted to a number, as in `int('giraffe')`, * then the value `NaN` (not a number) will be returned. * @param n value to convert. * @returns converted number. */ int(n: string | boolean | number): number; int(ns: any[]): number[]; /** * Converts a `Boolean` or `Number` to `String`. * * `str()` converts values to strings. See the * String reference page for guidance on using * template literals instead. * * The parameter, `n`, is the value to convert. If `n` is a Boolean, as in * `str(false)` or `str(true)`, then the value will be returned as a string, * as in `'false'` or `'true'`. If `n` is a number, as in `str(123)`, then its * value will be returned as a string, as in `'123'`. If an array is passed, * as in `str([12.34, 56.78])`, then an array of strings will be returned. * @param n value to convert. * @returns converted string. */ str(n: string | boolean | number): string; /** * Converts a `String` or `Number` to a `Boolean`. * * `boolean()` converts values to `true` or `false`. * * The parameter, `n`, is the value to convert. If `n` is a string, then * `boolean('true')` will return `true` and every other string value will * return `false`. If `n` is a number, then `boolean(0)` will return `false` * and every other numeric value will return `true`. If an array is passed, as * `in boolean([0, 1, 'true', 'blue'])`, then an array of Boolean values will * be returned. * @param n value to convert. * @returns converted Boolean value. */ boolean(n: string | boolean | number): boolean; boolean(ns: any[]): boolean[]; /** * Converts a `Boolean`, `String`, or `Number` to its byte value. * * `byte()` converts a value to an integer (whole number) between -128 and * 127. Values greater than 127 wrap around while negative values are * unchanged. For example, 128 becomes -128 and -129 remains the same. * * The parameter, `n`, is the value to convert. If `n` is a Boolean, as in * `byte(false)` or `byte(true)`, the number 0 (`false`) or 1 (`true`) will be * returned. If `n` is a string or number, as in `byte('256')` or `byte(256)`, * then the byte value will be returned. Decimal values are ignored. If an * array is passed, as in `byte([true, 123, '456'])`, then an array of byte * values will be returned. * * Note: If a value can't be converted to a number, as in `byte('giraffe')`, * then the value `NaN` (not a number) will be returned. * @param n value to convert. * @returns converted byte value. */ byte(n: string | boolean | number): number; byte(ns: any[]): number[]; /** * Converts a `Number` or `String` to a single-character `String`. * * `char()` converts numbers to their single-character string representations. * * The parameter, `n`, is the value to convert. If a number is passed, as in * `char(65)`, the corresponding single-character string is returned. If a * string is passed, as in `char('65')`, the string is converted to an integer * (whole number) and the corresponding single-character string is returned. * If an array is passed, as in `char([65, 66, 67])`, an array of * single-character strings is returned. * * See MDN * for more information about conversions. * @param n value to convert. * @returns converted single-character string. */ char(n: string | number): string; char(ns: any[]): string[]; /** * Converts a single-character `String` to a `Number`. * * `unchar()` converts single-character strings to their corresponding * integer (whole number). * * The parameter, `n`, is the character to convert. For example, * `unchar('A')`, returns the number 65. If an array is passed, as in * `unchar(['A', 'B', 'C'])`, an array of integers is returned. * @param n value to convert. * @returns converted number. */ unchar(n: string): number; unchar(ns: string[]): number[]; /** * Converts a `Number` to a `String` with its hexadecimal value. * * `hex()` converts a number to a string with its hexadecimal number value. * Hexadecimal (hex) numbers are base-16, which means there are 16 unique * digits. Hex extends the numbers 0–9 with the letters A–F. For example, the * number `11` (eleven) in base-10 is written as the letter `B` in hex. * * The first parameter, `n`, is the number to convert. For example, `hex(20)`, * returns the string `'00000014'`. If an array is passed, as in * `hex([1, 10, 100])`, an array of hexadecimal strings is returned. * * The second parameter, `digits`, is optional. If a number is passed, as in * `hex(20, 2)`, it sets the number of hexadecimal digits to display. For * example, calling `hex(20, 2)` returns the string `'14'`. * @param n value to convert. * @param digits number of digits to include. * @returns converted hexadecimal value. */ hex(n: number, digits?: number): string; hex(ns: number[], digits?: number): string[]; /** * Converts a `String` with a hexadecimal value to a `Number`. * * `unhex()` converts a string with its hexadecimal number value to a number. * Hexadecimal (hex) numbers are base-16, which means there are 16 unique * digits. Hex extends the numbers 0–9 with the letters A–F. For example, the * number `11` (eleven) in base-10 is written as the letter `B` in hex. * * The first parameter, `n`, is the hex string to convert. For example, * `unhex('FF')`, returns the number 255. If an array is passed, as in * `unhex(['00', '80', 'FF'])`, an array of numbers is returned. * @param n value to convert. * @returns converted number. */ unhex(n: string): number; unhex(ns: string[]): number[]; /** * Returns the current day as a number from 1–31. * @returns current day between 1 and 31. */ day(): number; /** * Returns the current hour as a number from 0–23. * @returns current hour between 0 and 23. */ hour(): number; /** * Returns the current minute as a number from 0–59. * @returns current minute between 0 and 59. */ minute(): number; /** * Returns the number of milliseconds since a sketch started running. * * `millis()` keeps track of how long a sketch has been running in * milliseconds (thousandths of a second). This information is often * helpful for timing events and animations. * * If a sketch has a * setup() function, then `millis()` begins tracking * time before the code in setup() runs. If a * sketch includes asynchronous loading using `async`/`await`, then * `millis()` begins tracking time as soon as the asynchronous code * starts running. * @returns number of milliseconds since starting the sketch. */ millis(): number; /** * Returns the current month as a number from 1–12. * @returns current month between 1 and 12. */ month(): number; /** * Returns the current second as a number from 0–59. * @returns current second between 0 and 59. */ second(): number; /** * Returns the current year as a number such as 1999. * @returns current year. */ year(): number; /** * Converts a `Number` into a `String` with a given number of digits. * * `nf()` converts numbers such as `123.45` into strings formatted with a set * number of digits, as in `'123.4500'`. * * The first parameter, `num`, is the number to convert to a string. For * example, calling `nf(123.45)` returns the string `'123.45'`. If an array of * numbers is passed, as in `nf([123.45, 67.89])`, an array of formatted * strings will be returned. * * The second parameter, `left`, is optional. If a number is passed, as in * `nf(123.45, 4)`, it sets the minimum number of digits to include to the * left of the decimal place. If `left` is larger than the number of digits in * `num`, then unused digits will be set to 0. For example, calling * `nf(123.45, 4)` returns the string `'0123.45'`. * * The third parameter, `right`, is also optional. If a number is passed, as * in `nf(123.45, 4, 1)`, it sets the minimum number of digits to include to * the right of the decimal place. If `right` is smaller than the number of * decimal places in `num`, then `num` will be rounded to the given number of * decimal places. For example, calling `nf(123.45, 4, 1)` returns the string * `'0123.5'`. If right is larger than the number of decimal places in `num`, * then unused decimal places will be set to 0. For example, calling * `nf(123.45, 4, 3)` returns the string `'0123.450'`. * * When the number is negative, for example, calling `nf(-123.45, 5, 2)` * returns the string `'-00123.45'`. * @param num number to format. * @param left number of digits to include to the left of * the decimal point. * @param right number of digits to include to the right * of the decimal point. * @returns formatted string. */ nf(num: number | string, left?: number | string, right?: number | string): string; nf(nums: number[], left?: number | string, right?: number | string): string[]; /** * Converts a `Number` into a `String` with commas to mark units of 1,000. * * `nfc()` converts numbers such as 12345 into strings formatted with commas * to mark the thousands place, as in `'12,345'`. * * The first parameter, `num`, is the number to convert to a string. For * example, calling `nfc(12345)` returns the string `'12,345'`. * * The second parameter, `right`, is optional. If a number is passed, as in * `nfc(12345, 1)`, it sets the minimum number of digits to include to the * right of the decimal place. If `right` is smaller than the number of * decimal places in `num`, then `num` will be rounded to the given number of * decimal places. For example, calling `nfc(12345.67, 1)` returns the string * `'12,345.7'`. If `right` is larger than the number of decimal places in * `num`, then unused decimal places will be set to 0. For example, calling * `nfc(12345.67, 3)` returns the string `'12,345.670'`. * @param num number to format. * @param right number of digits to include to the right * of the decimal point. * @returns formatted string. */ nfc(num: number | string, right?: number | string): string; nfc(nums: number[], right?: number | string): string[]; /** * Converts a `Number` into a `String` with a plus or minus sign. * * `nfp()` converts numbers such as 123 into strings formatted with a `+` or * `-` symbol to mark whether they're positive or negative, as in `'+123'`. * * The first parameter, `num`, is the number to convert to a string. For * example, calling `nfp(123.45)` returns the string `'+123.45'`. If an array * of numbers is passed, as in `nfp([123.45, -6.78])`, an array of formatted * strings will be returned. * * The second parameter, `left`, is optional. If a number is passed, as in * `nfp(123.45, 4)`, it sets the minimum number of digits to include to the * left of the decimal place. If `left` is larger than the number of digits in * `num`, then unused digits will be set to 0. For example, calling * `nfp(123.45, 4)` returns the string `'+0123.45'`. * * The third parameter, `right`, is also optional. If a number is passed, as * in `nfp(123.45, 4, 1)`, it sets the minimum number of digits to include to * the right of the decimal place. If `right` is smaller than the number of * decimal places in `num`, then `num` will be rounded to the given number of * decimal places. For example, calling `nfp(123.45, 4, 1)` returns the * string `'+0123.5'`. If `right` is larger than the number of decimal places * in `num`, then unused decimal places will be set to 0. For example, * calling `nfp(123.45, 4, 3)` returns the string `'+0123.450'`. * @param num number to format. * @param left number of digits to include to the left of the * decimal point. * @param right number of digits to include to the right of the * decimal point. * @returns formatted string. */ nfp(num: number, left?: number, right?: number): string; nfp(nums: number[], left?: number, right?: number): string[]; /** * Converts a positive `Number` into a `String` with an extra space in front. * * `nfs()` converts positive numbers such as 123.45 into strings formatted * with an extra space in front, as in ' 123.45'. Doing so can be helpful for * aligning positive and negative numbers. * * The first parameter, `num`, is the number to convert to a string. For * example, calling `nfs(123.45)` returns the string `' 123.45'`. * * The second parameter, `left`, is optional. If a number is passed, as in * `nfs(123.45, 4)`, it sets the minimum number of digits to include to the * left of the decimal place. If `left` is larger than the number of digits in * `num`, then unused digits will be set to 0. For example, calling * `nfs(123.45, 4)` returns the string `' 0123.45'`. * * The third parameter, `right`, is also optional. If a number is passed, as * in `nfs(123.45, 4, 1)`, it sets the minimum number of digits to include to * the right of the decimal place. If `right` is smaller than the number of * decimal places in `num`, then `num` will be rounded to the given number of * decimal places. For example, calling `nfs(123.45, 4, 1)` returns the * string `' 0123.5'`. If `right` is larger than the number of decimal places * in `num`, then unused decimal places will be set to 0. For example, * calling `nfs(123.45, 4, 3)` returns the string `' 0123.450'`. * @param num number to format. * @param left number of digits to include to the left of the * decimal point. * @param right number of digits to include to the right of the * decimal point. * @returns formatted string. */ nfs(num: number, left?: number, right?: number): string; nfs(nums: any[], left?: number, right?: number): string[]; /** * Splits a `String` into pieces and returns an array containing the pieces. * * `splitTokens()` is an enhanced version of * split(). It can split a string when any characters * from a list are detected. * * The first parameter, `value`, is the string to split. * * The second parameter, `delim`, is optional. It sets the character(s) that * should be used to split the string. `delim` can be a single string, as in * `splitTokens('rock...paper...scissors...shoot', '...')`, or an array of * strings, as in * `splitTokens('rock;paper,scissors...shoot, [';', ',', '...'])`. By default, * if no `delim` characters are specified, then any whitespace character is * used to split. Whitespace characters include tab (`\t`), line feed (`\n`), * carriage return (`\r`), form feed (`\f`), and space. * @param value string to split. * @param delim character(s) to use for splitting the string. * @returns separated strings. */ splitTokens(value: string, delim?: string): string[]; /** * Shuffles the elements of an array. * * The first parameter, `array`, is the array to be shuffled. For example, * calling `shuffle(myArray)` will shuffle the elements of `myArray`. By * default, the original array won’t be modified. Instead, a copy will be * created, shuffled, and returned. * * The second parameter, `modify`, is optional. If `true` is passed, as in * `shuffle(myArray, true)`, then the array will be shuffled in place without * making a copy. * @param array array to shuffle. * @param bool if `true`, shuffle the original array in place. Defaults to `false`. * @returns shuffled array. */ shuffle(array: any[], bool?: boolean): any[]; /** * Sets the stroke rendering mode to balance performance and visual features when drawing lines. * * `strokeMode()` offers two modes: * * - `SIMPLE`: Optimizes for speed by disabling caps, joins, and stroke color features. * Use this mode for faster line rendering when these visual details are unnecessary. * * - `FULL`: Enables caps, joins, and stroke color for lines. * This mode provides enhanced visuals but may reduce performance due to additional processing. * * Choose the mode that best suits your application's needs to either improve rendering speed or enhance visual quality. * @param mode The stroke mode to set. Possible values are: * * - `'SIMPLE'`: Fast rendering without caps, joins, or stroke color. * * - `'FULL'`: Detailed rendering with caps, joins, and stroke color. */ strokeMode(mode: string): void; /** * Creates a custom p5.Geometry object from * simpler 3D shapes. * * `buildGeometry()` helps with creating complex 3D shapes from simpler ones * such as sphere(). It can help to make sketches * more performant. For example, if a complex 3D shape doesn’t change while a * sketch runs, then it can be created with `buildGeometry()`. Creating a * p5.Geometry object once and then drawing it * will run faster than repeatedly drawing the individual pieces. * * The parameter, `callback`, is a function with the drawing instructions for * the new p5.Geometry object. It will be called * once to create the new 3D shape. * * See beginGeometry() and * endGeometry() for another way to build 3D * shapes. * * Note: `buildGeometry()` can only be used in WebGL mode. * @param callback function that draws the shape. * @returns new 3D shape. */ buildGeometry(callback: Function): p5.Geometry; /** * Clears a p5.Geometry object from the graphics * processing unit (GPU) memory. * * p5.Geometry objects can contain lots of data * about their vertices, surface normals, colors, and so on. Complex 3D shapes * can use lots of memory which is a limited resource in many GPUs. Calling * `freeGeometry()` can improve performance by freeing a * p5.Geometry object’s resources from GPU memory. * `freeGeometry()` works with p5.Geometry objects * created with beginGeometry() and * endGeometry(), * buildGeometry(), and * loadModel(). * * The parameter, `geometry`, is the p5.Geometry * object to be freed. * * Note: A p5.Geometry object can still be drawn * after its resources are cleared from GPU memory. It may take longer to draw * the first time it’s redrawn. * * Note: `freeGeometry()` can only be used in WebGL mode. * @param geometry 3D shape whose resources should be freed. */ freeGeometry(geometry: p5.Geometry): void; /** * Draws a plane. * * A plane is a four-sided, flat shape with every angle measuring 90˚. It’s * similar to a rectangle and offers advanced drawing features in WebGL mode. * * The first parameter, `width`, is optional. If a `Number` is passed, as in * `plane(20)`, it sets the plane’s width and height. By default, `width` is * 50. * * The second parameter, `height`, is also optional. If a `Number` is passed, * as in `plane(20, 30)`, it sets the plane’s height. By default, `height` is * set to the plane’s `width`. * * The third parameter, `detailX`, is also optional. If a `Number` is passed, * as in `plane(20, 30, 5)` it sets the number of triangle subdivisions to use * along the x-axis. All 3D shapes are made by connecting triangles to form * their surfaces. By default, `detailX` is 1. * * The fourth parameter, `detailY`, is also optional. If a `Number` is passed, * as in `plane(20, 30, 5, 7)` it sets the number of triangle subdivisions to * use along the y-axis. All 3D shapes are made by connecting triangles to * form their surfaces. By default, `detailY` is 1. * * Note: `plane()` can only be used in WebGL mode. * @param width width of the plane. * @param height height of the plane. * @param detailX number of triangle subdivisions along the x-axis. * @param detailY number of triangle subdivisions along the y-axis. */ plane(width?: number, height?: number, detailX?: number, detailY?: number): void; /** * Draws a box (rectangular prism). * * A box is a 3D shape with six faces. Each face makes a 90˚ with four * neighboring faces. * * The first parameter, `width`, is optional. If a `Number` is passed, as in * `box(20)`, it sets the box’s width and height. By default, `width` is 50. * * The second parameter, `height`, is also optional. If a `Number` is passed, * as in `box(20, 30)`, it sets the box’s height. By default, `height` is set * to the box’s `width`. * * The third parameter, `depth`, is also optional. If a `Number` is passed, as * in `box(20, 30, 40)`, it sets the box’s depth. By default, `depth` is set * to the box’s `height`. * * The fourth parameter, `detailX`, is also optional. If a `Number` is passed, * as in `box(20, 30, 40, 5)`, it sets the number of triangle subdivisions to * use along the x-axis. All 3D shapes are made by connecting triangles to * form their surfaces. By default, `detailX` is 1. * * The fifth parameter, `detailY`, is also optional. If a number is passed, as * in `box(20, 30, 40, 5, 7)`, it sets the number of triangle subdivisions to * use along the y-axis. All 3D shapes are made by connecting triangles to * form their surfaces. By default, `detailY` is 1. * * Note: `box()` can only be used in WebGL mode. * @param width width of the box. * @param height height of the box. * @param depth depth of the box. * @param detailX number of triangle subdivisions along the x-axis. * @param detailY number of triangle subdivisions along the y-axis. */ box(width?: number, height?: number, depth?: number, detailX?: number, detailY?: number): void; /** * Draws a sphere. * * A sphere is a 3D shape with triangular faces that connect to form a round * surface. Spheres with few faces look like crystals. Spheres with many faces * have smooth surfaces and look like balls. * * The first parameter, `radius`, is optional. If a `Number` is passed, as in * `sphere(20)`, it sets the radius of the sphere. By default, `radius` is 50. * * The second parameter, `detailX`, is also optional. If a `Number` is passed, * as in `sphere(20, 5)`, it sets the number of triangle subdivisions to use * along the x-axis. All 3D shapes are made by connecting triangles to form * their surfaces. By default, `detailX` is 24. * * The third parameter, `detailY`, is also optional. If a `Number` is passed, * as in `sphere(20, 5, 2)`, it sets the number of triangle subdivisions to * use along the y-axis. All 3D shapes are made by connecting triangles to * form their surfaces. By default, `detailY` is 16. * * Note: `sphere()` can only be used in WebGL mode. * @param radius radius of the sphere. Defaults to 50. * @param detailX number of triangle subdivisions along the x-axis. Defaults to 24. * @param detailY number of triangle subdivisions along the y-axis. Defaults to 16. */ sphere(radius?: number, detailX?: number, detailY?: number): void; /** * Draws a cylinder. * * A cylinder is a 3D shape with triangular faces that connect a flat bottom * to a flat top. Cylinders with few faces look like boxes. Cylinders with * many faces have smooth surfaces. * * The first parameter, `radius`, is optional. If a `Number` is passed, as in * `cylinder(20)`, it sets the radius of the cylinder’s base. By default, * `radius` is 50. * * The second parameter, `height`, is also optional. If a `Number` is passed, * as in `cylinder(20, 30)`, it sets the cylinder’s height. By default, * `height` is set to the cylinder’s `radius`. * * The third parameter, `detailX`, is also optional. If a `Number` is passed, * as in `cylinder(20, 30, 5)`, it sets the number of edges used to form the * cylinder's top and bottom. Using more edges makes the top and bottom look * more like circles. By default, `detailX` is 24. * * The fourth parameter, `detailY`, is also optional. If a `Number` is passed, * as in `cylinder(20, 30, 5, 2)`, it sets the number of triangle subdivisions * to use along the y-axis, between cylinder's the top and bottom. All 3D * shapes are made by connecting triangles to form their surfaces. By default, * `detailY` is 1. * * The fifth parameter, `bottomCap`, is also optional. If a `false` is passed, * as in `cylinder(20, 30, 5, 2, false)` the cylinder’s bottom won’t be drawn. * By default, `bottomCap` is `true`. * * The sixth parameter, `topCap`, is also optional. If a `false` is passed, as * in `cylinder(20, 30, 5, 2, false, false)` the cylinder’s top won’t be * drawn. By default, `topCap` is `true`. * * Note: `cylinder()` can only be used in WebGL mode. * @param radius radius of the cylinder. Defaults to 50. * @param height height of the cylinder. Defaults to the value of `radius`. * @param detailX number of edges along the top and bottom. Defaults to 24. * @param detailY number of triangle subdivisions along the y-axis. Defaults to 1. * @param bottomCap whether to draw the cylinder's bottom. Defaults to `true`. * @param topCap whether to draw the cylinder's top. Defaults to `true`. */ cylinder(radius?: number, height?: number, detailX?: number, detailY?: number, bottomCap?: boolean, topCap?: boolean): void; /** * Draws a cone. * * A cone is a 3D shape with triangular faces that connect a flat bottom to a * single point. Cones with few faces look like pyramids. Cones with many * faces have smooth surfaces. * * The first parameter, `radius`, is optional. If a `Number` is passed, as in * `cone(20)`, it sets the radius of the cone’s base. By default, `radius` is * 50. * * The second parameter, `height`, is also optional. If a `Number` is passed, * as in `cone(20, 30)`, it sets the cone’s height. By default, `height` is * set to the cone’s `radius`. * * The third parameter, `detailX`, is also optional. If a `Number` is passed, * as in `cone(20, 30, 5)`, it sets the number of edges used to form the * cone's base. Using more edges makes the base look more like a circle. By * default, `detailX` is 24. * * The fourth parameter, `detailY`, is also optional. If a `Number` is passed, * as in `cone(20, 30, 5, 7)`, it sets the number of triangle subdivisions to * use along the y-axis connecting the base to the tip. All 3D shapes are made * by connecting triangles to form their surfaces. By default, `detailY` is 1. * * The fifth parameter, `cap`, is also optional. If a `false` is passed, as * in `cone(20, 30, 5, 7, false)` the cone’s base won’t be drawn. By default, * `cap` is `true`. * * Note: `cone()` can only be used in WebGL mode. * @param radius radius of the cone's base. Defaults to 50. * @param height height of the cone. Defaults to the value of `radius`. * @param detailX number of edges used to draw the base. Defaults to 24. * @param detailY number of triangle subdivisions along the y-axis. Defaults to 1. * @param cap whether to draw the cone's base. Defaults to `true`. */ cone(radius?: number, height?: number, detailX?: number, detailY?: number, cap?: boolean): void; /** * Draws an ellipsoid. * * An ellipsoid is a 3D shape with triangular faces that connect to form a * round surface. Ellipsoids with few faces look like crystals. Ellipsoids * with many faces have smooth surfaces and look like eggs. `ellipsoid()` * defines a shape by its radii. This is different from * ellipse() which uses diameters * (width and height). * * The first parameter, `radiusX`, is optional. If a `Number` is passed, as in * `ellipsoid(20)`, it sets the radius of the ellipsoid along the x-axis. By * default, `radiusX` is 50. * * The second parameter, `radiusY`, is also optional. If a `Number` is passed, * as in `ellipsoid(20, 30)`, it sets the ellipsoid’s radius along the y-axis. * By default, `radiusY` is set to the ellipsoid’s `radiusX`. * * The third parameter, `radiusZ`, is also optional. If a `Number` is passed, * as in `ellipsoid(20, 30, 40)`, it sets the ellipsoid’s radius along the * z-axis. By default, `radiusZ` is set to the ellipsoid’s `radiusY`. * * The fourth parameter, `detailX`, is also optional. If a `Number` is passed, * as in `ellipsoid(20, 30, 40, 5)`, it sets the number of triangle * subdivisions to use along the x-axis. All 3D shapes are made by connecting * triangles to form their surfaces. By default, `detailX` is 24. * * The fifth parameter, `detailY`, is also optional. If a `Number` is passed, * as in `ellipsoid(20, 30, 40, 5, 7)`, it sets the number of triangle * subdivisions to use along the y-axis. All 3D shapes are made by connecting * triangles to form their surfaces. By default, `detailY` is 16. * * Note: `ellipsoid()` can only be used in WebGL mode. * @param radiusX radius of the ellipsoid along the x-axis. Defaults to 50. * @param radiusY radius of the ellipsoid along the y-axis. Defaults to `radiusX`. * @param radiusZ radius of the ellipsoid along the z-axis. Defaults to `radiusY`. * @param detailX number of triangle subdivisions along the x-axis. Defaults to 24. * @param detailY number of triangle subdivisions along the y-axis. Defaults to 16. */ ellipsoid(radiusX?: number, radiusY?: number, radiusZ?: number, detailX?: number, detailY?: number): void; /** * Draws a torus. * * A torus is a 3D shape with triangular faces that connect to form a ring. * Toruses with few faces look flattened. Toruses with many faces have smooth * surfaces. * * The first parameter, `radius`, is optional. If a `Number` is passed, as in * `torus(30)`, it sets the radius of the ring. By default, `radius` is 50. * * The second parameter, `tubeRadius`, is also optional. If a `Number` is * passed, as in `torus(30, 15)`, it sets the radius of the tube. By default, * `tubeRadius` is 10. * * The third parameter, `detailX`, is also optional. If a `Number` is passed, * as in `torus(30, 15, 5)`, it sets the number of edges used to draw the hole * of the torus. Using more edges makes the hole look more like a circle. By * default, `detailX` is 24. * * The fourth parameter, `detailY`, is also optional. If a `Number` is passed, * as in `torus(30, 15, 5, 7)`, it sets the number of triangle subdivisions to * use while filling in the torus’ height. By default, `detailY` is 16. * * Note: `torus()` can only be used in WebGL mode. * @param radius radius of the torus. Defaults to 50. * @param tubeRadius radius of the tube. Defaults to 10. * @param detailX number of edges that form the hole. Defaults to 24. * @param detailY number of triangle subdivisions along the y-axis. Defaults to 16. */ torus(radius?: number, tubeRadius?: number, detailX?: number, detailY?: number): void; /** * Sets the number of segments used to draw spline curves in WebGL mode. * * In WebGL mode, smooth shapes are drawn using many flat segments. Adding * more flat segments makes shapes appear smoother. * * The parameter, `detail`, is the density of segments to use while drawing a * spline curve. * * Note: `curveDetail()` has no effect in 2D mode. * @param resolution number of segments to use. Default is 1/4 */ curveDetail(resolution: number): void; /** * Allows the user to orbit around a 3D sketch using a mouse, trackpad, or * touchscreen. * * 3D sketches are viewed through an imaginary camera. Calling * `orbitControl()` within the draw() function allows * the user to change the camera’s position: * * `function draw() { * background(200); * * // Enable orbiting with the mouse. * orbitControl(); * * // Rest of sketch. * }`Left-clicking and dragging or swipe motion will rotate the camera position * about the center of the sketch. Right-clicking and dragging or multi-swipe * will pan the camera position without rotation. Using the mouse wheel * (scrolling) or pinch in/out will move the camera further or closer from the * center of the sketch. * * The first three parameters, `sensitivityX`, `sensitivityY`, and * `sensitivityZ`, are optional. They’re numbers that set the sketch’s * sensitivity to movement along each axis. For example, calling * `orbitControl(1, 2, -1)` keeps movement along the x-axis at its default * value, makes the sketch twice as sensitive to movement along the y-axis, * and reverses motion along the z-axis. By default, all sensitivity values * are 1. * * The fourth parameter, `options`, is also optional. It’s an object that * changes the behavior of orbiting. For example, calling * `orbitControl(1, 1, 1, options)` keeps the default sensitivity values while * changing the behaviors set with `options`. The object can have the * following properties: * * `let options = { * // Setting this to false makes mobile interactions smoother by * // preventing accidental interactions with the page while orbiting. * // By default, it's true. * disableTouchActions: true, * * // Setting this to true makes the camera always rotate in the * // direction the mouse/touch is moving. * // By default, it's false. * freeRotation: false * }; * * orbitControl(1, 1, 1, options);` * @param sensitivityX sensitivity to movement along the x-axis. Defaults to 1. * @param sensitivityY sensitivity to movement along the y-axis. Defaults to 1. * @param sensitivityZ sensitivity to movement along the z-axis. Defaults to 1. * @param options Settings for orbitControl: */ orbitControl(sensitivityX?: number, sensitivityY?: number, sensitivityZ?: number, options?: { disableTouchActions?: boolean; freeRotation?: boolean }): void; /** * Adds a grid and an axes icon to clarify orientation in 3D sketches. * * `debugMode()` adds a grid that shows where the “ground” is in a sketch. By * default, the grid will run through the origin `(0, 0, 0)` of the sketch * along the XZ plane. `debugMode()` also adds an axes icon that points along * the positive x-, y-, and z-axes. Calling `debugMode()` displays the grid * and axes icon with their default size and position. * * There are four ways to call `debugMode()` with optional parameters to * customize the debugging environment. * * The first way to call `debugMode()` has one parameter, `mode`. If the * system constant `GRID` is passed, as in `debugMode(GRID)`, then the grid * will be displayed and the axes icon will be hidden. If the constant `AXES` * is passed, as in `debugMode(AXES)`, then the axes icon will be displayed * and the grid will be hidden. * * The second way to call `debugMode()` has six parameters. The first * parameter, `mode`, selects either `GRID` or `AXES` to be displayed. The * next five parameters, `gridSize`, `gridDivisions`, `xOff`, `yOff`, and * `zOff` are optional. They’re numbers that set the appearance of the grid * (`gridSize` and `gridDivisions`) and the placement of the axes icon * (`xOff`, `yOff`, and `zOff`). For example, calling * `debugMode(20, 5, 10, 10, 10)` sets the `gridSize` to 20 pixels, the number * of `gridDivisions` to 5, and offsets the axes icon by 10 pixels along the * x-, y-, and z-axes. * * The third way to call `debugMode()` has five parameters. The first * parameter, `mode`, selects either `GRID` or `AXES` to be displayed. The * next four parameters, `axesSize`, `xOff`, `yOff`, and `zOff` are optional. * They’re numbers that set the appearance of the size of the axes icon * (`axesSize`) and its placement (`xOff`, `yOff`, and `zOff`). * * The fourth way to call `debugMode()` has nine optional parameters. The * first five parameters, `gridSize`, `gridDivisions`, `gridXOff`, `gridYOff`, * and `gridZOff` are numbers that set the appearance of the grid. For * example, calling `debugMode(100, 5, 0, 0, 0)` sets the `gridSize` to 100, * the number of `gridDivisions` to 5, and sets all the offsets to 0 so that * the grid is centered at the origin. The next four parameters, `axesSize`, * `xOff`, `yOff`, and `zOff` are numbers that set the appearance of the size * of the axes icon (`axesSize`) and its placement (`axesXOff`, `axesYOff`, * and `axesZOff`). For example, calling * `debugMode(100, 5, 0, 0, 0, 50, 10, 10, 10)` sets the `gridSize` to 100, * the number of `gridDivisions` to 5, and sets all the offsets to 0 so that * the grid is centered at the origin. It then sets the `axesSize` to 50 and * offsets the icon 10 pixels along each axis. */ debugMode(): void; debugMode(mode: typeof p5.GRID | typeof p5.AXES): void; debugMode(mode: typeof p5.GRID | typeof p5.AXES, gridSize?: number, gridDivisions?: number, xOff?: number, yOff?: number, zOff?: number): void; debugMode(mode: typeof p5.GRID | typeof p5.AXES, axesSize?: number, xOff?: number, yOff?: number, zOff?: number): void; debugMode(gridSize?: number, gridDivisions?: number, gridXOff?: number, gridYOff?: number, gridZOff?: number, axesSize?: number, axesXOff?: number, axesYOff?: number, axesZOff?: number): void; /** * Turns off debugMode() in a 3D sketch. */ noDebugMode(): void; /** * Creates a light that shines from all directions. * * Ambient light does not come from one direction. Instead, 3D shapes are * lit evenly from all sides. Ambient lights are almost always used in * combination with other types of lights. * * There are three ways to call `ambientLight()` with optional parameters to * set the light’s color. * * The first way to call `ambientLight()` has two parameters, `gray` and * `alpha`. `alpha` is optional. Grayscale and alpha values between 0 and 255 * can be passed to set the ambient light’s color, as in `ambientLight(50)` or * `ambientLight(50, 30)`. * * The second way to call `ambientLight()` has one parameter, color. A * p5.Color object, an array of color values, or a * CSS color string, as in `ambientLight('magenta')`, can be passed to set the * ambient light’s color. * * The third way to call `ambientLight()` has four parameters, `v1`, `v2`, * `v3`, and `alpha`. `alpha` is optional. RGBA, HSBA, or HSLA values can be * passed to set the ambient light’s colors, as in `ambientLight(255, 0, 0)` * or `ambientLight(255, 0, 0, 30)`. Color values will be interpreted using * the current colorMode(). * @param v1 red or hue value in the current * colorMode(). * @param v2 green or saturation value in the current * colorMode(). * @param v3 blue, brightness, or lightness value in the current * colorMode(). * @param alpha alpha (transparency) value in the current * colorMode(). */ ambientLight(v1: number, v2: number, v3: number, alpha?: number): void; ambientLight(gray: number, alpha?: number): void; ambientLight(value: string): void; ambientLight(values: number[]): void; ambientLight(color: p5.Color): void; /** * Sets the specular color for lights. * * `specularColor()` affects lights that bounce off a surface in a preferred * direction. These lights include * directionalLight(), * pointLight(), and * spotLight(). The function helps to create * highlights on p5.Geometry objects that are * styled with specularMaterial(). If a * geometry does not use * specularMaterial(), then * `specularColor()` will have no effect. * * Note: `specularColor()` doesn’t affect lights that bounce in all * directions, including ambientLight() and * imageLight(). * * There are three ways to call `specularColor()` with optional parameters to * set the specular highlight color. * * The first way to call `specularColor()` has two optional parameters, `gray` * and `alpha`. Grayscale and alpha values between 0 and 255, as in * `specularColor(50)` or `specularColor(50, 80)`, can be passed to set the * specular highlight color. * * The second way to call `specularColor()` has one optional parameter, * `color`. A p5.Color object, an array of color * values, or a CSS color string can be passed to set the specular highlight * color. * * The third way to call `specularColor()` has four optional parameters, `v1`, * `v2`, `v3`, and `alpha`. RGBA, HSBA, or HSLA values, as in * `specularColor(255, 0, 0, 80)`, can be passed to set the specular highlight * color. Color values will be interpreted using the current * colorMode(). * @param v1 red or hue value in the current * colorMode(). * @param v2 green or saturation value in the current * colorMode(). * @param v3 blue, brightness, or lightness value in the current * colorMode(). */ specularColor(v1: number, v2: number, v3: number): void; specularColor(gray: number): void; specularColor(value: string): void; specularColor(values: number[]): void; specularColor(color: p5.Color): void; /** * Creates a light that shines in one direction. * * Directional lights don’t shine from a specific point. They’re like a sun * that shines from somewhere offscreen. The light’s direction is set using * three `(x, y, z)` values between -1 and 1. For example, setting a light’s * direction as `(1, 0, 0)` will light p5.Geometry * objects from the left since the light faces directly to the right. A * maximum of 5 directional lights can be active at once. * * There are four ways to call `directionalLight()` with parameters to set the * light’s color and direction. * * The first way to call `directionalLight()` has six parameters. The first * three parameters, `v1`, `v2`, and `v3`, set the light’s color using the * current colorMode(). The last three * parameters, `x`, `y`, and `z`, set the light’s direction. For example, * `directionalLight(255, 0, 0, 1, 0, 0)` creates a red `(255, 0, 0)` light * that shines to the right `(1, 0, 0)`. * * The second way to call `directionalLight()` has four parameters. The first * three parameters, `v1`, `v2`, and `v3`, set the light’s color using the * current colorMode(). The last parameter, * `direction` sets the light’s direction using a * p5.Vector object. For example, * `directionalLight(255, 0, 0, lightDir)` creates a red `(255, 0, 0)` light * that shines in the direction the `lightDir` vector points. * * The third way to call `directionalLight()` has four parameters. The first * parameter, `color`, sets the light’s color using a * p5.Color object or an array of color values. The * last three parameters, `x`, `y`, and `z`, set the light’s direction. For * example, `directionalLight(myColor, 1, 0, 0)` creates a light that shines * to the right `(1, 0, 0)` with the color value of `myColor`. * * The fourth way to call `directionalLight()` has two parameters. The first * parameter, `color`, sets the light’s color using a * p5.Color object or an array of color values. The * second parameter, `direction`, sets the light’s direction using a * p5.Vector object. For example, * `directionalLight(myColor, lightDir)` creates a light that shines in the * direction the `lightDir` vector points with the color value of `myColor`. * @param v1 red or hue value in the current * colorMode(). * @param v2 green or saturation value in the current * colorMode(). * @param v3 blue, brightness, or lightness value in the current * colorMode(). * @param x x-component of the light's direction between -1 and 1. * @param y y-component of the light's direction between -1 and 1. * @param z z-component of the light's direction between -1 and 1. */ directionalLight(v1: number, v2: number, v3: number, x: number, y: number, z: number): void; directionalLight(v1: number, v2: number, v3: number, direction: p5.Vector): void; directionalLight(color: p5.Color | number[] | string, x: number, y: number, z: number): void; directionalLight(color: p5.Color | number[] | string, direction: p5.Vector): void; /** * Creates a light that shines from a point in all directions. * * Point lights are like light bulbs that shine in all directions. They can be * placed at different positions to achieve different lighting effects. A * maximum of 5 point lights can be active at once. * * There are four ways to call `pointLight()` with parameters to set the * light’s color and position. * * The first way to call `pointLight()` has six parameters. The first three * parameters, `v1`, `v2`, and `v3`, set the light’s color using the current * colorMode(). The last three parameters, `x`, * `y`, and `z`, set the light’s position. For example, * `pointLight(255, 0, 0, 50, 0, 0)` creates a red `(255, 0, 0)` light that * shines from the coordinates `(50, 0, 0)`. * * The second way to call `pointLight()` has four parameters. The first three * parameters, `v1`, `v2`, and `v3`, set the light’s color using the current * colorMode(). The last parameter, position sets * the light’s position using a p5.Vector object. * For example, `pointLight(255, 0, 0, lightPos)` creates a red `(255, 0, 0)` * light that shines from the position set by the `lightPos` vector. * * The third way to call `pointLight()` has four parameters. The first * parameter, `color`, sets the light’s color using a * p5.Color object or an array of color values. The * last three parameters, `x`, `y`, and `z`, set the light’s position. For * example, `directionalLight(myColor, 50, 0, 0)` creates a light that shines * from the coordinates `(50, 0, 0)` with the color value of `myColor`. * * The fourth way to call `pointLight()` has two parameters. The first * parameter, `color`, sets the light’s color using a * p5.Color object or an array of color values. The * second parameter, `position`, sets the light’s position using a * p5.Vector object. For example, * `directionalLight(myColor, lightPos)` creates a light that shines from the * position set by the `lightPos` vector with the color value of `myColor`. * @param v1 red or hue value in the current * colorMode(). * @param v2 green or saturation value in the current * colorMode(). * @param v3 blue, brightness, or lightness value in the current * colorMode(). * @param x x-coordinate of the light. * @param y y-coordinate of the light. * @param z z-coordinate of the light. */ pointLight(v1: number, v2: number, v3: number, x: number, y: number, z: number): void; pointLight(v1: number, v2: number, v3: number, position: p5.Vector): void; pointLight(color: p5.Color | number[] | string, x: number, y: number, z: number): void; pointLight(color: p5.Color | number[] | string, position: p5.Vector): void; /** * Creates an ambient light from an image. * * `imageLight()` simulates a light shining from all directions. The effect is * like placing the sketch at the center of a giant sphere that uses the image * as its texture. The image's diffuse light will be affected by * fill() and the specular reflections will be * affected by specularMaterial() and * shininess(). * * The parameter, `img`, is the p5.Image object to * use as the light source. * @param img image to use as the light source. */ imageLight(img: p5.Image): void; /** * Creates an immersive 3D background. * * `panorama()` transforms images containing 360˚ content, such as maps or * HDRIs, into immersive 3D backgrounds that surround a sketch. Exploring the * space requires changing the camera's perspective with functions such as * orbitControl() or * camera(). * @param img 360˚ image to use as the background. */ panorama(img: p5.Image): void; /** * Places an ambient and directional light in the scene. * The lights are set to ambientLight(128, 128, 128) and * directionalLight(128, 128, 128, 0, 0, -1). * * Note: lights need to be called (whether directly or indirectly) * within draw() to remain persistent in a looping program. * Placing them in setup() will cause them to only have an effect * the first time through the loop. */ lights(): void; /** * Sets the falloff rate for pointLight() * and spotLight(). * * A light’s falloff describes the intensity of its beam at a distance. For * example, a lantern has a slow falloff, a flashlight has a medium falloff, * and a laser pointer has a sharp falloff. * * `lightFalloff()` has three parameters, `constant`, `linear`, and * `quadratic`. They’re numbers used to calculate falloff at a distance, `d`, * as follows: * * `falloff = 1 / (constant + d * linear + (d * d) * quadratic)` * * Note: `constant`, `linear`, and `quadratic` should always be set to values * greater than 0. * @param constant constant value for calculating falloff. * @param linear linear value for calculating falloff. * @param quadratic quadratic value for calculating falloff. */ lightFalloff(constant: number, linear: number, quadratic: number): void; /** * Creates a light that shines from a point in one direction. * * Spot lights are like flashlights that shine in one direction creating a * cone of light. The shape of the cone can be controlled using the angle and * concentration parameters. A maximum of 5 spot lights can be active at once. * * There are eight ways to call `spotLight()` with parameters to set the * light’s color, position, direction. For example, * `spotLight(255, 0, 0, 0, 0, 0, 1, 0, 0)` creates a red `(255, 0, 0)` light * at the origin `(0, 0, 0)` that points to the right `(1, 0, 0)`. * * The `angle` parameter is optional. It sets the radius of the light cone. * For example, `spotLight(255, 0, 0, 0, 0, 0, 1, 0, 0, PI / 16)` creates a * red `(255, 0, 0)` light at the origin `(0, 0, 0)` that points to the right * `(1, 0, 0)` with an angle of `PI / 16` radians. By default, `angle` is * `PI / 3` radians. * * The `concentration` parameter is also optional. It focuses the light * towards the center of the light cone. For example, * `spotLight(255, 0, 0, 0, 0, 0, 1, 0, 0, PI / 16, 50)` creates a red * `(255, 0, 0)` light at the origin `(0, 0, 0)` that points to the right * `(1, 0, 0)` with an angle of `PI / 16` radians at concentration of 50. By * default, `concentration` is 100. * @param v1 red or hue value in the current * colorMode(). * @param v2 green or saturation value in the current * colorMode(). * @param v3 blue, brightness, or lightness value in the current * colorMode(). * @param x x-coordinate of the light. * @param y y-coordinate of the light. * @param z z-coordinate of the light. * @param rx x-component of light direction between -1 and 1. * @param ry y-component of light direction between -1 and 1. * @param rz z-component of light direction between -1 and 1. * @param angle angle of the light cone. Defaults to `PI / 3`. * @param concentration concentration of the light. Defaults to 100. */ spotLight(v1: number, v2: number, v3: number, x: number, y: number, z: number, rx: number, ry: number, rz: number, angle?: number, concentration?: number): void; spotLight(color: p5.Color | number[] | string, position: p5.Vector, direction: p5.Vector, angle?: number, concentration?: number): void; spotLight(v1: number, v2: number, v3: number, position: p5.Vector, direction: p5.Vector, angle?: number, concentration?: number): void; spotLight(color: p5.Color | number[] | string, x: number, y: number, z: number, direction: p5.Vector, angle?: number, concentration?: number): void; spotLight(color: p5.Color | number[] | string, position: p5.Vector, rx: number, ry: number, rz: number, angle?: number, concentration?: number): void; spotLight(v1: number, v2: number, v3: number, x: number, y: number, z: number, direction: p5.Vector, angle?: number, concentration?: number): void; spotLight(v1: number, v2: number, v3: number, position: p5.Vector, rx: number, ry: number, rz: number, angle?: number, concentration?: number): void; spotLight(color: p5.Color | number[] | string, x: number, y: number, z: number, rx: number, ry: number, rz: number, angle?: number, concentration?: number): void; /** * Removes all lights from the sketch. * * Calling `noLights()` removes any lights created with * lights(), * ambientLight(), * directionalLight(), * pointLight(), or * spotLight(). These functions may be called * after `noLights()` to create a new lighting scheme. */ noLights(): void; /** * Loads a 3D model to create a * p5.Geometry object. * * `loadModel()` can load 3D models from OBJ and STL files. Once the model is * loaded, it can be displayed with the * model() function, as in `model(shape)`. * * There are three ways to call `loadModel()` with optional parameters to help * process the model. * * The first parameter, `path`, is a `String` with the path to the file. Paths * to local files should be relative, as in `loadModel('assets/model.obj')`. * URLs such as `'https://example.com/model.obj'` may be blocked due to browser * security. The `path` parameter can also be defined as a `Request` * object for more advanced usage. * Note: When loading a `.obj` file that references materials stored in * `.mtl` files, p5.js will attempt to load and apply those materials. * To ensure that the `.obj` file reads the `.mtl` file correctly include the * `.mtl` file alongside it. * * The first way to call `loadModel()` has three optional parameters after the * file path. The first optional parameter, `successCallback`, is a function * to call once the model loads. For example, * `loadModel('assets/model.obj', handleModel)` will call the `handleModel()` * function once the model loads. The second optional parameter, * `failureCallback`, is a function to call if the model fails to load. For * example, `loadModel('assets/model.obj', handleModel, handleFailure)` will * call the `handleFailure()` function if an error occurs while loading. The * third optional parameter, `fileType`, is the model’s file extension as a * string. For example, * `loadModel('assets/model', handleModel, handleFailure, '.obj')` will try to * load the file model as a `.obj` file. * * The second way to call `loadModel()` has four optional parameters after the * file path. The first optional parameter is a `Boolean` value. If `true` is * passed, as in `loadModel('assets/model.obj', true)`, then the model will be * resized to ensure it fits the canvas. The next three parameters are * `successCallback`, `failureCallback`, and `fileType` as described above. * * The third way to call `loadModel()` has one optional parameter after the * file path. The optional parameter, `options`, is an `Object` with options, * as in `loadModel('assets/model.obj', options)`. The `options` object can * have the following properties: * * `let options = { * // Enables standardized size scaling during loading if set to true. * normalize: true, * * // Function to call once the model loads. * successCallback: handleModel, * * // Function to call if an error occurs while loading. * failureCallback: handleError, * * // Model's file extension. * fileType: '.stl', * * // Flips the U texture coordinates of the model. * flipU: false, * * // Flips the V texture coordinates of the model. * flipV: false * }; * * // Pass the options object to loadModel(). * loadModel('assets/model.obj', options);`This function returns a `Promise` and should be used in an `async` setup with * `await`. See the examples for the usage syntax. * * Note: There’s no support for colored STL files. STL files with color will * be rendered without color. * @param path path of the model to be loaded. * @param fileType model’s file extension. Either `'.obj'` or `'.stl'`. * @param normalize if `true`, scale the model to fit the canvas. * @param successCallback function to call once the model is loaded. Will be passed * the p5.Geometry object. * @param failureCallback function to call if the model fails to load. Will be passed an `Error` event object. * @returns the p5.Geometry object */ loadModel(path: string | Request, fileType?: string, normalize?: boolean, successCallback?: (arg0: p5.Geometry) => void, failureCallback?: (arg0: Event) => void): Promise; loadModel(path: string | Request, fileType?: string, successCallback?: (arg0: p5.Geometry) => void, failureCallback?: (arg0: Event) => void): Promise; loadModel(path: string | Request, options?: { fileType?: string; successCallback?: (arg0: p5.Geometry) => void; failureCallback?: (arg0: Event) => void; normalize?: boolean; flipU?: boolean; flipV?: boolean }): Promise; /** * Draws a p5.Geometry object to the canvas. * * The parameter, `model`, is the * p5.Geometry object to draw. * p5.Geometry objects can be built with * buildGeometry(), or * beginGeometry() and * endGeometry(). They can also be loaded from * a file with loadGeometry(). * * Note: `model()` can only be used in WebGL mode. * @param model 3D shape to be drawn. * @param count number of instances to draw. */ model(model: p5.Geometry, count?: number): void; /** * Load a 3d model from an OBJ or STL string. * * OBJ and STL files lack a built-in sense of scale, causing models exported from different programs to vary in size. * If your model doesn't display correctly, consider using `loadModel()` with `normalize` set to `true` to standardize its size. * Further adjustments can be made using the `scale()` function. * * Also, the support for colored STL files is not present. STL files with color will be * rendered without color properties. * * - Options can include: * * - `modelString`: Specifies the plain text string of either an stl or obj file to be loaded. * * - `fileType`: Defines the file extension of the model. * * - `normalize`: Enables standardized size scaling during loading if set to true. * * - `successCallback`: Callback for post-loading actions with the 3D model object. * * - `failureCallback`: Handles errors if model loading fails, receiving an event error. * * - `flipU`: Flips the U texture coordinates of the model. * * - `flipV`: Flips the V texture coordinates of the model. * @param modelString String of the object to be loaded * @param fileType The file extension of the model * (.stl, .obj). * @param normalize If true, scale the model to a * standardized size when loading * @param successCallback Function to be called * once the model is loaded. Will be passed * the 3D model object. * @param failureCallback called with event error if * the model fails to load. * @returns the p5.Geometry object */ createModel(modelString: string, fileType?: string, normalize?: boolean, successCallback?: (arg0: p5.Geometry) => void, failureCallback?: (arg0: Event) => void): p5.Geometry; createModel(modelString: string, fileType?: string, successCallback?: (arg0: p5.Geometry) => void, failureCallback?: (arg0: Event) => void): p5.Geometry; createModel(modelString: string, fileType?: string, options?: { successCallback?: (arg0: p5.Geometry) => void; failureCallback?: (arg0: Event) => void; normalize?: boolean; flipU?: boolean; flipV?: boolean }): p5.Geometry; /** * Loads vertex and fragment shaders to create a * p5.Shader object. * * Shaders are programs that run on the graphics processing unit (GPU). They * can process many pixels at the same time, making them fast for many * graphics tasks. They’re written in a language called * GLSL * and run along with the rest of the code in a sketch. * * Once the p5.Shader object is created, it can be * used with the shader() function, as in * `shader(myShader)`. A shader program consists of two files, a vertex shader * and a fragment shader. The vertex shader affects where 3D geometry is drawn * on the screen and the fragment shader affects color. * * `loadShader()` loads the vertex and fragment shaders from their `.vert` and * `.frag` files. For example, calling * `loadShader('assets/shader.vert', 'assets/shader.frag')` loads both * required shaders and returns a p5.Shader object. * * The third parameter, `successCallback`, is optional. If a function is * passed, it will be called once the shader has loaded. The callback function * can use the new p5.Shader object as its * parameter. The return value of the `successCallback()` function will be used * as the final return value of `loadShader()`. * * The fourth parameter, `failureCallback`, is also optional. If a function is * passed, it will be called if the shader fails to load. The callback * function can use the event error as its parameter. The return value of the ` * failureCallback()` function will be used as the final return value of `loadShader()`. * * This function returns a `Promise` and should be used in an `async` setup with * `await`. See the examples for the usage syntax. * * Note: Shaders can only be used in WebGL mode. * @param vertFilename path of the vertex shader to be loaded. * @param fragFilename path of the fragment shader to be loaded. * @param successCallback function to call once the shader is loaded. Can be passed the * p5.Shader object. * @param failureCallback function to call if the shader fails to load. Can be passed an * `Error` event object. * @returns new shader created from the vertex and fragment shader files. */ loadShader(vertFilename: string | Request, fragFilename: string | Request, successCallback?: Function, failureCallback?: Function): Promise; /** * Creates a new p5.Shader object. * * Shaders are programs that run on the graphics processing unit (GPU). They * can process many pixels at the same time, making them fast for many * graphics tasks. They’re written in a language called * GLSL * and run along with the rest of the code in a sketch. * * Once the p5.Shader object is created, it can be * used with the shader() function, as in * `shader(myShader)`. A shader program consists of two parts, a vertex shader * and a fragment shader. The vertex shader affects where 3D geometry is drawn * on the screen and the fragment shader affects color. * * The first parameter, `vertSrc`, sets the vertex shader. It’s a string that * contains the vertex shader program written in GLSL. * * The second parameter, `fragSrc`, sets the fragment shader. It’s a string * that contains the fragment shader program written in GLSL. * * A shader can optionally describe hooks, which are functions in GLSL that * users may choose to provide to customize the behavior of the shader using the * `modify()` method of `p5.Shader`. These are added by * describing the hooks in a third parameter, `options`, and referencing the hooks in * your `vertSrc` or `fragSrc`. Hooks for the vertex or fragment shader are described under * the `vertex` and `fragment` keys of `options`. Each one is an object. where each key is * the type and name of a hook function, and each value is a string with the * parameter list and default implementation of the hook. For example, to let users * optionally run code at the start of the vertex shader, the options object could * include: * * `{ * vertex: { * 'void beforeVertex': '() {}' * } * }`Then, in your vertex shader source, you can run a hook by calling a function * with the same name prefixed by `HOOK_`. If you want to check if the default * hook has been replaced, maybe to avoid extra overhead, you can check if the * same name prefixed by `AUGMENTED_HOOK_` has been defined: * * `void main() { * // In most cases, just calling the hook is fine: * HOOK_beforeVertex(); * * // Alternatively, for more efficiency: * #ifdef AUGMENTED_HOOK_beforeVertex * HOOK_beforeVertex(); * #endif * * // Add the rest of your shader code here! * }`Note: Only filter shaders can be used in 2D mode. All shaders can be used * in WebGL mode. * @param vertSrc source code for the vertex shader. * @param fragSrc source code for the fragment shader. * @param options An optional object describing how this shader can * be augmented with hooks. It can include: * @returns new shader object created from the * vertex and fragment shaders. */ createShader(vertSrc: string, fragSrc: string, options?: { vertex?: object; fragment?: object }): p5.Shader; /** * Creates and loads a filter shader from an external file. * @param fragFilename path to the fragment shader file * @param successCallback callback to be called once the shader is * loaded. Will be passed the * p5.Shader object. * @param failureCallback callback to be called if there is an error * loading the shader. Will be passed the * error event. * @returns a promise that resolves with a shader object */ loadFilterShader(fragFilename: string, successCallback?: Function, failureCallback?: Function): Promise; /** * Creates a p5.Shader object to be used with the * filter() function. * * `createFilterShader()` works like * createShader() but has a default vertex * shader included. `createFilterShader()` is intended to be used along with * filter() for filtering the contents of a canvas. * A filter shader will be applied to the whole canvas instead of just * p5.Geometry objects. * * The parameter, `fragSrc`, sets the fragment shader. It’s a string that * contains the fragment shader program written in * GLSL. * * The p5.Shader object that's created has some * uniforms that can be set: * * - `sampler2D tex0`, which contains the canvas contents as a texture. * * - `vec2 canvasSize`, which is the width and height of the canvas, not including pixel density. * * - `vec2 texelSize`, which is the size of a physical pixel including pixel density. This is calculated as `1.0 / (width * density)` for the pixel width and `1.0 / (height * density)` for the pixel height. * * The p5.Shader that's created also provides * `varying vec2 vTexCoord`, a coordinate with values between 0 and 1. * `vTexCoord` describes where on the canvas the pixel will be drawn. * * For more info about filters and shaders, see Adam Ferriss' repo of shader examples * or the Introduction to Shaders tutorial. * @param fragSrc source code for the fragment shader. * @returns new shader object created from the fragment shader. */ createFilterShader(fragSrc: string): p5.Shader; /** * Sets the p5.Shader object to apply while drawing. * * Shaders are programs that run on the graphics processing unit (GPU). They * can process many pixels or vertices at the same time, making them fast for * many graphics tasks. They’re written in a language called * GLSL * and run along with the rest of the code in a sketch. * p5.Shader objects can be created using the * createShader() and * loadShader() functions. * * The parameter, `s`, is the p5.Shader object to * apply. For example, calling `shader(myShader)` applies `myShader` to * process each pixel on the canvas. This only changes the fill (the inner part of shapes), * but does not affect the outlines (strokes) or any images drawn using the `image()` function. * The source code from a p5.Shader object's * fragment and vertex shaders will be compiled the first time it's passed to * `shader()`. See * MDN * for more information about compiling shaders. * * Calling resetShader() restores a sketch’s * default shaders. * * Note: Shaders can only be used in WebGL mode. * *
*

If you want to apply shaders to strokes or images, use the following methods: * * - strokeShader() : Applies a shader to the stroke (outline) of shapes, allowing independent control over the stroke rendering using shaders. * * - imageShader() : Applies a shader to images or textures, controlling how the shader modifies their appearance during rendering. * *

*
* @param s p5.Shader object * to apply. */ shader(s: p5.Shader): void; /** * Sets the p5.Shader object to apply for strokes. * * This method applies the given shader to strokes, allowing customization of * how lines and outlines are drawn in 3D space. The shader will be used for * strokes until resetShader() is called or another * strokeShader is applied. * * The shader will be used for: * * - Strokes only, regardless of whether the uniform `uStrokeWeight` is present. * * To further customize its behavior, refer to the various hooks provided by * the baseStrokeShader() method, which allow * control over stroke weight, vertex positions, colors, and more. * @param s p5.Shader object * to apply for strokes. */ strokeShader(s: p5.Shader): void; /** * Sets the p5.Shader object to apply for images. * * This method allows the user to apply a custom shader to images, enabling * advanced visual effects such as pixel manipulation, color adjustments, * or dynamic behavior. The shader will be applied to the image drawn using * the image() function. * * The shader will be used exclusively for: * * - `image()` calls, applying only when drawing 2D images. * * - This shader will NOT apply to images used in texture() or other 3D contexts. * Any attempts to use the imageShader in these cases will be ignored. * @param s p5.Shader object * to apply for images. */ imageShader(s: p5.Shader): void; /** * Get the default shader used with lights, materials, * and textures. * * You can call `baseMaterialShader().modify()` * and change any of the following hooks: * * * * * * * * * * * * * *
HookDescription
`void beforeVertex` * * Called at the start of the vertex shader. * *
`Vertex getObjectInputs` * * Update the vertex data of the model being drawn before any positioning has been applied. It takes in a `Vertex` struct, which includes: * * - `vec3 position`, the position of the vertex * * - `vec3 normal`, the direction facing out of the surface * * - `vec2 texCoord`, the texture coordinates associeted with the vertex * * - `vec4 color`, the per-vertex color * The struct can be modified and returned. * *
`Vertex getWorldInputs` * * Update the vertex data of the model being drawn after transformations such as `translate()` and `scale()` have been applied, but before the camera has been applied. It takes in a `Vertex` struct like, in the `getObjectInputs` hook above, that can be modified and returned. * *
`Vertex getCameraInputs` * * Update the vertex data of the model being drawn as they appear relative to the camera. It takes in a `Vertex` struct like, in the `getObjectInputs` hook above, that can be modified and returned. * *
`void afterVertex` * * Called at the end of the vertex shader. * *
`void beforeFragment` * * Called at the start of the fragment shader. * *
`Inputs getPixelInputs` * * Update the per-pixel inputs of the material. It takes in an `Inputs` struct, which includes: * * - `vec3 normal`, the direction pointing out of the surface * * - `vec2 texCoord`, a vector where `x` and `y` are between 0 and 1 describing the spot on a texture the pixel is mapped to, as a fraction of the texture size * * - `vec3 ambientLight`, the ambient light color on the vertex * * - `vec4 color`, the base material color of the pixel * * - `vec3 ambientMaterial`, the color of the pixel when affected by ambient light * * - `vec3 specularMaterial`, the color of the pixel when reflecting specular highlights * * - `vec3 emissiveMaterial`, the light color emitted by the pixel * * - `float shininess`, a number representing how sharp specular reflections should be, from 1 to infinity * * - `float metalness`, a number representing how mirrorlike the material should be, between 0 and 1 * The struct can be modified and returned. * *
`vec4 combineColors` * * Take in a `ColorComponents` struct containing all the different components of light, and combining them into * a single final color. The struct contains: * * - `vec3 baseColor`, the base color of the pixel * * - `float opacity`, the opacity between 0 and 1 that it should be drawn at * * - `vec3 ambientColor`, the color of the pixel when affected by ambient light * * - `vec3 specularColor`, the color of the pixel when affected by specular reflections * * - `vec3 diffuse`, the amount of diffused light hitting the pixel * * - `vec3 ambient`, the amount of ambient light hitting the pixel * * - `vec3 specular`, the amount of specular reflection hitting the pixel * * - `vec3 emissive`, the amount of light emitted by the pixel * *
`vec4 getFinalColor` * * Update the final color after mixing. It takes in a `vec4 color` and must return a modified version. * *
`void afterFragment` * * Called at the end of the fragment shader. * *
Most of the time, you will need to write your hooks in GLSL ES version 300. If you * are using WebGL 1 instead of 2, write your hooks in GLSL ES 100 instead. * * Call `baseMaterialShader().inspectHooks()` to see all the possible hooks and * their default implementations. * @returns The material shader */ baseMaterialShader(): p5.Shader; /** * Get the base shader for filters. * * You can then call `baseFilterShader().modify()` * and change the following hook: * * * * *
HookDescription
`vec4 getColor` * * Output the final color for the current pixel. It takes in two parameters: * `FilterInputs inputs`, and `in sampler2D canvasContent`, and must return a color * as a `vec4`. * * `FilterInputs inputs` is a scruct with the following properties: * * - `vec2 texCoord`, the position on the canvas, with coordinates between 0 and 1. Calling * `getTexture(canvasContent, texCoord)` returns the original color of the current pixel. * * - `vec2 canvasSize`, the width and height of the sketch. * * - `vec2 texelSize`, the size of one real pixel relative to the size of the whole canvas. * This is equivalent to `1 / (canvasSize * pixelDensity)`. * * `in sampler2D canvasContent` is a texture with the contents of the sketch, pre-filter. Call * `getTexture(canvasContent, someCoordinate)` to retrieve the color of the sketch at that coordinate, * with coordinate values between 0 and 1. * *
Most of the time, you will need to write your hooks in GLSL ES version 300. If you * are using WebGL 1, write your hooks in GLSL ES 100 instead. * @returns The filter shader */ baseFilterShader(): p5.Shader; /** * Get the shader used by `normalMaterial()`. * * You can call `baseNormalShader().modify()` * and change any of the following hooks: * * * * * * * * * * * *
HookDescription
`void beforeVertex` * * Called at the start of the vertex shader. * *
`Vertex getObjectInputs` * * Update the vertex data of the model being drawn before any positioning has been applied. It takes in a `Vertex` struct, which includes: * * - `vec3 position`, the position of the vertex * * - `vec3 normal`, the direction facing out of the surface * * - `vec2 texCoord`, the texture coordinates associeted with the vertex * * - `vec4 color`, the per-vertex color * The struct can be modified and returned. * *
`Vertex getWorldInputs` * * Update the vertex data of the model being drawn after transformations such as `translate()` and `scale()` have been applied, but before the camera has been applied. It takes in a `Vertex` struct like, in the `getObjectInputs` hook above, that can be modified and returned. * *
`Vertex getCameraInputs` * * Update the vertex data of the model being drawn as they appear relative to the camera. It takes in a `Vertex` struct like, in the `getObjectInputs` hook above, that can be modified and returned. * *
`void afterVertex` * * Called at the end of the vertex shader. * *
`void beforeFragment` * * Called at the start of the fragment shader. * *
`vec4 getFinalColor` * * Update the final color after mixing. It takes in a `vec4 color` and must return a modified version. * *
`void afterFragment` * * Called at the end of the fragment shader. * *
Most of the time, you will need to write your hooks in GLSL ES version 300. If you * are using WebGL 1 instead of 2, write your hooks in GLSL ES 100 instead. * * Call `baseNormalShader().inspectHooks()` to see all the possible hooks and * their default implementations. * @returns The `normalMaterial` shader */ baseNormalShader(): p5.Shader; /** * Get the shader used when no lights or materials are applied. * * You can call `baseColorShader().modify()` * and change any of the following hooks: * * * * * * * * * * * *
HookDescription
`void beforeVertex` * * Called at the start of the vertex shader. * *
`Vertex getObjectInputs` * * Update the vertex data of the model being drawn before any positioning has been applied. It takes in a `Vertex` struct, which includes: * * - `vec3 position`, the position of the vertex * * - `vec3 normal`, the direction facing out of the surface * * - `vec2 texCoord`, the texture coordinates associeted with the vertex * * - `vec4 color`, the per-vertex color * The struct can be modified and returned. * *
`Vertex getWorldInputs` * * Update the vertex data of the model being drawn after transformations such as `translate()` and `scale()` have been applied, but before the camera has been applied. It takes in a `Vertex` struct like, in the `getObjectInputs` hook above, that can be modified and returned. * *
`Vertex getCameraInputs` * * Update the vertex data of the model being drawn as they appear relative to the camera. It takes in a `Vertex` struct like, in the `getObjectInputs` hook above, that can be modified and returned. * *
`void afterVertex` * * Called at the end of the vertex shader. * *
`void beforeFragment` * * Called at the start of the fragment shader. * *
`vec4 getFinalColor` * * Update the final color after mixing. It takes in a `vec4 color` and must return a modified version. * *
`void afterFragment` * * Called at the end of the fragment shader. * *
Most of the time, you will need to write your hooks in GLSL ES version 300. If you * are using WebGL 1 instead of 2, write your hooks in GLSL ES 100 instead. * * Call `baseColorShader().inspectHooks()` to see all the possible hooks and * their default implementations. * @returns The color shader */ baseColorShader(): p5.Shader; /** * Get the shader used when drawing the strokes of shapes. * * You can call `baseStrokeShader().modify()` * and change any of the following hooks: * * * * * * * * * * * * * *
HookDescription
`void beforeVertex` * * Called at the start of the vertex shader. * *
`StrokeVertex getObjectInputs` * * Update the vertex data of the stroke being drawn before any positioning has been applied. It takes in a `StrokeVertex` struct, which includes: * * - `vec3 position`, the position of the vertex * * - `vec3 tangentIn`, the tangent coming in to the vertex * * - `vec3 tangentOut`, the tangent coming out of the vertex. In straight segments, this will be the same as `tangentIn`. In joins, it will be different. In caps, one of the tangents will be 0. * * - `vec4 color`, the per-vertex color * * - `float weight`, the stroke weight * The struct can be modified and returned. * *
`StrokeVertex getWorldInputs` * * Update the vertex data of the model being drawn after transformations such as `translate()` and `scale()` have been applied, but before the camera has been applied. It takes in a `StrokeVertex` struct like, in the `getObjectInputs` hook above, that can be modified and returned. * *
`StrokeVertex getCameraInputs` * * Update the vertex data of the model being drawn as they appear relative to the camera. It takes in a `StrokeVertex` struct like, in the `getObjectInputs` hook above, that can be modified and returned. * *
`void afterVertex` * * Called at the end of the vertex shader. * *
`void beforeFragment` * * Called at the start of the fragment shader. * *
`Inputs getPixelInputs` * * Update the inputs to the shader. It takes in a struct `Inputs inputs`, which includes: * * - `vec4 color`, the color of the stroke * * - `vec2 tangent`, the direction of the stroke in screen space * * - `vec2 center`, the coordinate of the center of the stroke in screen space p5.js pixels * * - `vec2 position`, the coordinate of the current pixel in screen space p5.js pixels * * - `float strokeWeight`, the thickness of the stroke in p5.js pixels * *
`bool shouldDiscard` * * Caps and joins are made by discarded pixels in the fragment shader to carve away unwanted areas. Use this to change this logic. It takes in a `bool willDiscard` and must return a modified version. * *
`vec4 getFinalColor` * * Update the final color after mixing. It takes in a `vec4 color` and must return a modified version. * *
`void afterFragment` * * Called at the end of the fragment shader. * *
Most of the time, you will need to write your hooks in GLSL ES version 300. If you * are using WebGL 1 instead of 2, write your hooks in GLSL ES 100 instead. * * Call `baseStrokeShader().inspectHooks()` to see all the possible hooks and * their default implementations. * @returns The stroke shader */ baseStrokeShader(): p5.Shader; /** * Restores the default shaders. * * `resetShader()` deactivates any shaders previously applied by * shader(), strokeShader(), * or imageShader(). * * Note: Shaders can only be used in WebGL mode. */ resetShader(): void; /** * Sets the texture that will be used on shapes. * * A texture is like a skin that wraps around a shape. `texture()` works with * built-in shapes, such as square() and * sphere(), and custom shapes created with * functions such as buildGeometry(). To * texture a geometry created with beginShape(), * uv coordinates must be passed to each * vertex() call. * * The parameter, `tex`, is the texture to apply. `texture()` can use a range * of sources including images, videos, and offscreen renderers such as * p5.Graphics and * p5.Framebuffer objects. * * To texture a geometry created with beginShape(), * you will need to specify uv coordinates in vertex(). * * Note: `texture()` can only be used in WebGL mode. * @param tex media to use as the texture. */ texture(tex: p5.Image | p5.MediaElement | p5.Graphics | p5.Texture | p5.Framebuffer | p5.FramebufferTexture): void; /** * Changes the coordinate system used for textures when they’re applied to * custom shapes. * * In order for texture() to work, a shape needs a * way to map the points on its surface to the pixels in an image. Built-in * shapes such as rect() and * box() already have these texture mappings based on * their vertices. Custom shapes created with * vertex() require texture mappings to be passed as * uv coordinates. * * Each call to vertex() must include 5 arguments, * as in `vertex(x, y, z, u, v)`, to map the vertex at coordinates `(x, y, z)` * to the pixel at coordinates `(u, v)` within an image. For example, the * corners of a rectangular image are mapped to the corners of a rectangle by default: * * `// Apply the image as a texture. * texture(img); * * // Draw the rectangle. * rect(0, 0, 30, 50);`If the image in the code snippet above has dimensions of 300 x 500 pixels, * the same result could be achieved as follows: * * `// Apply the image as a texture. * texture(img); * * // Draw the rectangle. * beginShape(); * * // Top-left. * // u: 0, v: 0 * vertex(0, 0, 0, 0, 0); * * // Top-right. * // u: 300, v: 0 * vertex(30, 0, 0, 300, 0); * * // Bottom-right. * // u: 300, v: 500 * vertex(30, 50, 0, 300, 500); * * // Bottom-left. * // u: 0, v: 500 * vertex(0, 50, 0, 0, 500); * * endShape();``textureMode()` changes the coordinate system for uv coordinates. * * The parameter, `mode`, accepts two possible constants. If `NORMAL` is * passed, as in `textureMode(NORMAL)`, then the texture’s uv coordinates can * be provided in the range 0 to 1 instead of the image’s dimensions. This can * be helpful for using the same code for multiple images of different sizes. * For example, the code snippet above could be rewritten as follows: * * `// Set the texture mode to use normalized coordinates. * textureMode(NORMAL); * * // Apply the image as a texture. * texture(img); * * // Draw the rectangle. * beginShape(); * * // Top-left. * // u: 0, v: 0 * vertex(0, 0, 0, 0, 0); * * // Top-right. * // u: 1, v: 0 * vertex(30, 0, 0, 1, 0); * * // Bottom-right. * // u: 1, v: 1 * vertex(30, 50, 0, 1, 1); * * // Bottom-left. * // u: 0, v: 1 * vertex(0, 50, 0, 0, 1); * * endShape();`By default, `mode` is `IMAGE`, which scales uv coordinates to the * dimensions of the image. Calling `textureMode(IMAGE)` applies the default. * * Note: `textureMode()` can only be used in WebGL mode. * @param mode either IMAGE or NORMAL. */ textureMode(mode: typeof p5.IMAGE | typeof p5.NORMAL): void; /** * Changes the way textures behave when a shape’s uv coordinates go beyond the * texture. * * In order for texture() to work, a shape needs a * way to map the points on its surface to the pixels in an image. Built-in * shapes such as rect() and * box() already have these texture mappings based on * their vertices. Custom shapes created with * vertex() require texture mappings to be passed as * uv coordinates. * * Each call to vertex() must include 5 arguments, * as in `vertex(x, y, z, u, v)`, to map the vertex at coordinates `(x, y, z)` * to the pixel at coordinates `(u, v)` within an image. For example, the * corners of a rectangular image are mapped to the corners of a rectangle by default: * * `// Apply the image as a texture. * texture(img); * * // Draw the rectangle. * rect(0, 0, 30, 50);`If the image in the code snippet above has dimensions of 300 x 500 pixels, * the same result could be achieved as follows: * * `// Apply the image as a texture. * texture(img); * * // Draw the rectangle. * beginShape(); * * // Top-left. * // u: 0, v: 0 * vertex(0, 0, 0, 0, 0); * * // Top-right. * // u: 300, v: 0 * vertex(30, 0, 0, 300, 0); * * // Bottom-right. * // u: 300, v: 500 * vertex(30, 50, 0, 300, 500); * * // Bottom-left. * // u: 0, v: 500 * vertex(0, 50, 0, 0, 500); * * endShape();``textureWrap()` controls how textures behave when their uv's go beyond the * texture. Doing so can produce interesting visual effects such as tiling. * For example, the custom shape above could have u-coordinates are greater * than the image’s width: * * `// Apply the image as a texture. * texture(img); * * // Draw the rectangle. * beginShape(); * vertex(0, 0, 0, 0, 0); * * // Top-right. * // u: 600 * vertex(30, 0, 0, 600, 0); * * // Bottom-right. * // u: 600 * vertex(30, 50, 0, 600, 500); * * vertex(0, 50, 0, 0, 500); * endShape();`The u-coordinates of 600 are greater than the texture image’s width of 300. * This creates interesting possibilities. * * The first parameter, `wrapX`, accepts three possible constants. If `CLAMP` * is passed, as in `textureWrap(CLAMP)`, the pixels at the edge of the * texture will extend to the shape’s edges. If `REPEAT` is passed, as in * `textureWrap(REPEAT)`, the texture will tile repeatedly until reaching the * shape’s edges. If `MIRROR` is passed, as in `textureWrap(MIRROR)`, the * texture will tile repeatedly until reaching the shape’s edges, flipping * its orientation between tiles. By default, textures `CLAMP`. * * The second parameter, `wrapY`, is optional. It accepts the same three * constants, `CLAMP`, `REPEAT`, and `MIRROR`. If one of these constants is * passed, as in `textureWRAP(MIRROR, REPEAT)`, then the texture will `MIRROR` * horizontally and `REPEAT` vertically. By default, `wrapY` will be set to * the same value as `wrapX`. * * Note: `textureWrap()` can only be used in WebGL mode. * @param wrapX either CLAMP, REPEAT, or MIRROR * @param wrapY either CLAMP, REPEAT, or MIRROR */ textureWrap(wrapX: typeof p5.CLAMP | typeof p5.REPEAT | typeof p5.MIRROR, wrapY?: typeof p5.CLAMP | typeof p5.REPEAT | typeof p5.MIRROR): void; /** * Sets the current material as a normal material. * * A normal material sets surfaces facing the x-axis to red, those facing the * y-axis to green, and those facing the z-axis to blue. Normal material isn't * affected by light. It’s often used as a placeholder material when debugging. * * Note: `normalMaterial()` can only be used in WebGL mode. */ normalMaterial(): void; /** * Sets the ambient color of shapes’ surface material. * * The `ambientMaterial()` color sets the components of the * ambientLight() color that shapes will * reflect. For example, calling `ambientMaterial(255, 255, 0)` would cause a * shape to reflect red and green light, but not blue light. * * `ambientMaterial()` can be called three ways with different parameters to * set the material’s color. * * The first way to call `ambientMaterial()` has one parameter, `gray`. * Grayscale values between 0 and 255, as in `ambientMaterial(50)`, can be * passed to set the material’s color. Higher grayscale values make shapes * appear brighter. * * The second way to call `ambientMaterial()` has one parameter, `color`. A * p5.Color object, an array of color values, or a * CSS color string, as in `ambientMaterial('magenta')`, can be passed to set * the material’s color. * * The third way to call `ambientMaterial()` has three parameters, `v1`, `v2`, * and `v3`. RGB, HSB, or HSL values, as in `ambientMaterial(255, 0, 0)`, can * be passed to set the material’s colors. Color values will be interpreted * using the current colorMode(). * * Note: `ambientMaterial()` can only be used in WebGL mode. * @param v1 red or hue value in the current * colorMode(). * @param v2 green or saturation value in the * current colorMode(). * @param v3 blue, brightness, or lightness value in the * current colorMode(). */ ambientMaterial(v1: number, v2: number, v3: number): void; ambientMaterial(gray: number): void; ambientMaterial(color: p5.Color | number[] | string): void; /** * Sets the emissive color of shapes’ surface material. * * The `emissiveMaterial()` color sets a color shapes display at full * strength, regardless of lighting. This can give the appearance that a shape * is glowing. However, emissive materials don’t actually emit light that * can affect surrounding objects. * * `emissiveMaterial()` can be called three ways with different parameters to * set the material’s color. * * The first way to call `emissiveMaterial()` has one parameter, `gray`. * Grayscale values between 0 and 255, as in `emissiveMaterial(50)`, can be * passed to set the material’s color. Higher grayscale values make shapes * appear brighter. * * The second way to call `emissiveMaterial()` has one parameter, `color`. A * p5.Color object, an array of color values, or a * CSS color string, as in `emissiveMaterial('magenta')`, can be passed to set * the material’s color. * * The third way to call `emissiveMaterial()` has four parameters, `v1`, `v2`, * `v3`, and `alpha`. `alpha` is optional. RGBA, HSBA, or HSLA values can be * passed to set the material’s colors, as in `emissiveMaterial(255, 0, 0)` or * `emissiveMaterial(255, 0, 0, 30)`. Color values will be interpreted using * the current colorMode(). * * Note: `emissiveMaterial()` can only be used in WebGL mode. * @param v1 red or hue value in the current * colorMode(). * @param v2 green or saturation value in the * current colorMode(). * @param v3 blue, brightness, or lightness value in the * current colorMode(). * @param alpha alpha value in the current * colorMode(). */ emissiveMaterial(v1: number, v2: number, v3: number, alpha?: number): void; emissiveMaterial(gray: number): void; emissiveMaterial(color: p5.Color | number[] | string): void; /** * Sets the specular color of shapes’ surface material. * * The `specularMaterial()` color sets the components of light color that * glossy coats on shapes will reflect. For example, calling * `specularMaterial(255, 255, 0)` would cause a shape to reflect red and * green light, but not blue light. * * Unlike ambientMaterial(), * `specularMaterial()` will reflect the full color of light sources including * directionalLight(), * pointLight(), * and spotLight(). This is what gives it shapes * their "shiny" appearance. The material’s shininess can be controlled by the * shininess() function. * * `specularMaterial()` can be called three ways with different parameters to * set the material’s color. * * The first way to call `specularMaterial()` has one parameter, `gray`. * Grayscale values between 0 and 255, as in `specularMaterial(50)`, can be * passed to set the material’s color. Higher grayscale values make shapes * appear brighter. * * The second way to call `specularMaterial()` has one parameter, `color`. A * p5.Color> object, an array of color values, or a CSS * color string, as in `specularMaterial('magenta')`, can be passed to set the * material’s color. * * The third way to call `specularMaterial()` has four parameters, `v1`, `v2`, * `v3`, and `alpha`. `alpha` is optional. RGBA, HSBA, or HSLA values can be * passed to set the material’s colors, as in `specularMaterial(255, 0, 0)` or * `specularMaterial(255, 0, 0, 30)`. Color values will be interpreted using * the current colorMode(). * @param gray grayscale value between 0 (black) and 255 (white). * @param alpha alpha value in the current current * colorMode(). */ specularMaterial(gray: number, alpha?: number): void; specularMaterial(v1: number, v2: number, v3: number, alpha?: number): void; specularMaterial(color: p5.Color | number[] | string): void; /** * Sets the amount of gloss ("shininess") of a * specularMaterial(). * * Shiny materials focus reflected light more than dull materials. * `shininess()` affects the way materials reflect light sources including * directionalLight(), * pointLight(), * and spotLight(). * * The parameter, `shine`, is a number that sets the amount of shininess. * `shine` must be greater than 1, which is its default value. * @param shine amount of shine. */ shininess(shine: number): void; /** * Sets the amount of "metalness" of a * specularMaterial(). * * `metalness()` can make materials appear more metallic. It affects the way * materials reflect light sources including * affects the way materials reflect light sources including * directionalLight(), * pointLight(), * spotLight(), and * imageLight(). * * The parameter, `metallic`, is a number that sets the amount of metalness. * `metallic` must be greater than 1, which is its default value. Higher * values, such as `metalness(100)`, make specular materials appear more * metallic. * @param metallic amount of metalness. */ metalness(metallic: number): void; /** * Rotates the camera in a clockwise/counter-clockwise direction. * * Rolling rotates the camera without changing its orientation. The rotation * happens in the camera’s "local" space. * * The parameter, `angle`, is the angle the camera should rotate. Passing a * positive angle, as in `myCamera.roll(0.001)`, rotates the camera in counter-clockwise direction. * Passing a negative angle, as in `myCamera.roll(-0.001)`, rotates the * camera in clockwise direction. * * Note: Angles are interpreted based on the current * angleMode(). * @param angle amount to rotate camera in current * angleMode units. */ roll(angle: number): void; /** * Sets the position and orientation of the current camera in a 3D sketch. * * `camera()` allows objects to be viewed from different angles. It has nine * parameters that are all optional. * * The first three parameters, `x`, `y`, and `z`, are the coordinates of the * camera’s position. For example, calling `camera(0, 0, 0)` places the camera * at the origin `(0, 0, 0)`. By default, the camera is placed at * `(0, 0, 800)`. * * The next three parameters, `centerX`, `centerY`, and `centerZ` are the * coordinates of the point where the camera faces. For example, calling * `camera(0, 0, 0, 10, 20, 30)` places the camera at the origin `(0, 0, 0)` * and points it at `(10, 20, 30)`. By default, the camera points at the * origin `(0, 0, 0)`. * * The last three parameters, `upX`, `upY`, and `upZ` are the components of * the "up" vector. The "up" vector orients the camera’s y-axis. For example, * calling `camera(0, 0, 0, 10, 20, 30, 0, -1, 0)` places the camera at the * origin `(0, 0, 0)`, points it at `(10, 20, 30)`, and sets the "up" vector * to `(0, -1, 0)` which is like holding it upside-down. By default, the "up" * vector is `(0, 1, 0)`. * * Note: `camera()` can only be used in WebGL mode. * @param x x-coordinate of the camera. Defaults to 0. * @param y y-coordinate of the camera. Defaults to 0. * @param z z-coordinate of the camera. Defaults to 800. * @param centerX x-coordinate of the point the camera faces. Defaults to 0. * @param centerY y-coordinate of the point the camera faces. Defaults to 0. * @param centerZ z-coordinate of the point the camera faces. Defaults to 0. * @param upX x-component of the camera’s "up" vector. Defaults to 0. * @param upY y-component of the camera’s "up" vector. Defaults to 1. * @param upZ z-component of the camera’s "up" vector. Defaults to 0. */ camera(x?: number, y?: number, z?: number, centerX?: number, centerY?: number, centerZ?: number, upX?: number, upY?: number, upZ?: number): void; /** * Sets a perspective projection for the current camera in a 3D sketch. * * In a perspective projection, shapes that are further from the camera appear * smaller than shapes that are near the camera. This technique, called * foreshortening, creates realistic 3D scenes. It’s applied by default in * WebGL mode. * * `perspective()` changes the camera’s perspective by changing its viewing * frustum. The frustum is the volume of space that’s visible to the camera. * Its shape is a pyramid with its top cut off. The camera is placed where * the top of the pyramid should be and views everything between the frustum’s * top (near) plane and its bottom (far) plane. * * The first parameter, `fovy`, is the camera’s vertical field of view. It’s * an angle that describes how tall or narrow a view the camera has. For * example, calling `perspective(0.5)` sets the camera’s vertical field of * view to 0.5 radians. By default, `fovy` is calculated based on the sketch’s * height and the camera’s default z-coordinate, which is 800. The formula for * the default `fovy` is `2 * atan(height / 2 / 800)`. * * The second parameter, `aspect`, is the camera’s aspect ratio. It’s a number * that describes the ratio of the top plane’s width to its height. For * example, calling `perspective(0.5, 1.5)` sets the camera’s field of view to * 0.5 radians and aspect ratio to 1.5, which would make shapes appear thinner * on a square canvas. By default, aspect is set to `width / height`. * * The third parameter, `near`, is the distance from the camera to the near * plane. For example, calling `perspective(0.5, 1.5, 100)` sets the camera’s * field of view to 0.5 radians, its aspect ratio to 1.5, and places the near * plane 100 pixels from the camera. Any shapes drawn less than 100 pixels * from the camera won’t be visible. By default, near is set to `0.1 * 800`, * which is 1/10th the default distance between the camera and the origin. * * The fourth parameter, `far`, is the distance from the camera to the far * plane. For example, calling `perspective(0.5, 1.5, 100, 10000)` sets the * camera’s field of view to 0.5 radians, its aspect ratio to 1.5, places the * near plane 100 pixels from the camera, and places the far plane 10,000 * pixels from the camera. Any shapes drawn more than 10,000 pixels from the * camera won’t be visible. By default, far is set to `10 * 800`, which is 10 * times the default distance between the camera and the origin. * * Note: `perspective()` can only be used in WebGL mode. * @param fovy camera frustum vertical field of view. Defaults to * `2 * atan(height / 2 / 800)`. * @param aspect camera frustum aspect ratio. Defaults to * `width / height`. * @param near distance from the camera to the near clipping plane. * Defaults to `0.1 * 800`. * @param far distance from the camera to the far clipping plane. * Defaults to `10 * 800`. */ perspective(fovy?: number, aspect?: number, near?: number, far?: number): void; /** * Enables or disables perspective for lines in 3D sketches. * * In WebGL mode, lines can be drawn with a thinner stroke when they’re * further from the camera. Doing so gives them a more realistic appearance. * * By default, lines are drawn differently based on the type of perspective * being used: * * - `perspective()` and `frustum()` simulate a realistic perspective. In * these modes, stroke weight is affected by the line’s distance from the * camera. Doing so results in a more natural appearance. `perspective()` is * the default mode for 3D sketches. * * - `ortho()` doesn’t simulate a realistic perspective. In this mode, stroke * weights are consistent regardless of the line’s distance from the camera. * Doing so results in a more predictable and consistent appearance. * * `linePerspective()` can override the default line drawing mode. * * The parameter, `enable`, is optional. It’s a `Boolean` value that sets the * way lines are drawn. If `true` is passed, as in `linePerspective(true)`, * then lines will appear thinner when they are further from the camera. If * `false` is passed, as in `linePerspective(false)`, then lines will have * consistent stroke weights regardless of their distance from the camera. By * default, `linePerspective()` is enabled. * * Calling `linePerspective()` without passing an argument returns `true` if * it's enabled and `false` if not. * * Note: `linePerspective()` can only be used in WebGL mode. * @param enable whether to enable line perspective. * @returns whether line perspective is enabled. */ linePerspective(enable: boolean): boolean; linePerspective(): boolean; /** * Sets an orthographic projection for the current camera in a 3D sketch. * * In an orthographic projection, shapes with the same size always appear the * same size, regardless of whether they are near or far from the camera. * * `ortho()` changes the camera’s perspective by changing its viewing frustum * from a truncated pyramid to a rectangular prism. The camera is placed in * front of the frustum and views everything between the frustum’s near plane * and its far plane. `ortho()` has six optional parameters to define the * frustum. * * The first four parameters, `left`, `right`, `bottom`, and `top`, set the * coordinates of the frustum’s sides, bottom, and top. For example, calling * `ortho(-100, 100, 200, -200)` creates a frustum that’s 200 pixels wide and * 400 pixels tall. By default, these coordinates are set based on the * sketch’s width and height, as in * `ortho(-width / 2, width / 2, -height / 2, height / 2)`. * * The last two parameters, `near` and `far`, set the distance of the * frustum’s near and far plane from the camera. For example, calling * `ortho(-100, 100, 200, 200, 50, 1000)` creates a frustum that’s 200 pixels * wide, 400 pixels tall, starts 50 pixels from the camera, and ends 1,000 * pixels from the camera. By default, `near` and `far` are set to 0 and * `max(width, height) + 800`, respectively. * * Note: `ortho()` can only be used in WebGL mode. * @param left x-coordinate of the frustum’s left plane. Defaults to `-width / 2`. * @param right x-coordinate of the frustum’s right plane. Defaults to `width / 2`. * @param bottom y-coordinate of the frustum’s bottom plane. Defaults to `height / 2`. * @param top y-coordinate of the frustum’s top plane. Defaults to `-height / 2`. * @param near z-coordinate of the frustum’s near plane. Defaults to 0. * @param far z-coordinate of the frustum’s far plane. Defaults to `max(width, height) + 800`. */ ortho(left?: number, right?: number, bottom?: number, top?: number, near?: number, far?: number): void; /** * Sets the frustum of the current camera in a 3D sketch. * * In a frustum projection, shapes that are further from the camera appear * smaller than shapes that are near the camera. This technique, called * foreshortening, creates realistic 3D scenes. * * `frustum()` changes the default camera’s perspective by changing its * viewing frustum. The frustum is the volume of space that’s visible to the * camera. The frustum’s shape is a pyramid with its top cut off. The camera * is placed where the top of the pyramid should be and points towards the * base of the pyramid. It views everything within the frustum. * * The first four parameters, `left`, `right`, `bottom`, and `top`, set the * coordinates of the frustum’s sides, bottom, and top. For example, calling * `frustum(-100, 100, 200, -200)` creates a frustum that’s 200 pixels wide * and 400 pixels tall. By default, these coordinates are set based on the * sketch’s width and height, as in * `ortho(-width / 20, width / 20, height / 20, -height / 20)`. * * The last two parameters, `near` and `far`, set the distance of the * frustum’s near and far plane from the camera. For example, calling * `ortho(-100, 100, 200, -200, 50, 1000)` creates a frustum that’s 200 pixels * wide, 400 pixels tall, starts 50 pixels from the camera, and ends 1,000 * pixels from the camera. By default, near is set to `0.1 * 800`, which is * 1/10th the default distance between the camera and the origin. `far` is set * to `10 * 800`, which is 10 times the default distance between the camera * and the origin. * * Note: `frustum()` can only be used in WebGL mode. * @param left x-coordinate of the frustum’s left plane. Defaults to `-width / 20`. * @param right x-coordinate of the frustum’s right plane. Defaults to `width / 20`. * @param bottom y-coordinate of the frustum’s bottom plane. Defaults to `height / 20`. * @param top y-coordinate of the frustum’s top plane. Defaults to `-height / 20`. * @param near z-coordinate of the frustum’s near plane. Defaults to `0.1 * 800`. * @param far z-coordinate of the frustum’s far plane. Defaults to `10 * 800`. */ frustum(left?: number, right?: number, bottom?: number, top?: number, near?: number, far?: number): void; /** * Creates a new p5.Camera object. * * The new camera is initialized with a default position `(0, 0, 800)` and a * default perspective projection. Its properties can be controlled with * p5.Camera methods such as * `myCamera.lookAt(0, 0, 0)`. * * Note: Every 3D sketch starts with a default camera initialized. * This camera can be controlled with the functions * camera(), * perspective(), * ortho(), and * frustum() if it's the only camera in the scene. * * Note: `createCamera()` can only be used in WebGL mode. * @returns the new camera. */ createCamera(): p5.Camera; /** * Sets the current (active) camera of a 3D sketch. * * `setCamera()` allows for switching between multiple cameras created with * createCamera(). * * Note: `setCamera()` can only be used in WebGL mode. * @param cam camera that should be made active. */ setCamera(cam: p5.Camera): void; /** * The `saveObj()` function exports `p5.Geometry` objects as * 3D models in the Wavefront .obj file format. * This way, you can use the 3D shapes you create in p5.js in other software * for rendering, animation, 3D printing, or more. * * The exported .obj file will include the faces and vertices of the `p5.Geometry`, * as well as its texture coordinates and normals, if it has them. * @param fileName The name of the file to save the model as. * If not specified, the default file name will be 'model.obj'. */ saveObj(fileName?: string): void; /** * The `saveStl()` function exports `p5.Geometry` objects as * 3D models in the STL stereolithography file format. * This way, you can use the 3D shapes you create in p5.js in other software * for rendering, animation, 3D printing, or more. * * The exported .stl file will include the faces, vertices, and normals of the `p5.Geometry`. * * By default, this method saves a text-based .stl file. Alternatively, you can save a more compact * but less human-readable binary .stl file by passing `{ binary: true }` as a second parameter. * @param fileName The name of the file to save the model as. * If not specified, the default file name will be 'model.stl'. * @param options Optional settings. */ saveStl(fileName?: string, options?: { binary?: boolean }): void; /** * Returns a Quaternion for the * axis angle representation of the rotation * @param angle Angle with which the points needs to be rotated * @param x x component of the axis vector * @param y y component of the axis vector * @param z z component of the axis vector */ fromAxisAngle(angle?: number, x?: number, y?: number, z?: number): void; /** * Multiplies a quaternion with other quaternion. * @param quat quaternion to multiply with the quaternion calling the method. */ mult(quat?: p5.Quat): void; /** * Rotates the Quaternion by the quaternion passed * which contains the axis of roation and angle of rotation * @param axesQuat axis quaternion which contains * the axis of rotation and angle of rotation */ rotateBy(axesQuat?: p5.Quat): void; /** * Set attributes for the WebGL Drawing context. * This is a way of adjusting how the WebGL * renderer works to fine-tune the display and performance. * * Note that this will reinitialize the drawing context * if called after the WebGL canvas is made. * * If an object is passed as the parameter, all attributes * not declared in the object will be set to defaults. * * The available attributes are: *
* alpha - indicates if the canvas contains an alpha buffer * default is true * * depth - indicates whether the drawing buffer has a depth buffer * of at least 16 bits - default is true * * stencil - indicates whether the drawing buffer has a stencil buffer * of at least 8 bits * * antialias - indicates whether or not to perform anti-aliasing * default is false (true in Safari) * * premultipliedAlpha - indicates that the page compositor will assume * the drawing buffer contains colors with pre-multiplied alpha * default is true * * preserveDrawingBuffer - if true the buffers will not be cleared and * and will preserve their values until cleared or overwritten by author * (note that p5 clears automatically on draw loop) * default is true * * perPixelLighting - if true, per-pixel lighting will be used in the * lighting shader otherwise per-vertex lighting is used. * default is true. * * version - either 1 or 2, to specify which WebGL version to ask for. By * default, WebGL 2 will be requested. If WebGL2 is not available, it will * fall back to WebGL 1. You can check what version is used with by looking at * the global `webglVersion` property. * @param key Name of attribute * @param value New value of named attribute */ setAttributes(key: string, value: boolean): void; setAttributes(obj: object): void; /** * GLSL built-in function acos */ acos(param0: any): any; /** * GLSL built-in function acosh */ acosh(param0: any): any; /** * GLSL built-in function asin */ asin(param0: any): any; /** * GLSL built-in function asinh */ asinh(param0: any): any; /** * GLSL built-in function atan */ atan(param0: any): any; atan(param0: any, param1: any): any; /** * GLSL built-in function atanh */ atanh(param0: any): any; /** * GLSL built-in function cos */ cos(param0: any): any; /** * GLSL built-in function cosh */ cosh(param0: any): any; /** * GLSL built-in function degrees */ degrees(param0: any): any; /** * GLSL built-in function radians */ radians(param0: any): any; /** * GLSL built-in function sin */ sin(param0: any): any; /** * GLSL built-in function sinh */ sinh(param0: any): any; /** * GLSL built-in function tan */ tan(param0: any): any; /** * GLSL built-in function tanh */ tanh(param0: any): any; /** * GLSL built-in function abs */ abs(param0: any): any; abs(param0: any): any; /** * GLSL built-in function ceil */ ceil(param0: any): any; /** * GLSL built-in function clamp */ clamp(param0: any, param1: any, param2: any): any; clamp(param0: any, param1: any, param2: any): any; clamp(param0: any, param1: any, param2: any): any; clamp(param0: any, param1: any, param2: any): any; /** * GLSL built-in function dFdx */ dFdx(param0: any): any; /** * GLSL built-in function dFdy */ dFdy(param0: any): any; /** * GLSL built-in function exp */ exp(param0: any): any; /** * GLSL built-in function exp2 */ exp2(param0: any): any; /** * GLSL built-in function floor */ floor(param0: any): any; /** * GLSL built-in function fma */ fma(param0: any, param1: any, param2: any): any; /** * GLSL built-in function fract */ fract(param0: any): any; /** * GLSL built-in function fwidth */ fwidth(param0: any): any; /** * GLSL built-in function inversesqrt */ inversesqrt(param0: any): any; /** * GLSL built-in function log */ log(param0: any): any; /** * GLSL built-in function log2 */ log2(param0: any): any; /** * GLSL built-in function max */ max(param0: any, param1: any): any; max(param0: any, param1: any): any; max(param0: any, param1: any): any; max(param0: any, param1: any): any; /** * GLSL built-in function min */ min(param0: any, param1: any): any; min(param0: any, param1: any): any; min(param0: any, param1: any): any; min(param0: any, param1: any): any; /** * GLSL built-in function mix */ mix(param0: any, param1: any, param2: any): any; mix(param0: any, param1: any, param2: any): any; mix(param0: any, param1: any, param2: any): any; /** * GLSL built-in function mod */ mod(param0: any, param1: any): any; mod(param0: any, param1: any): any; /** * GLSL built-in function pow */ pow(param0: any, param1: any): any; /** * GLSL built-in function round */ round(param0: any): any; /** * GLSL built-in function roundEven */ roundEven(param0: any): any; /** * GLSL built-in function sign */ sign(param0: any): any; sign(param0: any): any; /** * GLSL built-in function smoothstep */ smoothstep(param0: any, param1: any, param2: any): any; smoothstep(param0: any, param1: any, param2: any): any; /** * GLSL built-in function sqrt */ sqrt(param0: any): any; /** * GLSL built-in function step */ step(param0: any, param1: any): any; /** * GLSL built-in function trunc */ trunc(param0: any): any; /** * GLSL built-in function cross */ cross(param0: any, param1: any): any; /** * GLSL built-in function distance */ distance(param0: any, param1: any): any; /** * GLSL built-in function dot */ dot(param0: any, param1: any): any; /** * GLSL built-in function equal */ equal(param0: any, param1: any): any; equal(param0: any, param1: any): any; equal(param0: any, param1: any): any; /** * GLSL built-in function faceforward */ faceforward(param0: any, param1: any, param2: any): any; /** * GLSL built-in function length */ length(param0: any): any; /** * GLSL built-in function normalize */ normalize(param0: any): any; /** * GLSL built-in function notEqual */ notEqual(param0: any, param1: any): any; notEqual(param0: any, param1: any): any; notEqual(param0: any, param1: any): any; /** * GLSL built-in function reflect */ reflect(param0: any, param1: any): any; /** * GLSL built-in function refract */ refract(param0: any, param1: any, param2: any): any; /** * GLSL built-in function texture */ texture(param0: any, param1: any): any; /** * GLSL built-in function getTexture */ getTexture(param0: any, param1: any): any; /** * Create a Float uniform variable */ uniformFloat(name: string, defaultValue?: any): any; /** * Create a Vec2 uniform variable */ uniformVec2(name: string, defaultValue?: any): any; /** * Create a Vector2 uniform variable */ uniformVector2(name: string, defaultValue?: any): any; /** * Create a Vec3 uniform variable */ uniformVec3(name: string, defaultValue?: any): any; /** * Create a Vector3 uniform variable */ uniformVector3(name: string, defaultValue?: any): any; /** * Create a Vec4 uniform variable */ uniformVec4(name: string, defaultValue?: any): any; /** * Create a Vector4 uniform variable */ uniformVector4(name: string, defaultValue?: any): any; /** * Create a Int uniform variable */ uniformInt(name: string, defaultValue?: any): any; /** * Create a IVec2 uniform variable */ uniformIVec2(name: string, defaultValue?: any): any; /** * Create a IVec3 uniform variable */ uniformIVec3(name: string, defaultValue?: any): any; /** * Create a IVec4 uniform variable */ uniformIVec4(name: string, defaultValue?: any): any; /** * Create a Bool uniform variable */ uniformBool(name: string, defaultValue?: any): any; /** * Create a BVec2 uniform variable */ uniformBVec2(name: string, defaultValue?: any): any; /** * Create a BVec3 uniform variable */ uniformBVec3(name: string, defaultValue?: any): any; /** * Create a BVec4 uniform variable */ uniformBVec4(name: string, defaultValue?: any): any; /** * Create a Mat2x2 uniform variable */ uniformMat2x2(name: string, defaultValue?: any): any; /** * Create a Mat3x3 uniform variable */ uniformMat3x3(name: string, defaultValue?: any): any; /** * Create a Mat4x4 uniform variable */ uniformMat4x4(name: string, defaultValue?: any): any; /** * Create a Sampler2d uniform variable */ uniformSampler2d(name: string, defaultValue?: any): any; /** * GLSL type constructor for float */ float(value: any): any; /** * GLSL type constructor for vec2 */ vec2(value: any): any; /** * GLSL type constructor for vec3 */ vec3(value: any): any; /** * GLSL type constructor for vec4 */ vec4(value: any): any; /** * GLSL type constructor for int */ int(value: any): any; /** * GLSL type constructor for ivec2 */ ivec2(value: any): any; /** * GLSL type constructor for ivec3 */ ivec3(value: any): any; /** * GLSL type constructor for ivec4 */ ivec4(value: any): any; /** * GLSL type constructor for bool */ bool(value: any): any; /** * GLSL type constructor for bvec2 */ bvec2(value: any): any; /** * GLSL type constructor for bvec3 */ bvec3(value: any): any; /** * GLSL type constructor for bvec4 */ bvec4(value: any): any; /** * GLSL type constructor for mat2x2 */ mat2x2(value: any): any; /** * GLSL type constructor for mat3x3 */ mat3x3(value: any): any; /** * GLSL type constructor for mat4x4 */ mat4x4(value: any): any; /** * GLSL type constructor for sampler2D */ sampler2D(value: any): any; readonly RGB: typeof RGB; readonly RGBHDR: typeof RGBHDR; readonly HSB: typeof HSB; readonly HSL: typeof HSL; readonly HWB: typeof HWB; readonly LAB: typeof LAB; readonly LCH: typeof LCH; readonly OKLAB: typeof OKLAB; readonly OKLCH: typeof OKLCH; readonly RGBA: typeof RGBA; readonly VERSION: typeof VERSION; readonly P2D: typeof P2D; readonly P2DHDR: typeof P2DHDR; readonly WEBGL: typeof WEBGL; readonly WEBGL2: typeof WEBGL2; readonly ARROW: typeof ARROW; readonly SIMPLE: typeof SIMPLE; readonly FULL: typeof FULL; readonly CROSS: typeof CROSS; readonly HAND: typeof HAND; readonly MOVE: typeof MOVE; readonly TEXT: typeof TEXT; readonly WAIT: typeof WAIT; readonly HALF_PI: typeof HALF_PI; readonly PI: typeof PI; readonly QUARTER_PI: typeof QUARTER_PI; readonly TAU: typeof TAU; readonly TWO_PI: typeof TWO_PI; readonly DEG_TO_RAD: typeof DEG_TO_RAD; readonly RAD_TO_DEG: typeof RAD_TO_DEG; readonly CORNER: typeof CORNER; readonly CORNERS: typeof CORNERS; readonly RADIUS: typeof RADIUS; readonly RIGHT: typeof RIGHT; readonly LEFT: typeof LEFT; readonly CENTER: typeof CENTER; readonly TOP: typeof TOP; readonly BOTTOM: typeof BOTTOM; readonly BASELINE: typeof BASELINE; readonly POINTS: typeof POINTS; readonly LINES: typeof LINES; readonly LINE_STRIP: typeof LINE_STRIP; readonly LINE_LOOP: typeof LINE_LOOP; readonly TRIANGLES: typeof TRIANGLES; readonly TRIANGLE_FAN: typeof TRIANGLE_FAN; readonly TRIANGLE_STRIP: typeof TRIANGLE_STRIP; readonly QUADS: typeof QUADS; readonly QUAD_STRIP: typeof QUAD_STRIP; readonly TESS: typeof TESS; readonly EMPTY_PATH: typeof EMPTY_PATH; readonly PATH: typeof PATH; readonly CLOSE: typeof CLOSE; readonly OPEN: typeof OPEN; readonly CHORD: typeof CHORD; readonly PIE: typeof PIE; readonly PROJECT: typeof PROJECT; readonly SQUARE: typeof SQUARE; readonly ROUND: typeof ROUND; readonly BEVEL: typeof BEVEL; readonly MITER: typeof MITER; readonly AUTO: typeof AUTO; readonly ALT: typeof ALT; readonly BACKSPACE: typeof BACKSPACE; readonly CONTROL: typeof CONTROL; readonly DELETE: typeof DELETE; readonly DOWN_ARROW: typeof DOWN_ARROW; readonly ENTER: typeof ENTER; readonly ESCAPE: typeof ESCAPE; readonly LEFT_ARROW: typeof LEFT_ARROW; readonly OPTION: typeof OPTION; readonly RETURN: typeof RETURN; readonly RIGHT_ARROW: typeof RIGHT_ARROW; readonly SHIFT: typeof SHIFT; readonly TAB: typeof TAB; readonly UP_ARROW: typeof UP_ARROW; readonly BLEND: typeof BLEND; readonly REMOVE: typeof REMOVE; readonly ADD: typeof ADD; readonly DARKEST: typeof DARKEST; readonly LIGHTEST: typeof LIGHTEST; readonly DIFFERENCE: typeof DIFFERENCE; readonly SUBTRACT: typeof SUBTRACT; readonly EXCLUSION: typeof EXCLUSION; readonly MULTIPLY: typeof MULTIPLY; readonly SCREEN: typeof SCREEN; readonly REPLACE: typeof REPLACE; readonly OVERLAY: typeof OVERLAY; readonly HARD_LIGHT: typeof HARD_LIGHT; readonly SOFT_LIGHT: typeof SOFT_LIGHT; readonly DODGE: typeof DODGE; readonly BURN: typeof BURN; readonly THRESHOLD: typeof THRESHOLD; readonly GRAY: typeof GRAY; readonly OPAQUE: typeof OPAQUE; readonly INVERT: typeof INVERT; readonly POSTERIZE: typeof POSTERIZE; readonly DILATE: typeof DILATE; readonly ERODE: typeof ERODE; readonly BLUR: typeof BLUR; readonly NORMAL: typeof NORMAL; readonly ITALIC: typeof ITALIC; readonly BOLD: typeof BOLD; readonly BOLDITALIC: typeof BOLDITALIC; readonly CHAR: typeof CHAR; readonly WORD: typeof WORD; readonly LINEAR: typeof LINEAR; readonly QUADRATIC: typeof QUADRATIC; readonly BEZIER: typeof BEZIER; readonly CURVE: typeof CURVE; readonly STROKE: typeof STROKE; readonly FILL: typeof FILL; readonly TEXTURE: typeof TEXTURE; readonly IMMEDIATE: typeof IMMEDIATE; readonly IMAGE: typeof IMAGE; readonly NEAREST: typeof NEAREST; readonly REPEAT: typeof REPEAT; readonly CLAMP: typeof CLAMP; readonly MIRROR: typeof MIRROR; readonly FLAT: typeof FLAT; readonly SMOOTH: typeof SMOOTH; readonly LANDSCAPE: typeof LANDSCAPE; readonly PORTRAIT: typeof PORTRAIT; readonly GRID: typeof GRID; readonly AXES: typeof AXES; readonly LABEL: typeof LABEL; readonly FALLBACK: typeof FALLBACK; readonly CONTAIN: typeof CONTAIN; readonly COVER: typeof COVER; readonly UNSIGNED_BYTE: typeof UNSIGNED_BYTE; readonly UNSIGNED_INT: typeof UNSIGNED_INT; readonly FLOAT: typeof FLOAT; readonly HALF_FLOAT: typeof HALF_FLOAT; readonly INCLUDE: typeof INCLUDE; readonly EXCLUDE: typeof EXCLUDE; readonly frameCount: typeof frameCount; readonly deltaTime: typeof deltaTime; readonly focused: typeof focused; readonly webglVersion: typeof webglVersion; readonly displayWidth: typeof displayWidth; readonly displayHeight: typeof displayHeight; readonly windowWidth: typeof windowWidth; readonly windowHeight: typeof windowHeight; readonly deviceOrientation: typeof deviceOrientation; readonly accelerationX: typeof accelerationX; readonly accelerationY: typeof accelerationY; readonly accelerationZ: typeof accelerationZ; readonly pAccelerationX: typeof pAccelerationX; readonly pAccelerationY: typeof pAccelerationY; readonly pAccelerationZ: typeof pAccelerationZ; readonly rotationX: typeof rotationX; readonly rotationY: typeof rotationY; readonly rotationZ: typeof rotationZ; readonly pRotationX: typeof pRotationX; readonly pRotationY: typeof pRotationY; readonly pRotationZ: typeof pRotationZ; readonly turnAxis: typeof turnAxis; readonly keyIsPressed: typeof keyIsPressed; readonly key: typeof key; readonly code: typeof code; readonly keyCode: typeof keyCode; readonly movedX: typeof movedX; readonly movedY: typeof movedY; readonly mouseX: typeof mouseX; readonly mouseY: typeof mouseY; readonly pmouseX: typeof pmouseX; readonly pmouseY: typeof pmouseY; readonly winMouseX: typeof winMouseX; readonly winMouseY: typeof winMouseY; readonly pwinMouseX: typeof pwinMouseX; readonly pwinMouseY: typeof pwinMouseY; readonly mouseButton: typeof mouseButton; readonly touches: typeof touches; readonly mouseIsPressed: typeof mouseIsPressed; readonly width: typeof width; readonly height: typeof height; disableFriendlyErrors: typeof disableFriendlyErrors; readonly drawingContext: typeof drawingContext; readonly VIDEO: typeof VIDEO; readonly AUDIO: typeof AUDIO; readonly pixels: typeof pixels; readonly DEGREES: typeof DEGREES; readonly RADIANS: typeof RADIANS; } declare const __p5: typeof p5; declare namespace p5 { const p5: typeof __p5; const RGB: typeof __RGB; const RGBHDR: typeof __RGBHDR; const HSB: typeof __HSB; const HSL: typeof __HSL; const HWB: typeof __HWB; const LAB: typeof __LAB; const LCH: typeof __LCH; const OKLAB: typeof __OKLAB; const OKLCH: typeof __OKLCH; const RGBA: typeof __RGBA; const VERSION: typeof __VERSION; const P2D: typeof __P2D; const P2DHDR: typeof __P2DHDR; const WEBGL: typeof __WEBGL; const WEBGL2: typeof __WEBGL2; const ARROW: typeof __ARROW; const SIMPLE: typeof __SIMPLE; const FULL: typeof __FULL; const CROSS: typeof __CROSS; const HAND: typeof __HAND; const MOVE: typeof __MOVE; const TEXT: typeof __TEXT; const WAIT: typeof __WAIT; const HALF_PI: typeof __HALF_PI; const PI: typeof __PI; const QUARTER_PI: typeof __QUARTER_PI; const TAU: typeof __TAU; const TWO_PI: typeof __TWO_PI; const DEG_TO_RAD: typeof __DEG_TO_RAD; const RAD_TO_DEG: typeof __RAD_TO_DEG; const CORNER: typeof __CORNER; const CORNERS: typeof __CORNERS; const RADIUS: typeof __RADIUS; const RIGHT: typeof __RIGHT; const LEFT: typeof __LEFT; const CENTER: typeof __CENTER; const TOP: typeof __TOP; const BOTTOM: typeof __BOTTOM; const BASELINE: typeof __BASELINE; const POINTS: typeof __POINTS; const LINES: typeof __LINES; const LINE_STRIP: typeof __LINE_STRIP; const LINE_LOOP: typeof __LINE_LOOP; const TRIANGLES: typeof __TRIANGLES; const TRIANGLE_FAN: typeof __TRIANGLE_FAN; const TRIANGLE_STRIP: typeof __TRIANGLE_STRIP; const QUADS: typeof __QUADS; const QUAD_STRIP: typeof __QUAD_STRIP; const TESS: typeof __TESS; const EMPTY_PATH: typeof __EMPTY_PATH; const PATH: typeof __PATH; const CLOSE: typeof __CLOSE; const OPEN: typeof __OPEN; const CHORD: typeof __CHORD; const PIE: typeof __PIE; const PROJECT: typeof __PROJECT; const SQUARE: typeof __SQUARE; const ROUND: typeof __ROUND; const BEVEL: typeof __BEVEL; const MITER: typeof __MITER; const AUTO: typeof __AUTO; const ALT: typeof __ALT; const BACKSPACE: typeof __BACKSPACE; const CONTROL: typeof __CONTROL; const DELETE: typeof __DELETE; const DOWN_ARROW: typeof __DOWN_ARROW; const ENTER: typeof __ENTER; const ESCAPE: typeof __ESCAPE; const LEFT_ARROW: typeof __LEFT_ARROW; const OPTION: typeof __OPTION; const RETURN: typeof __RETURN; const RIGHT_ARROW: typeof __RIGHT_ARROW; const SHIFT: typeof __SHIFT; const TAB: typeof __TAB; const UP_ARROW: typeof __UP_ARROW; const BLEND: typeof __BLEND; const REMOVE: typeof __REMOVE; const ADD: typeof __ADD; const DARKEST: typeof __DARKEST; const LIGHTEST: typeof __LIGHTEST; const DIFFERENCE: typeof __DIFFERENCE; const SUBTRACT: typeof __SUBTRACT; const EXCLUSION: typeof __EXCLUSION; const MULTIPLY: typeof __MULTIPLY; const SCREEN: typeof __SCREEN; const REPLACE: typeof __REPLACE; const OVERLAY: typeof __OVERLAY; const HARD_LIGHT: typeof __HARD_LIGHT; const SOFT_LIGHT: typeof __SOFT_LIGHT; const DODGE: typeof __DODGE; const BURN: typeof __BURN; const THRESHOLD: typeof __THRESHOLD; const GRAY: typeof __GRAY; const OPAQUE: typeof __OPAQUE; const INVERT: typeof __INVERT; const POSTERIZE: typeof __POSTERIZE; const DILATE: typeof __DILATE; const ERODE: typeof __ERODE; const BLUR: typeof __BLUR; const NORMAL: typeof __NORMAL; const ITALIC: typeof __ITALIC; const BOLD: typeof __BOLD; const BOLDITALIC: typeof __BOLDITALIC; const CHAR: typeof __CHAR; const WORD: typeof __WORD; const LINEAR: typeof __LINEAR; const QUADRATIC: typeof __QUADRATIC; const BEZIER: typeof __BEZIER; const CURVE: typeof __CURVE; const STROKE: typeof __STROKE; const FILL: typeof __FILL; const TEXTURE: typeof __TEXTURE; const IMMEDIATE: typeof __IMMEDIATE; const IMAGE: typeof __IMAGE; const NEAREST: typeof __NEAREST; const REPEAT: typeof __REPEAT; const CLAMP: typeof __CLAMP; const MIRROR: typeof __MIRROR; const FLAT: typeof __FLAT; const SMOOTH: typeof __SMOOTH; const LANDSCAPE: typeof __LANDSCAPE; const PORTRAIT: typeof __PORTRAIT; const GRID: typeof __GRID; const AXES: typeof __AXES; const LABEL: typeof __LABEL; const FALLBACK: typeof __FALLBACK; const CONTAIN: typeof __CONTAIN; const COVER: typeof __COVER; const UNSIGNED_BYTE: typeof __UNSIGNED_BYTE; const UNSIGNED_INT: typeof __UNSIGNED_INT; const FLOAT: typeof __FLOAT; const HALF_FLOAT: typeof __HALF_FLOAT; const INCLUDE: typeof __INCLUDE; const EXCLUDE: typeof __EXCLUDE; const frameCount: typeof __frameCount; const deltaTime: typeof __deltaTime; const focused: typeof __focused; const webglVersion: typeof __webglVersion; const displayWidth: typeof __displayWidth; const displayHeight: typeof __displayHeight; const windowWidth: typeof __windowWidth; const windowHeight: typeof __windowHeight; const deviceOrientation: typeof __deviceOrientation; const accelerationX: typeof __accelerationX; const accelerationY: typeof __accelerationY; const accelerationZ: typeof __accelerationZ; const pAccelerationX: typeof __pAccelerationX; const pAccelerationY: typeof __pAccelerationY; const pAccelerationZ: typeof __pAccelerationZ; const rotationX: typeof __rotationX; const rotationY: typeof __rotationY; const rotationZ: typeof __rotationZ; const pRotationX: typeof __pRotationX; const pRotationY: typeof __pRotationY; const pRotationZ: typeof __pRotationZ; const turnAxis: typeof __turnAxis; const keyIsPressed: typeof __keyIsPressed; const key: typeof __key; const code: typeof __code; const keyCode: typeof __keyCode; const movedX: typeof __movedX; const movedY: typeof __movedY; const mouseX: typeof __mouseX; const mouseY: typeof __mouseY; const pmouseX: typeof __pmouseX; const pmouseY: typeof __pmouseY; const winMouseX: typeof __winMouseX; const winMouseY: typeof __winMouseY; const pwinMouseX: typeof __pwinMouseX; const pwinMouseY: typeof __pwinMouseY; const mouseButton: typeof __mouseButton; const touches: typeof __touches; const mouseIsPressed: typeof __mouseIsPressed; const width: typeof __width; const height: typeof __height; let disableFriendlyErrors: typeof __disableFriendlyErrors; const drawingContext: typeof __drawingContext; const VIDEO: typeof __VIDEO; const AUDIO: typeof __AUDIO; const pixels: typeof __pixels; const DEGREES: typeof __DEGREES; const RADIANS: typeof __RADIANS; /** * A class to describe a color. * * Each `p5.Color` object stores the color mode * and level maxes that were active during its construction. These values are * used to interpret the arguments passed to the object's constructor. They * also determine output formatting such as when * saturation() is called. * * Color is stored internally as an array of ideal RGBA values in floating * point form, normalized from 0 to 1. These values are used to calculate the * closest screen colors, which are RGBA levels from 0 to 255. Screen colors * are sent to the renderer. * * When different color representations are calculated, the results are cached * for performance. These values are normalized, floating-point numbers. * * Note: color() is the recommended way to create an * instance of this class. */ class Color { constructor(pInst: p5, vals: number[] | string); /** * Returns the color formatted as a `String`. * * Calling `myColor.toString()` can be useful for debugging, as in * `print(myColor.toString())`. It's also helpful for using p5.js with other * libraries. * * The parameter, `format`, is optional. If a format string is passed, as in * `myColor.toString('#rrggbb')`, it will determine how the color string is * formatted. By default, color strings are formatted as `'rgba(r, g, b, a)'`. * @param format how the color string will be formatted. * Leaving this empty formats the string as rgba(r, g, b, a). * '#rgb' '#rgba' '#rrggbb' and '#rrggbbaa' format as hexadecimal color codes. * 'rgb' 'hsb' and 'hsl' return the color formatted in the specified color mode. * 'rgba' 'hsba' and 'hsla' are the same as above but with alpha channels. * 'rgb%' 'hsb%' 'hsl%' 'rgba%' 'hsba%' and 'hsla%' format as percentages. * @returns the formatted string. */ toString(format?: string): string; toString(format?: string): string; toString(format?: string): string; toString(format?: string): string; toString(format?: string): string; /** * Checks the contrast between two colors. This method returns a boolean * value to indicate if the two color has enough contrast. `true` means that * the colors has enough contrast to be used as background color and body * text color. `false` means there is not enough contrast. * * A second argument can be passed to the method, `options` , which defines * the algorithm to be used. The algorithms currently supported are * WCAG 2.1 (`'WCAG21'`) or APCA (`'APCA'`). The default is WCAG 2.1. If a * value of `'all'` is passed to the `options` argument, an object containing * more details is returned. The details object will include the calculated * contrast value of the colors and different passing criteria. * * For more details about color contrast, you can check out * this page from color.js, and the * WebAIM color contrast checker. */ contrast(other: Color): boolean | object; contrast(other: Color): boolean | object; contrast(other: Color): boolean | object; contrast(other: Color): boolean | object; contrast(other: Color): boolean | object; /** * Sets the red component of a color. * * The range depends on the colorMode(). In the * default RGB mode it's between 0 and 255. * @param red the new red value. */ setRed(red: number): void; setRed(red: number): void; setRed(red: number): void; setRed(red: number): void; setRed(red: number): void; /** * Sets the green component of a color. * * The range depends on the colorMode(). In the * default RGB mode it's between 0 and 255. * @param green the new green value. */ setGreen(green: number): void; setGreen(green: number): void; setGreen(green: number): void; setGreen(green: number): void; setGreen(green: number): void; /** * Sets the blue component of a color. * * The range depends on the colorMode(). In the * default RGB mode it's between 0 and 255. * @param blue the new blue value. */ setBlue(blue: number): void; setBlue(blue: number): void; setBlue(blue: number): void; setBlue(blue: number): void; setBlue(blue: number): void; /** * Sets the alpha (transparency) value of a color. * * The range depends on the * colorMode(). In the default RGB mode it's * between 0 and 255. * @param alpha the new alpha value. */ setAlpha(alpha: number): void; setAlpha(alpha: number): void; setAlpha(alpha: number): void; setAlpha(alpha: number): void; setAlpha(alpha: number): void; } /** * A class to describe a drawing surface that's separate from the main canvas. * * Each `p5.Graphics` object provides a dedicated drawing surface called a * graphics buffer. Graphics buffers are helpful when drawing should happen * offscreen. For example, separate scenes can be drawn offscreen and * displayed only when needed. * * `p5.Graphics` objects have nearly all the drawing features of the main * canvas. For example, calling the method `myGraphics.circle(50, 50, 20)` * draws to the graphics buffer. The resulting image can be displayed on the * main canvas by passing the `p5.Graphics` object to the * image() function, as in `image(myGraphics, 0, 0)`. * * Note: createGraphics() is the recommended * way to create an instance of this class. */ class __Graphics extends p5.Element { elt: HTMLCanvasElement; constructor(w: number, h: number, renderer: typeof p5.P2D | typeof p5.WEBGL | typeof p5.P2DHDR, pInst?: p5, canvas?: HTMLCanvasElement); /** * Resets the graphics buffer's transformations and lighting. * * By default, the main canvas resets certain transformation and lighting * values each time draw() executes. `p5.Graphics` * objects must reset these values manually by calling `myGraphics.reset()`. */ reset(): void; /** * Removes the graphics buffer from the web page. * * Calling `myGraphics.remove()` removes the graphics buffer's * `<canvas>` element from the web page. The graphics buffer also uses * a bit of memory on the CPU that can be freed like so: * * `// Remove the graphics buffer from the web page. * myGraphics.remove(); * * // Delete the graphics buffer from CPU memory. * myGraphics = undefined;`Note: All variables that reference the graphics buffer must be assigned * the value `undefined` to delete the graphics buffer from CPU memory. If any * variable still refers to the graphics buffer, then it won't be garbage * collected. */ remove(): void; /** * Creates a new p5.Framebuffer object with * the same WebGL context as the graphics buffer. * * p5.Framebuffer objects are separate drawing * surfaces that can be used as textures in WebGL mode. They're similar to * p5.Graphics objects and generally run much * faster when used as textures. Creating a * p5.Framebuffer object in the same context * as the graphics buffer makes this speedup possible. * * The parameter, `options`, is optional. An object can be passed to configure * the p5.Framebuffer object. The available * properties are: * * - `format`: data format of the texture, either `UNSIGNED_BYTE`, `FLOAT`, or `HALF_FLOAT`. Default is `UNSIGNED_BYTE`. * * - `channels`: whether to store `RGB` or `RGBA` color channels. Default is to match the graphics buffer which is `RGBA`. * * - `depth`: whether to include a depth buffer. Default is `true`. * * - `depthFormat`: data format of depth information, either `UNSIGNED_INT` or `FLOAT`. Default is `FLOAT`. * * - `stencil`: whether to include a stencil buffer for masking. `depth` must be `true` for this feature to work. Defaults to the value of `depth` which is `true`. * * - `antialias`: whether to perform anti-aliasing. If set to `true`, as in `{ antialias: true }`, 2 samples will be used by default. The number of samples can also be set, as in `{ antialias: 4 }`. Default is to match setAttributes() which is `false` (`true` in Safari). * * - `width`: width of the p5.Framebuffer object. Default is to always match the graphics buffer width. * * - `height`: height of the p5.Framebuffer object. Default is to always match the graphics buffer height. * * - `density`: pixel density of the p5.Framebuffer object. Default is to always match the graphics buffer pixel density. * * - `textureFiltering`: how to read values from the p5.Framebuffer object. Either `LINEAR` (nearby pixels will be interpolated) or `NEAREST` (no interpolation). Generally, use `LINEAR` when using the texture as an image and `NEAREST` if reading the texture as data. Default is `LINEAR`. * * If the `width`, `height`, or `density` attributes are set, they won't * automatically match the graphics buffer and must be changed manually. * @param options configuration options. * @returns new framebuffer. */ createFramebuffer(options?: { format?: typeof p5.UNSIGNED_BYTE | typeof p5.FLOAT | typeof p5.HALF_FLOAT; channels?: typeof p5.RGB | typeof p5.RGBA; depth?: boolean; depthFormat?: typeof p5.UNSIGNED_INT | typeof p5.FLOAT; stencil?: boolean; antialias?: boolean | number; width?: number; height?: number; density?: number; textureFiltering?: typeof p5.LINEAR | typeof p5.NEAREST }): Framebuffer; } type Graphics = __Graphics & p5; /** * A class to describe an * HTML element. * * Sketches can use many elements. Common elements include the drawing canvas, * buttons, sliders, webcam feeds, and so on. * * All elements share the methods of the `p5.Element` class. They're created * with functions such as createCanvas() and * createButton(). */ class Element { constructor(elt: HTMLElement, pInst?: p5); /** * A `Number` property that stores the element's width. */ undefined: number; /** * The element's underlying `HTMLElement` object. * * The * HTMLElement * object's properties and methods can be used directly. */ elt: HTMLElement; /** * Removes the element, stops all audio/video streams, and removes all * callback functions. */ remove(): void; /** * Attaches the element to a parent element. * * For example, a `<div></div>` element may be used as a box to * hold two pieces of text, a header and a paragraph. The * `<div></div>` is the parent element of both the header and * paragraph. * * The parameter `parent` can have one of three types. `parent` can be a * string with the parent element's ID, as in * `myElement.parent('container')`. It can also be another * p5.Element object, as in * `myElement.parent(myDiv)`. Finally, `parent` can be an `HTMLElement` * object, as in `myElement.parent(anotherElement)`. * * Calling `myElement.parent()` without an argument returns the element's * parent. * @param parent ID, p5.Element, * or HTMLElement of desired parent element. */ parent(parent: string | Element | object): Element; parent(): Element; /** * Attaches the element as a child of another element. * * `myElement.child()` accepts either a string ID, DOM node, or * p5.Element. For example, * `myElement.child(otherElement)`. If no argument is provided, an array of * children DOM nodes is returned. * @returns an array of child nodes. */ child(): Element; child(child?: string | Element): Element; /** * Sets the inner HTML of the element, replacing any existing HTML. * * The second parameter, `append`, is optional. If `true` is passed, as in * `myElement.html('hi', true)`, the HTML is appended instead of replacing * existing HTML. * * If no arguments are passed, as in `myElement.html()`, the element's inner * HTML is returned. * @returns the inner HTML of the element */ html(): Element; html(html?: string, append?: boolean): Element; /** * Sets the element's ID using a given string. * * Calling `myElement.id()` without an argument returns its ID as a string. * @param id ID of the element. * @returns ID of the element. */ id(id: string): Element; id(): Element; /** * Adds a * class attribute * to the element using a given string. * * Calling `myElement.class()` without an argument returns a string with its current classes. * @param class class to add. * @returns element's classes, if any. */ class($class: string): Element; class(): Element; /** * Adds a class to the element. * @param class name of class to add. */ addClass($class: string): Element; /** * Removes a class from the element. * @param class name of class to remove. */ removeClass($class: string): Element; /** * Checks if a class is already applied to element. * @param c {String} name of class to check. * @returns a boolean value if element has specified class. */ hasClass(c: any): boolean; /** * Toggles whether a class is applied to the element. * @param c {String} class name to toggle. */ toggleClass(c: any): Element; /** * Centers the element either vertically, horizontally, or both. * * `center()` will center the element relative to its parent or according to * the page's body if the element has no parent. * * If no argument is passed, as in `myElement.center()` the element is aligned * both vertically and horizontally. * @param align passing 'vertical', 'horizontal' aligns element accordingly */ center(align?: string): Element; /** * Sets the element's position. * * The first two parameters, `x` and `y`, set the element's position relative * to the top-left corner of the web page. * * The third parameter, `positionType`, is optional. It sets the element's * positioning scheme. * `positionType` is a string that can be either `'static'`, `'fixed'`, * `'relative'`, `'sticky'`, `'initial'`, or `'inherit'`. * * If no arguments passed, as in `myElement.position()`, the method returns * the element's position in an object, as in `{ x: 0, y: 0 }`. * @returns object of form `{ x: 0, y: 0 }` containing the element's position. */ position(): Element; position(x?: number, y?: number, positionType?: string): Element; /** * Shows the current element. */ show(): Element; /** * Hides the current element. */ hide(): Element; /** * Sets the element's width and height. * * Calling `myElement.size()` without an argument returns the element's size * as an object with the properties `width` and `height`. For example, * `{ width: 20, height: 10 }`. * * The first parameter, `width`, is optional. It's a number used to set the * element's width. Calling `myElement.size(10)` * * The second parameter, 'height`, is also optional. It's a * number used to set the element's height. For example, calling * `myElement.size(20, 10)` sets the element's width to 20 pixels and height * to 10 pixels. * * The constant `AUTO` can be used to adjust one dimension at a time while * maintaining the aspect ratio, which is `width / height`. For example, * consider an element that's 200 pixels wide and 100 pixels tall. Calling * `myElement.size(20, AUTO)` sets the width to 20 pixels and height to 10 * pixels. * * Note: In the case of elements that need to load data, such as images, wait * to call `myElement.size()` until after the data loads. * @returns width and height of the element in an object. */ size(): Element; size(w?: number | typeof p5.AUTO, h?: number | typeof p5.AUTO): Element; /** * Applies a style to the element by adding a * CSS declaration. * * The first parameter, `property`, is a string. If the name of a style * property is passed, as in `myElement.style('color')`, the method returns * the current value as a string or `null` if it hasn't been set. If a * `property:style` string is passed, as in * `myElement.style('color:deeppink')`, the method sets the style `property` * to `value`. * * The second parameter, `value`, is optional. It sets the property's value. * `value` can be a string, as in * `myElement.style('color', 'deeppink')`, or a * p5.Color object, as in * `myElement.style('color', myColor)`. * @param property style property to set. * @returns value of the property. */ style(property: string): Element; style(property: string, value: string | Color): Element; /** * Adds an * attribute * to the element. * * This method is useful for advanced tasks. Most commonly-used attributes, * such as `id`, can be set with their dedicated methods. For example, * `nextButton.id('next')` sets an element's `id` attribute. Calling * `nextButton.attribute('id', 'next')` has the same effect. * * The first parameter, `attr`, is the attribute's name as a string. Calling * `myElement.attribute('align')` returns the attribute's current value as a * string or `null` if it hasn't been set. * * The second parameter, `value`, is optional. It's a string used to set the * attribute's value. For example, calling * `myElement.attribute('align', 'center')` sets the element's horizontal * alignment to `center`. * @returns value of the attribute. */ attribute(): Element; attribute(attr: string, value: string): Element; /** * Removes an attribute from the element. * * The parameter `attr` is the attribute's name as a string. For example, * calling `myElement.removeAttribute('align')` removes its `align` * attribute if it's been set. * @param attr attribute to remove. */ removeAttribute(attr: string): Element; /** * Returns or sets the element's value. * * Calling `myElement.value()` returns the element's current value. * * The parameter, `value`, is an optional number or string. If provided, * as in `myElement.value(123)`, it's used to set the element's value. * @returns value of the element. */ value(): Element; value(value: string | number): Element; /** * Calls a function when the mouse is pressed over the element. * * Calling `myElement.mousePressed(false)` disables the function. * * Note: Some mobile browsers may also trigger this event when the element * receives a quick tap. * @param fxn function to call when the mouse is * pressed over the element. * `false` disables the function. */ mousePressed(fxn: Function | boolean): Element; /** * Calls a function when the mouse is pressed twice over the element. * * Calling `myElement.doubleClicked(false)` disables the function. * @param fxn function to call when the mouse is * double clicked over the element. * `false` disables the function. */ doubleClicked(fxn: Function | boolean): Element; /** * Calls a function when the mouse wheel scrolls over the element. * * The callback function, `fxn`, is passed an `event` object. `event` has * two numeric properties, `deltaY` and `deltaX`. `event.deltaY` is * negative if the mouse wheel rotates away from the user. It's positive if * the mouse wheel rotates toward the user. `event.deltaX` is positive if * the mouse wheel moves to the right. It's negative if the mouse wheel moves * to the left. * * Calling `myElement.mouseWheel(false)` disables the function. * @param fxn function to call when the mouse wheel is * scrolled over the element. * `false` disables the function. */ mouseWheel(fxn: Function | boolean): Element; /** * Calls a function when the mouse is released over the element. * * Calling `myElement.mouseReleased(false)` disables the function. * * Note: Some mobile browsers may also trigger this event when the element * receives a quick tap. * @param fxn function to call when the mouse is * pressed over the element. * `false` disables the function. */ mouseReleased(fxn: Function | boolean): Element; /** * Calls a function when the mouse is pressed and released over the element. * * Calling `myElement.mouseReleased(false)` disables the function. * * Note: Some mobile browsers may also trigger this event when the element * receives a quick tap. * @param fxn function to call when the mouse is * pressed and released over the element. * `false` disables the function. */ mouseClicked(fxn: Function | boolean): Element; /** * Calls a function when the mouse moves over the element. * * Calling `myElement.mouseMoved(false)` disables the function. * @param fxn function to call when the mouse * moves over the element. * `false` disables the function. */ mouseMoved(fxn: Function | boolean): Element; /** * Calls a function when the mouse moves onto the element. * * Calling `myElement.mouseOver(false)` disables the function. * @param fxn function to call when the mouse * moves onto the element. * `false` disables the function. */ mouseOver(fxn: Function | boolean): Element; /** * Calls a function when the mouse moves off the element. * * Calling `myElement.mouseOut(false)` disables the function. * @param fxn function to call when the mouse * moves off the element. * `false` disables the function. */ mouseOut(fxn: Function | boolean): Element; /** * Calls a function when a file is dragged over the element. * * Calling `myElement.dragOver(false)` disables the function. * @param fxn function to call when the file is * dragged over the element. * `false` disables the function. */ dragOver(fxn: Function | boolean): Element; /** * Calls a function when a file is dragged off the element. * * Calling `myElement.dragLeave(false)` disables the function. * @param fxn function to call when the file is * dragged off the element. * `false` disables the function. */ dragLeave(fxn: Function | boolean): Element; /** * Calls a function when the element changes. * * Calling `myElement.changed(false)` disables the function. * @param fxn function to call when the element changes. * `false` disables the function. */ changed(fxn: Function | boolean): Element; /** * Calls a function when the element receives input. * * `myElement.input()` is often used to with text inputs and sliders. Calling * `myElement.input(false)` disables the function. * @param fxn function to call when input is detected within * the element. * `false` disables the function. */ input(fxn: Function | boolean): Element; /** * Calls a function when the user drops a file on the element. * * The first parameter, `callback`, is a function to call once the file loads. * The callback function should have one parameter, `file`, that's a * p5.File object. If the user drops multiple files on * the element, `callback`, is called once for each file. * * The second parameter, `fxn`, is a function to call when the browser detects * one or more dropped files. The callback function should have one * parameter, `event`, that's a * DragEvent. * @param callback called when a file loads. Called once for each file dropped. * @param fxn called once when any files are dropped. */ drop(callback: Function, fxn?: Function): Element; /** * Makes the element draggable. * * The parameter, `elmnt`, is optional. If another * p5.Element object is passed, as in * `myElement.draggable(otherElement)`, the other element will become draggable. * @param elmnt another p5.Element. */ draggable(elmnt?: Element): Element; } /** * A class to describe a file. * * `p5.File` objects are used by * myElement.drop() and * created by * createFileInput. */ class File { constructor(file: File); /** * Underlying * File * object. All `File` properties and methods are accessible. */ file: File; /** * The file * MIME type * as a string. * * For example, `'image'` and `'text'` are both MIME types. */ type: string; /** * The file subtype as a string. * * For example, a file with an `'image'` * MIME type * may have a subtype such as `png` or `jpeg`. */ subtype: string; /** * The file name as a string. */ name: string; /** * The number of bytes in the file. */ size: number; /** * A string containing the file's data. * * Data can be either image data, text contents, or a parsed object in the * case of JSON and p5.XML objects. */ data: any; } /** * A class to handle audio and video. * * `p5.MediaElement` extends p5.Element with * methods to handle audio and video. `p5.MediaElement` objects are created by * calling createVideo, * createAudio, and * createCapture. */ class MediaElement extends Element { elt: T; constructor(elt: string); /** * Path to the media element's source as a string. */ undefined: any; /** * Plays audio or video from a media element. */ play(): MediaElement; /** * Stops a media element and sets its current time to 0. * * Calling `media.play()` will restart playing audio/video from the beginning. */ stop(): MediaElement; /** * Pauses a media element. * * Calling `media.play()` will resume playing audio/video from the moment it paused. */ pause(): MediaElement; /** * Plays the audio/video repeatedly in a loop. */ loop(): MediaElement; /** * Stops the audio/video from playing in a loop. * * The media will stop when it finishes playing. */ noLoop(): MediaElement; /** * Sets the audio/video to play once it's loaded. * * The parameter, `shouldAutoplay`, is optional. Calling * `media.autoplay()` without an argument causes the media to play * automatically. If `true` is passed, as in `media.autoplay(true)`, the * media will automatically play. If `false` is passed, as in * `media.autoPlay(false)`, it won't play automatically. * @param shouldAutoplay whether the element should autoplay. */ autoplay(shouldAutoplay?: boolean): MediaElement; /** * Sets the audio/video volume. * * Calling `media.volume()` without an argument returns the current volume * as a number in the range 0 (off) to 1 (maximum). * * The parameter, `val`, is optional. It's a number that sets the volume * from 0 (off) to 1 (maximum). For example, calling `media.volume(0.5)` * sets the volume to half of its maximum. * @returns current volume. */ volume(): MediaElement; volume(val: number): MediaElement; /** * Sets the audio/video playback speed. * * The parameter, `val`, is optional. It's a number that sets the playback * speed. 1 plays the media at normal speed, 0.5 plays it at half speed, 2 * plays it at double speed, and so on. -1 plays the media at normal speed * in reverse. * * Calling `media.speed()` returns the current speed as a number. * * Note: Not all browsers support backward playback. Even if they do, * playback might not be smooth. * @returns current playback speed. */ speed(): MediaElement; speed(speed: number): MediaElement; /** * Sets the media element's playback time. * * The parameter, `time`, is optional. It's a number that specifies the * time, in seconds, to jump to when playback begins. * * Calling `media.time()` without an argument returns the number of seconds * the audio/video has played. * * Note: Time resets to 0 when looping media restarts. * @param time time to jump to (in seconds). * @returns current time (in seconds). */ time(time?: number): number; /** * Returns the audio/video's duration in seconds. * @returns duration (in seconds). */ duration(): number; /** * Calls a function when the audio/video reaches the end of its playback. * * The element is passed as an argument to the callback function. * * Note: The function won't be called if the media is looping. * @param callback function to call when playback ends. * The `p5.MediaElement` is passed as * the argument. */ onended(callback: Function): MediaElement; /** * Sends the element's audio to an output. * * The parameter, `audioNode`, can be an `AudioNode` or an object from the * `p5.sound` library. * * If no element is provided, as in `myElement.connect()`, the element * connects to the main output. All connections are removed by the * `.disconnect()` method. * * Note: This method is meant to be used with the p5.sound.js addon library. * @param audioNode AudioNode from the Web Audio API, * or an object from the p5.sound library */ connect(audioNode: AudioNode | object): void; /** * Disconnect all Web Audio routing, including to the main output. * * This is useful if you want to re-route the output through audio effects, * for example. */ disconnect(): void; /** * Show the default * HTMLMediaElement * controls. * * Note: The controls vary between web browsers. */ showControls(): void; /** * Hide the default * HTMLMediaElement * controls. */ hideControls(): void; /** * Schedules a function to call when the audio/video reaches a specific time * during its playback. * * The first parameter, `time`, is the time, in seconds, when the function * should run. This value is passed to `callback` as its first argument. * * The second parameter, `callback`, is the function to call at the specified * cue time. * * The third parameter, `value`, is optional and can be any type of value. * `value` is passed to `callback`. * * Calling `media.addCue()` returns an ID as a string. This is useful for * removing the cue later. * @param time cue time to run the callback function. * @param callback function to call at the cue time. * @param value object to pass as the argument to * `callback`. * @returns id ID of this cue, * useful for `media.removeCue(id)`. */ addCue(time: number, callback: Function, value?: object): number; /** * Removes a callback based on its ID. * @param id ID of the cue, created by `media.addCue()`. */ removeCue(id: number): void; /** * Removes all functions scheduled with `media.addCue()`. */ clearCues(): void; } /** * A class to describe an image. * * Images are rectangular grids of pixels that can be displayed and modified. * * Existing images can be loaded by calling * loadImage(). Blank images can be created by * calling createImage(). `p5.Image` objects * have methods for common tasks such as applying filters and modifying * pixel values. */ class Image { constructor(width: number, height: number); /** * The image's width in pixels. */ width: number; /** * The image's height in pixels. */ height: number; /** * An array containing the color of each pixel in the image. * * Colors are stored as numbers representing red, green, blue, and alpha * (RGBA) values. `img.pixels` is a one-dimensional array for performance * reasons. * * Each pixel occupies four elements in the pixels array, one for each * RGBA value. For example, the pixel at coordinates (0, 0) stores its * RGBA values at `img.pixels[0]`, `img.pixels[1]`, `img.pixels[2]`, * and `img.pixels[3]`, respectively. The next pixel at coordinates (1, 0) * stores its RGBA values at `img.pixels[4]`, `img.pixels[5]`, * `img.pixels[6]`, and `img.pixels[7]`. And so on. The `img.pixels` array * for a 100×100 p5.Image object has * 100 × 100 × 4 = 40,000 elements. * * Accessing the RGBA values for a pixel in the image requires a little * math as shown in the examples below. The * img.loadPixels() * method must be called before accessing the `img.pixels` array. The * img.updatePixels() method must be * called after any changes are made. */ pixels: number[]; /** * Gets or sets the pixel density for high pixel density displays. * * By default, the density will be set to 1. * * Call this method with no arguments to get the default density, or pass * in a number to set the density. If a non-positive number is provided, * it defaults to 1. * @param density A scaling factor for the number of pixels per * side * @returns The current density if called without arguments, or the instance for chaining if setting density. */ pixelDensity(density?: number): number; pixelDensity(density?: number): number; pixelDensity(density?: number): number; pixelDensity(density?: number): number; /** * Loads the current value of each pixel in the image into the `img.pixels` * array. * * `img.loadPixels()` must be called before reading or modifying pixel * values. */ loadPixels(): void; loadPixels(): void; loadPixels(): void; loadPixels(): void; /** * Updates the canvas with the RGBA values in the * img.pixels array. * * `img.updatePixels()` only needs to be called after changing values in * the img.pixels array. Such changes can be * made directly after calling * img.loadPixels() or by calling * img.set(). * * The optional parameters `x`, `y`, `width`, and `height` define a * subsection of the image to update. Doing so can improve performance in * some cases. * * If the image was loaded from a GIF, then calling `img.updatePixels()` * will update the pixels in current frame. * @param x x-coordinate of the upper-left corner * of the subsection to update. * @param y y-coordinate of the upper-left corner * of the subsection to update. * @param w width of the subsection to update. * @param h height of the subsection to update. */ updatePixels(x?: number, y?: number, w?: number, h?: number): void; updatePixels(x?: number, y?: number, w?: number, h?: number): void; updatePixels(x?: number, y?: number, w?: number, h?: number): void; updatePixels(x?: number, y?: number, w?: number, h?: number): void; /** * Gets a pixel or a region of pixels from the image. * * `img.get()` is easy to use but it's not as fast as * img.pixels. Use * img.pixels to read many pixel values. * * The version of `img.get()` with no parameters returns the entire image. * * The version of `img.get()` with two parameters, as in `img.get(10, 20)`, * interprets them as coordinates. It returns an array with the * `[R, G, B, A]` values of the pixel at the given point. * * The version of `img.get()` with four parameters, as in * `img,get(10, 20, 50, 90)`, interprets them as * coordinates and dimensions. The first two parameters are the coordinates * of the upper-left corner of the subsection. The last two parameters are * the width and height of the subsection. It returns a subsection of the * canvas in a new p5.Image object. * * Use `img.get()` instead of get() to work directly * with images. * @param x x-coordinate of the pixel. * @param y y-coordinate of the pixel. * @param w width of the subsection to be returned. * @param h height of the subsection to be returned. * @returns subsection as a p5.Image object. */ get(x: number, y: number, w: number, h: number): Image; get(): Image; get(x: number, y: number): number[]; get(x: number, y: number, w: number, h: number): Image; get(): Image; get(x: number, y: number): number[]; get(x: number, y: number, w: number, h: number): Image; get(): Image; get(x: number, y: number): number[]; get(x: number, y: number, w: number, h: number): Image; get(): Image; get(x: number, y: number): number[]; /** * Sets the color of one or more pixels within an image. * * `img.set()` is easy to use but it's not as fast as * img.pixels. Use * img.pixels to set many pixel values. * * `img.set()` interprets the first two parameters as x- and y-coordinates. It * interprets the last parameter as a grayscale value, a `[R, G, B, A]` pixel * array, a p5.Color object, or another * p5.Image object. * * img.updatePixels() must be called * after using `img.set()` for changes to appear. * @param x x-coordinate of the pixel. * @param y y-coordinate of the pixel. * @param a grayscale value | pixel array | * p5.Color object | * p5.Image to copy. */ set(x: number, y: number, a: number | number[] | object): void; set(x: number, y: number, a: number | number[] | object): void; set(x: number, y: number, a: number | number[] | object): void; set(x: number, y: number, a: number | number[] | object): void; /** * Resizes the image to a given width and height. * * The image's original aspect ratio can be kept by passing 0 for either * `width` or `height`. For example, calling `img.resize(50, 0)` on an image * that was 500 × 300 pixels will resize it to 50 × 30 pixels. * @param width resized image width. * @param height resized image height. */ resize(width: number, height: number): void; resize(width: number, height: number): void; resize(width: number, height: number): void; resize(width: number, height: number): void; /** * Copies pixels from a source image to this image. * * The first parameter, `srcImage`, is an optional * p5.Image object to copy. If a source image isn't * passed, then `img.copy()` can copy a region of this image to another * region. * * The next four parameters, `sx`, `sy`, `sw`, and `sh` determine the region * to copy from the source image. `(sx, sy)` is the top-left corner of the * region. `sw` and `sh` are the region's width and height. * * The next four parameters, `dx`, `dy`, `dw`, and `dh` determine the region * of this image to copy into. `(dx, dy)` is the top-left corner of the * region. `dw` and `dh` are the region's width and height. * * Calling `img.copy()` will scale pixels from the source region if it isn't * the same size as the destination region. * @param srcImage source image. * @param sx x-coordinate of the source's upper-left corner. * @param sy y-coordinate of the source's upper-left corner. * @param sw source image width. * @param sh source image height. * @param dx x-coordinate of the destination's upper-left corner. * @param dy y-coordinate of the destination's upper-left corner. * @param dw destination image width. * @param dh destination image height. */ copy(srcImage: Image | Element, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void; copy(sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void; copy(srcImage: Image | Element, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void; copy(sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void; copy(srcImage: Image | Element, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void; copy(sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void; copy(srcImage: Image | Element, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void; copy(sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void; /** * Masks part of the image with another. * * `img.mask()` uses another p5.Image object's * alpha channel as the alpha channel for this image. Masks are cumulative * and can't be removed once applied. If the mask has a different * pixel density from this image, the mask will be scaled. * @param srcImage source image. */ mask(srcImage: Image): void; mask(srcImage: Image): void; mask(srcImage: Image): void; mask(srcImage: Image): void; /** * Applies an image filter to the image. * * The preset options are: * * `INVERT` * Inverts the colors in the image. No parameter is used. * * `GRAY` * Converts the image to grayscale. No parameter is used. * * `THRESHOLD` * Converts the image to black and white. Pixels with a grayscale value * above a given threshold are converted to white. The rest are converted to * black. The threshold must be between 0.0 (black) and 1.0 (white). If no * value is specified, 0.5 is used. * * `OPAQUE` * Sets the alpha channel to be entirely opaque. No parameter is used. * * `POSTERIZE` * Limits the number of colors in the image. Each color channel is limited to * the number of colors specified. Values between 2 and 255 are valid, but * results are most noticeable with lower values. The default value is 4. * * `BLUR` * Blurs the image. The level of blurring is specified by a blur radius. Larger * values increase the blur. The default value is 4. A gaussian blur is used * in `P2D` mode. A box blur is used in `WEBGL` mode. * * `ERODE` * Reduces the light areas. No parameter is used. * * `DILATE` * Increases the light areas. No parameter is used. * @param filterType either THRESHOLD, GRAY, OPAQUE, INVERT, * POSTERIZE, ERODE, DILATE or BLUR. * @param filterParam parameter unique to each filter. */ filter(filterType: typeof p5.THRESHOLD | typeof p5.GRAY | typeof p5.OPAQUE | typeof p5.INVERT | typeof p5.POSTERIZE | typeof p5.ERODE | typeof p5.DILATE | typeof p5.BLUR, filterParam?: number): void; filter(filterType: typeof p5.THRESHOLD | typeof p5.GRAY | typeof p5.OPAQUE | typeof p5.INVERT | typeof p5.POSTERIZE | typeof p5.ERODE | typeof p5.DILATE | typeof p5.BLUR, filterParam?: number): void; filter(filterType: typeof p5.THRESHOLD | typeof p5.GRAY | typeof p5.OPAQUE | typeof p5.INVERT | typeof p5.POSTERIZE | typeof p5.ERODE | typeof p5.DILATE | typeof p5.BLUR, filterParam?: number): void; filter(filterType: typeof p5.THRESHOLD | typeof p5.GRAY | typeof p5.OPAQUE | typeof p5.INVERT | typeof p5.POSTERIZE | typeof p5.ERODE | typeof p5.DILATE | typeof p5.BLUR, filterParam?: number): void; /** * Copies a region of pixels from another image into this one. * * The first parameter, `srcImage`, is the * p5.Image object to blend. * * The next four parameters, `sx`, `sy`, `sw`, and `sh` determine the region * to blend from the source image. `(sx, sy)` is the top-left corner of the * region. `sw` and `sh` are the regions width and height. * * The next four parameters, `dx`, `dy`, `dw`, and `dh` determine the region * of the canvas to blend into. `(dx, dy)` is the top-left corner of the * region. `dw` and `dh` are the regions width and height. * * The tenth parameter, `blendMode`, sets the effect used to blend the images' * colors. The options are `BLEND`, `DARKEST`, `LIGHTEST`, `DIFFERENCE`, * `MULTIPLY`, `EXCLUSION`, `SCREEN`, `REPLACE`, `OVERLAY`, `HARD_LIGHT`, * `SOFT_LIGHT`, `DODGE`, `BURN`, `ADD`, or `NORMAL`. * @param srcImage source image * @param sx x-coordinate of the source's upper-left corner. * @param sy y-coordinate of the source's upper-left corner. * @param sw source image width. * @param sh source image height. * @param dx x-coordinate of the destination's upper-left corner. * @param dy y-coordinate of the destination's upper-left corner. * @param dw destination image width. * @param dh destination image height. * @param blendMode the blend mode. either * BLEND, DARKEST, LIGHTEST, DIFFERENCE, * MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT, * SOFT_LIGHT, DODGE, BURN, ADD or NORMAL. * * Available blend modes are: normal | multiply | screen | overlay | * darken | lighten | color-dodge | color-burn | hard-light | * soft-light | difference | exclusion | hue | saturation | * color | luminosity * * http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/ */ blend(srcImage: Image, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number, blendMode: typeof p5.BLEND | typeof p5.DARKEST | typeof p5.LIGHTEST | typeof p5.DIFFERENCE | typeof p5.MULTIPLY | typeof p5.EXCLUSION | typeof p5.SCREEN | typeof p5.REPLACE | typeof p5.OVERLAY | typeof p5.HARD_LIGHT | typeof p5.SOFT_LIGHT | typeof p5.DODGE | typeof p5.BURN | typeof p5.ADD | typeof p5.NORMAL): void; blend(sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number, blendMode: typeof p5.BLEND | typeof p5.DARKEST | typeof p5.LIGHTEST | typeof p5.DIFFERENCE | typeof p5.MULTIPLY | typeof p5.EXCLUSION | typeof p5.SCREEN | typeof p5.REPLACE | typeof p5.OVERLAY | typeof p5.HARD_LIGHT | typeof p5.SOFT_LIGHT | typeof p5.DODGE | typeof p5.BURN | typeof p5.ADD | typeof p5.NORMAL): void; blend(srcImage: Image, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number, blendMode: typeof p5.BLEND | typeof p5.DARKEST | typeof p5.LIGHTEST | typeof p5.DIFFERENCE | typeof p5.MULTIPLY | typeof p5.EXCLUSION | typeof p5.SCREEN | typeof p5.REPLACE | typeof p5.OVERLAY | typeof p5.HARD_LIGHT | typeof p5.SOFT_LIGHT | typeof p5.DODGE | typeof p5.BURN | typeof p5.ADD | typeof p5.NORMAL): void; blend(sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number, blendMode: typeof p5.BLEND | typeof p5.DARKEST | typeof p5.LIGHTEST | typeof p5.DIFFERENCE | typeof p5.MULTIPLY | typeof p5.EXCLUSION | typeof p5.SCREEN | typeof p5.REPLACE | typeof p5.OVERLAY | typeof p5.HARD_LIGHT | typeof p5.SOFT_LIGHT | typeof p5.DODGE | typeof p5.BURN | typeof p5.ADD | typeof p5.NORMAL): void; blend(srcImage: Image, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number, blendMode: typeof p5.BLEND | typeof p5.DARKEST | typeof p5.LIGHTEST | typeof p5.DIFFERENCE | typeof p5.MULTIPLY | typeof p5.EXCLUSION | typeof p5.SCREEN | typeof p5.REPLACE | typeof p5.OVERLAY | typeof p5.HARD_LIGHT | typeof p5.SOFT_LIGHT | typeof p5.DODGE | typeof p5.BURN | typeof p5.ADD | typeof p5.NORMAL): void; blend(sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number, blendMode: typeof p5.BLEND | typeof p5.DARKEST | typeof p5.LIGHTEST | typeof p5.DIFFERENCE | typeof p5.MULTIPLY | typeof p5.EXCLUSION | typeof p5.SCREEN | typeof p5.REPLACE | typeof p5.OVERLAY | typeof p5.HARD_LIGHT | typeof p5.SOFT_LIGHT | typeof p5.DODGE | typeof p5.BURN | typeof p5.ADD | typeof p5.NORMAL): void; blend(srcImage: Image, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number, blendMode: typeof p5.BLEND | typeof p5.DARKEST | typeof p5.LIGHTEST | typeof p5.DIFFERENCE | typeof p5.MULTIPLY | typeof p5.EXCLUSION | typeof p5.SCREEN | typeof p5.REPLACE | typeof p5.OVERLAY | typeof p5.HARD_LIGHT | typeof p5.SOFT_LIGHT | typeof p5.DODGE | typeof p5.BURN | typeof p5.ADD | typeof p5.NORMAL): void; blend(sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number, blendMode: typeof p5.BLEND | typeof p5.DARKEST | typeof p5.LIGHTEST | typeof p5.DIFFERENCE | typeof p5.MULTIPLY | typeof p5.EXCLUSION | typeof p5.SCREEN | typeof p5.REPLACE | typeof p5.OVERLAY | typeof p5.HARD_LIGHT | typeof p5.SOFT_LIGHT | typeof p5.DODGE | typeof p5.BURN | typeof p5.ADD | typeof p5.NORMAL): void; /** * Saves the image to a file. * * By default, `img.save()` saves the image as a PNG image called * `untitled.png`. * * The first parameter, `filename`, is optional. It's a string that sets the * file's name. If a file extension is included, as in * `img.save('drawing.png')`, then the image will be saved using that * format. * * The second parameter, `extension`, is also optional. It sets the files format. * Either `'png'` or `'jpg'` can be used. For example, `img.save('drawing', 'jpg')` * saves the canvas to a file called `drawing.jpg`. * * Note: The browser will either save the file immediately or prompt the user * with a dialogue window. * * The image will only be downloaded as an animated GIF if it was loaded * from a GIF file. See saveGif() to create new * GIFs. * @param filename filename. Defaults to 'untitled'. * @param extension file extension, either 'png' or 'jpg'. * Defaults to 'png'. */ save(filename: string, extension?: string): void; save(filename: string, extension?: string): void; save(filename: string, extension?: string): void; save(filename: string, extension?: string): void; /** * Restarts an animated GIF at its first frame. */ reset(): void; reset(): void; reset(): void; reset(): void; /** * Gets the index of the current frame in an animated GIF. * @returns index of the GIF's current frame. */ getCurrentFrame(): number; getCurrentFrame(): number; getCurrentFrame(): number; getCurrentFrame(): number; /** * Sets the current frame in an animated GIF. * @param index index of the frame to display. */ setFrame(index: number): void; setFrame(index: number): void; setFrame(index: number): void; setFrame(index: number): void; /** * Returns the number of frames in an animated GIF. * @returns number of frames in the GIF. */ numFrames(): number; numFrames(): number; numFrames(): number; numFrames(): number; /** * Plays an animated GIF that was paused with * img.pause(). */ play(): void; play(): void; play(): void; play(): void; /** * Pauses an animated GIF. * * The GIF can be resumed by calling * img.play(). */ pause(): void; pause(): void; pause(): void; pause(): void; /** * Changes the delay between frames in an animated GIF. * * The first parameter, `delay`, is the length of the delay in milliseconds. * * The second parameter, `index`, is optional. If provided, only the frame * at `index` will have its delay modified. All other frames will keep * their default delay. * @param d delay in milliseconds between switching frames. * @param index index of the frame that will have its delay modified. */ delay(d: number, index?: number): void; delay(d: number, index?: number): void; delay(d: number, index?: number): void; delay(d: number, index?: number): void; } /** * A class to describe a print stream. * * Each `p5.PrintWriter` object provides a way to save a sequence of text * data, called the print stream, to the user's computer. It's a low-level * object that enables precise control of text output. Functions such as * saveStrings() and * saveJSON() are easier to use for simple file * saving. * * Note: createWriter() is the recommended way * to make an instance of this class. */ class PrintWriter { constructor(filename: string, extension?: string); } /** * Table objects store data with multiple rows and columns, much * like in a traditional spreadsheet. Tables can be generated from * scratch, dynamically, or using data from an existing file. */ class Table { constructor(rows?: TableRow[]); /** * An array containing the names of the columns in the table, if the "header" the table is * loaded with the "header" parameter. */ columns: string[]; /** * An array containing the p5.TableRow objects that make up the * rows of the table. The same result as calling getRows() */ rows: TableRow[]; /** * Use addRow() to add a new row of data to a p5.Table object. By default, * an empty row is created. Typically, you would store a reference to * the new row in a TableRow object (see newRow in the example above), * and then set individual values using set(). * * If a p5.TableRow object is included as a parameter, then that row is * duplicated and added to the table. * @param row row to be added to the table * @returns the row that was added */ addRow(row?: TableRow): TableRow; /** * Removes a row from the table object. * @param id ID number of the row to remove */ removeRow(id: number): void; /** * Returns a reference to the specified p5.TableRow. The reference * can then be used to get and set values of the selected row. * @param rowID ID number of the row to get * @returns p5.TableRow object */ getRow(rowID: number): TableRow; /** * Gets all rows from the table. Returns an array of p5.TableRows. * @returns Array of p5.TableRows */ getRows(): TableRow[]; /** * Finds the first row in the Table that contains the value * provided, and returns a reference to that row. Even if * multiple rows are possible matches, only the first matching * row is returned. The column to search may be specified by * either its ID or title. * @param value The value to match * @param column ID number or title of the * column to search */ findRow(value: string, column: number | string): TableRow; /** * Finds the rows in the Table that contain the value * provided, and returns references to those rows. Returns an * Array, so for must be used to iterate through all the rows, * as shown in the example above. The column to search may be * specified by either its ID or title. * @param value The value to match * @param column ID number or title of the * column to search * @returns An Array of TableRow objects */ findRows(value: string, column: number | string): TableRow[]; /** * Finds the first row in the Table that matches the regular * expression provided, and returns a reference to that row. * Even if multiple rows are possible matches, only the first * matching row is returned. The column to search may be * specified by either its ID or title. * @param regexp The regular expression to match * @param column The column ID (number) or * title (string) * @returns TableRow object */ matchRow(regexp: string | RegExp, column: string | number): TableRow; /** * Finds the rows in the Table that match the regular expression provided, * and returns references to those rows. Returns an array, so for must be * used to iterate through all the rows, as shown in the example. The * column to search may be specified by either its ID or title. * @param regexp The regular expression to match * @param column The column ID (number) or * title (string) * @returns An Array of TableRow objects */ matchRows(regexp: string, column?: string | number): TableRow[]; /** * Retrieves all values in the specified column, and returns them * as an array. The column may be specified by either its ID or title. * @param column String or Number of the column to return * @returns Array of column values */ getColumn(column: string | number): any[]; /** * Removes all rows from a Table. While all rows are removed, * columns and column titles are maintained. */ clearRows(): void; /** * Use addColumn() to add a new column to a Table object. * Typically, you will want to specify a title, so the column * may be easily referenced later by name. (If no title is * specified, the new column's title will be null.) * @param title title of the given column */ addColumn(title?: string): void; /** * Returns the total number of columns in a Table. * @returns Number of columns in this table */ getColumnCount(): number; /** * Returns the total number of rows in a Table. * @returns Number of rows in this table */ getRowCount(): number; /** * Removes any of the specified characters (or "tokens"). * * If no column is specified, then the values in all columns and * rows are processed. A specific column may be referenced by * either its ID or title. * @param chars String listing characters to be removed * @param column Column ID (number) * or name (string) */ removeTokens(chars: string, column?: string | number): void; /** * Trims leading and trailing whitespace, such as spaces and tabs, * from String table values. If no column is specified, then the * values in all columns and rows are trimmed. A specific column * may be referenced by either its ID or title. * @param column Column ID (number) * or name (string) */ trim(column?: string | number): void; /** * Use removeColumn() to remove an existing column from a Table * object. The column to be removed may be identified by either * its title (a String) or its index value (an int). * removeColumn(0) would remove the first column, removeColumn(1) * would remove the second column, and so on. * @param column columnName (string) or ID (number) */ removeColumn(column: string | number): void; /** * Stores a value in the Table's specified row and column. * The row is specified by its ID, while the column may be specified * by either its ID or title. * @param row row ID * @param column column ID (Number) * or title (String) * @param value value to assign */ set(row: number, column: string | number, value: string | number): void; /** * Stores a Float value in the Table's specified row and column. * The row is specified by its ID, while the column may be specified * by either its ID or title. * @param row row ID * @param column column ID (Number) * or title (String) * @param value value to assign */ setNum(row: number, column: string | number, value: number): void; /** * Stores a String value in the Table's specified row and column. * The row is specified by its ID, while the column may be specified * by either its ID or title. * @param row row ID * @param column column ID (Number) * or title (String) * @param value value to assign */ setString(row: number, column: string | number, value: string): void; /** * Retrieves a value from the Table's specified row and column. * The row is specified by its ID, while the column may be specified by * either its ID or title. * @param row row ID * @param column columnName (string) or * ID (number) */ get(row: number, column: string | number): string | number; /** * Retrieves a Float value from the Table's specified row and column. * The row is specified by its ID, while the column may be specified by * either its ID or title. * @param row row ID * @param column columnName (string) or * ID (number) */ getNum(row: number, column: string | number): number; /** * Retrieves a String value from the Table's specified row and column. * The row is specified by its ID, while the column may be specified by * either its ID or title. * @param row row ID * @param column columnName (string) or * ID (number) */ getString(row: number, column: string | number): string; /** * Retrieves all table data and returns as an object. If a column name is * passed in, each row object will be stored with that attribute as its * title. * @param headerColumn Name of the column which should be used to * title each row object (optional) */ getObject(headerColumn?: string): object; /** * Retrieves all table data and returns it as a multidimensional array. */ getArray(): any[]; } /** * A TableRow object represents a single row of data values, * stored in columns, from a table. * * A Table Row contains both an ordered array, and an unordered * JSON object. */ class TableRow { constructor(row: any[]); /** * Stores a value in the TableRow's specified column. * The column may be specified by either its ID or title. * @param column Column ID (Number) * or Title (String) * @param value The value to be stored */ set(column: string | number, value: string | number): void; /** * Stores a Float value in the TableRow's specified column. * The column may be specified by either its ID or title. * @param column Column ID (Number) * or Title (String) * @param value The value to be stored * as a Float */ setNum(column: string | number, value: number | string): void; /** * Stores a String value in the TableRow's specified column. * The column may be specified by either its ID or title. * @param column Column ID (Number) * or Title (String) * @param value The value to be stored * as a String */ setString(column: string | number, value: string | number | boolean | object): void; /** * Retrieves a value from the TableRow's specified column. * The column may be specified by either its ID or title. * @param column columnName (string) or * ID (number) */ get(column: string | number): string | number; /** * Retrieves a Float value from the TableRow's specified * column. The column may be specified by either its ID or * title. * @param column columnName (string) or * ID (number) * @returns Float Floating point number */ getNum(column: string | number): number; /** * Retrieves an String value from the TableRow's specified * column. The column may be specified by either its ID or * title. * @param column columnName (string) or * ID (number) * @returns String */ getString(column: string | number): string; } /** * A class to describe an XML object. * * Each `p5.XML` object provides an easy way to interact with XML data. * Extensible Markup Language * (XML) * is a standard format for sending data between applications. Like HTML, the * XML format is based on tags and attributes, as in * `<time units="s">1234</time>`. * * Note: Use loadXML() to load external XML files. */ class XML { /** * Returns the element's parent element as a new p5.XML * object. * @returns parent element. */ getParent(): XML; /** * Returns the element's name as a `String`. * * An XML element's name is given by its tag. For example, the element * `<language>JavaScript</language>` has the name `language`. * @returns name of the element. */ getName(): string; /** * Sets the element's tag name. * * An XML element's name is given by its tag. For example, the element * `<language>JavaScript</language>` has the name `language`. * * The parameter, `name`, is the element's new name as a string. For example, * calling `myXML.setName('planet')` will make the element's new tag name * `<planet></planet>`. * @param name new tag name of the element. */ setName(name: string): void; /** * Returns `true` if the element has child elements and `false` if not. * @returns whether the element has children. */ hasChildren(): boolean; /** * Returns an array with the names of the element's child elements as * `String`s. * @returns names of the child elements. */ listChildren(): string[]; /** * Returns an array with the element's child elements as new * p5.XML objects. * * The parameter, `name`, is optional. If a string is passed, as in * `myXML.getChildren('cat')`, then the method will only return child elements * with the tag `<cat>`. * @param name name of the elements to return. * @returns child elements. */ getChildren(name?: string): XML[]; /** * Returns the first matching child element as a new * p5.XML object. * * The parameter, `name`, is optional. If a string is passed, as in * `myXML.getChild('cat')`, then the first child element with the tag * `<cat>` will be returned. If a number is passed, as in * `myXML.getChild(1)`, then the child element at that index will be returned. * @param name element name or index. * @returns child element. */ getChild(name: string | number): XML; /** * Adds a new child element and returns a reference to it. * * The parameter, `child`, is the p5.XML object to add * as a child element. For example, calling `myXML.addChild(otherXML)` inserts * `otherXML` as a child element of `myXML`. * @param child child element to add. * @returns added child element. */ addChild(child: XML): XML; /** * Removes the first matching child element. * * The parameter, `name`, is the child element to remove. If a string is * passed, as in `myXML.removeChild('cat')`, then the first child element * with the tag `<cat>` will be removed. If a number is passed, as in * `myXML.removeChild(1)`, then the child element at that index will be * removed. * @param name name or index of the child element to remove. */ removeChild(name: string | number): void; /** * Returns the number of attributes the element has. * @returns number of attributes. */ getAttributeCount(): number; /** * Returns an `Array` with the names of the element's attributes. * * Note: Use * myXML.getString() or * myXML.getNum() to return an attribute's value. * @returns attribute names. */ listAttributes(): string[]; /** * Returns `true` if the element has a given attribute and `false` if not. * * The parameter, `name`, is a string with the name of the attribute being * checked. * * Note: Use * myXML.getString() or * myXML.getNum() to return an attribute's value. * @param name name of the attribute to be checked. * @returns whether the element has the attribute. */ hasAttribute(name: string): boolean; /** * Return an attribute's value as a `Number`. * * The first parameter, `name`, is a string with the name of the attribute * being checked. For example, calling `myXML.getNum('id')` returns the * element's `id` attribute as a number. * * The second parameter, `defaultValue`, is optional. If a number is passed, * as in `myXML.getNum('id', -1)`, it will be returned if the attribute * doesn't exist or can't be converted to a number. * * Note: Use * myXML.getString() or * myXML.getNum() to return an attribute's value. * @param name name of the attribute to be checked. * @param defaultValue value to return if the attribute doesn't exist. * @returns attribute value as a number. */ getNum(name: string, defaultValue?: number): number; /** * Return an attribute's value as a string. * * The first parameter, `name`, is a string with the name of the attribute * being checked. For example, calling `myXML.getString('color')` returns the * element's `id` attribute as a string. * * The second parameter, `defaultValue`, is optional. If a string is passed, * as in `myXML.getString('color', 'deeppink')`, it will be returned if the * attribute doesn't exist. * * Note: Use * myXML.getString() or * myXML.getNum() to return an attribute's value. * @param name name of the attribute to be checked. * @param defaultValue value to return if the attribute doesn't exist. * @returns attribute value as a string. */ getString(name: string, defaultValue?: number): string; /** * Sets an attribute to a given value. * * The first parameter, `name`, is a string with the name of the attribute * being set. * * The second parameter, `value`, is the attribute's new value. For example, * calling `myXML.setAttribute('id', 123)` sets the `id` attribute to the * value 123. * @param name name of the attribute to be set. * @param value attribute's new value. */ setAttribute(name: string, value: number | string | boolean): void; /** * Returns the element's content as a `String`. * * The parameter, `defaultValue`, is optional. If a string is passed, as in * `myXML.getContent('???')`, it will be returned if the element has no * content. * @param defaultValue value to return if the element has no * content. * @returns element's content as a string. */ getContent(defaultValue?: string): string; /** * Returns the element as a `String`. * * `myXML.serialize()` is useful for sending the element over the network or * saving it to a file. * @returns element as a string. */ serialize(): string; } /** * A class to describe a two or three-dimensional vector. * * A vector can be thought of in different ways. In one view, a vector is like * an arrow pointing in space. Vectors have both magnitude (length) and * direction. * * `p5.Vector` objects are often used to program motion because they simplify * the math. For example, a moving ball has a position and a velocity. * Position describes where the ball is in space. The ball's position vector * extends from the origin to the ball's center. Velocity describes the ball's * speed and the direction it's moving. If the ball is moving straight up, its * velocity vector points straight up. Adding the ball's velocity vector to * its position vector moves it, as in `pos.add(vel)`. Vector math relies on * methods inside the `p5.Vector` class. * * Note: createVector() is the recommended way * to make an instance of this class. */ class Vector { constructor(x?: number, y?: number, z?: number); /** * The x component of the vector */ x: number; /** * The y component of the vector */ y: number; /** * The z component of the vector */ z: number; /** * Creates a new 2D vector from an angle. * @param angle desired angle, in radians. Unaffected by angleMode(). * @param length length of the new vector (defaults to 1). * @returns new p5.Vector object. */ static fromAngle(angle: number, length?: number): Vector; /** * Creates a new 3D vector from a pair of ISO spherical angles. * @param theta polar angle in radians (zero is up). * @param phi azimuthal angle in radians * (zero is out of the screen). * @param length length of the new vector (defaults to 1). * @returns new p5.Vector object. */ static fromAngles(theta: number, phi: number, length?: number): Vector; /** * Creates a new 2D unit vector with a random heading. * @returns new p5.Vector object. */ static random2D(): Vector; /** * Creates a new 3D unit vector with a random heading. * @returns new p5.Vector object. */ static random3D(): Vector; static copy(v: Vector): Vector; static add(v1: Vector, v2: Vector, target?: Vector): Vector; static rem(v1: Vector, v2: Vector): Vector; static rem(v1: Vector, v2: Vector): Vector; static sub(v1: Vector, v2: Vector, target?: Vector): Vector; /** * Multiplies a vector by a scalar and returns a new vector. * @returns resulting new p5.Vector. */ static mult(): Vector; static mult(x: number, y: number, z?: number): Vector; static mult(v: Vector, n: number, target?: Vector): Vector; static mult(v0: Vector, v1: Vector, target?: Vector): Vector; static mult(v0: Vector, arr: number[], target?: Vector): Vector; /** * Rotates the vector (only 2D vectors) by the given angle; magnitude remains the same. Returns a new vector. */ static rotate(): void; static rotate(v: Vector, angle: number, target?: Vector): void; /** * Divides a vector by a scalar and returns a new vector. * @returns The resulting new p5.Vector */ static div(): Vector; static div(x: number, y: number, z?: number): Vector; static div(v: Vector, n: number, target?: Vector): Vector; static div(v0: Vector, v1: Vector, target?: Vector): Vector; static div(v0: Vector, arr: number[], target?: Vector): Vector; /** * Calculates the dot product of two vectors. * @returns dot product. */ static dot(): number; static dot(v1: Vector, v2: Vector): number; /** * Calculates the cross product of two vectors. * @returns cross product. */ static cross(): number; static cross(v1: Vector, v2: Vector): number; /** * Calculates the Euclidean distance between two points (considering a * point as a vector object). * @returns The distance */ static dist(): number; static dist(v1: Vector, v2: Vector): number; /** * Linear interpolate a vector to another vector and return the result as a * new vector. * @returns The lerped value */ static lerp(): Vector; static lerp(v1: Vector, v2: Vector, amt: number, target?: Vector): Vector; /** * Performs spherical linear interpolation with the other vector * and returns the resulting vector. * This works in both 3D and 2D. As for 2D, the result of slerping * between 2D vectors is always a 2D vector. * @returns slerped vector between v1 and v2 */ static slerp(): Vector; static slerp(v1: Vector, v2: Vector, amt: number, target?: Vector): Vector; /** * Calculates the magnitude (length) of the vector and returns the result as * a float (this is simply the equation `sqrt(x*x + y*y + z*z)`.) * @returns The magnitude of vecT */ static mag(): number; static mag(vecT: Vector): number; /** * Calculates the squared magnitude of the vector and returns the result * as a float (this is simply the equation (x*x + y*y + z*z).) * Faster if the real length is not required in the * case of comparing vectors, etc. * @returns the squared magnitude of vecT */ static magSq(): number; static magSq(vecT: Vector): number; /** * Normalize the vector to length 1 (make it a unit vector). * @returns The vector v, normalized to a length of 1 */ static normalize(): Vector; static normalize(v: Vector, target?: Vector): Vector; /** * Limit the magnitude of the vector to the value used for the max * parameter. * @returns v with a magnitude limited to max */ static limit(): Vector; static limit(v: Vector, max: number, target?: Vector): Vector; /** * Set the magnitude of the vector to the value used for the len * parameter. * @returns v with a magnitude set to len */ static setMag(): Vector; static setMag(v: Vector, len: number, target?: Vector): Vector; /** * Calculate the angle of rotation for this vector (only 2D vectors). * p5.Vectors created using createVector() * will take the current angleMode into * consideration, and give the angle in radians or degrees accordingly. * @returns the angle of rotation */ static heading(): number; static heading(v: Vector): number; /** * Calculates and returns the angle between two vectors. This function will take * the angleMode on v1 into consideration, and * give the angle in radians or degrees accordingly. * @returns angle between the two vectors. */ static angleBetween(): number; static angleBetween(v1: Vector, v2: Vector): number; /** * Reflect a vector about a normal to a line in 2D, or about a normal to a * plane in 3D. * @returns the reflected vector */ static reflect(): Vector; static reflect(incidentVector: Vector, surfaceNormal: Vector, target?: Vector): Vector; /** * Return a representation of this vector as a float array. This is only * for temporary use. If used in any other fashion, the contents should be * copied by using the p5.Vector.copy() * method to copy into your own vector. * @returns an Array with the 3 values */ static array(): number[]; static array(v: Vector): number[]; /** * Equality check against a p5.Vector */ static equals(): boolean; static equals(v1: Vector | any[], v2: Vector | any[]): boolean; /** * Retrieves the value at the specified index from the vector. * * This method allows you to get the value of a specific component of the vector * by providing its index. Think of the vector as a list of numbers, where each * number represents a different direction (like x, y, or z). The index is just * the position of the number in that list. * * For example, if you have a vector with values 10, 20, 30 the index 0 would * give you the first value 10, index 1 would give you the second value 20, * and so on. * @param index The position of the value you want to get from the vector. * @returns The value at the specified position in the vector. */ getValue(index: number): number; /** * Sets the value at the specified index of the vector. * * This method allows you to change a specific component of the vector by providing its index and the new value you want to set. * Think of the vector as a list of numbers, where each number represents a different direction (like x, y, or z). * The index is just the position of the number in that list. * * For example, if you have a vector with values [0, 20, 30], and you want to change the second value (20) to 50, * you would use this method with index 1 (since indexes start at 0) and value 50. * @param index The position in the vector where you want to set the new value. * @param value The new value you want to set at the specified position. */ setValue(index: number, value: number): void; /** * Returns a string representation of a vector. * * Calling `toString()` is useful for printing vectors to the console while * debugging. * @returns string representation of the vector. */ toString(): string; /** * Sets the vector's `x`, `y`, and `z` components. * * `set()` can use separate numbers, as in `v.set(1, 2, 3)`, a * p5.Vector object, as in `v.set(v2)`, or an * array of numbers, as in `v.set([1, 2, 3])`. * * If a value isn't provided for a component, it will be set to 0. For * example, `v.set(4, 5)` sets `v.x` to 4, `v.y` to 5, and `v.z` to 0. * Calling `set()` with no arguments, as in `v.set()`, sets all the vector's * components to 0. * @param x x component of the vector. * @param y y component of the vector. * @param z z component of the vector. */ set(x?: number, y?: number, z?: number): Vector; set(value: Vector | number[]): Vector; /** * Returns a copy of the p5.Vector object. * @returns copy of the p5.Vector object. */ copy(): Vector; /** * Adds to a vector's components. * * `add()` can use separate numbers, as in `v.add(1, 2, 3)`, * another p5.Vector object, as in `v.add(v2)`, or * an array of numbers, as in `v.add([1, 2, 3])`. * * If a value isn't provided for a component, it won't change. For * example, `v.add(4, 5)` adds 4 to `v.x`, 5 to `v.y`, and 0 to `v.z`. * Calling `add()` with no arguments, as in `v.add()`, has no effect. * * This method supports N-dimensional vectors. * * The static version of `add()`, as in `p5.Vector.add(v2, v1)`, returns a new * p5.Vector object and doesn't change the * originals. * @param x x component of the vector to be added or an array of components. * @param y y component of the vector to be added. * @param z z component of the vector to be added. */ add(x: number | any[], y?: number, z?: number): Vector; add(value: Vector | number[]): Vector; /** * Performs modulo (remainder) division with a vector's `x`, `y`, and `z` * components. * * `rem()` can use separate numbers, as in `v.rem(1, 2, 3)`, * another p5.Vector object, as in `v.rem(v2)`, or * an array of numbers, as in `v.rem([1, 2, 3])`. * * If only one value is provided, as in `v.rem(2)`, then all the components * will be set to their values modulo 2. If two values are provided, as in * `v.rem(2, 3)`, then `v.z` won't change. Calling `rem()` with no * arguments, as in `v.rem()`, has no effect. * * The static version of `rem()`, as in `p5.Vector.rem(v2, v1)`, returns a * new p5.Vector object and doesn't change the * originals. * @param x x component of divisor vector. * @param y y component of divisor vector. * @param z z component of divisor vector. */ rem(x: number, y: number, z: number): Vector; rem(value: Vector | number[]): Vector; /** * Subtracts from a vector's `x`, `y`, and `z` components. * * `sub()` can use separate numbers, as in `v.sub(1, 2, 3)`, another * p5.Vector object, as in `v.sub(v2)`, or an array * of numbers, as in `v.sub([1, 2, 3])`. * * If a value isn't provided for a component, it won't change. For * example, `v.sub(4, 5)` subtracts 4 from `v.x`, 5 from `v.y`, and 0 from `v.z`. * Calling `sub()` with no arguments, as in `v.sub()`, has no effect. * * The static version of `sub()`, as in `p5.Vector.sub(v2, v1)`, returns a new * p5.Vector object and doesn't change the * originals. * @param x x component of the vector to subtract. * @param y y component of the vector to subtract. * @param z z component of the vector to subtract. */ sub(x: number, y?: number, z?: number): Vector; sub(value: Vector | number[]): Vector; /** * Multiplies a vector's `x`, `y`, and `z` components. * * `mult()` can use separate numbers, as in `v.mult(1, 2, 3)`, another * p5.Vector object, as in `v.mult(v2)`, or an array * of numbers, as in `v.mult([1, 2, 3])`. * * If only one value is provided, as in `v.mult(2)`, then all the components * will be multiplied by 2. If a value isn't provided for a component, it * won't change. For example, `v.mult(4, 5)` multiplies `v.x` by, `v.y` by 5, * and `v.z` by 1. Calling `mult()` with no arguments, as in `v.mult()`, has * no effect. * * The static version of `mult()`, as in `p5.Vector.mult(v, 2)`, returns a new * p5.Vector object and doesn't change the * originals. * @param n The number to multiply with the vector */ mult(n: number): Vector; mult(x: number, y: number, z?: number): Vector; mult(arr: number[]): Vector; mult(v: Vector): Vector; /** * Divides a vector's `x`, `y`, and `z` components. * * `div()` can use separate numbers, as in `v.div(1, 2, 3)`, another * p5.Vector object, as in `v.div(v2)`, or an array * of numbers, as in `v.div([1, 2, 3])`. * * If only one value is provided, as in `v.div(2)`, then all the components * will be divided by 2. If a value isn't provided for a component, it * won't change. For example, `v.div(4, 5)` divides `v.x` by, `v.y` by 5, * and `v.z` by 1. Calling `div()` with no arguments, as in `v.div()`, has * no effect. * * The static version of `div()`, as in `p5.Vector.div(v, 2)`, returns a new * p5.Vector object and doesn't change the * originals. * @param n The number to divide the vector by */ div(n: number): Vector; div(x: number, y: number, z?: number): Vector; div(arr: number[]): Vector; div(v: Vector): Vector; /** * Calculates the magnitude (length) of the vector. * * Use mag() to calculate the magnitude of a 2D vector * using components as in `mag(x, y)`. * @returns magnitude of the vector. */ mag(): number; /** * Calculates the magnitude (length) of the vector squared. * @returns squared magnitude of the vector. */ magSq(): number; /** * Calculates the dot product of two vectors. * * The dot product is a number that describes the overlap between two vectors. * Visually, the dot product can be thought of as the "shadow" one vector * casts on another. The dot product's magnitude is largest when two vectors * point in the same or opposite directions. Its magnitude is 0 when two * vectors form a right angle. * * The version of `dot()` with one parameter interprets it as another * p5.Vector object. * * The version of `dot()` with multiple parameters interprets them as the * `x`, `y`, and `z` components of another vector. * * The static version of `dot()`, as in `p5.Vector.dot(v1, v2)`, is the same * as calling `v1.dot(v2)`. * @param x x component of the vector. * @param y y component of the vector. * @param z z component of the vector. * @returns dot product. */ dot(x: number, y?: number, z?: number): number; dot(v: Vector): number; /** * Calculates the cross product of two vectors. * * The cross product is a vector that points straight out of the plane created * by two vectors. The cross product's magnitude is the area of the parallelogram * formed by the original two vectors. * * The static version of `cross()`, as in `p5.Vector.cross(v1, v2)`, is the same * as calling `v1.cross(v2)`. * @param v p5.Vector to be crossed. * @returns cross product as a p5.Vector. */ cross(v: Vector): Vector; /** * Calculates the distance between two points represented by vectors. * * A point's coordinates can be represented by the components of a vector * that extends from the origin to the point. * * The static version of `dist()`, as in `p5.Vector.dist(v1, v2)`, is the same * as calling `v1.dist(v2)`. * * Use dist() to calculate the distance between points * using coordinates as in `dist(x1, y1, x2, y2)`. * @param v x, y, and z coordinates of a p5.Vector. * @returns distance. */ dist(v: Vector): number; /** * Scales the components of a p5.Vector object so * that its magnitude is 1. * * The static version of `normalize()`, as in `p5.Vector.normalize(v)`, * returns a new p5.Vector object and doesn't change * the original. * @returns normalized p5.Vector. */ normalize(): Vector; /** * Limits a vector's magnitude to a maximum value. * * The static version of `limit()`, as in `p5.Vector.limit(v, 5)`, returns a * new p5.Vector object and doesn't change the * original. * @param max maximum magnitude for the vector. */ limit(max: number): Vector; /** * Sets a vector's magnitude to a given value. * * The static version of `setMag()`, as in `p5.Vector.setMag(v, 10)`, returns * a new p5.Vector object and doesn't change the * original. * @param len new length for this vector. */ setMag(len: number): Vector; /** * Calculates the angle a 2D vector makes with the positive x-axis. * * By convention, the positive x-axis has an angle of 0. Angles increase in * the clockwise direction. * * If the vector was created with * createVector(), `heading()` returns angles * in the units of the current angleMode(). * * The static version of `heading()`, as in `p5.Vector.heading(v)`, works the * same way. * @returns angle of rotation. */ heading(): number; /** * Rotates a 2D vector to a specific angle without changing its magnitude. * * By convention, the positive x-axis has an angle of 0. Angles increase in * the clockwise direction. * * If the vector was created with * createVector(), `setHeading()` uses * the units of the current angleMode(). * @param angle angle of rotation. */ setHeading(angle: number): Vector; /** * Rotates a 2D vector by an angle without changing its magnitude. * * By convention, the positive x-axis has an angle of 0. Angles increase in * the clockwise direction. * * If the vector was created with * createVector(), `rotate()` uses * the units of the current angleMode(). * * The static version of `rotate()`, as in `p5.Vector.rotate(v, PI)`, * returns a new p5.Vector object and doesn't change * the original. * @param angle angle of rotation. */ rotate(angle: number): Vector; /** * Calculates the angle between two vectors. * * The angles returned are signed, which means that * `v1.angleBetween(v2) === -v2.angleBetween(v1)`. * * If the vector was created with * createVector(), `angleBetween()` returns * angles in the units of the current * angleMode(). * @param value x, y, and z components of a p5.Vector. * @returns angle between the vectors. */ angleBetween(value: Vector): number; /** * Calculates new `x`, `y`, and `z` components that are proportionally the * same distance between two vectors. * * The `amt` parameter is the amount to interpolate between the old vector and * the new vector. 0.0 keeps all components equal to the old vector's, 0.5 is * halfway between, and 1.0 sets all components equal to the new vector's. * * The static version of `lerp()`, as in `p5.Vector.lerp(v0, v1, 0.5)`, * returns a new p5.Vector object and doesn't change * the original. * @param x x component. * @param y y component. * @param z z component. * @param amt amount of interpolation between 0.0 (old vector) * and 1.0 (new vector). 0.5 is halfway between. */ lerp(x: number, y: number, z: number, amt: number): Vector; lerp(v: Vector, amt: number): Vector; /** * Calculates a new heading and magnitude that are between two vectors. * * The `amt` parameter is the amount to interpolate between the old vector and * the new vector. 0.0 keeps the heading and magnitude equal to the old * vector's, 0.5 sets them halfway between, and 1.0 sets the heading and * magnitude equal to the new vector's. * * `slerp()` differs from lerp() because * it interpolates magnitude. Calling `v0.slerp(v1, 0.5)` sets `v0`'s * magnitude to a value halfway between its original magnitude and `v1`'s. * Calling `v0.lerp(v1, 0.5)` makes no such guarantee. * * The static version of `slerp()`, as in `p5.Vector.slerp(v0, v1, 0.5)`, * returns a new p5.Vector object and doesn't change * the original. * @param v p5.Vector to slerp toward. * @param amt amount of interpolation between 0.0 (old vector) * and 1.0 (new vector). 0.5 is halfway between. */ slerp(v: Vector, amt: number): Vector; /** * Reflects a vector about a line in 2D or a plane in 3D. * * The orientation of the line or plane is described by a normal vector that * points away from the shape. * * The static version of `reflect()`, as in `p5.Vector.reflect(v, n)`, * returns a new p5.Vector object and doesn't change * the original. * @param surfaceNormal p5.Vector * to reflect about. */ reflect(surfaceNormal: Vector): Vector; /** * Returns the vector's components as an array of numbers. * @returns array with the vector's components. */ array(): number[]; /** * Checks whether all the vector's components are equal to another vector's. * * `equals()` returns `true` if the vector's components are all the same as another * vector's and `false` if not. * * The version of `equals()` with one parameter interprets it as another * p5.Vector object. * * The version of `equals()` with multiple parameters interprets them as the * components of another vector. Any missing parameters are assigned the value * 0. * * The static version of `equals()`, as in `p5.Vector.equals(v0, v1)`, * interprets both parameters as p5.Vector objects. * @param x x component of the vector. * @param y y component of the vector. * @param z z component of the vector. * @returns whether the vectors are equal. */ equals(x?: number, y?: number, z?: number): boolean; equals(value: Vector | any[]): boolean; /** * Replaces the components of a p5.Vector that are very close to zero with zero. * * In computers, handling numbers with decimals can give slightly imprecise answers due to the way those numbers are represented. * This can make it hard to check if a number is zero, as it may be close but not exactly zero. * This method rounds very close numbers to zero to make those checks easier * * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON * @returns with components very close to zero replaced with zero. */ clampToZero(): Vector; } /** * A class to describe fonts. Create through `loadFont()`. */ class Font { /** The CSS name for the font. */ name: string; /** The CSS FontFace definition for the font. */ face: FontFace; /** Typr data for the font. */ data?: { _data: Uint8Array; GSUB: Record; 'OS/2': Record; cmap: { ids: Record; tables: Array>; off: number; }; glyf: Array; head: Record; hhea: Record; htmx: Record; loca: Array; maxp: Record; name: Record; post: Record; }; /** * Returns a flat array of path commands that describe the outlines of a string of text. * * Each command is represented as an array of the form `[type, ...coords]`, where: * * - `type` is one of `'M'`, `'L'`, `'Q'`, `'C'`, or `'Z'`, * * - `coords` are the numeric values needed for that command. * * `'M'` indicates a "move to" (starting a new contour), * `'L'` a line segment, * `'Q'` a quadratic bezier, * `'C'` a cubic bezier, and * `'Z'` closes the current path. * * The first two parameters, `x` and `y`, specify the baseline origin for the text. * Optionally, you can provide a `width` and `height` for text wrapping; if you don't need * wrapping, you can omit them and directly pass `options` as the fourth parameter. * @param str The text to convert into path commands. * @param x x‐coordinate of the text baseline. * @param y y‐coordinate of the text baseline. * @param width Optional width for text wrapping. * @param height Optional height for text wrapping. * @returns A flat array of path commands. */ textToPaths(str: string, x: number, y: number, width?: number, height?: number): any[][]; /** * Returns an array of points outlining a string of text written using the * font. * * Each point object in the array has three properties that describe the * point's location and orientation, called its path angle. For example, * `{ x: 10, y: 20, alpha: 450 }`. * * The first parameter, `str`, is a string of text. The second and third * parameters, `x` and `y`, are the text's position. By default, they set the * coordinates of the bounding box's bottom-left corner. See * textAlign() for more ways to align text. * * The fourth parameter, `options`, is also optional. `font.textToPoints()` * expects an object with the following properties: * * `sampleFactor` is the ratio of the text's path length to the number of * samples. It defaults to 0.1. Higher values produce more points along the * path and are more precise. * * `simplifyThreshold` removes collinear points if it's set to a number other * than 0. The value represents the threshold angle in radians to use when determining * whether two edges are collinear. * @param str string of text. * @param x x-coordinate of the text. * @param y y-coordinate of the text. * @param options Configuration: * @returns array of point objects, each with `x`, `y`, and `alpha` (path angle) properties. */ textToPoints(str: string, x: number, y: number, options?: { sampleFactor?: number; simplifyThreshold?: number }): object[]; /** * Returns an array of arrays of points outlining a string of text written using the * font. Each array represents a contour, so the letter O will have two outer arrays: * one for the outer edge of the shape, and one for the inner edge of the hole. * * Each point object in a contour array has three properties that describe the * point's location and orientation, called its path angle. For example, * `{ x: 10, y: 20, alpha: 450 }`. * * The first parameter, `str`, is a string of text. The second and third * parameters, `x` and `y`, are the text's position. By default, they set the * coordinates of the bounding box's bottom-left corner. See * textAlign() for more ways to align text. * * The fourth parameter, `options`, is also optional. `font.textToPoints()` * expects an object with the following properties: * * `sampleFactor` is the ratio of the text's path length to the number of * samples. It defaults to 0.1. Higher values produce more points along the * path and are more precise. * * `simplifyThreshold` removes collinear points if it's set to a number other * than 0. The value represents the threshold angle in radians to use when determining * whether two edges are collinear. * @param str string of text. * @param x x-coordinate of the text. * @param y y-coordinate of the text. * @param options Configuration options: * @returns array of point objects, each with `x`, `y`, and `alpha` (path angle) properties. */ textToContours(str: string, x: number, y: number, options?: { sampleFactor?: number; simplifyThreshold?: number }): { x: number; y: number; alpha: number }[][]; /** * Converts text into a 3D model that can be rendered in WebGL mode. * * This method transforms flat text into extruded 3D geometry, allowing * for dynamic effects like depth, warping, and custom shading. * * It works by taking the outlines (contours) of each character in the * provided text string and constructing a 3D shape from them. * * Once your 3D text is ready, you can rotate it in 3D space using orbitControl() * — just click and drag with your mouse to see it from all angles! * * Use the extrude slider to give your letters depth: slide it up, and your * flat text turns into a solid, multi-dimensional object. * * You can also choose from various fonts such as "Anton", "Montserrat", or "Source Serif", * much like selecting fancy fonts in a word processor, * * The generated model (a Geometry object) can be manipulated further—rotated, scaled, * or styled with shaders—to create engaging, interactive visual art. * @param str The text string to convert into a 3D model. * @param x The x-coordinate for the starting position of the text. * @param y The y-coordinate for the starting position of the text. * @param width Maximum width of the text block (wraps text if exceeded). * @param height Maximum height of the text block. * @param options Configuration options for the 3D text: * @returns A geometry object representing the 3D model of the text. */ textToModel(str: string, x: number, y: number, width: number, height: number, options?: { extrude?: number; sampleFactor?: number }): Geometry; } /** * A class to describe a camera for viewing a 3D sketch. * * Each `p5.Camera` object represents a camera that views a section of 3D * space. It stores information about the camera’s position, orientation, and * projection. * * In WebGL mode, the default camera is a `p5.Camera` object that can be * controlled with the camera(), * perspective(), * ortho(), and * frustum() functions. Additional cameras can be * created with createCamera() and activated * with setCamera(). * * Note: `p5.Camera`’s methods operate in two coordinate systems: * * - The “world” coordinate system describes positions in terms of their * relationship to the origin along the x-, y-, and z-axes. For example, * calling `myCamera.setPosition()` places the camera in 3D space using * "world" coordinates. * * - The "local" coordinate system describes positions from the camera's point * of view: left-right, up-down, and forward-backward. For example, calling * `myCamera.move()` moves the camera along its own axes. */ class Camera { constructor(rendererGL: RendererGL); /** * The camera’s x-coordinate. * * By default, the camera’s x-coordinate is set to 0 in "world" space. */ eyeX: number; /** * The camera’s y-coordinate. * * By default, the camera’s y-coordinate is set to 0 in "world" space. */ eyeY: number; /** * The camera’s z-coordinate. * * By default, the camera’s z-coordinate is set to 800 in "world" space. */ eyeZ: number; /** * The x-coordinate of the place where the camera looks. * * By default, the camera looks at the origin `(0, 0, 0)` in "world" space, so * `myCamera.centerX` is 0. */ centerX: number; /** * The y-coordinate of the place where the camera looks. * * By default, the camera looks at the origin `(0, 0, 0)` in "world" space, so * `myCamera.centerY` is 0. */ centerY: number; /** * The y-coordinate of the place where the camera looks. * * By default, the camera looks at the origin `(0, 0, 0)` in "world" space, so * `myCamera.centerZ` is 0. */ centerZ: number; /** * The x-component of the camera's "up" vector. * * The camera's "up" vector orients its y-axis. By default, the "up" vector is * `(0, 1, 0)`, so its x-component is 0 in "local" space. */ upX: number; /** * The y-component of the camera's "up" vector. * * The camera's "up" vector orients its y-axis. By default, the "up" vector is * `(0, 1, 0)`, so its y-component is 1 in "local" space. */ upY: number; /** * The z-component of the camera's "up" vector. * * The camera's "up" vector orients its y-axis. By default, the "up" vector is * `(0, 1, 0)`, so its z-component is 0 in "local" space. */ upZ: number; /** * Sets a perspective projection for the camera. * * In a perspective projection, shapes that are further from the camera appear * smaller than shapes that are near the camera. This technique, called * foreshortening, creates realistic 3D scenes. It’s applied by default in new * `p5.Camera` objects. * * `myCamera.perspective()` changes the camera’s perspective by changing its * viewing frustum. The frustum is the volume of space that’s visible to the * camera. The frustum’s shape is a pyramid with its top cut off. The camera * is placed where the top of the pyramid should be and points towards the * base of the pyramid. It views everything within the frustum. * * The first parameter, `fovy`, is the camera’s vertical field of view. It’s * an angle that describes how tall or narrow a view the camera has. For * example, calling `myCamera.perspective(0.5)` sets the camera’s vertical * field of view to 0.5 radians. By default, `fovy` is calculated based on the * sketch’s height and the camera’s default z-coordinate, which is 800. The * formula for the default `fovy` is `2 * atan(height / 2 / 800)`. * * The second parameter, `aspect`, is the camera’s aspect ratio. It’s a number * that describes the ratio of the top plane’s width to its height. For * example, calling `myCamera.perspective(0.5, 1.5)` sets the camera’s field * of view to 0.5 radians and aspect ratio to 1.5, which would make shapes * appear thinner on a square canvas. By default, `aspect` is set to * `width / height`. * * The third parameter, `near`, is the distance from the camera to the near * plane. For example, calling `myCamera.perspective(0.5, 1.5, 100)` sets the * camera’s field of view to 0.5 radians, its aspect ratio to 1.5, and places * the near plane 100 pixels from the camera. Any shapes drawn less than 100 * pixels from the camera won’t be visible. By default, `near` is set to * `0.1 * 800`, which is 1/10th the default distance between the camera and * the origin. * * The fourth parameter, `far`, is the distance from the camera to the far * plane. For example, calling `myCamera.perspective(0.5, 1.5, 100, 10000)` * sets the camera’s field of view to 0.5 radians, its aspect ratio to 1.5, * places the near plane 100 pixels from the camera, and places the far plane * 10,000 pixels from the camera. Any shapes drawn more than 10,000 pixels * from the camera won’t be visible. By default, `far` is set to `10 * 800`, * which is 10 times the default distance between the camera and the origin. * @param fovy camera frustum vertical field of view. Defaults to * `2 * atan(height / 2 / 800)`. * @param aspect camera frustum aspect ratio. Defaults to * `width / height`. * @param near distance from the camera to the near clipping plane. * Defaults to `0.1 * 800`. * @param far distance from the camera to the far clipping plane. * Defaults to `10 * 800`. */ perspective(fovy?: number, aspect?: number, near?: number, far?: number): void; /** * Sets an orthographic projection for the camera. * * In an orthographic projection, shapes with the same size always appear the * same size, regardless of whether they are near or far from the camera. * * `myCamera.ortho()` changes the camera’s perspective by changing its viewing * frustum from a truncated pyramid to a rectangular prism. The frustum is the * volume of space that’s visible to the camera. The camera is placed in front * of the frustum and views everything within the frustum. `myCamera.ortho()` * has six optional parameters to define the viewing frustum. * * The first four parameters, `left`, `right`, `bottom`, and `top`, set the * coordinates of the frustum’s sides, bottom, and top. For example, calling * `myCamera.ortho(-100, 100, 200, -200)` creates a frustum that’s 200 pixels * wide and 400 pixels tall. By default, these dimensions are set based on * the sketch’s width and height, as in * `myCamera.ortho(-width / 2, width / 2, -height / 2, height / 2)`. * * The last two parameters, `near` and `far`, set the distance of the * frustum’s near and far plane from the camera. For example, calling * `myCamera.ortho(-100, 100, 200, -200, 50, 1000)` creates a frustum that’s * 200 pixels wide, 400 pixels tall, starts 50 pixels from the camera, and * ends 1,000 pixels from the camera. By default, `near` and `far` are set to * 0 and `max(width, height) + 800`, respectively. * @param left x-coordinate of the frustum’s left plane. Defaults to `-width / 2`. * @param right x-coordinate of the frustum’s right plane. Defaults to `width / 2`. * @param bottom y-coordinate of the frustum’s bottom plane. Defaults to `height / 2`. * @param top y-coordinate of the frustum’s top plane. Defaults to `-height / 2`. * @param near z-coordinate of the frustum’s near plane. Defaults to 0. * @param far z-coordinate of the frustum’s far plane. Defaults to `max(width, height) + 800`. */ ortho(left?: number, right?: number, bottom?: number, top?: number, near?: number, far?: number): void; /** * Sets the camera's frustum. * * In a frustum projection, shapes that are further from the camera appear * smaller than shapes that are near the camera. This technique, called * foreshortening, creates realistic 3D scenes. * * `myCamera.frustum()` changes the camera’s perspective by changing its * viewing frustum. The frustum is the volume of space that’s visible to the * camera. The frustum’s shape is a pyramid with its top cut off. The camera * is placed where the top of the pyramid should be and points towards the * base of the pyramid. It views everything within the frustum. * * The first four parameters, `left`, `right`, `bottom`, and `top`, set the * coordinates of the frustum’s sides, bottom, and top. For example, calling * `myCamera.frustum(-100, 100, 200, -200)` creates a frustum that’s 200 * pixels wide and 400 pixels tall. By default, these coordinates are set * based on the sketch’s width and height, as in * `myCamera.frustum(-width / 20, width / 20, height / 20, -height / 20)`. * * The last two parameters, `near` and `far`, set the distance of the * frustum’s near and far plane from the camera. For example, calling * `myCamera.frustum(-100, 100, 200, -200, 50, 1000)` creates a frustum that’s * 200 pixels wide, 400 pixels tall, starts 50 pixels from the camera, and ends * 1,000 pixels from the camera. By default, near is set to `0.1 * 800`, which * is 1/10th the default distance between the camera and the origin. `far` is * set to `10 * 800`, which is 10 times the default distance between the * camera and the origin. * @param left x-coordinate of the frustum’s left plane. Defaults to `-width / 20`. * @param right x-coordinate of the frustum’s right plane. Defaults to `width / 20`. * @param bottom y-coordinate of the frustum’s bottom plane. Defaults to `height / 20`. * @param top y-coordinate of the frustum’s top plane. Defaults to `-height / 20`. * @param near z-coordinate of the frustum’s near plane. Defaults to `0.1 * 800`. * @param far z-coordinate of the frustum’s far plane. Defaults to `10 * 800`. */ frustum(left?: number, right?: number, bottom?: number, top?: number, near?: number, far?: number): void; /** * Rotates the camera left and right. * * Panning rotates the camera without changing its position. The rotation * happens in the camera’s "local" space. * * The parameter, `angle`, is the angle the camera should rotate. Passing a * positive angle, as in `myCamera.pan(0.001)`, rotates the camera to the * right. Passing a negative angle, as in `myCamera.pan(-0.001)`, rotates the * camera to the left. * * Note: Angles are interpreted based on the current * angleMode(). * @param angle amount to rotate in the current * angleMode(). */ pan(angle: number): void; /** * Rotates the camera up and down. * * Tilting rotates the camera without changing its position. The rotation * happens in the camera’s "local" space. * * The parameter, `angle`, is the angle the camera should rotate. Passing a * positive angle, as in `myCamera.tilt(0.001)`, rotates the camera down. * Passing a negative angle, as in `myCamera.tilt(-0.001)`, rotates the camera * up. * * Note: Angles are interpreted based on the current * angleMode(). * @param angle amount to rotate in the current * angleMode(). */ tilt(angle: number): void; /** * Points the camera at a location. * * `myCamera.lookAt()` changes the camera’s orientation without changing its * position. * * The parameters, `x`, `y`, and `z`, are the coordinates in "world" space * where the camera should point. For example, calling * `myCamera.lookAt(10, 20, 30)` points the camera at the coordinates * `(10, 20, 30)`. * @param x x-coordinate of the position where the camera should look in "world" space. * @param y y-coordinate of the position where the camera should look in "world" space. * @param z z-coordinate of the position where the camera should look in "world" space. */ lookAt(x: number, y: number, z: number): void; /** * Sets the position and orientation of the camera. * * `myCamera.camera()` allows objects to be viewed from different angles. It * has nine parameters that are all optional. * * The first three parameters, `x`, `y`, and `z`, are the coordinates of the * camera’s position in "world" space. For example, calling * `myCamera.camera(0, 0, 0)` places the camera at the origin `(0, 0, 0)`. By * default, the camera is placed at `(0, 0, 800)`. * * The next three parameters, `centerX`, `centerY`, and `centerZ` are the * coordinates of the point where the camera faces in "world" space. For * example, calling `myCamera.camera(0, 0, 0, 10, 20, 30)` places the camera * at the origin `(0, 0, 0)` and points it at `(10, 20, 30)`. By default, the * camera points at the origin `(0, 0, 0)`. * * The last three parameters, `upX`, `upY`, and `upZ` are the components of * the "up" vector in "local" space. The "up" vector orients the camera’s * y-axis. For example, calling * `myCamera.camera(0, 0, 0, 10, 20, 30, 0, -1, 0)` places the camera at the * origin `(0, 0, 0)`, points it at `(10, 20, 30)`, and sets the "up" vector * to `(0, -1, 0)` which is like holding it upside-down. By default, the "up" * vector is `(0, 1, 0)`. * @param x x-coordinate of the camera. Defaults to 0. * @param y y-coordinate of the camera. Defaults to 0. * @param z z-coordinate of the camera. Defaults to 800. * @param centerX x-coordinate of the point the camera faces. Defaults to 0. * @param centerY y-coordinate of the point the camera faces. Defaults to 0. * @param centerZ z-coordinate of the point the camera faces. Defaults to 0. * @param upX x-component of the camera’s "up" vector. Defaults to 0. * @param upY x-component of the camera’s "up" vector. Defaults to 1. * @param upZ z-component of the camera’s "up" vector. Defaults to 0. */ camera(x?: number, y?: number, z?: number, centerX?: number, centerY?: number, centerZ?: number, upX?: number, upY?: number, upZ?: number): void; /** * Moves the camera along its "local" axes without changing its orientation. * * The parameters, `x`, `y`, and `z`, are the distances the camera should * move. For example, calling `myCamera.move(10, 20, 30)` moves the camera 10 * pixels to the right, 20 pixels down, and 30 pixels backward in its "local" * space. * @param x distance to move along the camera’s "local" x-axis. * @param y distance to move along the camera’s "local" y-axis. * @param z distance to move along the camera’s "local" z-axis. */ move(x: number, y: number, z: number): void; /** * Sets the camera’s position in "world" space without changing its * orientation. * * The parameters, `x`, `y`, and `z`, are the coordinates where the camera * should be placed. For example, calling `myCamera.setPosition(10, 20, 30)` * places the camera at coordinates `(10, 20, 30)` in "world" space. * @param x x-coordinate in "world" space. * @param y y-coordinate in "world" space. * @param z z-coordinate in "world" space. */ setPosition(x: number, y: number, z: number): void; /** * Sets the camera’s position, orientation, and projection by copying another * camera. * * The parameter, `cam`, is the `p5.Camera` object to copy. For example, calling * `cam2.set(cam1)` will set `cam2` using `cam1`’s configuration. * @param cam camera to copy. */ set(cam: Camera): void; /** * Sets the camera’s position and orientation to values that are in-between * those of two other cameras. * * `myCamera.slerp()` uses spherical linear interpolation to calculate a * position and orientation that’s in-between two other cameras. Doing so is * helpful for transitioning smoothly between two perspectives. * * The first two parameters, `cam0` and `cam1`, are the `p5.Camera` objects * that should be used to set the current camera. * * The third parameter, `amt`, is the amount to interpolate between `cam0` and * `cam1`. 0.0 keeps the camera’s position and orientation equal to `cam0`’s, * 0.5 sets them halfway between `cam0`’s and `cam1`’s , and 1.0 sets the * position and orientation equal to `cam1`’s. * * For example, calling `myCamera.slerp(cam0, cam1, 0.1)` sets cam’s position * and orientation very close to `cam0`’s. Calling * `myCamera.slerp(cam0, cam1, 0.9)` sets cam’s position and orientation very * close to `cam1`’s. * * Note: All of the cameras must use the same projection. * @param cam0 first camera. * @param cam1 second camera. * @param amt amount of interpolation between 0.0 (`cam0`) and 1.0 (`cam1`). */ slerp(cam0: Camera, cam1: Camera, amt: number): void; } /** * A class to describe a high-performance drawing surface for textures. * * Each `p5.Framebuffer` object provides a dedicated drawing surface called * a framebuffer. They're similar to * p5.Graphics objects but can run much faster. * Performance is improved because the framebuffer shares the same WebGL * context as the canvas used to create it. * * `p5.Framebuffer` objects have all the drawing features of the main * canvas. Drawing instructions meant for the framebuffer must be placed * between calls to * myBuffer.begin() and * myBuffer.end(). The resulting image * can be applied as a texture by passing the `p5.Framebuffer` object to the * texture() function, as in `texture(myBuffer)`. * It can also be displayed on the main canvas by passing it to the * image() function, as in `image(myBuffer, 0, 0)`. * * Note: createFramebuffer() is the * recommended way to create an instance of this class. */ class Framebuffer { constructor(target: Graphics | p5, settings?: object); /** * An object that stores the framebuffer's color data. * * Each framebuffer uses a * WebGLTexture * object internally to store its color data. The `myBuffer.color` property * makes it possible to pass this data directly to other functions. For * example, calling `texture(myBuffer.color)` or * `myShader.setUniform('colorTexture', myBuffer.color)` may be helpful for * advanced use cases. * * Note: By default, a framebuffer's y-coordinates are flipped compared to * images and videos. It's easy to flip a framebuffer's y-coordinates as * needed when applying it as a texture. For example, calling * `plane(myBuffer.width, -myBuffer.height)` will flip the framebuffer. */ color: FramebufferTexture; /** * An object that stores the framebuffer's depth data. * * Each framebuffer uses a * WebGLTexture * object internally to store its depth data. The `myBuffer.depth` property * makes it possible to pass this data directly to other functions. For * example, calling `texture(myBuffer.depth)` or * `myShader.setUniform('depthTexture', myBuffer.depth)` may be helpful for * advanced use cases. * * Note: By default, a framebuffer's y-coordinates are flipped compared to * images and videos. It's easy to flip a framebuffer's y-coordinates as * needed when applying it as a texture. For example, calling * `plane(myBuffer.width, -myBuffer.height)` will flip the framebuffer. */ depth: FramebufferTexture; /** * An array containing the color of each pixel in the framebuffer. * * myBuffer.loadPixels() must be * called before accessing the `myBuffer.pixels` array. * myBuffer.updatePixels() * must be called after any changes are made. * * Note: Updating pixels via this property is slower than drawing to the * framebuffer directly. Consider using a * p5.Shader object instead of looping over * `myBuffer.pixels`. */ pixels: number[]; /** * The current width of the framebuffer. */ width: number; /** * The current width of the framebuffer. */ height: number; /** * Resizes the framebuffer to a given width and height. * * The parameters, `width` and `height`, set the dimensions of the * framebuffer. For example, calling `myBuffer.resize(300, 500)` resizes * the framebuffer to 300×500 pixels, then sets `myBuffer.width` to 300 * and `myBuffer.height` 500. * @param width width of the framebuffer. * @param height height of the framebuffer. */ resize(width: number, height: number): void; /** * Sets the framebuffer's pixel density or returns its current density. * * Computer displays are grids of little lights called pixels. A display's * pixel density describes how many pixels it packs into an area. Displays * with smaller pixels have a higher pixel density and create sharper * images. * * The parameter, `density`, is optional. If a number is passed, as in * `myBuffer.pixelDensity(1)`, it sets the framebuffer's pixel density. By * default, the framebuffer's pixel density will match that of the canvas * where it was created. All canvases default to match the display's pixel * density. * * Calling `myBuffer.pixelDensity()` without an argument returns its current * pixel density. * @param density pixel density to set. * @returns current pixel density. */ pixelDensity(density?: number): number; /** * Toggles the framebuffer's autosizing mode or returns the current mode. * * By default, the framebuffer automatically resizes to match the canvas * that created it. Calling `myBuffer.autoSized(false)` disables this * behavior and calling `myBuffer.autoSized(true)` re-enables it. * * Calling `myBuffer.autoSized()` without an argument returns `true` if * the framebuffer automatically resizes and `false` if not. * @param autoSized whether to automatically resize the framebuffer to match the canvas. * @returns current autosize setting. */ autoSized(autoSized?: boolean): boolean; /** * Creates a new * p5.Camera object to use with the framebuffer. * * The new camera is initialized with a default position `(0, 0, 800)` and a * default perspective projection. Its properties can be controlled with * p5.Camera methods such as `myCamera.lookAt(0, 0, 0)`. * * Framebuffer cameras should be created between calls to * myBuffer.begin() and * myBuffer.end() like so: * * `let myCamera; * * myBuffer.begin(); * * // Create the camera for the framebuffer. * myCamera = myBuffer.createCamera(); * * myBuffer.end();`Calling setCamera() updates the * framebuffer's projection using the camera. * resetMatrix() must also be called for the * view to change properly: * * `myBuffer.begin(); * * // Set the camera for the framebuffer. * setCamera(myCamera); * * // Reset all transformations. * resetMatrix(); * * // Draw stuff... * * myBuffer.end();` * @returns new camera. */ createCamera(): Camera; /** * Deletes the framebuffer from GPU memory. * * Calling `myBuffer.remove()` frees the GPU memory used by the framebuffer. * The framebuffer also uses a bit of memory on the CPU which can be freed * like so: * * `// Delete the framebuffer from GPU memory. * myBuffer.remove(); * * // Delete the framebuffer from CPU memory. * myBuffer = undefined;`Note: All variables that reference the framebuffer must be assigned * the value `undefined` to delete the framebuffer from CPU memory. If any * variable still refers to the framebuffer, then it won't be garbage * collected. */ remove(): void; /** * Begins drawing shapes to the framebuffer. * * `myBuffer.begin()` and myBuffer.end() * allow shapes to be drawn to the framebuffer. `myBuffer.begin()` begins * drawing to the framebuffer and * myBuffer.end() stops drawing to the * framebuffer. Changes won't be visible until the framebuffer is displayed * as an image or texture. */ begin(): void; /** * Stops drawing shapes to the framebuffer. * * myBuffer.begin() and `myBuffer.end()` * allow shapes to be drawn to the framebuffer. * myBuffer.begin() begins drawing to * the framebuffer and `myBuffer.end()` stops drawing to the framebuffer. * Changes won't be visible until the framebuffer is displayed as an image * or texture. */ end(): void; /** * Draws to the framebuffer by calling a function that contains drawing * instructions. * * The parameter, `callback`, is a function with the drawing instructions * for the framebuffer. For example, calling `myBuffer.draw(myFunction)` * will call a function named `myFunction()` to draw to the framebuffer. * Doing so has the same effect as the following: * * `myBuffer.begin(); * myFunction(); * myBuffer.end();` * @param callback function that draws to the framebuffer. */ draw(callback: Function): void; /** * Loads the current value of each pixel in the framebuffer into its * pixels array. * * `myBuffer.loadPixels()` must be called before reading from or writing to * myBuffer.pixels. */ loadPixels(): void; /** * Gets a pixel or a region of pixels from the framebuffer. * * `myBuffer.get()` is easy to use but it's not as fast as * myBuffer.pixels. Use * myBuffer.pixels to read many pixel * values. * * The version of `myBuffer.get()` with no parameters returns the entire * framebuffer as a a p5.Image object. * * The version of `myBuffer.get()` with two parameters interprets them as * coordinates. It returns an array with the `[R, G, B, A]` values of the * pixel at the given point. * * The version of `myBuffer.get()` with four parameters interprets them as * coordinates and dimensions. It returns a subsection of the framebuffer as * a p5.Image object. The first two parameters are * the coordinates for the upper-left corner of the subsection. The last two * parameters are the width and height of the subsection. * @param x x-coordinate of the pixel. Defaults to 0. * @param y y-coordinate of the pixel. Defaults to 0. * @param w width of the subsection to be returned. * @param h height of the subsection to be returned. * @returns subsection as a p5.Image object. */ get(x: number, y: number, w: number, h: number): Image; get(): Image; get(x: number, y: number): number[]; } /** * A class to describe a 3D shape. * * Each `p5.Geometry` object represents a 3D shape as a set of connected * points called vertices. All 3D shapes are made by connecting vertices to * form triangles that are stitched together. Each triangular patch on the * geometry's surface is called a face. The geometry stores information * about its vertices and faces for use with effects such as lighting and * texture mapping. * * The first parameter, `detailX`, is optional. If a number is passed, as in * `new p5.Geometry(24)`, it sets the number of triangle subdivisions to use * along the geometry's x-axis. By default, `detailX` is 1. * * The second parameter, `detailY`, is also optional. If a number is passed, * as in `new p5.Geometry(24, 16)`, it sets the number of triangle * subdivisions to use along the geometry's y-axis. By default, `detailX` is * 1. * * The third parameter, `callback`, is also optional. If a function is passed, * as in `new p5.Geometry(24, 16, createShape)`, it will be called once to add * vertices to the new 3D shape. */ class Geometry { constructor( detailX?: number, detailY?: number, callback?: (this: Geometry) => void); /** * An array with the geometry's vertices. * * The geometry's vertices are stored as * p5.Vector objects in the `myGeometry.vertices` * array. The geometry's first vertex is the * p5.Vector object at `myGeometry.vertices[0]`, * its second vertex is `myGeometry.vertices[1]`, its third vertex is * `myGeometry.vertices[2]`, and so on. */ vertices: any; /** * An array with the vectors that are normal to the geometry's vertices. * * A face's orientation is defined by its normal vector which points out * of the face and is normal (perpendicular) to the surface. Calling * `myGeometry.computeNormals()` first calculates each face's normal * vector. Then it calculates the normal vector for each vertex by * averaging the normal vectors of the faces surrounding the vertex. The * vertex normals are stored as p5.Vector * objects in the `myGeometry.vertexNormals` array. */ vertexNormals: any; /** * An array that lists which of the geometry's vertices form each of its * faces. * * All 3D shapes are made by connecting sets of points called vertices. A * geometry's surface is formed by connecting vertices to form triangles * that are stitched together. Each triangular patch on the geometry's * surface is called a face. * * The geometry's vertices are stored as * p5.Vector objects in the * myGeometry.vertices array. The * geometry's first vertex is the p5.Vector * object at `myGeometry.vertices[0]`, its second vertex is * `myGeometry.vertices[1]`, its third vertex is `myGeometry.vertices[2]`, * and so on. * * For example, a geometry made from a rectangle has two faces because a * rectangle is made by joining two triangles. `myGeometry.faces` for a * rectangle would be the two-dimensional array `[[0, 1, 2], [2, 1, 3]]`. * The first face, `myGeometry.faces[0]`, is the array `[0, 1, 2]` because * it's formed by connecting `myGeometry.vertices[0]`, * `myGeometry.vertices[1]`,and `myGeometry.vertices[2]`. The second face, * `myGeometry.faces[1]`, is the array `[2, 1, 3]` because it's formed by * connecting `myGeometry.vertices[2]`, `myGeometry.vertices[1]`,and * `myGeometry.vertices[3]`. */ faces: any; /** * An array that lists the texture coordinates for each of the geometry's * vertices. * * In order for texture() to work, the geometry * needs a way to map the points on its surface to the pixels in a * rectangular image that's used as a texture. The geometry's vertex at * coordinates `(x, y, z)` maps to the texture image's pixel at coordinates * `(u, v)`. * * The `myGeometry.uvs` array stores the `(u, v)` coordinates for each * vertex in the order it was added to the geometry. For example, the * first vertex, `myGeometry.vertices[0]`, has its `(u, v)` coordinates * stored at `myGeometry.uvs[0]` and `myGeometry.uvs[1]`. */ uvs: any; /** * A unique identifier for this geometry. The renderer will use this to cache resources. */ gid: string; /** * Calculates the position and size of the smallest box that contains the geometry. * * A bounding box is the smallest rectangular prism that contains the entire * geometry. It's defined by the box's minimum and maximum coordinates along * each axis, as well as the size (length) and offset (center). * * Calling `myGeometry.calculateBoundingBox()` returns an object with four * properties that describe the bounding box: * * `// Get myGeometry's bounding box. * let bbox = myGeometry.calculateBoundingBox(); * * // Print the bounding box to the console. * console.log(bbox); * * // { * // // The minimum coordinate along each axis. * // min: { x: -1, y: -2, z: -3 }, * // * // // The maximum coordinate along each axis. * // max: { x: 1, y: 2, z: 3}, * // * // // The size (length) along each axis. * // size: { x: 2, y: 4, z: 6}, * // * // // The offset (center) along each axis. * // offset: { x: 0, y: 0, z: 0} * // }` * @returns bounding box of the geometry. */ calculateBoundingBox(): { min: p5.Vector; max: p5.Vector; size: p5.Vector; offset: p5.Vector }; /** * Removes the geometry’s internal colors. * * `p5.Geometry` objects can be created with "internal colors" assigned to * vertices or the entire shape. When a geometry has internal colors, * fill() has no effect. Calling * `myGeometry.clearColors()` allows the * fill() function to apply color to the geometry. */ clearColors(): void; /** * Flips the geometry’s texture u-coordinates. * * In order for texture() to work, the geometry * needs a way to map the points on its surface to the pixels in a rectangular * image that's used as a texture. The geometry's vertex at coordinates * `(x, y, z)` maps to the texture image's pixel at coordinates `(u, v)`. * * The myGeometry.uvs array stores the * `(u, v)` coordinates for each vertex in the order it was added to the * geometry. Calling `myGeometry.flipU()` flips a geometry's u-coordinates * so that the texture appears mirrored horizontally. * * For example, a plane's four vertices are added clockwise starting from the * top-left corner. Here's how calling `myGeometry.flipU()` would change a * plane's texture coordinates: * * `// Print the original texture coordinates. * // Output: [0, 0, 1, 0, 0, 1, 1, 1] * console.log(myGeometry.uvs); * * // Flip the u-coordinates. * myGeometry.flipU(); * * // Print the flipped texture coordinates. * // Output: [1, 0, 0, 0, 1, 1, 0, 1] * console.log(myGeometry.uvs); * * // Notice the swaps: * // Top vertices: [0, 0, 1, 0] --> [1, 0, 0, 0] * // Bottom vertices: [0, 1, 1, 1] --> [1, 1, 0, 1]` */ flipU(): void; /** * Computes the geometry's faces using its vertices. * * All 3D shapes are made by connecting sets of points called vertices. A * geometry's surface is formed by connecting vertices to form triangles that * are stitched together. Each triangular patch on the geometry's surface is * called a face. `myGeometry.computeFaces()` performs the math needed to * define each face based on the distances between vertices. * * The geometry's vertices are stored as p5.Vector * objects in the myGeometry.vertices * array. The geometry's first vertex is the * p5.Vector object at `myGeometry.vertices[0]`, * its second vertex is `myGeometry.vertices[1]`, its third vertex is * `myGeometry.vertices[2]`, and so on. * * Calling `myGeometry.computeFaces()` fills the * myGeometry.faces array with three-element * arrays that list the vertices that form each face. For example, a geometry * made from a rectangle has two faces because a rectangle is made by joining * two triangles. myGeometry.faces for a * rectangle would be the two-dimensional array * `[[0, 1, 2], [2, 1, 3]]`. The first face, `myGeometry.faces[0]`, is the * array `[0, 1, 2]` because it's formed by connecting * `myGeometry.vertices[0]`, `myGeometry.vertices[1]`,and * `myGeometry.vertices[2]`. The second face, `myGeometry.faces[1]`, is the * array `[2, 1, 3]` because it's formed by connecting * `myGeometry.vertices[2]`, `myGeometry.vertices[1]`, and * `myGeometry.vertices[3]`. * * Note: `myGeometry.computeFaces()` only works when geometries have four or more vertices. */ computeFaces(): Geometry; /** * Calculates the normal vector for each vertex on the geometry. * * All 3D shapes are made by connecting sets of points called vertices. A * geometry's surface is formed by connecting vertices to create triangles * that are stitched together. Each triangular patch on the geometry's * surface is called a face. `myGeometry.computeNormals()` performs the * math needed to orient each face. Orientation is important for lighting * and other effects. * * A face's orientation is defined by its normal vector which points out * of the face and is normal (perpendicular) to the surface. Calling * `myGeometry.computeNormals()` first calculates each face's normal vector. * Then it calculates the normal vector for each vertex by averaging the * normal vectors of the faces surrounding the vertex. The vertex normals * are stored as p5.Vector objects in the * myGeometry.vertexNormals array. * * The first parameter, `shadingType`, is optional. Passing the constant * `FLAT`, as in `myGeometry.computeNormals(FLAT)`, provides neighboring * faces with their own copies of the vertices they share. Surfaces appear * tiled with flat shading. Passing the constant `SMOOTH`, as in * `myGeometry.computeNormals(SMOOTH)`, makes neighboring faces reuse their * shared vertices. Surfaces appear smoother with smooth shading. By * default, `shadingType` is `FLAT`. * * The second parameter, `options`, is also optional. If an object with a * `roundToPrecision` property is passed, as in * `myGeometry.computeNormals(SMOOTH, { roundToPrecision: 5 })`, it sets the * number of decimal places to use for calculations. By default, * `roundToPrecision` uses 3 decimal places. * @param shadingType shading type. either FLAT or SMOOTH. Defaults to `FLAT`. * @param options shading options. */ computeNormals(shadingType?: typeof p5.FLAT | typeof p5.SMOOTH, options?: { roundToPrecision?: any }): Geometry; makeEdgesFromFaces(): void; /** * Transforms the geometry's vertices to fit snugly within a 100×100×100 box * centered at the origin. * * Calling `myGeometry.normalize()` translates the geometry's vertices so that * they're centered at the origin `(0, 0, 0)`. Then it scales the vertices so * that they fill a 100×100×100 box. As a result, small geometries will grow * and large geometries will shrink. * * Note: `myGeometry.normalize()` only works when called in the * setup() function. */ normalize(): Geometry; /** * Sets the shader's vertex property or attribute variables. * * A vertex property, or vertex attribute, is a variable belonging to a vertex in a shader. p5.js provides some * default properties, such as `aPosition`, `aNormal`, `aVertexColor`, etc. These are * set using vertex(), normal() * and fill() respectively. Custom properties can also * be defined within beginShape() and * endShape(). * * The first parameter, `propertyName`, is a string with the property's name. * This is the same variable name which should be declared in the shader, as in * `in vec3 aProperty`, similar to .`setUniform()`. * * The second parameter, `data`, is the value assigned to the shader variable. This value * will be pushed directly onto the Geometry object. There should be the same number * of custom property values as vertices, this method should be invoked once for each * vertex. * * The `data` can be a Number or an array of numbers. Tn the shader program the type * can be declared according to the WebGL specification. Common types include `float`, * `vec2`, `vec3`, `vec4` or matrices. * * See also the global vertexProperty() function. * @param propertyName the name of the vertex property. * @param data the data tied to the vertex property. * @param size optional size of each unit of data. */ vertexProperty(propertyName: string, data: number | number[], size?: number): void; /** * Flips the geometry’s texture v-coordinates. * * In order for texture() to work, the geometry * needs a way to map the points on its surface to the pixels in a rectangular * image that's used as a texture. The geometry's vertex at coordinates * `(x, y, z)` maps to the texture image's pixel at coordinates `(u, v)`. * * The myGeometry.uvs array stores the * `(u, v)` coordinates for each vertex in the order it was added to the * geometry. Calling `myGeometry.flipV()` flips a geometry's v-coordinates * so that the texture appears mirrored vertically. * * For example, a plane's four vertices are added clockwise starting from the * top-left corner. Here's how calling `myGeometry.flipV()` would change a * plane's texture coordinates: * * `// Print the original texture coordinates. * // Output: [0, 0, 1, 0, 0, 1, 1, 1] * console.log(myGeometry.uvs); * * // Flip the v-coordinates. * myGeometry.flipV(); * * // Print the flipped texture coordinates. * // Output: [0, 1, 1, 1, 0, 0, 1, 0] * console.log(myGeometry.uvs); * * // Notice the swaps: * // Left vertices: [0, 0] <--> [1, 0] * // Right vertices: [1, 0] <--> [1, 1]` */ flipV(): void; } /** * A class to describe a shader program. * * Each `p5.Shader` object contains a shader program that runs on the graphics * processing unit (GPU). Shaders can process many pixels or vertices at the * same time, making them fast for many graphics tasks. They’re written in a * language called * GLSL * and run along with the rest of the code in a sketch. * * A shader program consists of two files, a vertex shader and a fragment * shader. The vertex shader affects where 3D geometry is drawn on the screen * and the fragment shader affects color. Once the `p5.Shader` object is * created, it can be used with the shader() * function, as in `shader(myShader)`. * * A shader can optionally describe hooks, which are functions in GLSL that * users may choose to provide to customize the behavior of the shader. For the * vertex or the fragment shader, users can pass in an object where each key is * the type and name of a hook function, and each value is a string with the * parameter list and default implementation of the hook. For example, to let users * optionally run code at the start of the vertex shader, the options object could * include: * * `{ * vertex: { * 'void beforeVertex': '() {}' * } * }`Then, in your vertex shader source, you can run a hook by calling a function * with the same name prefixed by `HOOK_`: * * `void main() { * HOOK_beforeVertex(); * // Add the rest ofy our shader code here! * }`Note: createShader(), * createFilterShader(), and * loadShader() are the recommended ways to * create an instance of this class. */ class Shader { constructor(renderer: RendererGL, vertSrc: string, fragSrc: string, options?: object); /** * Shaders are written in GLSL, but * there are different versions of GLSL that it might be written in. * * Calling this method on a `p5.Shader` will return the GLSL version it uses, either `100 es` or `300 es`. * WebGL 1 shaders will only use `100 es`, and WebGL 2 shaders may use either. * @returns The GLSL version used by the shader. */ version(): string; /** * Logs the hooks available in this shader, and their current implementation. * * Each shader may let you override bits of its behavior. Each bit is called * a hook. A hook is either for the vertex shader, if it affects the * position of vertices, or in the fragment shader, if it affects the pixel * color. This method logs those values to the console, letting you know what * you are able to use in a call to * `modify()`. * * For example, this shader will produce the following output: * * `myShader = baseMaterialShader().modify({ * declarations: 'uniform float time;', * 'vec3 getWorldPosition': `(vec3 pos) { * pos.y += 20. * sin(time * 0.001 + pos.x * 0.05); * return pos; * }` * }); * myShader.inspectHooks();``==== Vertex shader hooks: ==== * void beforeVertex() {} * vec3 getLocalPosition(vec3 position) { return position; } * [MODIFIED] vec3 getWorldPosition(vec3 pos) { * pos.y += 20. * sin(time * 0.001 + pos.x * 0.05); * return pos; * } * vec3 getLocalNormal(vec3 normal) { return normal; } * vec3 getWorldNormal(vec3 normal) { return normal; } * vec2 getUV(vec2 uv) { return uv; } * vec4 getVertexColor(vec4 color) { return color; } * void afterVertex() {} * * ==== Fragment shader hooks: ==== * void beforeFragment() {} * Inputs getPixelInputs(Inputs inputs) { return inputs; } * vec4 combineColors(ColorComponents components) { * vec4 color = vec4(0.); * color.rgb += components.diffuse * components.baseColor; * color.rgb += components.ambient * components.ambientColor; * color.rgb += components.specular * components.specularColor; * color.rgb += components.emissive; * color.a = components.opacity; * return color; * } * vec4 getFinalColor(vec4 color) { return color; } * void afterFragment() {}` */ inspectHooks(): void; /** * Returns a new shader, based on the original, but with custom snippets * of shader code replacing default behaviour. * * Each shader may let you override bits of its behavior. Each bit is called * a hook. For example, a hook can let you adjust positions of vertices, or * the color of a pixel. You can inspect the different hooks available by calling * `yourShader.inspectHooks()`. You can * also read the reference for the default material, normal material, color, line, and point shaders to * see what hooks they have available. * * `modify()` can be passed a function as a parameter. Inside, you can override hooks * by calling them as functions. Each hook will take in a callback that takes in inputs * and is expected to return an output. For example, here is a function that changes the * material color to red: * * `let myShader; * * function setup() { * createCanvas(200, 200, WEBGL); * myShader = baseMaterialShader().modify(() => { * getPixelInputs((inputs) => { * inputs.color = [inputs.texCoord, 0, 1]; * return inputs; * }); * }); * } * * function draw() { * background(255); * noStroke(); * shader(myShader); // Apply the custom shader * plane(width, height); // Draw a plane with the shader applied * }`In addition to calling hooks, you can create uniforms, which are special variables * used to pass data from p5.js into the shader. They can be created by calling `uniform` + the * type of the data, such as `uniformFloat` for a number of `uniformVector2` for a two-component vector. * They take in a function that returns the data for the variable. You can then reference these * variables in your hooks, and their values will update every time you apply * the shader with the result of your function. * * `let myShader; * * function setup() { * createCanvas(200, 200, WEBGL); * myShader = baseMaterialShader().modify(() => { * // Get the current time from p5.js * let t = uniformFloat(() => millis()); * * getPixelInputs((inputs) => { * inputs.color = [ * inputs.texCoord, * sin(t * 0.01) / 2 + 0.5, * 1, * ]; * return inputs; * }); * }); * } * * function draw() { * background(255); * noStroke(255); * shader(myShader); // Apply the custom shader * plane(width, height); // Draw a plane with the shader applied * }`p5.strands functions are special, since they get turned into a shader instead of being * run like the rest of your code. They only have access to p5.js functions, and variables * you declare inside the `modify` callback. If you need access to local variables, you * can pass them into `modify` with an optional second parameter, `variables`. If you are * using instance mode, you will need to pass your sketch object in this way. * * `new p5((sketch) => { * let myShader; * * sketch.setup = function() { * sketch.createCanvas(200, 200, sketch.WEBGL); * myShader = sketch.baseMaterialShader().modify(() => { * sketch.getPixelInputs((inputs) => { * inputs.color = [inputs.texCoord, 0, 1]; * return inputs; * }); * }, { sketch }); * } * * sketch.draw = function() { * sketch.background(255); * sketch.noStroke(); * sketch.shader(myShader); // Apply the custom shader * sketch.plane(sketch.width, sketch.height); // Draw a plane with the shader applied * } * });`You can also write GLSL directly in `modify` if you need direct access. To do so, * `modify()` takes one parameter, `hooks`, an object with the hooks you want * to override. Each key of the `hooks` object is the name * of a hook, and the value is a string with the GLSL code for your hook. * * If you supply functions that aren't existing hooks, they will get added at the start of * the shader as helper functions so that you can use them in your hooks. * * To add new uniforms to your shader, you can pass in a `uniforms` object containing * the type and name of the uniform as the key, and a default value or function returning * a default value as its value. These will be automatically set when the shader is set * with `shader(yourShader)`. * * `let myShader; * * function setup() { * createCanvas(200, 200, WEBGL); * myShader = baseMaterialShader().modify({ * uniforms: { * 'float time': () => millis() // Uniform for time * }, * 'Vertex getWorldInputs': `(Vertex inputs) { * inputs.position.y += * 20. * sin(time * 0.001 + inputs.position.x * 0.05); * return inputs; * }` * }); * } * * function draw() { * background(255); * shader(myShader); // Apply the custom shader * lights(); // Enable lighting * noStroke(); // Disable stroke * fill('red'); // Set fill color to red * sphere(50); // Draw a sphere with the shader applied * }`You can also add a `declarations` key, where the value is a GLSL string declaring * custom uniform variables, globals, and functions shared * between hooks. To add declarations just in a vertex or fragment shader, add * `vertexDeclarations` and `fragmentDeclarations` keys. * * `let myShader; * * function setup() { * createCanvas(200, 200, WEBGL); * myShader = baseMaterialShader().modify({ * // Manually specifying a uniform * declarations: 'uniform float time;', * 'Vertex getWorldInputs': `(Vertex inputs) { * inputs.position.y += * 20. * sin(time * 0.001 + inputs.position.x * 0.05); * return inputs; * }` * }); * } * * function draw() { * background(255); * shader(myShader); * myShader.setUniform('time', millis()); * lights(); * noStroke(); * fill('red'); * sphere(50); * }` * @param callback A function with p5.strands code to modify the shader. * @param variables An optional object with local variables p5.strands * should have access to. */ modify(callback: Function, variables?: object): Shader; modify(hooks?: object): Shader; /** * Copies the shader from one drawing context to another. * * Each `p5.Shader` object must be compiled by calling * shader() before it can run. Compilation happens * in a drawing context which is usually the main canvas or an instance of * p5.Graphics. A shader can only be used in the * context where it was compiled. The `copyToContext()` method compiles the * shader again and copies it to another drawing context where it can be * reused. * * The parameter, `context`, is the drawing context where the shader will be * used. The shader can be copied to an instance of * p5.Graphics, as in * `myShader.copyToContext(pg)`. The shader can also be copied from a * p5.Graphics object to the main canvas using * the `p5.instance` variable, as in `myShader.copyToContext(p5.instance)`. * * Note: A p5.Shader object created with * createShader(), * createFilterShader(), or * loadShader() * can be used directly with a p5.Framebuffer * object created with * createFramebuffer(). Both objects * have the same context as the main canvas. * @param context WebGL context for the copied shader. * @returns new shader compiled for the target context. */ copyToContext(context: p5 | Graphics): Shader; /** * Sets the shader’s uniform (global) variables. * * Shader programs run on the computer’s graphics processing unit (GPU). * They live in part of the computer’s memory that’s completely separate * from the sketch that runs them. Uniforms are global variables within a * shader program. They provide a way to pass values from a sketch running * on the CPU to a shader program running on the GPU. * * The first parameter, `uniformName`, is a string with the uniform’s name. * For the shader above, `uniformName` would be `'r'`. * * The second parameter, `data`, is the value that should be used to set the * uniform. For example, calling `myShader.setUniform('r', 0.5)` would set * the `r` uniform in the shader above to `0.5`. data should match the * uniform’s type. Numbers, strings, booleans, arrays, and many types of * images can all be passed to a shader with `setUniform()`. * @param uniformName name of the uniform. Must match the name * used in the vertex and fragment shaders. * @param data value to assign to the uniform. Must match the uniform’s data type. */ setUniform(uniformName: string, data: boolean | number | number[] | Image | Graphics | MediaElement | Texture): Shader; } class Renderer extends Element { elt: HTMLCanvasElement; } class Renderer2D {} class RendererGL {} class FramebufferTexture {} class Texture {} class Quat {} } export default p5; export as namespace p5;