referenceData = { "project": { "name": "p5", "description": "[![npm version](https://badge.fury.io/js/p5.svg)](https://www.npmjs.com/package/p5)", "version": "1.5.0", "url": "https://github.com/processing/p5.js#readme" }, "files": { "src/accessibility/color_namer.js": { "name": "src/accessibility/color_namer.js", "modules": { "Environment": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/accessibility/describe.js": { "name": "src/accessibility/describe.js", "modules": {}, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/accessibility/gridOutput.js": { "name": "src/accessibility/gridOutput.js", "modules": {}, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/accessibility/outputs.js": { "name": "src/accessibility/outputs.js", "modules": {}, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/accessibility/textOutput.js": { "name": "src/accessibility/textOutput.js", "modules": {}, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/color/color_conversion.js": { "name": "src/color/color_conversion.js", "modules": { "Color Conversion": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/color/creating_reading.js": { "name": "src/color/creating_reading.js", "modules": { "Creating & Reading": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/color/p5.Color.js": { "name": "src/color/p5.Color.js", "modules": {}, "classes": { "p5.Color": 1 }, "fors": { "p5": 1 }, "namespaces": {} }, "src/color/setting.js": { "name": "src/color/setting.js", "modules": { "Setting": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/core/friendly_errors/fes_core.js": { "name": "src/core/friendly_errors/fes_core.js", "modules": {}, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/core/friendly_errors/file_errors.js": { "name": "src/core/friendly_errors/file_errors.js", "modules": {}, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/core/friendly_errors/sketch_reader.js": { "name": "src/core/friendly_errors/sketch_reader.js", "modules": {}, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/core/friendly_errors/stacktrace.js": { "name": "src/core/friendly_errors/stacktrace.js", "modules": {}, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/core/friendly_errors/validate_params.js": { "name": "src/core/friendly_errors/validate_params.js", "modules": {}, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/core/shape/2d_primitives.js": { "name": "src/core/shape/2d_primitives.js", "modules": { "2D Primitives": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/core/shape/attributes.js": { "name": "src/core/shape/attributes.js", "modules": { "Attributes": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/core/shape/curves.js": { "name": "src/core/shape/curves.js", "modules": { "Curves": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/core/shape/vertex.js": { "name": "src/core/shape/vertex.js", "modules": { "Vertex": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/core/constants.js": { "name": "src/core/constants.js", "modules": { "Constants": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/core/environment.js": { "name": "src/core/environment.js", "modules": {}, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/core/helpers.js": { "name": "src/core/helpers.js", "modules": {}, "classes": {}, "fors": {}, "namespaces": {} }, "src/core/init.js": { "name": "src/core/init.js", "modules": {}, "classes": {}, "fors": {}, "namespaces": {} }, "src/core/internationalization.js": { "name": "src/core/internationalization.js", "modules": {}, "classes": {}, "fors": {}, "namespaces": {} }, "src/core/legacy.js": { "name": "src/core/legacy.js", "modules": {}, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/core/main.js": { "name": "src/core/main.js", "modules": { "Structure": 1 }, "classes": { "p5": 1 }, "fors": { "p5": 1 }, "namespaces": {} }, "src/core/p5.Element.js": { "name": "src/core/p5.Element.js", "modules": { "DOM": 1 }, "classes": { "p5.Element": 1 }, "fors": { "p5.Element": 1 }, "namespaces": {} }, "src/core/p5.Graphics.js": { "name": "src/core/p5.Graphics.js", "modules": { "Rendering": 1 }, "classes": { "p5.Graphics": 1 }, "fors": { "p5": 1 }, "namespaces": {} }, "src/core/p5.Renderer.js": { "name": "src/core/p5.Renderer.js", "modules": {}, "classes": { "p5.Renderer": 1 }, "fors": { "p5": 1 }, "namespaces": {} }, "src/core/p5.Renderer2D.js": { "name": "src/core/p5.Renderer2D.js", "modules": {}, "classes": {}, "fors": {}, "namespaces": {} }, "src/core/reference.js": { "name": "src/core/reference.js", "modules": { "Foundation": 1 }, "classes": {}, "fors": { "p5": 1, "JSON": 1, "console": 1 }, "namespaces": {} }, "src/core/rendering.js": { "name": "src/core/rendering.js", "modules": {}, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/core/shim.js": { "name": "src/core/shim.js", "modules": {}, "classes": {}, "fors": {}, "namespaces": {} }, "src/core/structure.js": { "name": "src/core/structure.js", "modules": {}, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/core/transform.js": { "name": "src/core/transform.js", "modules": { "Transform": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/data/local_storage.js": { "name": "src/data/local_storage.js", "modules": { "LocalStorage": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/data/p5.TypedDict.js": { "name": "src/data/p5.TypedDict.js", "modules": { "Dictionary": 1 }, "classes": { "p5.TypedDict": 1, "p5.StringDict": 1, "p5.NumberDict": 1 }, "fors": { "p5.TypedDict": 1, "p5": 1 }, "namespaces": {} }, "src/dom/dom.js": { "name": "src/dom/dom.js", "modules": {}, "classes": { "p5.MediaElement": 1, "p5.File": 1 }, "fors": { "p5": 1, "p5.Element": 1 }, "namespaces": {} }, "src/events/acceleration.js": { "name": "src/events/acceleration.js", "modules": { "Acceleration": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/events/keyboard.js": { "name": "src/events/keyboard.js", "modules": { "Keyboard": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/events/mouse.js": { "name": "src/events/mouse.js", "modules": { "Mouse": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/events/touch.js": { "name": "src/events/touch.js", "modules": { "Touch": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/image/filters.js": { "name": "src/image/filters.js", "modules": {}, "classes": {}, "fors": {}, "namespaces": {} }, "src/image/image.js": { "name": "src/image/image.js", "modules": { "Image": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/image/loading_displaying.js": { "name": "src/image/loading_displaying.js", "modules": { "Loading & Displaying": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/image/p5.Image.js": { "name": "src/image/p5.Image.js", "modules": {}, "classes": { "p5.Image": 1 }, "fors": {}, "namespaces": {} }, "src/image/pixels.js": { "name": "src/image/pixels.js", "modules": { "Pixels": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/io/files.js": { "name": "src/io/files.js", "modules": { "Input": 1, "Output": 1 }, "classes": { "p5.PrintWriter": 1 }, "fors": { "p5": 1 }, "namespaces": {} }, "src/io/p5.Table.js": { "name": "src/io/p5.Table.js", "modules": { "Table": 1 }, "classes": { "p5.Table": 1 }, "fors": {}, "namespaces": {} }, "src/io/p5.TableRow.js": { "name": "src/io/p5.TableRow.js", "modules": {}, "classes": { "p5.TableRow": 1 }, "fors": {}, "namespaces": {} }, "src/io/p5.XML.js": { "name": "src/io/p5.XML.js", "modules": {}, "classes": { "p5.XML": 1 }, "fors": {}, "namespaces": {} }, "src/math/calculation.js": { "name": "src/math/calculation.js", "modules": { "Calculation": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/math/math.js": { "name": "src/math/math.js", "modules": { "Vector": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/math/noise.js": { "name": "src/math/noise.js", "modules": { "Noise": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/math/p5.Vector.js": { "name": "src/math/p5.Vector.js", "modules": {}, "classes": { "p5.Vector": 1 }, "fors": {}, "namespaces": {} }, "src/math/random.js": { "name": "src/math/random.js", "modules": { "Random": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/math/trigonometry.js": { "name": "src/math/trigonometry.js", "modules": { "Trigonometry": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/typography/attributes.js": { "name": "src/typography/attributes.js", "modules": {}, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/typography/loading_displaying.js": { "name": "src/typography/loading_displaying.js", "modules": {}, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/typography/p5.Font.js": { "name": "src/typography/p5.Font.js", "modules": {}, "classes": { "p5.Font": 1 }, "fors": {}, "namespaces": {} }, "src/utilities/array_functions.js": { "name": "src/utilities/array_functions.js", "modules": { "Array Functions": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/utilities/conversion.js": { "name": "src/utilities/conversion.js", "modules": { "Conversion": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/utilities/string_functions.js": { "name": "src/utilities/string_functions.js", "modules": { "String Functions": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/utilities/time_date.js": { "name": "src/utilities/time_date.js", "modules": { "Time & Date": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/webgl/3d_primitives.js": { "name": "src/webgl/3d_primitives.js", "modules": { "3D Primitives": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/webgl/interaction.js": { "name": "src/webgl/interaction.js", "modules": { "Interaction": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/webgl/light.js": { "name": "src/webgl/light.js", "modules": { "Lights": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/webgl/loading.js": { "name": "src/webgl/loading.js", "modules": { "3D Models": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/webgl/material.js": { "name": "src/webgl/material.js", "modules": { "Material": 1 }, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "src/webgl/p5.Camera.js": { "name": "src/webgl/p5.Camera.js", "modules": { "Camera": 1 }, "classes": { "p5.Camera": 1 }, "fors": { "p5": 1, "p5.Camera": 1 }, "namespaces": {} }, "src/webgl/p5.Geometry.js": { "name": "src/webgl/p5.Geometry.js", "modules": {}, "classes": { "p5.Geometry": 1 }, "fors": { "p5": 1 }, "namespaces": {} }, "src/webgl/p5.Matrix.js": { "name": "src/webgl/p5.Matrix.js", "modules": {}, "classes": { "p5.Matrix": 1 }, "fors": {}, "namespaces": {} }, "src/webgl/p5.RenderBuffer.js": { "name": "src/webgl/p5.RenderBuffer.js", "modules": {}, "classes": {}, "fors": {}, "namespaces": {} }, "src/webgl/p5.RendererGL.Immediate.js": { "name": "src/webgl/p5.RendererGL.Immediate.js", "modules": {}, "classes": {}, "fors": {}, "namespaces": {} }, "src/webgl/p5.RendererGL.Retained.js": { "name": "src/webgl/p5.RendererGL.Retained.js", "modules": {}, "classes": {}, "fors": {}, "namespaces": {} }, "src/webgl/p5.RendererGL.js": { "name": "src/webgl/p5.RendererGL.js", "modules": {}, "classes": { "p5.RendererGL": 1 }, "fors": { "p5": 1 }, "namespaces": {} }, "src/webgl/p5.Shader.js": { "name": "src/webgl/p5.Shader.js", "modules": {}, "classes": { "p5.Shader": 1 }, "fors": { "p5": 1 }, "namespaces": {} }, "src/webgl/p5.Texture.js": { "name": "src/webgl/p5.Texture.js", "modules": {}, "classes": { "p5.Texture": 1 }, "fors": { "p5": 1 }, "namespaces": {} }, "src/webgl/text.js": { "name": "src/webgl/text.js", "modules": {}, "classes": { "ImageInfos": 1, "FontInfo": 1, "Cubic": 1 }, "fors": {}, "namespaces": {} }, "lib/addons/p5.sound.js": { "name": "lib/addons/p5.sound.js", "modules": { "p5.sound": 1 }, "classes": { "p5.SoundFile": 1, "p5.Amplitude": 1, "p5.FFT": 1, "p5.Oscillator": 1, "p5.SinOsc": 1, "p5.TriOsc": 1, "p5.SawOsc": 1, "p5.SqrOsc": 1, "p5.Envelope": 1, "p5.Noise": 1, "p5.Pulse": 1, "p5.AudioIn": 1, "p5.Effect": 1, "p5.Filter": 1, "p5.LowPass": 1, "p5.HighPass": 1, "p5.BandPass": 1, "p5.EQ": 1, "p5.Panner3D": 1, "p5.Delay": 1, "p5.Reverb": 1, "p5.Convolver": 1, "p5.Phrase": 1, "p5.Part": 1, "p5.Score": 1, "p5.SoundLoop": 1, "p5.Compressor": 1, "p5.PeakDetect": 1, "p5.SoundRecorder": 1, "p5.Distortion": 1, "p5.Gain": 1, "p5.AudioVoice": 1, "p5.MonoSynth": 1, "p5.OnsetDetect": 1, "p5.PolySynth": 1 }, "fors": { "p5.sound": 1, "p5": 1, "p5.SoundFile": 1, "p5.Amplitude": 1, "p5.FFT": 1, "p5.Oscillator": 1, "p5.Envelope": 1, "p5.AudioIn": 1, "p5.Effect": 1, "p5.EQ": 1, "p5.Panner3D": 1, "p5.Delay": 1, "p5.Reverb": 1, "p5.Convolver": 1, "p5.Part": 1, "p5.Score": 1, "p5.SoundLoop": 1, "p5.Compressor": 1, "p5.SoundRecorder": 1, "p5.Distortion": 1, "p5.Gain": 1, "p5.AudioVoice": 1, "p5.MonoSynth": 1, "p5.PolySynth": 1 }, "namespaces": {} }, "lib/addons/p5.sound.min.js": { "name": "lib/addons/p5.sound.min.js", "modules": {}, "classes": {}, "fors": {}, "namespaces": {} } }, "modules": { "Environment": { "name": "Environment", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "namespaces": {}, "module": "Environment", "file": "src/accessibility/color_namer.js", "line": 1, "requires": [ "core" ] }, "Color": { "name": "Color", "submodules": { "Color Conversion": 1, "Creating & Reading": 1, "Setting": 1 }, "elements": {}, "classes": { "p5.Color": 1 }, "fors": { "p5": 1 }, "namespaces": {}, "file": "src/color/p5.Color.js", "line": 14 }, "Color Conversion": { "name": "Color Conversion", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Color", "namespace": "", "file": "src/color/color_conversion.js", "line": 1, "requires": [ "core" ] }, "Creating & Reading": { "name": "Creating & Reading", "submodules": {}, "elements": {}, "classes": { "p5.Color": 1 }, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Color", "namespace": "", "file": "src/color/p5.Color.js", "line": 14, "requires": [ "core", "constants" ], "description": "
Each color stores the color mode and level maxes that were applied at the\ntime of its construction. These are used to interpret the input arguments\n(at construction and later for that instance of color) and to format the\noutput e.g. when saturation() is requested.
\nInternally, we store an array representing the ideal RGBA values in floating\npoint form, normalized from 0 to 1. From this we calculate the closest\nscreen color (RGBA levels from 0 to 255) and expose this to the renderer.
\nWe also cache normalized, floating-point components of the color in various\nrepresentations as they are calculated. This is done to prevent repeating a\nconversion that has already been performed.
\n" }, "Setting": { "name": "Setting", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Color", "namespace": "", "file": "src/color/setting.js", "line": 1, "requires": [ "core", "constants" ] }, "Shape": { "name": "Shape", "submodules": { "2D Primitives": 1, "Curves": 1, "Vertex": 1, "3D Primitives": 1, "3D Models": 1 }, "elements": {}, "classes": { "p5.Geometry": 1, "p5.Matrix": 1 }, "fors": { "p5": 1 }, "namespaces": {}, "file": "src/webgl/p5.Matrix.js", "line": 19 }, "2D Primitives": { "name": "2D Primitives", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Shape", "namespace": "", "file": "src/core/shape/2d_primitives.js", "line": 1, "requires": [ "core", "constants" ] }, "Attributes": { "name": "Attributes", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Typography", "namespace": "", "file": "src/core/shape/attributes.js", "line": 1, "requires": [ "core", "constants" ] }, "Curves": { "name": "Curves", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Shape", "namespace": "", "file": "src/core/shape/curves.js", "line": 1, "requires": [ "core" ] }, "Vertex": { "name": "Vertex", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Shape", "namespace": "", "file": "src/core/shape/vertex.js", "line": 1, "requires": [ "core", "constants" ] }, "Constants": { "name": "Constants", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "namespaces": {}, "module": "Constants", "file": "src/core/constants.js", "line": 1 }, "Structure": { "name": "Structure", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "namespaces": {}, "module": "IO", "file": "src/core/main.js", "line": 1, "requires": [ "constants" ] }, "DOM": { "name": "DOM", "submodules": {}, "elements": {}, "classes": { "p5.Element": 1, "p5.MediaElement": 1, "p5.File": 1 }, "fors": { "p5.Element": 1, "p5": 1 }, "namespaces": {}, "module": "DOM", "file": "src/dom/dom.js", "line": 3547, "description": "The web is much more than just canvas and the DOM functionality makes it easy to interact\nwith other HTML5 objects, including text, hyperlink, image, input, video,\naudio, and webcam.\nThere is a set of creation methods, DOM manipulation methods, and\nan extended p5.Element that supports a range of HTML elements. See the\n\nbeyond the canvas tutorial for a full overview of how this addon works.
\nSee tutorial: beyond the canvas\nfor more info on how to use this library.
\n", "requires": [ "p5" ] }, "Rendering": { "name": "Rendering", "submodules": { "undefined": 1 }, "elements": {}, "classes": { "p5.RendererGL": 1, "p5.Graphics": 1, "p5.Renderer": 1 }, "fors": { "p5": 1 }, "namespaces": {}, "module": "Rendering", "file": "src/webgl/p5.RendererGL.js", "line": 598, "description": "Thin wrapper around a renderer, to be used for creating a\ngraphics buffer object. Use this class if you need\nto draw into an off-screen graphics buffer. The two parameters define the\nwidth and height in pixels. The fields and methods for this class are\nextensive, but mirror the normal drawing API for p5.
\n" }, "Foundation": { "name": "Foundation", "submodules": {}, "elements": {}, "classes": { "JSON": 1, "console": 1 }, "fors": { "p5": 1, "JSON": 1, "console": 1 }, "namespaces": {}, "module": "Foundation", "file": "src/core/reference.js", "line": 1 }, "Transform": { "name": "Transform", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "namespaces": {}, "module": "Transform", "file": "src/core/transform.js", "line": 1, "requires": [ "core", "constants" ] }, "Data": { "name": "Data", "submodules": { "LocalStorage": 1, "Dictionary": 1, "Array Functions": 1, "Conversion": 1, "String Functions": 1 }, "elements": {}, "classes": { "p5.TypedDict": 1, "p5.StringDict": 1, "p5.NumberDict": 1 }, "fors": { "p5": 1, "p5.TypedDict": 1 }, "namespaces": {}, "file": "src/data/p5.TypedDict.js", "line": 410 }, "LocalStorage": { "name": "LocalStorage", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Data", "namespace": "", "file": "src/data/local_storage.js", "line": 1, "requires": [ "core\n\nThis module defines the p5 methods for working with local storage" ] }, "Dictionary": { "name": "Dictionary", "submodules": {}, "elements": {}, "classes": { "p5.TypedDict": 1, "p5.StringDict": 1, "p5.NumberDict": 1 }, "fors": { "p5.TypedDict": 1, "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Data", "namespace": "", "file": "src/data/p5.TypedDict.js", "line": 410, "requires": [ "core\n\nThis module defines the p5 methods for the p5 Dictionary classes.\nThe classes StringDict and NumberDict are for storing and working\nwith key-value pairs." ], "description": "Base class for all p5.Dictionary types. Specifically\n typed Dictionary classes inherit from this class.
\n" }, "Events": { "name": "Events", "submodules": { "Acceleration": 1, "Keyboard": 1, "Mouse": 1, "Touch": 1 }, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "namespaces": {} }, "Acceleration": { "name": "Acceleration", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Events", "namespace": "", "file": "src/events/acceleration.js", "line": 1, "requires": [ "core" ] }, "Keyboard": { "name": "Keyboard", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Events", "namespace": "", "file": "src/events/keyboard.js", "line": 1, "requires": [ "core" ] }, "Mouse": { "name": "Mouse", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Events", "namespace": "", "file": "src/events/mouse.js", "line": 1, "requires": [ "core", "constants" ] }, "Touch": { "name": "Touch", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Events", "namespace": "", "file": "src/events/touch.js", "line": 1, "requires": [ "core" ] }, "Image": { "name": "Image", "submodules": { "Pixels": 1 }, "elements": {}, "classes": { "p5.Image": 1 }, "fors": { "p5": 1 }, "namespaces": {}, "module": "Image", "file": "src/image/p5.Image.js", "line": 21, "requires": [ "core" ], "description": "Creates a new p5.Image. A p5.Image is a canvas backed representation of an\nimage.
\np5 can display .gif, .jpg and .png images. Images may be displayed\nin 2D and 3D space. Before an image is used, it must be loaded with the\nloadImage() function. The p5.Image class contains fields for the width and\nheight of the image, as well as an array called pixels[] that contains the\nvalues for every pixel in the image.
\nThe methods described below allow easy access to the image's pixels and\nalpha channel and simplify the process of compositing.
\nBefore using the pixels[] array, be sure to use the loadPixels() method on\nthe image to make sure that the pixel data is properly loaded.
\n" }, "Loading & Displaying": { "name": "Loading & Displaying", "submodules": {}, "elements": {}, "classes": { "p5.Font": 1 }, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Typography", "namespace": "", "file": "src/typography/p5.Font.js", "line": 13, "requires": [ "core" ], "description": "This module defines the p5.Font class and functions for\ndrawing text to the display canvas.
\n" }, "Pixels": { "name": "Pixels", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Image", "namespace": "", "file": "src/image/pixels.js", "line": 1, "requires": [ "core" ] }, "IO": { "name": "IO", "submodules": { "Structure": 1, "Input": 1, "Output": 1, "Table": 1, "Time & Date": 1 }, "elements": {}, "classes": { "p5": 1, "p5.PrintWriter": 1, "p5.Table": 1, "p5.TableRow": 1, "p5.XML": 1 }, "fors": { "p5": 1 }, "namespaces": {}, "file": "src/io/p5.XML.js", "line": 9 }, "Input": { "name": "Input", "submodules": {}, "elements": {}, "classes": { "p5.XML": 1 }, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "IO", "namespace": "", "file": "src/io/p5.XML.js", "line": 9, "requires": [ "core" ], "description": "XML is a representation of an XML object, able to parse XML code. Use\nloadXML() to load external XML files and create XML objects.
\n" }, "Output": { "name": "Output", "submodules": {}, "elements": {}, "classes": { "p5": 1, "p5.PrintWriter": 1 }, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "IO", "namespace": "", "file": "src/io/files.js", "line": 1191, "description": "This is the p5 instance constructor.
\nA p5 instance holds all the properties and methods related to\na p5 sketch. It expects an incoming sketch closure and it can also\ntake an optional node parameter for attaching the generated p5 canvas\nto a node. The sketch closure takes the newly created p5 instance as\nits sole argument and may optionally set preload(),\nsetup(), and/or\ndraw() properties on it for running a sketch.
\nA p5 sketch can run in \"global\" or \"instance\" mode:\n\"global\" - all properties and methods are attached to the window\n\"instance\" - all properties and methods are bound to this p5 object
\n" }, "Table": { "name": "Table", "submodules": {}, "elements": {}, "classes": { "p5.Table": 1, "p5.TableRow": 1 }, "fors": {}, "is_submodule": 1, "namespaces": {}, "module": "IO", "namespace": "", "file": "src/io/p5.TableRow.js", "line": 9, "requires": [ "core" ], "description": "Table objects store data with multiple rows and columns, much\nlike in a traditional spreadsheet. Tables can be generated from\nscratch, dynamically, or using data from an existing file.
\n" }, "Math": { "name": "Math", "submodules": { "Calculation": 1, "Vector": 1, "Noise": 1, "Random": 1, "Trigonometry": 1 }, "elements": {}, "classes": { "p5.Vector": 1 }, "fors": { "p5": 1 }, "namespaces": {}, "file": "src/math/p5.Vector.js", "line": 10 }, "Calculation": { "name": "Calculation", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Math", "namespace": "", "file": "src/math/calculation.js", "line": 1, "requires": [ "core" ] }, "Vector": { "name": "Vector", "submodules": {}, "elements": {}, "classes": { "p5.Vector": 1 }, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Math", "namespace": "", "file": "src/math/p5.Vector.js", "line": 10, "requires": [ "core" ], "description": "A class to describe a two or three-dimensional vector, specifically\na Euclidean (also known as geometric) vector. A vector is an entity\nthat has both magnitude and direction. The datatype, however, stores\nthe components of the vector (x
, y
for 2D; or x
, y
, z
for 3D). The magnitude\nand direction can be accessed via the methods p5.Vector.mag() and heading().
In many of the p5.js examples, you will see p5.Vector used to describe a\nposition, velocity, or acceleration. For example, if you consider a rectangle\nmoving across the screen, at any given instant it has a position (a vector\nthat points from the origin to its location), a velocity (the rate at which\nthe object's position changes per time unit, expressed as a vector), and\nacceleration (the rate at which the object's velocity changes per time\nunit, expressed as a vector).
\nSince vectors represent groupings of values, we cannot simply use\ntraditional addition/multiplication/etc. Instead, we'll need to do some\n\"vector\" math, which is made easy by the methods inside the p5.Vector class.
\n" }, "Noise": { "name": "Noise", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Math", "namespace": "", "file": "src/math/noise.js", "line": 14, "requires": [ "core" ] }, "Random": { "name": "Random", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Math", "namespace": "", "file": "src/math/random.js", "line": 1, "requires": [ "core" ] }, "Trigonometry": { "name": "Trigonometry", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Math", "namespace": "", "file": "src/math/trigonometry.js", "line": 1, "requires": [ "core", "constants" ] }, "Typography": { "name": "Typography", "submodules": { "Attributes": 1, "Loading & Displaying": 1 }, "elements": {}, "classes": { "p5.Font": 1 }, "fors": { "p5": 1 }, "namespaces": {}, "file": "src/typography/p5.Font.js", "line": 13 }, "Array Functions": { "name": "Array Functions", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Data", "namespace": "", "file": "src/utilities/array_functions.js", "line": 1, "requires": [ "core" ] }, "Conversion": { "name": "Conversion", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Data", "namespace": "", "file": "src/utilities/conversion.js", "line": 1, "requires": [ "core" ] }, "String Functions": { "name": "String Functions", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Data", "namespace": "", "file": "src/utilities/string_functions.js", "line": 1, "requires": [ "core" ] }, "Time & Date": { "name": "Time & Date", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "IO", "namespace": "", "file": "src/utilities/time_date.js", "line": 1, "requires": [ "core" ] }, "3D Primitives": { "name": "3D Primitives", "submodules": {}, "elements": {}, "classes": { "p5.Geometry": 1 }, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Shape", "namespace": "", "file": "src/webgl/p5.Geometry.js", "line": 12, "requires": [ "core", "p5.Geometry" ], "description": "p5 Geometry class
\n" }, "3D": { "name": "3D", "submodules": { "Interaction": 1, "Lights": 1, "Material": 1, "Camera": 1 }, "elements": {}, "classes": { "p5.Camera": 1, "p5.Shader": 1, "p5.Texture": 1, "ImageInfos": 1, "FontInfo": 1, "Cubic": 1 }, "fors": { "p5": 1, "p5.Camera": 1 }, "namespaces": {}, "file": "src/webgl/text.js", "line": 260 }, "Interaction": { "name": "Interaction", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "3D", "namespace": "", "file": "src/webgl/interaction.js", "line": 1, "requires": [ "core" ] }, "Lights": { "name": "Lights", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "3D", "namespace": "", "file": "src/webgl/light.js", "line": 1, "requires": [ "core" ] }, "3D Models": { "name": "3D Models", "submodules": {}, "elements": {}, "classes": {}, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Shape", "namespace": "", "file": "src/webgl/loading.js", "line": 1, "requires": [ "core", "p5.Geometry" ] }, "Material": { "name": "Material", "submodules": {}, "elements": {}, "classes": { "p5.Shader": 1, "p5.Texture": 1 }, "fors": { "p5": 1 }, "is_submodule": 1, "namespaces": {}, "module": "3D", "namespace": "", "file": "src/webgl/p5.Texture.js", "line": 12, "requires": [ "core" ], "description": "This module defines the p5.Shader class
\n" }, "Camera": { "name": "Camera", "submodules": {}, "elements": {}, "classes": { "p5.Camera": 1 }, "fors": { "p5": 1, "p5.Camera": 1 }, "is_submodule": 1, "namespaces": {}, "module": "3D", "namespace": "", "file": "src/webgl/p5.Camera.js", "line": 371, "requires": [ "core" ], "description": "This class describes a camera for use in p5's\n\nWebGL mode. It contains camera position, orientation, and projection\ninformation necessary for rendering a 3D scene.
\nNew p5.Camera objects can be made through the\ncreateCamera() function and controlled through\nthe methods described below. A camera created in this way will use a default\nposition in the scene and a default perspective projection until these\nproperties are changed through the various methods available. It is possible\nto create multiple cameras, in which case the current camera\ncan be set through the setCamera() method.
\nNote:\nThe methods below operate in two coordinate systems: the 'world' coordinate\nsystem describe positions in terms of their relationship to the origin along\nthe X, Y and Z axes whereas the camera's 'local' coordinate system\ndescribes positions from the camera's point of view: left-right, up-down,\nand forward-backward. The move() method,\nfor instance, moves the camera along its own axes, whereas the\nsetPosition()\nmethod sets the camera's position in world-space.
\nThe camera object propreties\neyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ
\nwhich describes camera position, orientation, and projection\nare also accessible via the camera object generated using\ncreateCamera()
p5.sound extends p5 with Web Audio functionality including audio input,\nplayback, analysis and synthesis.\n
\np5.sound is on GitHub.\nDownload the latest version\nhere.
", "tag": "main", "itemtype": "main" } }, "classes": { "p5": { "name": "p5", "shortname": "p5", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "IO", "submodule": "Output", "namespace": "", "file": "src/core/main.js", "line": 13, "description": "This is the p5 instance constructor.
\nA p5 instance holds all the properties and methods related to\na p5 sketch. It expects an incoming sketch closure and it can also\ntake an optional node parameter for attaching the generated p5 canvas\nto a node. The sketch closure takes the newly created p5 instance as\nits sole argument and may optionally set preload(),\nsetup(), and/or\ndraw() properties on it for running a sketch.
\nA p5 sketch can run in \"global\" or \"instance\" mode:\n\"global\" - all properties and methods are attached to the window\n\"instance\" - all properties and methods are bound to this p5 object
\n", "is_constructor": 1, "params": [ { "name": "sketch", "description": "a closure that can set optional preload(),\n setup(), and/or draw() properties on the\n given p5 instance
\n", "type": "Function" }, { "name": "node", "description": "element to attach canvas to
\n", "type": "HTMLElement", "optional": true } ], "return": { "description": "a p5 instance", "type": "P5" } }, "p5.Color": { "name": "p5.Color", "shortname": "p5.Color", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "Color", "submodule": "Creating & Reading", "namespace": "", "file": "src/color/p5.Color.js", "line": 14, "description": "Each color stores the color mode and level maxes that were applied at the\ntime of its construction. These are used to interpret the input arguments\n(at construction and later for that instance of color) and to format the\noutput e.g. when saturation() is requested.
\nInternally, we store an array representing the ideal RGBA values in floating\npoint form, normalized from 0 to 1. From this we calculate the closest\nscreen color (RGBA levels from 0 to 255) and expose this to the renderer.
\nWe also cache normalized, floating-point components of the color in various\nrepresentations as they are calculated. This is done to prevent repeating a\nconversion that has already been performed.
\n", "is_constructor": 1 }, "p5.Element": { "name": "p5.Element", "shortname": "p5.Element", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "DOM", "submodule": "DOM", "namespace": "", "file": "src/core/p5.Element.js", "line": 9, "description": "Base class for all elements added to a sketch, including canvas,\ngraphics buffers, and other HTML elements. It is not called directly, but p5.Element\nobjects are created by calling createCanvas(), createGraphics(),\ncreateDiv(), createImg(), createInput(), etc.
\n", "is_constructor": 1, "params": [ { "name": "elt", "description": "DOM node that is wrapped
\n", "type": "String" }, { "name": "pInst", "description": "pointer to p5 instance
\n", "type": "P5", "optional": true } ] }, "p5.Graphics": { "name": "p5.Graphics", "shortname": "p5.Graphics", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "Rendering", "submodule": "Rendering", "namespace": "", "file": "src/core/p5.Graphics.js", "line": 10, "description": "Thin wrapper around a renderer, to be used for creating a\ngraphics buffer object. Use this class if you need\nto draw into an off-screen graphics buffer. The two parameters define the\nwidth and height in pixels. The fields and methods for this class are\nextensive, but mirror the normal drawing API for p5.
\n", "is_constructor": 1, "extends": "p5.Element", "params": [ { "name": "w", "description": "width
\n", "type": "Number" }, { "name": "h", "description": "height
\n", "type": "Number" }, { "name": "renderer", "description": "the renderer to use, either P2D or WEBGL
\n", "type": "Constant" }, { "name": "pInst", "description": "pointer to p5 instance
\n", "type": "P5", "optional": true } ] }, "p5.Renderer": { "name": "p5.Renderer", "shortname": "p5.Renderer", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "Rendering", "submodule": "Rendering", "namespace": "", "file": "src/core/p5.Renderer.js", "line": 10, "description": "Main graphics and rendering context, as well as the base API\nimplementation for p5.js \"core\". To be used as the superclass for\nRenderer2D and Renderer3D classes, respectively.
\n", "is_constructor": 1, "extends": "p5.Element", "params": [ { "name": "elt", "description": "DOM node that is wrapped
\n", "type": "String" }, { "name": "pInst", "description": "pointer to p5 instance
\n", "type": "P5", "optional": true }, { "name": "isMainCanvas", "description": "whether we're using it as main canvas
\n", "type": "Boolean", "optional": true } ] }, "JSON": { "name": "JSON", "shortname": "JSON", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "Foundation", "submodule": "Foundation", "namespace": "" }, "console": { "name": "console", "shortname": "console", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "Foundation", "submodule": "Foundation", "namespace": "" }, "p5.TypedDict": { "name": "p5.TypedDict", "shortname": "p5.TypedDict", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "Data", "submodule": "Dictionary", "namespace": "", "file": "src/data/p5.TypedDict.js", "line": 82, "description": "Base class for all p5.Dictionary types. Specifically\n typed Dictionary classes inherit from this class.
\n", "is_constructor": 1 }, "p5.StringDict": { "name": "p5.StringDict", "shortname": "p5.StringDict", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "Data", "submodule": "Dictionary", "namespace": "", "file": "src/data/p5.TypedDict.js", "line": 394, "description": "A simple Dictionary class for Strings.
\n", "extends": "p5.TypedDict" }, "p5.NumberDict": { "name": "p5.NumberDict", "shortname": "p5.NumberDict", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "Data", "submodule": "Dictionary", "namespace": "", "file": "src/data/p5.TypedDict.js", "line": 410, "description": "A simple Dictionary class for Numbers.
\n", "is_constructor": 1, "extends": "p5.TypedDict" }, "p5.MediaElement": { "name": "p5.MediaElement", "shortname": "p5.MediaElement", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "DOM", "submodule": "DOM", "namespace": "", "file": "src/dom/dom.js", "line": 2391, "description": "Extends p5.Element to handle audio and video. In addition to the methods\nof p5.Element, it also contains methods for controlling media. It is not\ncalled directly, but p5.MediaElements are created by calling createVideo,\ncreateAudio, and createCapture.
\n", "is_constructor": 1, "params": [ { "name": "elt", "description": "DOM node that is wrapped
\n", "type": "String" } ] }, "p5.File": { "name": "p5.File", "shortname": "p5.File", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "DOM", "submodule": "DOM", "namespace": "", "file": "src/dom/dom.js", "line": 3547, "description": "Base class for a file.\nUsed for Element.drop and createFileInput.
\n", "is_constructor": 1, "params": [ { "name": "file", "description": "File that is wrapped
\n", "type": "File" } ] }, "p5.Image": { "name": "p5.Image", "shortname": "p5.Image", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "Image", "submodule": "Image", "namespace": "", "file": "src/image/p5.Image.js", "line": 21, "description": "Creates a new p5.Image. A p5.Image is a canvas backed representation of an\nimage.
\np5 can display .gif, .jpg and .png images. Images may be displayed\nin 2D and 3D space. Before an image is used, it must be loaded with the\nloadImage() function. The p5.Image class contains fields for the width and\nheight of the image, as well as an array called pixels[] that contains the\nvalues for every pixel in the image.
\nThe methods described below allow easy access to the image's pixels and\nalpha channel and simplify the process of compositing.
\nBefore using the pixels[] array, be sure to use the loadPixels() method on\nthe image to make sure that the pixel data is properly loaded.
\n", "example": [ "\n\nfunction setup() {\n let img = createImage(100, 100); // same as new p5.Image(100, 100);\n img.loadPixels();\n createCanvas(100, 100);\n background(0);\n\n // helper for writing color to array\n function writeColor(image, x, y, red, green, blue, alpha) {\n let index = (x + y * width) * 4;\n image.pixels[index] = red;\n image.pixels[index + 1] = green;\n image.pixels[index + 2] = blue;\n image.pixels[index + 3] = alpha;\n }\n\n let x, y;\n // fill with random colors\n for (y = 0; y < img.height; y++) {\n for (x = 0; x < img.width; x++) {\n let red = random(255);\n let green = random(255);\n let blue = random(255);\n let alpha = 255;\n writeColor(img, x, y, red, green, blue, alpha);\n }\n }\n\n // draw a red line\n y = 0;\n for (x = 0; x < img.width; x++) {\n writeColor(img, x, y, 255, 0, 0, 255);\n }\n\n // draw a green line\n y = img.height - 1;\n for (x = 0; x < img.width; x++) {\n writeColor(img, x, y, 0, 255, 0, 255);\n }\n\n img.updatePixels();\n image(img, 0, 0);\n}\n
Table objects store data with multiple rows and columns, much\nlike in a traditional spreadsheet. Tables can be generated from\nscratch, dynamically, or using data from an existing file.
\n", "is_constructor": 1, "params": [ { "name": "rows", "description": "An array of p5.TableRow objects
\n", "type": "p5.TableRow[]", "optional": true } ] }, "p5.TableRow": { "name": "p5.TableRow", "shortname": "p5.TableRow", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "IO", "submodule": "Table", "namespace": "", "file": "src/io/p5.TableRow.js", "line": 9, "description": "A TableRow object represents a single row of data values,\nstored in columns, from a table.
\nA Table Row contains both an ordered array, and an unordered\nJSON object.
\n", "is_constructor": 1, "params": [ { "name": "str", "description": "optional: populate the row with a\n string of values, separated by the\n separator
\n", "type": "String", "optional": true }, { "name": "separator", "description": "comma separated values (csv) by default
\n", "type": "String", "optional": true } ] }, "p5.XML": { "name": "p5.XML", "shortname": "p5.XML", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "IO", "submodule": "Input", "namespace": "", "file": "src/io/p5.XML.js", "line": 9, "description": "XML is a representation of an XML object, able to parse XML code. Use\nloadXML() to load external XML files and create XML objects.
\n", "is_constructor": 1, "example": [ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let children = xml.getChildren('animal');\n\n for (let i = 0; i < children.length; i++) {\n let id = children[i].getNum('id');\n let coloring = children[i].getString('species');\n let name = children[i].getContent();\n print(id + ', ' + coloring + ', ' + name);\n }\n\n describe('no image displayed');\n}\n\n// Sketch prints:\n// 0, Capra hircus, Goat\n// 1, Panthera pardus, Leopard\n// 2, Equus zebra, Zebra\n
A class to describe a two or three-dimensional vector, specifically\na Euclidean (also known as geometric) vector. A vector is an entity\nthat has both magnitude and direction. The datatype, however, stores\nthe components of the vector (x
, y
for 2D; or x
, y
, z
for 3D). The magnitude\nand direction can be accessed via the methods p5.Vector.mag() and heading().
In many of the p5.js examples, you will see p5.Vector used to describe a\nposition, velocity, or acceleration. For example, if you consider a rectangle\nmoving across the screen, at any given instant it has a position (a vector\nthat points from the origin to its location), a velocity (the rate at which\nthe object's position changes per time unit, expressed as a vector), and\nacceleration (the rate at which the object's velocity changes per time\nunit, expressed as a vector).
\nSince vectors represent groupings of values, we cannot simply use\ntraditional addition/multiplication/etc. Instead, we'll need to do some\n\"vector\" math, which is made easy by the methods inside the p5.Vector class.
\n", "is_constructor": 1, "params": [ { "name": "x", "description": "x component of the vector
\n", "type": "Number", "optional": true }, { "name": "y", "description": "y component of the vector
\n", "type": "Number", "optional": true }, { "name": "z", "description": "z component of the vector
\n", "type": "Number", "optional": true } ], "example": [ "\n\nlet v1 = createVector(40, 50);\nlet v2 = createVector(40, 50);\n\nellipse(v1.x, v1.y, 50, 50);\nellipse(v2.x, v2.y, 50, 50);\nv1.add(v2);\nellipse(v1.x, v1.y, 50, 50);\n\ndescribe(`2 white ellipses. One center-left the other\n bottom right and off canvas`);\n
\nBase class for font handling
\n", "is_constructor": 1, "params": [ { "name": "pInst", "description": "pointer to p5 instance
\n", "type": "P5", "optional": true } ] }, "p5.Camera": { "name": "p5.Camera", "shortname": "p5.Camera", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "3D", "submodule": "Camera", "namespace": "", "file": "src/webgl/p5.Camera.js", "line": 371, "description": "This class describes a camera for use in p5's\n\nWebGL mode. It contains camera position, orientation, and projection\ninformation necessary for rendering a 3D scene.
\nNew p5.Camera objects can be made through the\ncreateCamera() function and controlled through\nthe methods described below. A camera created in this way will use a default\nposition in the scene and a default perspective projection until these\nproperties are changed through the various methods available. It is possible\nto create multiple cameras, in which case the current camera\ncan be set through the setCamera() method.
\nNote:\nThe methods below operate in two coordinate systems: the 'world' coordinate\nsystem describe positions in terms of their relationship to the origin along\nthe X, Y and Z axes whereas the camera's 'local' coordinate system\ndescribes positions from the camera's point of view: left-right, up-down,\nand forward-backward. The move() method,\nfor instance, moves the camera along its own axes, whereas the\nsetPosition()\nmethod sets the camera's position in world-space.
\nThe camera object propreties\neyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ
\nwhich describes camera position, orientation, and projection\nare also accessible via the camera object generated using\ncreateCamera()
instance of WebGL renderer
\n", "type": "RendererGL" } ], "example": [ "\n\nlet cam;\nlet delta = 0.01;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n // set initial pan angle\n cam.pan(-0.8);\n describe(\n 'camera view pans left and right across a series of rotating 3D boxes.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // pan camera according to angle 'delta'\n cam.pan(delta);\n\n // every 160 frames, switch direction\n if (frameCount % 160 === 0) {\n delta *= -1;\n }\n\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n
\np5 Geometry class
\n", "is_constructor": 1, "params": [ { "name": "detailX", "description": "number of vertices along the x-axis.
\n", "type": "Integer", "optional": true }, { "name": "detailY", "description": "number of vertices along the y-axis.
\n", "type": "Integer", "optional": true }, { "name": "callback", "description": "function to call upon object instantiation.
\n", "type": "Function", "optional": true } ] }, "p5.Shader": { "name": "p5.Shader", "shortname": "p5.Shader", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "3D", "submodule": "Material", "namespace": "", "file": "src/webgl/p5.Shader.js", "line": 11, "description": "Shader class for WEBGL Mode
\n", "is_constructor": 1, "params": [ { "name": "renderer", "description": "an instance of p5.RendererGL that\nwill provide the GL context for this new p5.Shader
\n", "type": "p5.RendererGL" }, { "name": "vertSrc", "description": "source code for the vertex shader (as a string)
\n", "type": "String" }, { "name": "fragSrc", "description": "source code for the fragment shader (as a string)
\n", "type": "String" } ] }, "p5.sound": { "name": "p5.sound", "shortname": "p5.sound", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "p5.sound", "submodule": "p5.sound", "namespace": "" }, "p5.SoundFile": { "name": "p5.SoundFile", "shortname": "p5.SoundFile", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "p5.sound", "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", "line": 1405, "description": "SoundFile object with a path to a file.
\n\nThe p5.SoundFile may not be available immediately because\nit loads the file information asynchronously.
\n\nTo do something with the sound as soon as it loads\npass the name of a function as the second parameter.
\n\nOnly one file path is required. However, audio file formats\n(i.e. mp3, ogg, wav and m4a/aac) are not supported by all\nweb browsers. If you want to ensure compatability, instead of a single\nfile path, you may include an Array of filepaths, and the browser will\nchoose a format that works.
", "is_constructor": 1, "params": [ { "name": "path", "description": "path to a sound file (String). Optionally,\n you may include multiple file formats in\n an array. Alternately, accepts an object\n from the HTML5 File API, or a p5.File.
\n", "type": "String|Array" }, { "name": "successCallback", "description": "Name of a function to call once file loads
\n", "type": "Function", "optional": true }, { "name": "errorCallback", "description": "Name of a function to call if file fails to\n load. This function will receive an error or\n XMLHttpRequest object with information\n about what went wrong.
\n", "type": "Function", "optional": true }, { "name": "whileLoadingCallback", "description": "Name of a function to call while file\n is loading. That function will\n receive progress of the request to\n load the sound file\n (between 0 and 1) as its first\n parameter. This progress\n does not account for the additional\n time needed to decode the audio data.
\n", "type": "Function", "optional": true } ], "example": [ "\n\nlet mySound;\nfunction preload() {\n soundFormats('mp3', 'ogg');\n mySound = loadSound('assets/doorbell');\n}\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(canvasPressed);\n background(220);\n text('tap here to play', 10, 20);\n}\n\nfunction canvasPressed() {\n // playing a sound file on a user gesture\n // is equivalent to `userStartAudio()`\n mySound.play();\n}\n
Amplitude measures volume between 0.0 and 1.0.\nListens to all p5sound by default, or use setInput()\nto listen to a specific sound source. Accepts an optional\nsmoothing value, which defaults to 0.
\n", "is_constructor": 1, "params": [ { "name": "smoothing", "description": "between 0.0 and .999 to smooth\n amplitude readings (defaults to 0)
\n", "type": "Number", "optional": true } ], "example": [ "\n\nlet sound, amplitude;\n\nfunction preload(){\n sound = loadSound('assets/beat.mp3');\n}\nfunction setup() {\n let cnv = createCanvas(100,100);\n cnv.mouseClicked(togglePlay);\n amplitude = new p5.Amplitude();\n}\n\nfunction draw() {\n background(220);\n text('tap to play', 20, 20);\n\n let level = amplitude.getLevel();\n let size = map(level, 0, 1, 0, 200);\n ellipse(width/2, height/2, size, size);\n}\n\nfunction togglePlay() {\n if (sound.isPlaying() ){\n sound.pause();\n } else {\n sound.loop();\n\t\tamplitude = new p5.Amplitude();\n\t\tamplitude.setInput(sound);\n }\n}\n\n
FFT (Fast Fourier Transform) is an analysis algorithm that\nisolates individual\n\naudio frequencies within a waveform.
\n\nOnce instantiated, a p5.FFT object can return an array based on\ntwo types of analyses:
• FFT.waveform()
computes\namplitude values along the time domain. The array indices correspond\nto samples across a brief moment in time. Each value represents\namplitude of the waveform at that sample of time.
\n• FFT.analyze()
computes amplitude values along the\nfrequency domain. The array indices correspond to frequencies (i.e.\npitches), from the lowest to the highest that humans can hear. Each\nvalue represents amplitude at that slice of the frequency spectrum.\nUse with getEnergy()
to measure amplitude at specific\nfrequencies, or within a range of frequencies.
FFT analyzes a very short snapshot of sound called a sample\nbuffer. It returns an array of amplitude measurements, referred\nto as bins
. The array is 1024 bins long by default.\nYou can change the bin array length, but it must be a power of 2\nbetween 16 and 1024 in order for the FFT algorithm to function\ncorrectly. The actual size of the FFT buffer is twice the\nnumber of bins, so given a standard sample rate, the buffer is\n2048/44100 seconds long.
Smooth results of Freq Spectrum.\n 0.0 < smoothing < 1.0.\n Defaults to 0.8.
\n", "type": "Number", "optional": true }, { "name": "bins", "description": "Length of resulting array.\n Must be a power of two between\n 16 and 1024. Defaults to 1024.
\n", "type": "Number", "optional": true } ], "example": [ "\n\nfunction preload(){\n sound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup(){\n let cnv = createCanvas(100,100);\n cnv.mouseClicked(togglePlay);\n fft = new p5.FFT();\n sound.amp(0.2);\n}\n\nfunction draw(){\n background(220);\n\n let spectrum = fft.analyze();\n noStroke();\n fill(255, 0, 255);\n for (let i = 0; i< spectrum.length; i++){\n let x = map(i, 0, spectrum.length, 0, width);\n let h = -height + map(spectrum[i], 0, 255, height, 0);\n rect(x, height, width / spectrum.length, h )\n }\n\n let waveform = fft.waveform();\n noFill();\n beginShape();\n stroke(20);\n for (let i = 0; i < waveform.length; i++){\n let x = map(i, 0, waveform.length, 0, width);\n let y = map( waveform[i], -1, 1, 0, height);\n vertex(x,y);\n }\n endShape();\n\n text('tap to play', 20, 20);\n}\n\nfunction togglePlay() {\n if (sound.isPlaying()) {\n sound.pause();\n } else {\n sound.loop();\n }\n}\n
Creates a signal that oscillates between -1.0 and 1.0.\nBy default, the oscillation takes the form of a sinusoidal\nshape ('sine'). Additional types include 'triangle',\n'sawtooth' and 'square'. The frequency defaults to\n440 oscillations per second (440Hz, equal to the pitch of an\n'A' note).
\n\nSet the type of oscillation with setType(), or by instantiating a\nspecific oscillator: p5.SinOsc, p5.TriOsc, p5.SqrOsc, or p5.SawOsc.\n
", "is_constructor": 1, "params": [ { "name": "freq", "description": "frequency defaults to 440Hz
\n", "type": "Number", "optional": true }, { "name": "type", "description": "type of oscillator. Options:\n 'sine' (default), 'triangle',\n 'sawtooth', 'square'
\n", "type": "String", "optional": true } ], "example": [ "\n\nlet osc, playing, freq, amp;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(playOscillator);\n osc = new p5.Oscillator('sine');\n}\n\nfunction draw() {\n background(220)\n freq = constrain(map(mouseX, 0, width, 100, 500), 100, 500);\n amp = constrain(map(mouseY, height, 0, 0, 1), 0, 1);\n\n text('tap to play', 20, 20);\n text('freq: ' + freq, 20, 40);\n text('amp: ' + amp, 20, 60);\n\n if (playing) {\n // smooth the transitions by 0.1 seconds\n osc.freq(freq, 0.1);\n osc.amp(amp, 0.1);\n }\n}\n\nfunction playOscillator() {\n // starting an oscillator on a user gesture will enable audio\n // in browsers that have a strict autoplay policy.\n // See also: userStartAudio();\n osc.start();\n playing = true;\n}\n\nfunction mouseReleased() {\n // ramp amplitude to 0 over 0.5 seconds\n osc.amp(0, 0.5);\n playing = false;\n}\n
Constructor: new p5.SinOsc()
.\nThis creates a Sine Wave Oscillator and is\nequivalent to new p5.Oscillator('sine')\n
or creating a p5.Oscillator and then calling\nits method setType('sine')
.\nSee p5.Oscillator for methods.
Set the frequency
\n", "type": "Number", "optional": true } ] }, "p5.TriOsc": { "name": "p5.TriOsc", "shortname": "p5.TriOsc", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "p5.sound", "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", "line": 4629, "description": "Constructor: new p5.TriOsc()
.\nThis creates a Triangle Wave Oscillator and is\nequivalent to new p5.Oscillator('triangle')\n
or creating a p5.Oscillator and then calling\nits method setType('triangle')
.\nSee p5.Oscillator for methods.
Set the frequency
\n", "type": "Number", "optional": true } ] }, "p5.SawOsc": { "name": "p5.SawOsc", "shortname": "p5.SawOsc", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "p5.sound", "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", "line": 4656, "description": "Constructor: new p5.SawOsc()
.\nThis creates a SawTooth Wave Oscillator and is\nequivalent to new p5.Oscillator('sawtooth')\n
or creating a p5.Oscillator and then calling\nits method setType('sawtooth')
.\nSee p5.Oscillator for methods.
Set the frequency
\n", "type": "Number", "optional": true } ] }, "p5.SqrOsc": { "name": "p5.SqrOsc", "shortname": "p5.SqrOsc", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "p5.sound", "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", "line": 4683, "description": "Constructor: new p5.SqrOsc()
.\nThis creates a Square Wave Oscillator and is\nequivalent to new p5.Oscillator('square')\n
or creating a p5.Oscillator and then calling\nits method setType('square')
.\nSee p5.Oscillator for methods.
Set the frequency
\n", "type": "Number", "optional": true } ] }, "p5.Envelope": { "name": "p5.Envelope", "shortname": "p5.Envelope", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "p5.sound", "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", "line": 4721, "description": "Envelopes are pre-defined amplitude distribution over time.\nTypically, envelopes are used to control the output volume\nof an object, a series of fades referred to as Attack, Decay,\nSustain and Release (\nADSR\n). Envelopes can also control other Web Audio Parameters—for example, a p5.Envelope can\ncontrol an Oscillator's frequency like this: osc.freq(env)
.
Use setRange
to change the attack/release level.\nUse setADSR
to change attackTime, decayTime, sustainPercent and releaseTime.
Use the play
method to play the entire envelope,\nthe ramp
method for a pingable trigger,\nor triggerAttack
/\ntriggerRelease
to trigger noteOn/noteOff.
\nlet t1 = 0.1; // attack time in seconds\nlet l1 = 0.7; // attack level 0.0 to 1.0\nlet t2 = 0.3; // decay time in seconds\nlet l2 = 0.1; // decay level 0.0 to 1.0\n\nlet env;\nlet triOsc;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n background(220);\n text('tap to play', 20, 20);\n cnv.mousePressed(playSound);\n\n env = new p5.Envelope(t1, l1, t2, l2);\n triOsc = new p5.Oscillator('triangle');\n}\n\nfunction playSound() {\n // starting the oscillator ensures that audio is enabled.\n triOsc.start();\n env.play(triOsc);\n}\n
Noise is a type of oscillator that generates a buffer with random values.
\n", "extends": "p5.Oscillator", "is_constructor": 1, "params": [ { "name": "type", "description": "Type of noise can be 'white' (default),\n 'brown' or 'pink'.
\n", "type": "String" } ] }, "p5.Pulse": { "name": "p5.Pulse", "shortname": "p5.Pulse", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "p5.sound", "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", "line": 5779, "description": "Creates a Pulse object, an oscillator that implements\nPulse Width Modulation.\nThe pulse is created with two oscillators.\nAccepts a parameter for frequency, and to set the\nwidth between the pulses. See \np5.Oscillator
for a full list of methods.
Frequency in oscillations per second (Hz)
\n", "type": "Number", "optional": true }, { "name": "w", "description": "Width between the pulses (0 to 1.0,\n defaults to 0)
\n", "type": "Number", "optional": true } ], "example": [ "\n\nlet pulse;\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(startPulse);\n background(220);\n\n pulse = new p5.Pulse();\n pulse.amp(0.5);\n pulse.freq(220);\n}\nfunction startPulse() {\n pulse.start();\n pulse.amp(0.5, 0.02);\n}\nfunction mouseReleased() {\n pulse.amp(0, 0.2);\n}\nfunction draw() {\n background(220);\n text('tap to play', 5, 20, width - 20);\n let w = map(mouseX, 0, width, 0, 1);\n w = constrain(w, 0, 1);\n pulse.width(w);\n text('pulse width: ' + w, 5, height - 20);\n}\n
Get audio from an input, i.e. your computer's microphone.
\n\nTurn the mic on/off with the start() and stop() methods. When the mic\nis on, its volume can be measured with getLevel or by connecting an\nFFT object.
\n\nIf you want to hear the AudioIn, use the .connect() method.\nAudioIn does not connect to p5.sound output by default to prevent\nfeedback.
\n\nNote: This uses the getUserMedia/\nStream API, which is not supported by certain browsers. Access in Chrome browser\nis limited to localhost and https, but access over http may be limited.
", "is_constructor": 1, "params": [ { "name": "errorCallback", "description": "A function to call if there is an error\n accessing the AudioIn. For example,\n Safari and iOS devices do not\n currently allow microphone access.
\n", "type": "Function", "optional": true } ], "example": [ "\n\nlet mic;\n\n function setup(){\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(userStartAudio);\n textAlign(CENTER);\n mic = new p5.AudioIn();\n mic.start();\n}\n\nfunction draw(){\n background(0);\n fill(255);\n text('tap to start', width/2, 20);\n\n micLevel = mic.getLevel();\n let y = height - micLevel * height;\n ellipse(width/2, y, 10, 10);\n}\n
Effect is a base class for audio effects in p5.
\nThis module handles the nodes and methods that are\ncommon and useful for current and future effects.
This class is extended by p5.Distortion,\np5.Compressor,\np5.Delay,\np5.Filter,\np5.Reverb.
\n", "is_constructor": 1, "params": [ { "name": "ac", "description": "Reference to the audio context of the p5 object
\n", "type": "Object", "optional": true }, { "name": "input", "description": "Gain Node effect wrapper
\n", "type": "AudioNode", "optional": true }, { "name": "output", "description": "Gain Node effect wrapper
\n", "type": "AudioNode", "optional": true }, { "name": "_drywet", "description": "Tone.JS CrossFade node (defaults to value: 1)
\n", "type": "Object", "optional": true }, { "name": "wet", "description": "Effects that extend this class should connect\n to the wet signal to this gain node, so that dry and wet\n signals are mixed properly.
\n", "type": "AudioNode", "optional": true } ] }, "p5.Filter": { "name": "p5.Filter", "shortname": "p5.Filter", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "p5.sound", "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", "line": 6628, "description": "A p5.Filter uses a Web Audio Biquad Filter to filter\nthe frequency response of an input source. Subclasses\ninclude:
\np5.LowPass
:\nAllows frequencies below the cutoff frequency to pass through,\nand attenuates frequencies above the cutoff.p5.HighPass
:\nThe opposite of a lowpass filter. p5.BandPass
:\nAllows a range of frequencies to pass through and attenuates\nthe frequencies below and above this frequency range.The .res()
method controls either width of the\nbandpass, or resonance of the low/highpass cutoff frequency.
This class extends p5.Effect.\nMethods amp(), chain(),\ndrywet(), connect(), and\ndisconnect() are available.
\n", "extends": "p5.Effect", "is_constructor": 1, "params": [ { "name": "type", "description": "'lowpass' (default), 'highpass', 'bandpass'
\n", "type": "String", "optional": true } ], "example": [ "\n\nlet fft, noise, filter;\n\nfunction setup() {\n let cnv = createCanvas(100,100);\n cnv.mousePressed(makeNoise);\n fill(255, 0, 255);\n\n filter = new p5.BandPass();\n noise = new p5.Noise();\n noise.disconnect();\n noise.connect(filter);\n\n fft = new p5.FFT();\n}\n\nfunction draw() {\n background(220);\n\n // set the BandPass frequency based on mouseX\n let freq = map(mouseX, 0, width, 20, 10000);\n freq = constrain(freq, 0, 22050);\n filter.freq(freq);\n // give the filter a narrow band (lower res = wider bandpass)\n filter.res(50);\n\n // draw filtered spectrum\n let spectrum = fft.analyze();\n noStroke();\n for (let i = 0; i < spectrum.length; i++) {\n let x = map(i, 0, spectrum.length, 0, width);\n let h = -height + map(spectrum[i], 0, 255, height, 0);\n rect(x, height, width/spectrum.length, h);\n }\n if (!noise.started) {\n text('tap here and drag to change frequency', 10, 20, width - 20);\n } else {\n text('Frequency: ' + round(freq)+'Hz', 20, 20, width - 20);\n }\n}\n\nfunction makeNoise() {\n // see also: `userStartAudio()`\n noise.start();\n noise.amp(0.5, 0.2);\n}\n\nfunction mouseReleased() {\n noise.amp(0, 0.2);\n}\n\n
Constructor: new p5.LowPass()
Filter.\nThis is the same as creating a p5.Filter and then calling\nits method setType('lowpass')
.\nSee p5.Filter for methods.
Constructor: new p5.HighPass()
Filter.\nThis is the same as creating a p5.Filter and then calling\nits method setType('highpass')
.\nSee p5.Filter for methods.
Constructor: new p5.BandPass()
Filter.\nThis is the same as creating a p5.Filter and then calling\nits method setType('bandpass')
.\nSee p5.Filter for methods.
p5.EQ is an audio effect that performs the function of a multiband\naudio equalizer. Equalization is used to adjust the balance of\nfrequency compoenents of an audio signal. This process is commonly used\nin sound production and recording to change the waveform before it reaches\na sound output device. EQ can also be used as an audio effect to create\ninteresting distortions by filtering out parts of the spectrum. p5.EQ is\nbuilt using a chain of Web Audio Biquad Filter Nodes and can be\ninstantiated with 3 or 8 bands. Bands can be added or removed from\nthe EQ by directly modifying p5.EQ.bands (the array that stores filters).
\nThis class extends p5.Effect.\nMethods amp(), chain(),\ndrywet(), connect(), and\ndisconnect() are available.
\n", "is_constructor": 1, "extends": "p5.Effect", "params": [ { "name": "_eqsize", "description": "Constructor will accept 3 or 8, defaults to 3
\n", "type": "Number", "optional": true } ], "return": { "description": "p5.EQ object", "type": "Object" }, "example": [ "\n\nlet eq, soundFile\nlet eqBandIndex = 0;\nlet eqBandNames = ['lows', 'mids', 'highs'];\n\nfunction preload() {\n soundFormats('mp3', 'ogg');\n soundFile = loadSound('assets/beat');\n}\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(toggleSound);\n\n eq = new p5.EQ(eqBandNames.length);\n soundFile.disconnect();\n eq.process(soundFile);\n}\n\nfunction draw() {\n background(30);\n noStroke();\n fill(255);\n textAlign(CENTER);\n text('filtering ', 50, 25);\n\n fill(255, 40, 255);\n textSize(26);\n text(eqBandNames[eqBandIndex], 50, 55);\n\n fill(255);\n textSize(9);\n\n if (!soundFile.isPlaying()) {\n text('tap to play', 50, 80);\n } else {\n text('tap to filter next band', 50, 80)\n }\n}\n\nfunction toggleSound() {\n if (!soundFile.isPlaying()) {\n soundFile.play();\n } else {\n eqBandIndex = (eqBandIndex + 1) % eq.bands.length;\n }\n\n for (let i = 0; i < eq.bands.length; i++) {\n eq.bands[i].gain(0);\n }\n // filter the band we want to filter\n eq.bands[eqBandIndex].gain(-40);\n}\n
Panner3D is based on the \nWeb Audio Spatial Panner Node.\nThis panner is a spatial processing node that allows audio to be positioned\nand oriented in 3D space.
\nThe position is relative to an \nAudio Context Listener, which can be accessed\nby p5.soundOut.audiocontext.listener
Delay is an echo effect. It processes an existing sound source,\nand outputs a delayed version of that sound. The p5.Delay can\nproduce different effects depending on the delayTime, feedback,\nfilter, and type. In the example below, a feedback of 0.5 (the\ndefault value) will produce a looping delay that decreases in\nvolume by 50% each repeat. A filter will cut out the high\nfrequencies so that the delay does not sound as piercing as the\noriginal source.
\nThis class extends p5.Effect.\nMethods amp(), chain(),\ndrywet(), connect(), and\ndisconnect() are available.
\n", "extends": "p5.Effect", "is_constructor": 1, "example": [ "\n\nlet osc;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n background(220);\n textAlign(CENTER);\n text('tap to play', width/2, height/2);\n\n osc = new p5.Oscillator('square');\n osc.amp(0.5);\n delay = new p5.Delay();\n\n // delay.process() accepts 4 parameters:\n // source, delayTime (in seconds), feedback, filter frequency\n delay.process(osc, 0.12, .7, 2300);\n\n cnv.mousePressed(oscStart);\n}\n\nfunction oscStart() {\n osc.start();\n}\n\nfunction mouseReleased() {\n osc.stop();\n}\n
Reverb adds depth to a sound through a large number of decaying\nechoes. It creates the perception that sound is occurring in a\nphysical space. The p5.Reverb has paramters for Time (how long does the\nreverb last) and decayRate (how much the sound decays with each echo)\nthat can be set with the .set() or .process() methods. The p5.Convolver\nextends p5.Reverb allowing you to recreate the sound of actual physical\nspaces through convolution.
\nThis class extends p5.Effect.\nMethods amp(), chain(),\ndrywet(), connect(), and\ndisconnect() are available.
\n", "extends": "p5.Effect", "is_constructor": 1, "example": [ "\n\nlet soundFile, reverb;\nfunction preload() {\n soundFile = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(playSound);\n\n reverb = new p5.Reverb();\n soundFile.disconnect(); // so we'll only hear reverb...\n\n // connect soundFile to reverb, process w/\n // 3 second reverbTime, decayRate of 2%\n reverb.process(soundFile, 3, 2);\n}\n\nfunction draw() {\n let dryWet = constrain(map(mouseX, 0, width, 0, 1), 0, 1);\n // 1 = all reverb, 0 = no reverb\n reverb.drywet(dryWet);\n\n background(220);\n text('tap to play', 10, 20);\n text('dry/wet: ' + round(dryWet * 100) + '%', 10, height - 20);\n}\n\nfunction playSound() {\n soundFile.play();\n}\n
p5.Convolver extends p5.Reverb. It can emulate the sound of real\nphysical spaces through a process called \nconvolution.
\n\nConvolution multiplies any audio input by an \"impulse response\"\nto simulate the dispersion of sound over time. The impulse response is\ngenerated from an audio file that you provide. One way to\ngenerate an impulse response is to pop a balloon in a reverberant space\nand record the echo. Convolution can also be used to experiment with\nsound.
\n\nUse the method createConvolution(path)
to instantiate a\np5.Convolver with a path to your impulse response audio file.
path to a sound file
\n", "type": "String" }, { "name": "callback", "description": "function to call when loading succeeds
\n", "type": "Function", "optional": true }, { "name": "errorCallback", "description": "function to call if loading fails.\n This function will receive an error or\n XMLHttpRequest object with information\n about what went wrong.
\n", "type": "Function", "optional": true } ], "example": [ "\n\nlet cVerb, sound;\nfunction preload() {\n // We have both MP3 and OGG versions of all sound assets\n soundFormats('ogg', 'mp3');\n\n // Try replacing 'bx-spring' with other soundfiles like\n // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox'\n cVerb = createConvolver('assets/bx-spring.mp3');\n\n // Try replacing 'Damscray_DancingTiger' with\n // 'beat', 'doorbell', lucky_dragons_-_power_melody'\n sound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(playSound);\n background(220);\n text('tap to play', 20, 20);\n\n // disconnect from main output...\n sound.disconnect();\n\n // ...and process with cVerb\n // so that we only hear the convolution\n cVerb.process(sound);\n}\n\nfunction playSound() {\n sound.play();\n}\n
A phrase is a pattern of musical events over time, i.e.\na series of notes and rests.
\n\nPhrases must be added to a p5.Part for playback, and\neach part can play multiple phrases at the same time.\nFor example, one Phrase might be a kick drum, another\ncould be a snare, and another could be the bassline.
\n\nThe first parameter is a name so that the phrase can be\nmodified or deleted later. The callback is a a function that\nthis phrase will call at every step—for example it might be\ncalled playNote(value){}
. The array determines\nwhich value is passed into the callback at each step of the\nphrase. It can be numbers, an object with multiple numbers,\nor a zero (0) indicates a rest so the callback won't be called).
Name so that you can access the Phrase.
\n", "type": "String" }, { "name": "callback", "description": "The name of a function that this phrase\n will call. Typically it will play a sound,\n and accept two parameters: a time at which\n to play the sound (in seconds from now),\n and a value from the sequence array. The\n time should be passed into the play() or\n start() method to ensure precision.
\n", "type": "Function" }, { "name": "sequence", "description": "Array of values to pass into the callback\n at each step of the phrase.
\n", "type": "Array" } ], "example": [ "\n\nlet mySound, myPhrase, myPart;\nlet pattern = [1,0,0,2,0,2,0,0];\n\nfunction preload() {\n mySound = loadSound('assets/beatbox.mp3');\n}\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(playMyPart);\n background(220);\n text('tap to play', width/2, height/2);\n textAlign(CENTER, CENTER);\n\n myPhrase = new p5.Phrase('bbox', onEachStep, pattern);\n myPart = new p5.Part();\n myPart.addPhrase(myPhrase);\n myPart.setBPM(60);\n}\n\nfunction onEachStep(time, playbackRate) {\n mySound.rate(playbackRate);\n mySound.play(time);\n}\n\nfunction playMyPart() {\n userStartAudio();\n myPart.start();\n}\n
A p5.Part plays back one or more p5.Phrases. Instantiate a part\nwith steps and tatums. By default, each step represents a 1/16th note.
\n\nSee p5.Phrase for more about musical timing.
", "is_constructor": 1, "params": [ { "name": "steps", "description": "Steps in the part
\n", "type": "Number", "optional": true }, { "name": "tatums", "description": "Divisions of a beat, e.g. use 1/4, or 0.25 for a quater note (default is 1/16, a sixteenth note)
\n", "type": "Number", "optional": true } ], "example": [ "\n\nlet box, drum, myPart;\nlet boxPat = [1,0,0,2,0,2,0,0];\nlet drumPat = [0,1,1,0,2,0,1,0];\n\nfunction preload() {\n box = loadSound('assets/beatbox.mp3');\n drum = loadSound('assets/drum.mp3');\n}\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(playMyPart);\n background(220);\n textAlign(CENTER, CENTER);\n text('tap to play', width/2, height/2);\n\n let boxPhrase = new p5.Phrase('box', playBox, boxPat);\n let drumPhrase = new p5.Phrase('drum', playDrum, drumPat);\n myPart = new p5.Part();\n myPart.addPhrase(boxPhrase);\n myPart.addPhrase(drumPhrase);\n myPart.setBPM(60);\n}\n\nfunction playBox(time, playbackRate) {\n box.rate(playbackRate);\n box.play(time);\n}\n\nfunction playDrum(time, playbackRate) {\n drum.rate(playbackRate);\n drum.play(time);\n}\n\nfunction playMyPart() {\n userStartAudio();\n\n myPart.start();\n}\n
A Score consists of a series of Parts. The parts will\nbe played back in order. For example, you could have an\nA part, a B part, and a C part, and play them back in this order\nnew p5.Score(a, a, b, a, c)
One or multiple parts, to be played in sequence.
\n", "type": "p5.Part", "optional": true, "multiple": true } ] }, "p5.SoundLoop": { "name": "p5.SoundLoop", "shortname": "p5.SoundLoop", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "p5.sound", "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", "line": 9673, "description": "SoundLoop
\n", "is_constructor": 1, "params": [ { "name": "callback", "description": "this function will be called on each iteration of theloop
\n", "type": "Function" }, { "name": "interval", "description": "amount of time (if a number) or beats (if a string, following Tone.Time convention) for each iteration of the loop. Defaults to 1 second.
\n", "type": "Number|String", "optional": true } ], "example": [ "\n\n let synth, soundLoop;\n let notePattern = [60, 62, 64, 67, 69, 72];\n\n function setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(canvasPressed);\n colorMode(HSB);\n background(0, 0, 86);\n text('tap to start/stop', 10, 20);\n\n //the looper's callback is passed the timeFromNow\n //this value should be used as a reference point from\n //which to schedule sounds\n let intervalInSeconds = 0.2;\n soundLoop = new p5.SoundLoop(onSoundLoop, intervalInSeconds);\n\n synth = new p5.MonoSynth();\n}\n\nfunction canvasPressed() {\n // ensure audio is enabled\n userStartAudio();\n\n if (soundLoop.isPlaying) {\n soundLoop.stop();\n } else {\n // start the loop\n soundLoop.start();\n }\n}\n\nfunction onSoundLoop(timeFromNow) {\n let noteIndex = (soundLoop.iterations - 1) % notePattern.length;\n let note = midiToFreq(notePattern[noteIndex]);\n synth.play(note, 0.5, timeFromNow);\n background(noteIndex * 360 / notePattern.length, 50, 100);\n}\n
Compressor is an audio effect class that performs dynamics compression\non an audio input source. This is a very commonly used technique in music\nand sound production. Compression creates an overall louder, richer,\nand fuller sound by lowering the volume of louds and raising that of softs.\nCompression can be used to avoid clipping (sound distortion due to\npeaks in volume) and is especially useful when many sounds are played\nat once. Compression can be used on indivudal sound sources in addition\nto the main output.
\nThis class extends p5.Effect.\nMethods amp(), chain(),\ndrywet(), connect(), and\ndisconnect() are available.
\n", "is_constructor": 1, "extends": "p5.Effect" }, "p5.PeakDetect": { "name": "p5.PeakDetect", "shortname": "p5.PeakDetect", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "p5.sound", "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", "line": 10312, "description": "PeakDetect works in conjunction with p5.FFT to\nlook for onsets in some or all of the frequency spectrum.\n
\n\nTo use p5.PeakDetect, call update
in the draw loop\nand pass in a p5.FFT object.\n
\nYou can listen for a specific part of the frequency spectrum by\nsetting the range between freq1
and freq2
.\n
threshold
is the threshold for detecting a peak,\nscaled between 0 and 1. It is logarithmic, so 0.1 is half as loud\nas 1.0.
\nThe update method is meant to be run in the draw loop, and\nframes determines how many loops must pass before\nanother peak can be detected.\nFor example, if the frameRate() = 60, you could detect the beat of a\n120 beat-per-minute song with this equation:\n framesPerPeak = 60 / (estimatedBPM / 60 );
\n
\nBased on example contribtued by @b2renger, and a simple beat detection\nexplanation by Felix Turner.\n
", "is_constructor": 1, "params": [ { "name": "freq1", "description": "lowFrequency - defaults to 20Hz
\n", "type": "Number", "optional": true }, { "name": "freq2", "description": "highFrequency - defaults to 20000 Hz
\n", "type": "Number", "optional": true }, { "name": "threshold", "description": "Threshold for detecting a beat between 0 and 1\n scaled logarithmically where 0.1 is 1/2 the loudness\n of 1.0. Defaults to 0.35.
\n", "type": "Number", "optional": true }, { "name": "framesPerPeak", "description": "Defaults to 20.
\n", "type": "Number", "optional": true } ], "example": [ "\n\n\nvar cnv, soundFile, fft, peakDetect;\nvar ellipseWidth = 10;\n\nfunction preload() {\n soundFile = loadSound('assets/beat.mp3');\n}\n\nfunction setup() {\n background(0);\n noStroke();\n fill(255);\n textAlign(CENTER);\n\n // p5.PeakDetect requires a p5.FFT\n fft = new p5.FFT();\n peakDetect = new p5.PeakDetect();\n}\n\nfunction draw() {\n background(0);\n text('click to play/pause', width/2, height/2);\n\n // peakDetect accepts an fft post-analysis\n fft.analyze();\n peakDetect.update(fft);\n\n if ( peakDetect.isDetected ) {\n ellipseWidth = 50;\n } else {\n ellipseWidth *= 0.95;\n }\n\n ellipse(width/2, height/2, ellipseWidth, ellipseWidth);\n}\n\n// toggle play/stop when canvas is clicked\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n if (soundFile.isPlaying() ) {\n soundFile.stop();\n } else {\n soundFile.play();\n }\n }\n}\n
Record sounds for playback and/or to save as a .wav file.\nThe p5.SoundRecorder records all sound output from your sketch,\nor can be assigned a specific source with setInput().
\nThe record() method accepts a p5.SoundFile as a parameter.\nWhen playback is stopped (either after the given amount of time,\nor with the stop() method), the p5.SoundRecorder will send its\nrecording to that p5.SoundFile for playback.
", "is_constructor": 1, "example": [ "\n\nlet mic, recorder, soundFile;\nlet state = 0;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(canvasPressed);\n background(220);\n textAlign(CENTER, CENTER);\n\n // create an audio in\n mic = new p5.AudioIn();\n\n // prompts user to enable their browser mic\n mic.start();\n\n // create a sound recorder\n recorder = new p5.SoundRecorder();\n\n // connect the mic to the recorder\n recorder.setInput(mic);\n\n // this sound file will be used to\n // playback & save the recording\n soundFile = new p5.SoundFile();\n\n text('tap to record', width/2, height/2);\n}\n\nfunction canvasPressed() {\n // ensure audio is enabled\n userStartAudio();\n\n // make sure user enabled the mic\n if (state === 0 && mic.enabled) {\n\n // record to our p5.SoundFile\n recorder.record(soundFile);\n\n background(255,0,0);\n text('Recording!', width/2, height/2);\n state++;\n }\n else if (state === 1) {\n background(0,255,0);\n\n // stop recorder and\n // send result to soundFile\n recorder.stop();\n\n text('Done! Tap to play and download', width/2, height/2, width - 20);\n state++;\n }\n\n else if (state === 2) {\n soundFile.play(); // play the result!\n save(soundFile, 'mySound.wav');\n state++;\n }\n}\n
A Distortion effect created with a Waveshaper Node,\nwith an approach adapted from\nKevin Ennis
\nThis class extends p5.Effect.\nMethods amp(), chain(),\ndrywet(), connect(), and\ndisconnect() are available.
\n", "extends": "p5.Effect", "is_constructor": 1, "params": [ { "name": "amount", "description": "Unbounded distortion amount.\n Normal values range from 0-1.
\n", "type": "Number", "optional": true, "optdefault": "0.25" }, { "name": "oversample", "description": "'none', '2x', or '4x'.
\n", "type": "String", "optional": true, "optdefault": "'none'" } ] }, "p5.Gain": { "name": "p5.Gain", "shortname": "p5.Gain", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "p5.sound", "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", "line": 10973, "description": "A gain node is usefull to set the relative volume of sound.\nIt's typically used to build mixers.
\n", "is_constructor": 1, "example": [ "\n\n\n// load two soundfile and crossfade beetween them\nlet sound1,sound2;\nlet sound1Gain, sound2Gain, mixGain;\nfunction preload(){\n soundFormats('ogg', 'mp3');\n sound1 = loadSound('assets/Damscray_-_Dancing_Tiger_01');\n sound2 = loadSound('assets/beat');\n}\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(startSound);\n // create a 'mix' gain bus to which we will connect both soundfiles\n mixGain = new p5.Gain();\n mixGain.connect();\n sound1.disconnect(); // diconnect from p5 output\n sound1Gain = new p5.Gain(); // setup a gain node\n sound1Gain.setInput(sound1); // connect the first sound to its input\n sound1Gain.connect(mixGain); // connect its output to the final mix bus\n sound2.disconnect();\n sound2Gain = new p5.Gain();\n sound2Gain.setInput(sound2);\n sound2Gain.connect(mixGain);\n}\nfunction startSound() {\n sound1.loop();\n sound2.loop();\n loop();\n}\nfunction mouseReleased() {\n sound1.stop();\n sound2.stop();\n}\nfunction draw(){\n background(220);\n textAlign(CENTER);\n textSize(11);\n fill(0);\n if (!sound1.isPlaying()) {\n text('tap and drag to play', width/2, height/2);\n return;\n }\n // map the horizontal position of the mouse to values useable for volume * control of sound1\n var sound1Volume = constrain(map(mouseX,width,0,0,1), 0, 1);\n var sound2Volume = 1-sound1Volume;\n sound1Gain.amp(sound1Volume);\n sound2Gain.amp(sound2Volume);\n // map the vertical position of the mouse to values useable for 'output * volume control'\n var outputVolume = constrain(map(mouseY,height,0,0,1), 0, 1);\n mixGain.amp(outputVolume);\n text('output', width/2, height - outputVolume * height * 0.9)\n fill(255, 0, 255);\n textAlign(LEFT);\n text('sound1', 5, height - sound1Volume * height * 0.9);\n textAlign(RIGHT);\n text('sound2', width - 5, height - sound2Volume * height * 0.9);\n}\n
Base class for monophonic synthesizers. Any extensions of this class\nshould follow the API and implement the methods below in order to\nremain compatible with p5.PolySynth();
\n", "is_constructor": 1 }, "p5.MonoSynth": { "name": "p5.MonoSynth", "shortname": "p5.MonoSynth", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "p5.sound", "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", "line": 11247, "description": "A MonoSynth is used as a single voice for sound synthesis.\nThis is a class to be used in conjunction with the PolySynth\nclass. Custom synthetisers should be built inheriting from\nthis class.
\n", "is_constructor": 1, "example": [ "\n\nlet monoSynth;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(playSynth);\n background(220);\n textAlign(CENTER);\n text('tap to play', width/2, height/2);\n\n monoSynth = new p5.MonoSynth();\n}\n\nfunction playSynth() {\n userStartAudio();\n\n let note = random(['Fb4', 'G4']);\n // note velocity (volume, from 0 to 1)\n let velocity = random();\n // time from now (in seconds)\n let time = 0;\n // note duration (in seconds)\n let dur = 1/6;\n\n monoSynth.play(note, velocity, time, dur);\n}\n
Listen for onsets (a sharp increase in volume) within a given\nfrequency range.
\n", "is_constructor": 1, "params": [ { "name": "freqLow", "description": "Low frequency
\n", "type": "Number" }, { "name": "freqHigh", "description": "High frequency
\n", "type": "Number" }, { "name": "threshold", "description": "Amplitude threshold between 0 (no energy) and 1 (maximum)
\n", "type": "Number" }, { "name": "callback", "description": "Function to call when an onset is detected
\n", "type": "Function" } ] }, "p5.PolySynth": { "name": "p5.PolySynth", "shortname": "p5.PolySynth", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "p5.sound", "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", "line": 11691, "description": "An AudioVoice is used as a single voice for sound synthesis.\nThe PolySynth class holds an array of AudioVoice, and deals\nwith voices allocations, with setting notes to be played, and\nparameters to be set.
\n", "is_constructor": 1, "params": [ { "name": "synthVoice", "description": "A monophonic synth voice inheriting\n the AudioVoice class. Defaults to p5.MonoSynth
\n", "type": "Number", "optional": true }, { "name": "maxVoices", "description": "Number of voices, defaults to 8;
\n", "type": "Number", "optional": true } ], "example": [ "\n\nlet polySynth;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(playSynth);\n background(220);\n text('click to play', 20, 20);\n\n polySynth = new p5.PolySynth();\n}\n\nfunction playSynth() {\n userStartAudio();\n\n // note duration (in seconds)\n let dur = 1.5;\n\n // time from now (in seconds)\n let time = 0;\n\n // velocity (volume, from 0 to 1)\n let vel = 0.1;\n\n // notes can overlap with each other\n polySynth.play('G2', vel, 0, dur);\n polySynth.play('C3', vel, time += 1/3, dur);\n polySynth.play('G3', vel, time += 1/3, dur);\n}\n
Creates a screen reader accessible description for the canvas.\nThe first parameter should be a string with a description of the canvas.\nThe second parameter is optional. If specified, it determines how the\ndescription is displayed.
\ndescribe(text, LABEL)
displays\nthe description to all users as a \ntombstone or exhibit label/caption in a div\nadjacent to the canvas. You can style it as you wish in your CSS.
describe(text, FALLBACK)
makes the\ndescription accessible to screen-reader users only, in\n\na sub DOM inside the canvas element. If a second parameter is not\nspecified, by default, the description will only be available to\nscreen-reader users.
description of the canvas
\n", "type": "String" }, { "name": "display", "description": "either LABEL or FALLBACK
\n", "type": "Constant", "optional": true } ], "example": [ "\n\ndescribe('pink square with red heart in the bottom right corner');\nbackground('pink');\nfill('red');\nnoStroke();\nellipse(67, 67, 20, 20);\nellipse(83, 67, 20, 20);\ntriangle(91, 73, 75, 95, 59, 73);\n
\n\nlet x = 0;\nfunction draw() {\n if (x > 100) {\n x = 0;\n }\n background(220);\n fill(0, 255, 0);\n ellipse(x, 50, 40, 40);\n x = x + 0.1;\n describe('green circle at x pos ' + round(x) + ' moving to the right');\n}\n
\nThis function creates a screen-reader accessible\ndescription for elements —shapes or groups of shapes that create\nmeaning together— in the canvas. The first paramater should\nbe the name of the element. The second parameter should be a string\nwith a description of the element. The third parameter is optional.\nIf specified, it determines how the element description is displayed.
\ndescribeElement(name, text, LABEL)
\ndisplays the element description to all users as a\n\ntombstone or exhibit label/caption in a div\nadjacent to the canvas. You can style it as you wish in your CSS.
describeElement(name, text, FALLBACK)
\nmakes the element description accessible to screen-reader users\nonly, in \na sub DOM inside the canvas element. If a second parameter is not\nspecified, by default, the element description will only be available\nto screen-reader users.
name of the element
\n", "type": "String" }, { "name": "text", "description": "description of the element
\n", "type": "String" }, { "name": "display", "description": "either LABEL or FALLBACK
\n", "type": "Constant", "optional": true } ], "example": [ "\n\ndescribe('Heart and yellow circle over pink background');\nnoStroke();\nbackground('pink');\ndescribeElement('Circle', 'Yellow circle in the top left corner');\nfill('yellow');\nellipse(25, 25, 40, 40);\ndescribeElement('Heart', 'red heart in the bottom right corner');\nfill('red');\nellipse(66.6, 66.6, 20, 20);\nellipse(83.2, 66.6, 20, 20);\ntriangle(91.2, 72.6, 75, 95, 58.6, 72.6);\n
\ntextOutput()
creates a screenreader\naccessible output that describes the shapes present on the canvas.\nThe general description of the canvas includes canvas size,\ncanvas color, and number of elements in the canvas\n(example: 'Your output is a, 400 by 400 pixels, lavender blue\ncanvas containing the following 4 shapes:'). This description\nis followed by a list of shapes where the color, position, and area\nof each shape are described (example: \"orange ellipse at top left\ncovering 1% of the canvas\"). Each element can be selected to get\nmore details. A table of elements is also provided. In this table,\nshape, color, location, coordinates and area are described\n(example: \"orange ellipse location=top left area=2\").
textOutput()
and textOutput(FALLBACK)
\nmake the output available in \na sub DOM inside the canvas element which is accessible to screen readers.\ntextOutput(LABEL)
creates an\nadditional div with the output adjacent to the canvas, this is useful\nfor non-screen reader users that might want to display the output outside\nof the canvas' sub DOM as they code. However, using LABEL will create\nunnecessary redundancy for screen reader users. We recommend using LABEL\nonly as part of the development process of a sketch and removing it before\npublishing or sharing with screen reader users.
either FALLBACK or LABEL
\n", "type": "Constant", "optional": true } ], "example": [ "\n\ntextOutput();\nbackground(148, 196, 0);\nfill(255, 0, 0);\nellipse(20, 20, 20, 20);\nfill(0, 0, 255);\nrect(50, 50, 50, 50);\n
\n\nlet x = 0;\nfunction draw() {\n textOutput();\n background(148, 196, 0);\n fill(255, 0, 0);\n ellipse(x, 20, 20, 20);\n fill(0, 0, 255);\n rect(50, 50, 50, 50);\n ellipse(20, 20, 20, 20);\n x += 0.1;\n}\n
\ngridOutput()
lays out the\ncontent of the canvas in the form of a grid (html table) based\non the spatial location of each shape. A brief\ndescription of the canvas is available before the table output.\nThis description includes: color of the background, size of the canvas,\nnumber of objects, and object types (example: \"lavender blue canvas is\n200 by 200 and contains 4 objects - 3 ellipses 1 rectangle\"). The grid\ndescribes the content spatially, each element is placed on a cell of the\ntable depending on its position. Within each cell an element the color\nand type of shape of that element are available (example: \"orange ellipse\").\nThese descriptions can be selected individually to get more details.\nA list of elements where shape, color, location, and area are described\n(example: \"orange ellipse location=top left area=1%\") is also available.
gridOutput()
and gridOutput(FALLBACK)
\nmake the output available in \na sub DOM inside the canvas element which is accessible to screen readers.\ngridOutput(LABEL)
creates an\nadditional div with the output adjacent to the canvas, this is useful\nfor non-screen reader users that might want to display the output outside\nof the canvas' sub DOM as they code. However, using LABEL will create\nunnecessary redundancy for screen reader users. We recommend using LABEL\nonly as part of the development process of a sketch and removing it before\npublishing or sharing with screen reader users.
either FALLBACK or LABEL
\n", "type": "Constant", "optional": true } ], "example": [ "\n\ngridOutput();\nbackground(148, 196, 0);\nfill(255, 0, 0);\nellipse(20, 20, 20, 20);\nfill(0, 0, 255);\nrect(50, 50, 50, 50);\n
\n\nlet x = 0;\nfunction draw() {\n gridOutput();\n background(148, 196, 0);\n fill(255, 0, 0);\n ellipse(x, 20, 20, 20);\n fill(0, 0, 255);\n rect(50, 50, 50, 50);\n ellipse(20, 20, 20, 20);\n x += 0.1;\n}\n
\nConversions adapted from http://www.easyrgb.com/en/math.php.
\nIn these functions, hue is always in the range [0, 1], just like all other\ncomponents are in the range [0, 1]. 'Brightness' and 'value' are used\ninterchangeably.
\n", "class": "p5", "module": "Color", "submodule": "Color Conversion" }, { "file": "src/color/color_conversion.js", "line": 19, "description": "Convert an HSBA array to HSLA.
\n", "class": "p5", "module": "Color", "submodule": "Color Conversion" }, { "file": "src/color/color_conversion.js", "line": 45, "description": "Convert an HSBA array to RGBA.
\n", "class": "p5", "module": "Color", "submodule": "Color Conversion" }, { "file": "src/color/color_conversion.js", "line": 100, "description": "Convert an HSLA array to HSBA.
\n", "class": "p5", "module": "Color", "submodule": "Color Conversion" }, { "file": "src/color/color_conversion.js", "line": 123, "description": "Convert an HSLA array to RGBA.
\nWe need to change basis from HSLA to something that can be more easily be\nprojected onto RGBA. We will choose hue and brightness as our first two\ncomponents, and pick a convenient third one ('zest') so that we don't need\nto calculate formal HSBA saturation.
\n", "class": "p5", "module": "Color", "submodule": "Color Conversion" }, { "file": "src/color/color_conversion.js", "line": 187, "description": "Convert an RGBA array to HSBA.
\n", "class": "p5", "module": "Color", "submodule": "Color Conversion" }, { "file": "src/color/color_conversion.js", "line": 226, "description": "Convert an RGBA array to HSLA.
\n", "class": "p5", "module": "Color", "submodule": "Color Conversion" }, { "file": "src/color/creating_reading.js", "line": 16, "description": "Extracts the alpha value from a color or pixel array.
\n", "itemtype": "method", "name": "alpha", "params": [ { "name": "color", "description": "p5.Color object, color components,\n or CSS color
\n", "type": "p5.Color|Number[]|String" } ], "return": { "description": "the alpha value", "type": "Number" }, "example": [ "\n\nnoStroke();\nlet c = color(0, 126, 255, 102);\nfill(c);\nrect(15, 15, 35, 70);\nlet value = alpha(c); // Sets 'value' to 102\nfill(value);\nrect(50, 15, 35, 70);\ndescribe('Left half of canvas light blue and right half light charcoal grey.');\n
\nExtracts the blue value from a color or pixel array.
\n", "itemtype": "method", "name": "blue", "params": [ { "name": "color", "description": "p5.Color object, color components,\n or CSS color
\n", "type": "p5.Color|Number[]|String" } ], "return": { "description": "the blue value", "type": "Number" }, "example": [ "\n\nlet c = color(175, 100, 220);\nfill(c);\nrect(15, 20, 35, 60); // Draw left rectangle\nlet blueValue = blue(c);\nfill(0, 0, blueValue);\nrect(50, 20, 35, 60); // Draw right rectangle\ndescribe('Left half of canvas light purple and right half a royal blue.');\n
\nExtracts the HSB brightness value from a color or pixel array.
\n", "itemtype": "method", "name": "brightness", "params": [ { "name": "color", "description": "p5.Color object, color components,\n or CSS color
\n", "type": "p5.Color|Number[]|String" } ], "return": { "description": "the brightness value", "type": "Number" }, "example": [ "\n\nnoStroke();\ncolorMode(HSB, 255);\nlet c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nlet value = brightness(c); // Sets 'value' to 255\nfill(value);\nrect(50, 20, 35, 60);\ndescribe(`Left half of canvas salmon pink and the right half with its\nbrightness colored white.`);\n
\n\nnoStroke();\ncolorMode(HSB, 255);\nlet c = color('hsb(60, 100%, 50%)');\nfill(c);\nrect(15, 20, 35, 60);\nlet value = brightness(c); // A 'value' of 50% is 127.5\nfill(value);\nrect(50, 20, 35, 60);\ndescribe(`Left half of canvas olive colored and the right half with its\nbrightness color gray.`);\n
\nCreates colors for storing in variables of the color datatype. The\nparameters are interpreted as RGB or HSB values depending on the\ncurrent colorMode(). The default mode is RGB values from 0 to 255\nand, therefore, the function call color(255, 204, 0) will return a\nbright yellow color.
\nNote that if only one value is provided to color(), it will be interpreted\nas a grayscale value. Add a second value, and it will be used for alpha\ntransparency. When three values are specified, they are interpreted as\neither RGB or HSB values. Adding a fourth value applies alpha\ntransparency.
\nIf a single string argument is provided, RGB, RGBA and Hex CSS color\nstrings and all named color strings are supported. In this case, an alpha\nnumber value as a second argument is not supported, the RGBA form should be\nused.
\n", "itemtype": "method", "name": "color", "return": { "description": "resulting color", "type": "p5.Color" }, "example": [ "\n\nlet c = color(255, 204, 0);\nfill(c);\nnoStroke();\nrect(30, 20, 55, 55);\ndescribe(`Yellow rect in middle right of canvas,\nwith 55 pixel width and height.`);\n
\n\nlet c = color(255, 204, 0);\nfill(c);\nnoStroke();\nellipse(25, 25, 80, 80); // Draw left circle\n// Using only one value generates a grayscale value.\nc = color(65);\nfill(c);\nellipse(75, 75, 80, 80);\ndescribe(`Yellow ellipse in top left of canvas, black ellipse in bottom\nright, both 80×80.`);\n
\n\n// You can use named SVG & CSS colors\nlet c = color('magenta');\nfill(c);\nnoStroke();\nrect(20, 20, 60, 60);\ndescribe('Bright fuchsia rect in middle of canvas, 60 pixel width and height.');\n
\n\n// Example of hex color codes\nnoStroke();\nlet c = color('#0f0');\nfill(c);\nrect(0, 10, 45, 80);\nc = color('#00ff00');\nfill(c);\nrect(55, 10, 45, 80);\ndescribe('Two bright green rects on opposite sides of the canvas, both 45×80.');\n
\n\n// RGB and RGBA color strings are also supported\n// these all set to the same color (solid blue)\nlet c;\nnoStroke();\nc = color('rgb(0,0,255)');\nfill(c);\nrect(10, 10, 35, 35); // Draw rectangle\nc = color('rgb(0%, 0%, 100%)');\nfill(c);\nrect(55, 10, 35, 35); // Draw rectangle\nc = color('rgba(0, 0, 255, 1)');\nfill(c);\nrect(10, 55, 35, 35); // Draw rectangle\nc = color('rgba(0%, 0%, 100%, 1)');\nfill(c);\nrect(55, 55, 35, 35); // Draw rectangle\ndescribe('Four blue rects in each corner of the canvas, each are 35×35.');\n
\n\n// HSL color can also be specified by value\nlet c = color('hsl(160, 100%, 50%)');\nnoStroke();\nfill(c);\nrect(0, 10, 45, 80); // Draw rectangle\nc = color('hsla(160, 100%, 50%, 0.5)');\nfill(c);\nrect(55, 10, 45, 80); // Draw rectangle\ndescribe(`Bright sea green rect on left and darker rect on right of canvas,\nboth 45×80.`);\n
\n\n// HSB color can also be specified\nlet c = color('hsb(160, 100%, 50%)');\nnoStroke();\nfill(c);\nrect(0, 10, 45, 80); // Draw rectangle\nc = color('hsba(160, 100%, 50%, 0.5)');\nfill(c);\nrect(55, 10, 45, 80); // Draw rectangle\ndescribe(`Dark green rect on left and lighter green rect on right of canvas,\nboth 45×80.`);\n
\n\nnoStroke();\nlet c = color(50, 55, 100);\nfill(c);\nrect(0, 10, 45, 80); // Draw left rect\ncolorMode(HSB, 100);\nc = color(50, 55, 100);\nfill(c);\nrect(55, 10, 45, 80);\ndescribe(`Dark blue rect on left and light teal rect on right of canvas,\nboth 45×80.`);\n
\nnumber specifying value between white and black.
\n", "type": "Number" }, { "name": "alpha", "description": "alpha value relative to current color range\n (default is 0-255)
\n", "type": "Number", "optional": true } ], "return": { "description": "resulting color", "type": "p5.Color" } }, { "line": 257, "params": [ { "name": "v1", "description": "red or hue value relative to\n the current color range
\n", "type": "Number" }, { "name": "v2", "description": "green or saturation value\n relative to the current color range
\n", "type": "Number" }, { "name": "v3", "description": "blue or brightness value\n relative to the current color range
\n", "type": "Number" }, { "name": "alpha", "description": "", "type": "Number", "optional": true } ], "return": { "description": "", "type": "p5.Color" } }, { "line": 269, "params": [ { "name": "value", "description": "a color string
\n", "type": "String" } ], "return": { "description": "", "type": "p5.Color" } }, { "line": 275, "params": [ { "name": "values", "description": "an array containing the red,green,blue &\n and alpha components of the color
\n", "type": "Number[]" } ], "return": { "description": "", "type": "p5.Color" } }, { "line": 282, "params": [ { "name": "color", "description": "", "type": "p5.Color" } ], "return": { "description": "", "type": "p5.Color" } } ] }, { "file": "src/color/creating_reading.js", "line": 297, "description": "Extracts the green value from a color or pixel array.
\n", "itemtype": "method", "name": "green", "params": [ { "name": "color", "description": "p5.Color object, color components,\n or CSS color
\n", "type": "p5.Color|Number[]|String" } ], "return": { "description": "the green value", "type": "Number" }, "example": [ "\n\nlet c = color(20, 75, 200); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nlet greenValue = green(c); // Get green in 'c'\nprint(greenValue); // Print \"75.0\"\nfill(0, greenValue, 0); // Use 'greenValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\ndescribe(`blue rect on left and green on right, both with black outlines\n& 35×60.`);\n
\nExtracts the hue value from a color or pixel array.
\nHue exists in both HSB and HSL. This function will return the\nHSB-normalized hue when supplied with an HSB color object (or when supplied\nwith a pixel array while the color mode is HSB), but will default to the\nHSL-normalized hue otherwise. (The values will only be different if the\nmaximum hue setting for each system is different.)
\n", "itemtype": "method", "name": "hue", "params": [ { "name": "color", "description": "p5.Color object, color components,\n or CSS color
\n", "type": "p5.Color|Number[]|String" } ], "return": { "description": "the hue", "type": "Number" }, "example": [ "\n\nnoStroke();\ncolorMode(HSB, 255);\nlet c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nlet value = hue(c); // Sets 'value' to \"0\"\nfill(value);\nrect(50, 20, 35, 60);\ndescribe('salmon pink rect on left and black on right, both 35×60.');\n
\nBlends two colors to find a third color somewhere between them. The amt\nparameter is the amount to interpolate between the two values where 0.0\nis equal to the first color, 0.1 is very near the first color, 0.5 is halfway\nin between, etc. An amount below 0 will be treated as 0. Likewise, amounts\nabove 1 will be capped at 1. This is different from the behavior of lerp(),\nbut necessary because otherwise numbers outside the range will produce\nstrange and unexpected colors.
\nThe way that colors are interpolated depends on the current color mode.
\n", "itemtype": "method", "name": "lerpColor", "params": [ { "name": "c1", "description": "interpolate from this color
\n", "type": "p5.Color" }, { "name": "c2", "description": "interpolate to this color
\n", "type": "p5.Color" }, { "name": "amt", "description": "number between 0 and 1
\n", "type": "Number" } ], "return": { "description": "interpolated color", "type": "p5.Color" }, "example": [ "\n\ncolorMode(RGB);\nstroke(255);\nbackground(51);\nlet from = color(218, 165, 32);\nlet to = color(72, 61, 139);\ncolorMode(RGB); // Try changing to HSB.\nlet interA = lerpColor(from, to, 0.33);\nlet interB = lerpColor(from, to, 0.66);\nfill(from);\nrect(10, 20, 20, 60);\nfill(interA);\nrect(30, 20, 20, 60);\nfill(interB);\nrect(50, 20, 20, 60);\nfill(to);\nrect(70, 20, 20, 60);\ndescribe(`4 rects one tan, brown, brownish purple, purple, with white\noutlines & 20×60`);\n
\nExtracts the HSL lightness value from a color or pixel array.
\n", "itemtype": "method", "name": "lightness", "params": [ { "name": "color", "description": "p5.Color object, color components,\n or CSS color
\n", "type": "p5.Color|Number[]|String" } ], "return": { "description": "the lightness", "type": "Number" }, "example": [ "\n\nnoStroke();\ncolorMode(HSL);\nlet c = color(156, 100, 50, 1);\nfill(c);\nrect(15, 20, 35, 60);\nlet value = lightness(c); // Sets 'value' to 50\nfill(value);\nrect(50, 20, 35, 60);\ndescribe(`light pastel green rect on left and dark grey rect on right,\nboth 35×60.`);\n
\nExtracts the red value from a color or pixel array.
\n", "itemtype": "method", "name": "red", "params": [ { "name": "color", "description": "p5.Color object, color components,\n or CSS color
\n", "type": "p5.Color|Number[]|String" } ], "return": { "description": "the red value", "type": "Number" }, "example": [ "\n\nlet c = color(255, 204, 0); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nlet redValue = red(c); // Get red in 'c'\nprint(redValue); // Print \"255.0\"\nfill(redValue, 0, 0); // Use 'redValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\ndescribe(`yellow rect on left and red rect on right, both with black\noutlines and 35×60.`);\n
\n\ncolorMode(RGB, 255); // Sets the range for red, green, and blue to 255\nlet c = color(127, 255, 0);\ncolorMode(RGB, 1); // Sets the range for red, green, and blue to 1\nlet myColor = red(c);\nprint(myColor); // 0.4980392156862745\ndescribe('grey canvas');\n
\nExtracts the saturation value from a color or pixel array.
\nSaturation is scaled differently in HSB and HSL. This function will return\nthe HSB saturation when supplied with an HSB color object (or when supplied\nwith a pixel array while the color mode is HSB), but will default to the\nHSL saturation otherwise.
\n", "itemtype": "method", "name": "saturation", "params": [ { "name": "color", "description": "p5.Color object, color components,\n or CSS color
\n", "type": "p5.Color|Number[]|String" } ], "return": { "description": "the saturation value", "type": "Number" }, "example": [ "\n\nnoStroke();\ncolorMode(HSB, 255);\nlet c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nlet value = saturation(c); // Sets 'value' to 126\nfill(value);\nrect(50, 20, 35, 60);\ndescribe('deep pink rect on left and grey rect on right, both 35×60.');\n
\nThis method returns the color formatted as a string. This can be useful\nfor debugging, or for using p5.js with other libraries.
\n", "itemtype": "method", "name": "toString", "params": [ { "name": "format", "description": "How the color string will be formatted.\nLeaving this empty formats the string as rgba(r, g, b, a).\n'#rgb' '#rgba' '#rrggbb' and '#rrggbbaa' format as hexadecimal color codes.\n'rgb' 'hsb' and 'hsl' return the color formatted in the specified color mode.\n'rgba' 'hsba' and 'hsla' are the same as above but with alpha channels.\n'rgb%' 'hsb%' 'hsl%' 'rgba%' 'hsba%' and 'hsla%' format as percentages.
\n", "type": "String", "optional": true } ], "return": { "description": "the formatted string", "type": "String" }, "example": [ "\n\ncreateCanvas(200, 100);\nlet myColor;\nstroke(255);\nmyColor = color(100, 100, 250);\nfill(myColor);\nrotate(HALF_PI);\ntext(myColor.toString(), 0, -5);\ntext(myColor.toString('#rrggbb'), 0, -30);\ntext(myColor.toString('rgba%'), 0, -55);\ndescribe('A canvas with 3 text representation of their color.');\n
\n\nlet myColor = color(100, 130, 250);\ntext(myColor.toString('#rrggbb'), 25, 25);\n
\nThe setRed method sets the red component of a color.\nThe range depends on your color mode, in the default RGB mode it's between 0 and 255.
\n", "itemtype": "method", "name": "setRed", "params": [ { "name": "red", "description": "the new red value
\n", "type": "Number" } ], "example": [ "\n\nlet backgroundColor;\n\nfunction setup() {\n backgroundColor = color(100, 50, 150);\n}\n\nfunction draw() {\n backgroundColor.setRed(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n describe('canvas with gradually changing background color');\n}\n
\nThe setGreen method sets the green component of a color.\nThe range depends on your color mode, in the default RGB mode it's between 0 and 255.
\n", "itemtype": "method", "name": "setGreen", "params": [ { "name": "green", "description": "the new green value
\n", "type": "Number" } ], "example": [ "\n\nlet backgroundColor = color(100, 50, 150);\nfunction draw() {\n backgroundColor.setGreen(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n describe('canvas with gradually changing background color');\n}\n
\nThe setBlue method sets the blue component of a color.\nThe range depends on your color mode, in the default RGB mode it's between 0 and 255.
\n", "itemtype": "method", "name": "setBlue", "params": [ { "name": "blue", "description": "the new blue value
\n", "type": "Number" } ], "example": [ "\n\nlet backgroundColor = color(100, 50, 150);\nfunction draw() {\n backgroundColor.setBlue(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n describe('canvas with gradually changing background color');\n}\n
\nThe setAlpha method sets the transparency (alpha) value of a color.\nThe range depends on your color mode, in the default RGB mode it's between 0 and 255.
\n", "itemtype": "method", "name": "setAlpha", "params": [ { "name": "alpha", "description": "the new alpha value
\n", "type": "Number" } ], "example": [ "\n\nfunction draw() {\n clear();\n background(200);\n squareColor = color(100, 50, 100);\n squareColor.setAlpha(128 + 128 * sin(millis() / 1000));\n fill(squareColor);\n rect(13, 13, width - 26, height - 26);\n describe('a square with gradually changing opacity on a gray background');\n}\n
\nHue is the same in HSB and HSL, but the maximum value may be different.\nThis function will return the HSB-normalized saturation when supplied with\nan HSB color object, but will default to the HSL-normalized saturation\notherwise.
\n", "class": "p5.Color", "module": "Color", "submodule": "Creating & Reading" }, { "file": "src/color/p5.Color.js", "line": 431, "description": "Saturation is scaled differently in HSB and HSL. This function will return\nthe HSB saturation when supplied with an HSB color object, but will default\nto the HSL saturation otherwise.
\n", "class": "p5.Color", "module": "Color", "submodule": "Creating & Reading" }, { "file": "src/color/p5.Color.js", "line": 450, "description": "CSS named colors.
\n", "class": "p5.Color", "module": "Color", "submodule": "Creating & Reading" }, { "file": "src/color/p5.Color.js", "line": 604, "description": "These regular expressions are used to build up the patterns for matching\nviable CSS color strings: fragmenting the regexes in this way increases the\nlegibility and comprehensibility of the code.
\nNote that RGB values of .9 are not parsed by IE, but are supported here for\ncolor string consistency.
\n", "class": "p5.Color", "module": "Color", "submodule": "Creating & Reading" }, { "file": "src/color/p5.Color.js", "line": 617, "description": "Full color string patterns. The capture groups are necessary.
\n", "class": "p5.Color", "module": "Color", "submodule": "Creating & Reading" }, { "file": "src/color/p5.Color.js", "line": 964, "description": "For HSB and HSL, interpret the gray level as a brightness/lightness\nvalue (they are equivalent when chroma is zero). For RGB, normalize the\ngray level according to the blue maximum.
\n", "class": "p5.Color", "module": "Color", "submodule": "Creating & Reading" }, { "file": "src/color/setting.js", "line": 13, "description": "The background() function sets the color used\nfor the background of the p5.js canvas. The default background is transparent.\nThis function is typically used within draw() to clear\nthe display window at the beginning of each frame, but it can be used inside\nsetup() to set the background on the first frame of\nanimation or if the background need only be set once.
\nThe color is either specified in terms of the RGB, HSB, or HSL color depending\non the current colorMode. (The default color space\nis RGB, with each value in the range from 0 to 255). The alpha range by default\nis also 0 to 255.
If a single string argument is provided, RGB, RGBA and Hex CSS color strings\nand all named color strings are supported. In this case, an alpha number\nvalue as a second argument is not supported, the RGBA form should be used.
\nA p5.Color object can also be provided to set the background color.
\nA p5.Image can also be provided to set the background image.
\n", "itemtype": "method", "name": "background", "chainable": 1, "example": [ "\n\n// Grayscale integer value\nbackground(51);\ndescribe('canvas with darkest charcoal grey background');\n
\n\n// R, G & B integer values\nbackground(255, 204, 0);\ndescribe('canvas with yellow background');\n
\n\n// H, S & B integer values\ncolorMode(HSB);\nbackground(255, 204, 100);\ndescribe('canvas with royal blue background');\n
\n\n// Named SVG/CSS color string\nbackground('red');\ndescribe('canvas with red background');\n
\n\n// three-digit hexadecimal RGB notation\nbackground('#fae');\ndescribe('canvas with pink background');\n
\n\n// six-digit hexadecimal RGB notation\nbackground('#222222');\ndescribe('canvas with black background');\n
\n\n// integer RGB notation\nbackground('rgb(0,255,0)');\ndescribe('canvas with bright green background');\n
\n\n// integer RGBA notation\nbackground('rgba(0,255,0, 0.25)');\ndescribe('canvas with soft green background');\n
\n\n// percentage RGB notation\nbackground('rgb(100%,0%,10%)');\ndescribe('canvas with red background');\n
\n\n// percentage RGBA notation\nbackground('rgba(100%,0%,100%,0.5)');\ndescribe('canvas with light purple background');\n
\n\n// p5 Color object\nbackground(color(0, 0, 255));\ndescribe('canvas with blue background');\n
\nany value created by the color() function
\n", "type": "p5.Color" } ], "chainable": 1 }, { "line": 130, "params": [ { "name": "colorstring", "description": "color string, possible formats include: integer\n rgb() or rgba(), percentage rgb() or rgba(),\n 3-digit hex, 6-digit hex
\n", "type": "String" }, { "name": "a", "description": "opacity of the background relative to current\n color range (default is 0-255)
\n", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 140, "params": [ { "name": "gray", "description": "specifies a value between white and black
\n", "type": "Number" }, { "name": "a", "description": "", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 147, "params": [ { "name": "v1", "description": "red or hue value (depending on the current color\n mode)
\n", "type": "Number" }, { "name": "v2", "description": "green or saturation value (depending on the current\n color mode)
\n", "type": "Number" }, { "name": "v3", "description": "blue or brightness value (depending on the current\n color mode)
\n", "type": "Number" }, { "name": "a", "description": "", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 159, "params": [ { "name": "values", "description": "an array containing the red, green, blue\n and alpha components of the color
\n", "type": "Number[]" } ], "chainable": 1 }, { "line": 166, "params": [ { "name": "image", "description": "image created with loadImage() or createImage(),\n to set as background\n (must be same size as the sketch window)
\n", "type": "p5.Image" }, { "name": "a", "description": "", "type": "Number", "optional": true } ], "chainable": 1 } ] }, { "file": "src/color/setting.js", "line": 179, "description": "Clears the pixels within a buffer. This function only clears the canvas.\nIt will not clear objects created by createX() methods such as\ncreateVideo() or createDiv().\nUnlike the main graphics context, pixels in additional graphics areas created\nwith createGraphics() can be entirely\nor partially transparent. This function clears everything to make all of\nthe pixels 100% transparent.
\nNote: In WebGL mode, this function can be passed normalized RGBA color values in\norder to clear the screen to a specific color. In addition to color, it will also\nclear the depth buffer. If you are not using the webGL renderer\nthese color values will have no effect.
\n", "itemtype": "method", "name": "clear", "chainable": 1, "example": [ "\n\n// Clear the screen on mouse press.\nfunction draw() {\n ellipse(mouseX, mouseY, 20, 20);\n describe(`small white ellipses are continually drawn at mouse’s x and y\n coordinates.`);\n}\nfunction mousePressed() {\n clear();\n background(128);\n describe(\n 'canvas is cleared, small white ellipse is drawn at mouse X and mouse Y'\n );\n}\n
\nnormalized red val.
\n", "type": "Number" }, { "name": "g", "description": "normalized green val.
\n", "type": "Number" }, { "name": "b", "description": "normalized blue val.
\n", "type": "Number" }, { "name": "a", "description": "normalized alpha val.
\n", "type": "Number" } ], "class": "p5", "module": "Color", "submodule": "Setting" }, { "file": "src/color/setting.js", "line": 229, "description": "colorMode() changes the way p5.js interprets\ncolor data. By default, the parameters for fill(),\nstroke(), background(),\nand color() are defined by values between 0 and 255\nusing the RGB color model. This is equivalent to setting colorMode(RGB, 255).\nSetting colorMode(HSB) lets you use the HSB system instead. By default, this\nis colorMode(HSB, 360, 100, 100, 1). You can also use HSL.
\nNote: existing color objects remember the mode that they were created in,\nso you can change modes as you like without affecting their appearance.
\n", "itemtype": "method", "name": "colorMode", "chainable": 1, "example": [ "\n\nnoStroke();\ncolorMode(RGB, 100);\nfor (let i = 0; i < 100; i++) {\n for (let j = 0; j < 100; j++) {\n stroke(i, j, 0);\n point(i, j);\n }\n}\ndescribe(\n 'Green to red gradient from bottom left to top right with shading from top left'\n);\n
\n\nnoStroke();\ncolorMode(HSB, 100);\nfor (let i = 0; i < 100; i++) {\n for (let j = 0; j < 100; j++) {\n stroke(i, j, 100);\n point(i, j);\n }\n}\ndescribe(`Rainbow gradient from left to right.\nBrightness increasing to white at top.`);\n
\n\ncolorMode(RGB, 255);\nlet c = color(127, 255, 0);\ncolorMode(RGB, 1);\nlet myColor = c._getRed();\ntext(myColor, 10, 10, 80, 80);\ndescribe('value of color red 0.4980... written on canvas');\n
\n\nnoFill();\ncolorMode(RGB, 255, 255, 255, 1);\nbackground(255);\nstrokeWeight(4);\nstroke(255, 0, 10, 0.3);\nellipse(40, 40, 50, 50);\nellipse(50, 50, 40, 40);\ndescribe('two translucent pink ellipse outlines at middle left and at center');\n
\neither RGB, HSB or HSL, corresponding to\n Red/Green/Blue and Hue/Saturation/Brightness\n (or Lightness)
\n", "type": "Constant" }, { "name": "max", "description": "range for all values
\n", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 306, "params": [ { "name": "mode", "description": "", "type": "Constant" }, { "name": "max1", "description": "range for the red or hue depending on the\n current color mode
\n", "type": "Number" }, { "name": "max2", "description": "range for the green or saturation depending\n on the current color mode
\n", "type": "Number" }, { "name": "max3", "description": "range for the blue or brightness/lightness\n depending on the current color mode
\n", "type": "Number" }, { "name": "maxA", "description": "range for the alpha
\n", "type": "Number", "optional": true } ], "chainable": 1 } ] }, { "file": "src/color/setting.js", "line": 350, "description": "Sets the color used to fill shapes. For example, if you run fill(204, 102, 0),\nall shapes drawn after the fill command will be filled with the color orange.\nThis color is either specified in terms of the RGB or HSB color depending on\nthe current colorMode(). (The default color space\nis RGB, with each value in the range from 0 to 255). The alpha range by default\nis also 0 to 255.
\nIf a single string argument is provided, RGB, RGBA and Hex CSS color strings\nand all named color strings are supported. In this case, an alpha number\nvalue as a second argument is not supported, the RGBA form should be used.
\nA p5.Color object can also be provided to set the fill color.
\n", "itemtype": "method", "name": "fill", "chainable": 1, "example": [ "\n\n// Grayscale integer value\nfill(51);\nrect(20, 20, 60, 60);\ndescribe('dark charcoal grey rect with black outline in center of canvas');\n
\n\n// R, G & B integer values\nfill(255, 204, 0);\nrect(20, 20, 60, 60);\ndescribe('yellow rect with black outline in center of canvas');\n
\n\n// H, S & B integer values\ncolorMode(HSB);\nfill(255, 204, 100);\nrect(20, 20, 60, 60);\ndescribe('royal blue rect with black outline in center of canvas');\n
\n\n// Named SVG/CSS color string\nfill('red');\nrect(20, 20, 60, 60);\ndescribe('red rect with black outline in center of canvas');\n
\n\n// three-digit hexadecimal RGB notation\nfill('#fae');\nrect(20, 20, 60, 60);\ndescribe('pink rect with black outline in center of canvas');\n
\n\n// six-digit hexadecimal RGB notation\nfill('#222222');\nrect(20, 20, 60, 60);\ndescribe('black rect with black outline in center of canvas');\n
\n\n// integer RGB notation\nfill('rgb(0,255,0)');\nrect(20, 20, 60, 60);\ndescribe('bright green rect with black outline in center of canvas');\n
\n\n// integer RGBA notation\nfill('rgba(0,255,0, 0.25)');\nrect(20, 20, 60, 60);\ndescribe('soft green rect with black outline in center of canvas');\n
\n\n// percentage RGB notation\nfill('rgb(100%,0%,10%)');\nrect(20, 20, 60, 60);\ndescribe('red rect with black outline in center of canvas');\n
\n\n// percentage RGBA notation\nfill('rgba(100%,0%,100%,0.5)');\nrect(20, 20, 60, 60);\ndescribe('dark fuchsia rect with black outline in center of canvas');\n
\n\n// p5 Color object\nfill(color(0, 0, 255));\nrect(20, 20, 60, 60);\ndescribe('blue rect with black outline in center of canvas');\n
\nred or hue value relative to\n the current color range
\n", "type": "Number" }, { "name": "v2", "description": "green or saturation value\n relative to the current color range
\n", "type": "Number" }, { "name": "v3", "description": "blue or brightness value\n relative to the current color range
\n", "type": "Number" }, { "name": "alpha", "description": "", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 475, "params": [ { "name": "value", "description": "a color string
\n", "type": "String" } ], "chainable": 1 }, { "line": 481, "params": [ { "name": "gray", "description": "a gray value
\n", "type": "Number" }, { "name": "alpha", "description": "", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 488, "params": [ { "name": "values", "description": "an array containing the red,green,blue &\n and alpha components of the color
\n", "type": "Number[]" } ], "chainable": 1 }, { "line": 495, "params": [ { "name": "color", "description": "the fill color
\n", "type": "p5.Color" } ], "chainable": 1 } ] }, { "file": "src/color/setting.js", "line": 507, "description": "Disables filling geometry. If both noStroke() and noFill() are called,\nnothing will be drawn to the screen.
\n", "itemtype": "method", "name": "noFill", "chainable": 1, "example": [ "\n\nrect(15, 10, 55, 55);\nnoFill();\nrect(20, 20, 60, 60);\ndescribe(`White rect at top middle and noFill rect center,\nboth with black outlines.`);\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(0);\n noFill();\n stroke(100, 100, 240);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(45, 45, 45);\n describe('black canvas with purple cube wireframe spinning');\n}\n
\nDisables drawing the stroke (outline). If both noStroke() and noFill()\nare called, nothing will be drawn to the screen.
\n", "itemtype": "method", "name": "noStroke", "chainable": 1, "example": [ "\n\nnoStroke();\nrect(20, 20, 60, 60);\ndescribe('White rect at center; no outline.');\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(0);\n noStroke();\n fill(240, 150, 150);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(45, 45, 45);\n describe('black canvas with pink cube spinning');\n}\n
\nSets the color used to draw lines and borders around shapes. This color\nis either specified in terms of the RGB or HSB color depending on the\ncurrent colorMode() (the default color space\nis RGB, with each value in the range from 0 to 255). The alpha range by\ndefault is also 0 to 255.
\nIf a single string argument is provided, RGB, RGBA and Hex CSS color\nstrings and all named color strings are supported. In this case, an alpha\nnumber value as a second argument is not supported, the RGBA form should be\nused.
\nA p5.Color object can also be provided to set the stroke color.
\n", "itemtype": "method", "name": "stroke", "chainable": 1, "example": [ "\n\n// Grayscale integer value\nstrokeWeight(4);\nstroke(51);\nrect(20, 20, 60, 60);\ndescribe('White rect at center with dark charcoal grey outline.');\n
\n\n// R, G & B integer values\nstroke(255, 204, 0);\nstrokeWeight(4);\nrect(20, 20, 60, 60);\ndescribe('White rect at center with yellow outline.');\n
\n\n// H, S & B integer values\ncolorMode(HSB);\nstrokeWeight(4);\nstroke(255, 204, 100);\nrect(20, 20, 60, 60);\ndescribe('White rect at center with royal blue outline.');\n
\n\n// Named SVG/CSS color string\nstroke('red');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\ndescribe('White rect at center with red outline.');\n
\n\n// three-digit hexadecimal RGB notation\nstroke('#fae');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\ndescribe('White rect at center with pink outline.');\n
\n\n// six-digit hexadecimal RGB notation\nstroke('#222222');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\ndescribe('White rect at center with black outline.');\n
\n\n// integer RGB notation\nstroke('rgb(0,255,0)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\ndescribe('White rect at center with bright green outline.');\n
\n\n// integer RGBA notation\nstroke('rgba(0,255,0,0.25)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\ndescribe('White rect at center with soft green outline.');\n
\n\n// percentage RGB notation\nstroke('rgb(100%,0%,10%)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\ndescribe('White rect at center with red outline.');\n
\n\n// percentage RGBA notation\nstroke('rgba(100%,0%,100%,0.5)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\ndescribe('White rect at center with dark fuchsia outline.');\n
\n\n// p5 Color object\nstroke(color(0, 0, 255));\nstrokeWeight(4);\nrect(20, 20, 60, 60);\ndescribe('White rect at center with blue outline.');\n
\nred or hue value relative to\n the current color range
\n", "type": "Number" }, { "name": "v2", "description": "green or saturation value\n relative to the current color range
\n", "type": "Number" }, { "name": "v3", "description": "blue or brightness value\n relative to the current color range
\n", "type": "Number" }, { "name": "alpha", "description": "", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 722, "params": [ { "name": "value", "description": "a color string
\n", "type": "String" } ], "chainable": 1 }, { "line": 728, "params": [ { "name": "gray", "description": "a gray value
\n", "type": "Number" }, { "name": "alpha", "description": "", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 735, "params": [ { "name": "values", "description": "an array containing the red,green,blue &\n and alpha components of the color
\n", "type": "Number[]" } ], "chainable": 1 }, { "line": 742, "params": [ { "name": "color", "description": "the stroke color
\n", "type": "p5.Color" } ], "chainable": 1 } ] }, { "file": "src/color/setting.js", "line": 755, "description": "All drawing that follows erase() will subtract from\nthe canvas.Erased areas will reveal the web page underneath the canvas.Erasing\ncan be canceled with noErase().
\nDrawing done with image() and \nbackground() in between erase() and\nnoErase() will not erase the canvas but works as usual.
\n", "itemtype": "method", "name": "erase", "params": [ { "name": "strengthFill", "description": "A number (0-255) for the strength of erasing for a shape's fill.\n This will default to 255 when no argument is given, which\n is full strength.
\n", "type": "Number", "optional": true }, { "name": "strengthStroke", "description": "A number (0-255) for the strength of erasing for a shape's stroke.\n This will default to 255 when no argument is given, which\n is full strength.
\n", "type": "Number", "optional": true } ], "chainable": 1, "example": [ "\n\nbackground(100, 100, 250);\nfill(250, 100, 100);\nrect(20, 20, 60, 60);\nerase();\nellipse(25, 30, 30);\nnoErase();\ndescribe(`60×60 centered pink rect, purple background.\nElliptical area in top-left of rect is erased white.`);\n
\n\nbackground(150, 250, 150);\nfill(100, 100, 250);\nrect(20, 20, 60, 60);\nstrokeWeight(5);\nerase(150, 255);\ntriangle(50, 10, 70, 50, 90, 10);\nnoErase();\ndescribe(`60×60 centered purple rect, mint green background.\nTriangle in top-right is partially erased with fully erased outline.`);\n
\n\nfunction setup() {\n smooth();\n createCanvas(100, 100, WEBGL);\n // Make a <p> element and put it behind the canvas\n let p = createP('I am a dom element');\n p.center();\n p.style('font-size', '20px');\n p.style('text-align', 'center');\n p.style('z-index', '-9999');\n}\n\nfunction draw() {\n background(250, 250, 150);\n fill(15, 195, 185);\n noStroke();\n sphere(30);\n erase();\n rotateY(frameCount * 0.02);\n translate(0, 0, 40);\n torus(15, 5);\n noErase();\n describe(`60×60 centered teal sphere, yellow background.\n Torus rotating around sphere erases to reveal black text underneath.`);\n}\n
\nEnds erasing that was started with erase().\nThe fill(), stroke(), and\nblendMode() settings will return to what they were\nprior to calling erase().
\n", "itemtype": "method", "name": "noErase", "chainable": 1, "example": [ "\n\nbackground(235, 145, 15);\nnoStroke();\nfill(30, 45, 220);\nrect(30, 10, 10, 80);\nerase();\nellipse(50, 50, 60);\nnoErase();\nrect(70, 10, 10, 80);\ndescribe(`Orange background, with two tall blue rectangles.\nA centered ellipse erased the first blue rect but not the second.`);\n
\nPrints out all the colors in the color pallete with white text.\nFor color blindness testing.
\n", "class": "p5", "module": "Color" }, { "file": "src/core/friendly_errors/file_errors.js", "line": 1, "requires": [ "core" ], "class": "p5", "module": "Color" }, { "file": "src/core/friendly_errors/sketch_reader.js", "line": 1, "requires": [ "core" ], "class": "p5", "module": "Color" }, { "file": "src/core/friendly_errors/stacktrace.js", "line": 1, "requires": [ "core" ], "class": "p5", "module": "Color" }, { "file": "src/core/friendly_errors/validate_params.js", "line": 1, "requires": [ "core" ], "class": "p5", "module": "Color" }, { "file": "src/core/shape/2d_primitives.js", "line": 16, "description": "This function does 3 things:
\nBounds the desired start/stop angles for an arc (in radians) so that:
\n0 <= start < TWO_PI ; start <= stop < start + TWO_PI\n
\nThis means that the arc rendering functions don't have to be concerned\nwith what happens if stop is smaller than start, or if the arc 'goes\nround more than once', etc.: they can just start at start and increase\nuntil stop and the correct arc will be drawn.
\nOptionally adjusts the angles within each quadrant to counter the naive\nscaling of the underlying ellipse up from the unit circle. Without\nthis, the angles become arbitrary when width != height: 45 degrees\nmight be drawn at 5 degrees on a 'wide' ellipse, or at 85 degrees on\na 'tall' ellipse.
\nFlags up when start and stop correspond to the same place on the\nunderlying ellipse. This is useful if you want to do something special\nthere (like rendering a whole ellipse instead).
\nDraw an arc to the screen. If called with only x, y, w, h, start and stop,\nthe arc will be drawn and filled as an open pie segment. If a mode parameter\nis provided, the arc will be filled like an open semi-circle (OPEN), a closed\nsemi-circle (CHORD), or as a closed pie segment (PIE). The origin may be changed\nwith the ellipseMode() function.
\nThe arc is always drawn clockwise from wherever start falls to wherever stop\nfalls on the ellipse. Adding or subtracting TWO_PI to either angle does not\nchange where they fall. If both start and stop fall at the same place, a full\nellipse will be drawn. Be aware that the y-axis increases in the downward\ndirection, therefore angles are measured clockwise from the positive\nx-direction (\"3 o'clock\").
\n", "itemtype": "method", "name": "arc", "params": [ { "name": "x", "description": "x-coordinate of the arc's ellipse
\n", "type": "Number" }, { "name": "y", "description": "y-coordinate of the arc's ellipse
\n", "type": "Number" }, { "name": "w", "description": "width of the arc's ellipse by default
\n", "type": "Number" }, { "name": "h", "description": "height of the arc's ellipse by default
\n", "type": "Number" }, { "name": "start", "description": "angle to start the arc, specified in radians
\n", "type": "Number" }, { "name": "stop", "description": "angle to stop the arc, specified in radians
\n", "type": "Number" }, { "name": "mode", "description": "optional parameter to determine the way of drawing\n the arc. either CHORD, PIE or OPEN
\n", "type": "Constant", "optional": true }, { "name": "detail", "description": "optional parameter for WebGL mode only. This is to\n specify the number of vertices that makes up the\n perimeter of the arc. Default value is 25. Won't\n draw a stroke for a detail of more than 50.
\n", "type": "Integer", "optional": true } ], "chainable": 1, "example": [ "\n\narc(50, 55, 50, 50, 0, HALF_PI);\nnoFill();\narc(50, 55, 60, 60, HALF_PI, PI);\narc(50, 55, 70, 70, PI, PI + QUARTER_PI);\narc(50, 55, 80, 80, PI + QUARTER_PI, TWO_PI);\ndescribe(\n 'shattered outline of ellipse with a quarter of a white circle bottom-right'\n);\n
\n\narc(50, 50, 80, 80, 0, PI + QUARTER_PI);\ndescribe('white ellipse with top right quarter missing');\n
\n\narc(50, 50, 80, 80, 0, PI + QUARTER_PI, OPEN);\ndescribe('white ellipse with black outline with top right missing');\n
\n\narc(50, 50, 80, 80, 0, PI + QUARTER_PI, CHORD);\ndescribe('white open arc with black outline with top right missing');\n
\n\narc(50, 50, 80, 80, 0, PI + QUARTER_PI, PIE);\ndescribe(\n 'white ellipse with top right quarter missing with black outline around the shape'\n);\n
\nDraws an ellipse (oval) to the screen. By default, the first two parameters\nset the location of the center of the ellipse, and the third and fourth\nparameters set the shape's width and height. If no height is specified, the\nvalue of width is used for both the width and height. If a negative height or\nwidth is specified, the absolute value is taken.
\nAn ellipse with equal width and height is a circle. The origin may be changed\nwith the ellipseMode() function.
\n", "itemtype": "method", "name": "ellipse", "chainable": 1, "example": [ "\n\nellipse(56, 46, 55, 55);\ndescribe('white ellipse with black outline in middle of a gray canvas');\n
\nx-coordinate of the center of the ellipse.
\n", "type": "Number" }, { "name": "y", "description": "y-coordinate of the center of the ellipse.
\n", "type": "Number" }, { "name": "w", "description": "width of the ellipse.
\n", "type": "Number" }, { "name": "h", "description": "height of the ellipse.
\n", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 261, "params": [ { "name": "x", "description": "", "type": "Number" }, { "name": "y", "description": "", "type": "Number" }, { "name": "w", "description": "", "type": "Number" }, { "name": "h", "description": "", "type": "Number" }, { "name": "detail", "description": "optional parameter for WEBGL mode only. This is to\n specify the number of vertices that makes up the\n perimeter of the ellipse. Default value is 25. Won't\n draw a stroke for a detail of more than 50.
\n", "type": "Integer", "optional": true } ] } ] }, { "file": "src/core/shape/2d_primitives.js", "line": 277, "description": "Draws a circle to the screen. A circle is a simple closed shape. It is the set\nof all points in a plane that are at a given distance from a given point,\nthe center. This function is a special case of the\nellipse() function, where the width and height\nof the ellipse are the same. Height and width of the ellipse correspond to\nthe diameter of the circle. By default, the first two parameters set the\nlocation of the center of the circle, the third sets the diameter of the\ncircle.
\n", "itemtype": "method", "name": "circle", "params": [ { "name": "x", "description": "x-coordinate of the center of the circle.
\n", "type": "Number" }, { "name": "y", "description": "y-coordinate of the center of the circle.
\n", "type": "Number" }, { "name": "d", "description": "diameter of the circle.
\n", "type": "Number" } ], "chainable": 1, "example": [ "\n\n// Draw a circle at location (30, 30) with a diameter of 20.\ncircle(30, 30, 20);\ndescribe('white circle with black outline in mid of gray canvas');\n
\nDraws a line (a direct path between two points) to the screen. If called with\nonly 4 parameters, it will draw a line in 2D with a default width of 1 pixel.\nThis width can be modified by using the \nstrokeWeight() function. A line cannot be filled, therefore the fill() function will not affect the color of a line. So to\ncolor a line, use the stroke() function.
\n", "itemtype": "method", "name": "line", "chainable": 1, "example": [ "\n\nline(30, 20, 85, 75);\ndescribe(\n 'a 78 pixels long line running from mid-top to bottom-right of canvas'\n);\n
\n\nline(30, 20, 85, 20);\nstroke(126);\nline(85, 20, 85, 75);\nstroke(255);\nline(85, 75, 30, 75);\ndescribe(\n '3 lines of various stroke colors. Form top, bottom and right sides of a square'\n);\n
\nthe x-coordinate of the first point
\n", "type": "Number" }, { "name": "y1", "description": "the y-coordinate of the first point
\n", "type": "Number" }, { "name": "x2", "description": "the x-coordinate of the second point
\n", "type": "Number" }, { "name": "y2", "description": "the y-coordinate of the second point
\n", "type": "Number" } ], "chainable": 1 }, { "line": 380, "params": [ { "name": "x1", "description": "", "type": "Number" }, { "name": "y1", "description": "", "type": "Number" }, { "name": "z1", "description": "the z-coordinate of the first point
\n", "type": "Number" }, { "name": "x2", "description": "", "type": "Number" }, { "name": "y2", "description": "", "type": "Number" }, { "name": "z2", "description": "the z-coordinate of the second point
\n", "type": "Number" } ], "chainable": 1 } ] }, { "file": "src/core/shape/2d_primitives.js", "line": 405, "description": "Draws a point, a coordinate in space at the dimension of one pixel.\nThe first parameter is the horizontal value for the point, the second\nparam is the vertical value for the point. The color of the point is\nchanged with the stroke() function. The size of the point\ncan be changed with the strokeWeight() function.
\n", "itemtype": "method", "name": "point", "chainable": 1, "example": [ "\n\npoint(30, 20);\npoint(85, 20);\npoint(85, 75);\npoint(30, 75);\ndescribe('4 points create the corners of a square');\n
\n\npoint(30, 20);\npoint(85, 20);\nstroke('purple'); // Change the color\nstrokeWeight(10); // Make the points 10 pixels in size\npoint(85, 75);\npoint(30, 75);\ndescribe('2 points and 2 large purple points in middle-right of canvas');\n
\n\nlet a = createVector(10, 10);\npoint(a);\nlet b = createVector(10, 20);\npoint(b);\npoint(createVector(20, 10));\npoint(createVector(20, 20));\ndescribe(\n 'four points create vertices of 10x10 pixel square on top-left of canvas'\n);\n
\nthe x-coordinate
\n", "type": "Number" }, { "name": "y", "description": "the y-coordinate
\n", "type": "Number" }, { "name": "z", "description": "the z-coordinate (for WebGL mode)
\n", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 456, "params": [ { "name": "coordinate_vector", "description": "the coordinate vector
\n", "type": "p5.Vector" } ], "chainable": 1 } ] }, { "file": "src/core/shape/2d_primitives.js", "line": 484, "description": "Draws a quad on the canvas. A quad is a quadrilateral, a four-sided polygon. It is\nsimilar to a rectangle, but the angles between its edges are not\nconstrained to ninety degrees. The first pair of parameters (x1,y1)\nsets the first vertex and the subsequent pairs should proceed\nclockwise or counter-clockwise around the defined shape.\nz-arguments only work when quad() is used in WEBGL mode.
\n", "itemtype": "method", "name": "quad", "chainable": 1, "example": [ "\n\nquad(38, 31, 86, 20, 69, 63, 30, 76);\ndescribe('irregular white quadrilateral with black outline');\n
\nthe x-coordinate of the first point
\n", "type": "Number" }, { "name": "y1", "description": "the y-coordinate of the first point
\n", "type": "Number" }, { "name": "x2", "description": "the x-coordinate of the second point
\n", "type": "Number" }, { "name": "y2", "description": "the y-coordinate of the second point
\n", "type": "Number" }, { "name": "x3", "description": "the x-coordinate of the third point
\n", "type": "Number" }, { "name": "y3", "description": "the y-coordinate of the third point
\n", "type": "Number" }, { "name": "x4", "description": "the x-coordinate of the fourth point
\n", "type": "Number" }, { "name": "y4", "description": "the y-coordinate of the fourth point
\n", "type": "Number" }, { "name": "detailX", "description": "number of segments in the x-direction
\n", "type": "Integer", "optional": true }, { "name": "detailY", "description": "number of segments in the y-direction
\n", "type": "Integer", "optional": true } ], "chainable": 1 }, { "line": 513, "params": [ { "name": "x1", "description": "", "type": "Number" }, { "name": "y1", "description": "", "type": "Number" }, { "name": "z1", "description": "the z-coordinate of the first point
\n", "type": "Number" }, { "name": "x2", "description": "", "type": "Number" }, { "name": "y2", "description": "", "type": "Number" }, { "name": "z2", "description": "the z-coordinate of the second point
\n", "type": "Number" }, { "name": "x3", "description": "", "type": "Number" }, { "name": "y3", "description": "", "type": "Number" }, { "name": "z3", "description": "the z-coordinate of the third point
\n", "type": "Number" }, { "name": "x4", "description": "", "type": "Number" }, { "name": "y4", "description": "", "type": "Number" }, { "name": "z4", "description": "the z-coordinate of the fourth point
\n", "type": "Number" }, { "name": "detailX", "description": "", "type": "Integer", "optional": true }, { "name": "detailY", "description": "", "type": "Integer", "optional": true } ], "chainable": 1 } ] }, { "file": "src/core/shape/2d_primitives.js", "line": 556, "description": "Draws a rectangle on the canvas. A rectangle is a four-sided closed shape with\nevery angle at ninety degrees. By default, the first two parameters set\nthe location of the upper-left corner, the third sets the width, and the\nfourth sets the height. The way these parameters are interpreted may be\nchanged with the rectMode() function.
\nThe fifth, sixth, seventh and eighth parameters, if specified,\ndetermine corner radius for the top-left, top-right, lower-right and\nlower-left corners, respectively. An omitted corner radius parameter is set\nto the value of the previously specified radius value in the parameter list.
\n", "itemtype": "method", "name": "rect", "chainable": 1, "example": [ "\n\n// Draw a rectangle at location (30, 20) with a width and height of 55.\nrect(30, 20, 55, 55);\ndescribe('white rect with black outline in mid-right of canvas');\n
\n\n// Draw a rectangle with rounded corners, each having a radius of 20.\nrect(30, 20, 55, 55, 20);\ndescribe(\n 'white rect with black outline and round edges in mid-right of canvas'\n);\n
\n\n// Draw a rectangle with rounded corners having the following radii:\n// top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5.\nrect(30, 20, 55, 55, 20, 15, 10, 5);\ndescribe('white rect with black outline and round edges of different radii');\n
\nx-coordinate of the rectangle.
\n", "type": "Number" }, { "name": "y", "description": "y-coordinate of the rectangle.
\n", "type": "Number" }, { "name": "w", "description": "width of the rectangle.
\n", "type": "Number" }, { "name": "h", "description": "height of the rectangle.
\n", "type": "Number", "optional": true }, { "name": "tl", "description": "optional radius of top-left corner.
\n", "type": "Number", "optional": true }, { "name": "tr", "description": "optional radius of top-right corner.
\n", "type": "Number", "optional": true }, { "name": "br", "description": "optional radius of bottom-right corner.
\n", "type": "Number", "optional": true }, { "name": "bl", "description": "optional radius of bottom-left corner.
\n", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 608, "params": [ { "name": "x", "description": "", "type": "Number" }, { "name": "y", "description": "", "type": "Number" }, { "name": "w", "description": "", "type": "Number" }, { "name": "h", "description": "", "type": "Number" }, { "name": "detailX", "description": "number of segments in the x-direction (for WebGL mode)
\n", "type": "Integer", "optional": true }, { "name": "detailY", "description": "number of segments in the y-direction (for WebGL mode)
\n", "type": "Integer", "optional": true } ], "chainable": 1 } ] }, { "file": "src/core/shape/2d_primitives.js", "line": 623, "description": "Draws a square to the screen. A square is a four-sided shape with every angle\nat ninety degrees, and equal side size. This function is a special case of the\nrect() function, where the width and height are the same, and the parameter\nis called \"s\" for side size. By default, the first two parameters set the\nlocation of the upper-left corner, the third sets the side size of the square.\nThe way these parameters are interpreted, may be changed with the rectMode() function.
\nThe fourth, fifth, sixth and seventh parameters, if specified,\ndetermine corner radius for the top-left, top-right, lower-right and\nlower-left corners, respectively. An omitted corner radius parameter is set\nto the value of the previously specified radius value in the parameter list.
\n", "itemtype": "method", "name": "square", "params": [ { "name": "x", "description": "x-coordinate of the square.
\n", "type": "Number" }, { "name": "y", "description": "y-coordinate of the square.
\n", "type": "Number" }, { "name": "s", "description": "side size of the square.
\n", "type": "Number" }, { "name": "tl", "description": "optional radius of top-left corner.
\n", "type": "Number", "optional": true }, { "name": "tr", "description": "optional radius of top-right corner.
\n", "type": "Number", "optional": true }, { "name": "br", "description": "optional radius of bottom-right corner.
\n", "type": "Number", "optional": true }, { "name": "bl", "description": "optional radius of bottom-left corner.
\n", "type": "Number", "optional": true } ], "chainable": 1, "example": [ "\n\n// Draw a square at location (30, 20) with a side size of 55.\nsquare(30, 20, 55);\ndescribe('white square with black outline in mid-right of canvas');\n
\n\n// Draw a square with rounded corners, each having a radius of 20.\nsquare(30, 20, 55, 20);\ndescribe(\n 'white square with black outline and round edges in mid-right of canvas'\n);\n
\n\n// Draw a square with rounded corners having the following radii:\n// top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5.\nsquare(30, 20, 55, 20, 15, 10, 5);\ndescribe('white square with black outline and round edges of different radii');\n
\nDraws a triangle to the canvas. A triangle is a plane created by connecting\nthree points. The first two arguments specify the first point, the middle two\narguments specify the second point, and the last two arguments specify the\nthird point.
\n", "itemtype": "method", "name": "triangle", "params": [ { "name": "x1", "description": "x-coordinate of the first point
\n", "type": "Number" }, { "name": "y1", "description": "y-coordinate of the first point
\n", "type": "Number" }, { "name": "x2", "description": "x-coordinate of the second point
\n", "type": "Number" }, { "name": "y2", "description": "y-coordinate of the second point
\n", "type": "Number" }, { "name": "x3", "description": "x-coordinate of the third point
\n", "type": "Number" }, { "name": "y3", "description": "y-coordinate of the third point
\n", "type": "Number" } ], "chainable": 1, "example": [ "\n\ntriangle(30, 75, 58, 20, 86, 75);\ndescribe('white triangle with black outline in mid-right of canvas');\n
\nModifies the location from which ellipses are drawn by changing the way in\nwhich parameters given to ellipse(),\ncircle() and arc() are interpreted.
\nThe default mode is CENTER, in which the first two parameters are interpreted\nas the shape's center point's x and y coordinates respectively, while the third\nand fourth parameters are its width and height.
\nellipseMode(RADIUS) also uses the first two parameters as the shape's center\npoint's x and y coordinates, but uses the third and fourth parameters to\nspecify half of the shapes's width and height.
\nellipseMode(CORNER) interprets the first two parameters as the upper-left\ncorner of the shape, while the third and fourth parameters are its width\nand height.
\nellipseMode(CORNERS) interprets the first two parameters as the location of\none corner of the ellipse's bounding box, and the third and fourth parameters\nas the location of the opposite corner.
\nThe parameter to this method must be written in ALL CAPS because they are\npredefined as constants in ALL CAPS and Javascript is a case-sensitive language.
\n", "itemtype": "method", "name": "ellipseMode", "params": [ { "name": "mode", "description": "either CENTER, RADIUS, CORNER, or CORNERS
\n", "type": "Constant" } ], "chainable": 1, "example": [ "\n\n// Example showing RADIUS and CENTER ellipsemode with 2 overlaying ellipses\nellipseMode(RADIUS);\nfill(255);\nellipse(50, 50, 30, 30); // Outer white ellipse\nellipseMode(CENTER);\nfill(100);\nellipse(50, 50, 30, 30); // Inner gray ellipse\n
\n\n// Example showing CORNER and CORNERS ellipseMode with 2 overlaying ellipses\nellipseMode(CORNER);\nfill(255);\nellipse(25, 25, 50, 50); // Outer white ellipse\nellipseMode(CORNERS);\nfill(100);\nellipse(25, 25, 50, 50); // Inner gray ellipse\n
\nDraws all geometry with jagged (aliased) edges. Note that smooth() is\nactive by default in 2D mode, so it is necessary to call noSmooth() to disable\nsmoothing of geometry, images, and fonts. In 3D mode, noSmooth() is enabled\nby default, so it is necessary to call smooth() if you would like\nsmooth (antialiased) edges on your geometry.
\n", "itemtype": "method", "name": "noSmooth", "chainable": 1, "example": [ "\n\nbackground(0);\nnoStroke();\nsmooth();\nellipse(30, 48, 36, 36);\nnoSmooth();\nellipse(70, 48, 36, 36);\n
\nModifies the location from which rectangles are drawn by changing the way\nin which parameters given to rect() are interpreted.
\nThe default mode is CORNER, which interprets the first two parameters as the\nupper-left corner of the shape, while the third and fourth parameters are its\nwidth and height.
\nrectMode(CORNERS) interprets the first two parameters as the location of\none of the corners, and the third and fourth parameters as the location of\nthe diagonally opposite corner. Note, the rectangle is drawn between the\ncoordinates, so it is not necessary that the first corner be the upper left\ncorner.
\nrectMode(CENTER) interprets the first two parameters as the shape's center\npoint, while the third and fourth parameters are its width and height.
\nrectMode(RADIUS) also uses the first two parameters as the shape's center\npoint, but uses the third and fourth parameters to specify half of the shape's\nwidth and height respectively.
\nThe parameter to this method must be written in ALL CAPS because they are\npredefined as constants in ALL CAPS and Javascript is a case-sensitive language.
\n", "itemtype": "method", "name": "rectMode", "params": [ { "name": "mode", "description": "either CORNER, CORNERS, CENTER, or RADIUS
\n", "type": "Constant" } ], "chainable": 1, "example": [ "\n\nrectMode(CORNER);\nfill(255);\nrect(25, 25, 50, 50); // Draw white rectangle using CORNER mode\n\nrectMode(CORNERS);\nfill(100);\nrect(25, 25, 50, 50); // Draw gray rectangle using CORNERS mode\n
\n\nrectMode(RADIUS);\nfill(255);\nrect(50, 50, 30, 30); // Draw white rectangle using RADIUS mode\n\nrectMode(CENTER);\nfill(100);\nrect(50, 50, 30, 30); // Draw gray rectangle using CENTER mode\n
\nDraws all geometry with smooth (anti-aliased) edges. smooth() will also\nimprove image quality of resized images. Note that smooth() is active by\ndefault in 2D mode; noSmooth() can be used to disable smoothing of geometry,\nimages, and fonts. In 3D mode, noSmooth() is enabled\nby default, so it is necessary to call smooth() if you would like\nsmooth (antialiased) edges on your geometry.
\n", "itemtype": "method", "name": "smooth", "chainable": 1, "example": [ "\n\nbackground(0);\nnoStroke();\nsmooth();\nellipse(30, 48, 36, 36);\nnoSmooth();\nellipse(70, 48, 36, 36);\n
\nSets the style for rendering line endings. These ends are either rounded,\nsquared or extended, each of which specified with the corresponding\nparameters: ROUND, SQUARE and PROJECT. The default cap is ROUND.
\nThe parameter to this method must be written in ALL CAPS because they are\npredefined as constants in ALL CAPS and Javascript is a case-sensitive language.
\n", "itemtype": "method", "name": "strokeCap", "params": [ { "name": "cap", "description": "either ROUND, SQUARE or PROJECT
\n", "type": "Constant" } ], "chainable": 1, "example": [ "\n\n// Example of different strokeCaps\nstrokeWeight(12.0);\nstrokeCap(ROUND);\nline(20, 30, 80, 30);\nstrokeCap(SQUARE);\nline(20, 50, 80, 50);\nstrokeCap(PROJECT);\nline(20, 70, 80, 70);\n
\nSets the style of the joints which connect line segments. These joints\nare either mitered, beveled or rounded and specified with the\ncorresponding parameters MITER, BEVEL and ROUND. The default joint is\nMITER.
\nThe parameter to this method must be written in ALL CAPS because they are\npredefined as constants in ALL CAPS and Javascript is a case-sensitive language.
\n", "itemtype": "method", "name": "strokeJoin", "params": [ { "name": "join", "description": "either MITER, BEVEL, ROUND
\n", "type": "Constant" } ], "chainable": 1, "example": [ "\n\n// Example of MITER type of joints\nnoFill();\nstrokeWeight(10.0);\nstrokeJoin(MITER);\nbeginShape();\nvertex(35, 20);\nvertex(65, 50);\nvertex(35, 80);\nendShape();\n
\n\n// Example of BEVEL type of joints\nnoFill();\nstrokeWeight(10.0);\nstrokeJoin(BEVEL);\nbeginShape();\nvertex(35, 20);\nvertex(65, 50);\nvertex(35, 80);\nendShape();\n
\n\n// Example of ROUND type of joints\nnoFill();\nstrokeWeight(10.0);\nstrokeJoin(ROUND);\nbeginShape();\nvertex(35, 20);\nvertex(65, 50);\nvertex(35, 80);\nendShape();\n
\nSets the width of the stroke used for lines, points and the border around\nshapes. All widths are set in units of pixels.
\nNote that it is affected by any transformation or scaling that has\nbeen applied previously.
\n", "itemtype": "method", "name": "strokeWeight", "params": [ { "name": "weight", "description": "the weight of the stroke (in pixels)
\n", "type": "Number" } ], "chainable": 1, "example": [ "\n\n// Example of different stroke weights\nstrokeWeight(1); // Default\nline(20, 20, 80, 20);\nstrokeWeight(4); // Thicker\nline(20, 40, 80, 40);\nstrokeWeight(10); // Beastly\nline(20, 70, 80, 70);\n
\n\n//Example of stroke weights\n//after transformations\nstrokeWeight(1); // Default\nline(20, 20, 80, 20);\nscale(5); // Adding scale transformation\nstrokeWeight(1); // Resulting strokeweight is 5\nline(4, 8, 16, 8); // Coordinates adjusted for scaling\n
\nDraws a cubic Bezier curve on the screen. These curves are defined by a\nseries of anchor and control points. The first two parameters specify\nthe first anchor point and the last two parameters specify the other\nanchor point, which become the first and last points on the curve. The\nmiddle parameters specify the two control points which define the shape\nof the curve. Approximately speaking, control points \"pull\" the curve\ntowards them.
\nBezier curves were developed by French automotive engineer Pierre Bezier,\nand are commonly used in computer graphics to define gently sloping curves.\nSee also curve().
\n", "itemtype": "method", "name": "bezier", "chainable": 1, "example": [ "\n\nnoFill();\nstroke(255, 102, 0);\nline(85, 20, 10, 10);\nline(90, 90, 15, 80);\nstroke(0, 0, 0);\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\n
\n\nbackground(0, 0, 0);\nnoFill();\nstroke(255);\nbezier(250, 250, 0, 100, 100, 0, 100, 0, 0, 0, 100, 0);\n
\nx-coordinate for the first anchor point
\n", "type": "Number" }, { "name": "y1", "description": "y-coordinate for the first anchor point
\n", "type": "Number" }, { "name": "x2", "description": "x-coordinate for the first control point
\n", "type": "Number" }, { "name": "y2", "description": "y-coordinate for the first control point
\n", "type": "Number" }, { "name": "x3", "description": "x-coordinate for the second control point
\n", "type": "Number" }, { "name": "y3", "description": "y-coordinate for the second control point
\n", "type": "Number" }, { "name": "x4", "description": "x-coordinate for the second anchor point
\n", "type": "Number" }, { "name": "y4", "description": "y-coordinate for the second anchor point
\n", "type": "Number" } ], "chainable": 1 }, { "line": 62, "params": [ { "name": "x1", "description": "", "type": "Number" }, { "name": "y1", "description": "", "type": "Number" }, { "name": "z1", "description": "z-coordinate for the first anchor point
\n", "type": "Number" }, { "name": "x2", "description": "", "type": "Number" }, { "name": "y2", "description": "", "type": "Number" }, { "name": "z2", "description": "z-coordinate for the first control point
\n", "type": "Number" }, { "name": "x3", "description": "", "type": "Number" }, { "name": "y3", "description": "", "type": "Number" }, { "name": "z3", "description": "z-coordinate for the second control point
\n", "type": "Number" }, { "name": "x4", "description": "", "type": "Number" }, { "name": "y4", "description": "", "type": "Number" }, { "name": "z4", "description": "z-coordinate for the second anchor point
\n", "type": "Number" } ], "chainable": 1 } ] }, { "file": "src/core/shape/curves.js", "line": 92, "description": "Sets the resolution at which Bezier's curve is displayed. The default value is 20.
\nNote, This function is only useful when using the WEBGL renderer\nas the default canvas renderer does not use this information.
\n", "itemtype": "method", "name": "bezierDetail", "params": [ { "name": "detail", "description": "resolution of the curves
\n", "type": "Number" } ], "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noFill();\n bezierDetail(5);\n}\n\nfunction draw() {\n background(200);\n bezier(\n -40, -40, 0,\n 90, -40, 0,\n -90, 40, 0,\n 40, 40, 0\n );\n}\n
\nGiven the x or y co-ordinate values of control and anchor points of a bezier\ncurve, it evaluates the x or y coordinate of the bezier at position t. The\nparameters a and d are the x or y coordinates of first and last points on the\ncurve while b and c are of the control points.The final parameter t is the\nposition of the resultant point which is given between 0 and 1.\nThis can be done once with the x coordinates and a second time\nwith the y coordinates to get the location of a bezier curve at t.
\n", "itemtype": "method", "name": "bezierPoint", "params": [ { "name": "a", "description": "coordinate of first point on the curve
\n", "type": "Number" }, { "name": "b", "description": "coordinate of first control point
\n", "type": "Number" }, { "name": "c", "description": "coordinate of second control point
\n", "type": "Number" }, { "name": "d", "description": "coordinate of second point on the curve
\n", "type": "Number" }, { "name": "t", "description": "value between 0 and 1
\n", "type": "Number" } ], "return": { "description": "the value of the Bezier at position t", "type": "Number" }, "example": [ "\n\nnoFill();\nlet x1 = 85,\n x2 = 10,\n x3 = 90,\n x4 = 15;\nlet y1 = 20,\n y2 = 10,\n y3 = 90,\n y4 = 80;\nbezier(x1, y1, x2, y2, x3, y3, x4, y4);\nfill(255);\nlet steps = 10;\nfor (let i = 0; i <= steps; i++) {\n let t = i / steps;\n let x = bezierPoint(x1, x2, x3, x4, t);\n let y = bezierPoint(y1, y2, y3, y4, t);\n circle(x, y, 5);\n}\n
\nEvaluates the tangent to the Bezier at position t for points a, b, c, d.\nThe parameters a and d are the first and last points\non the curve, and b and c are the control points.\nThe final parameter t varies between 0 and 1.
\n", "itemtype": "method", "name": "bezierTangent", "params": [ { "name": "a", "description": "coordinate of first point on the curve
\n", "type": "Number" }, { "name": "b", "description": "coordinate of first control point
\n", "type": "Number" }, { "name": "c", "description": "coordinate of second control point
\n", "type": "Number" }, { "name": "d", "description": "coordinate of second point on the curve
\n", "type": "Number" }, { "name": "t", "description": "value between 0 and 1
\n", "type": "Number" } ], "return": { "description": "the tangent at position t", "type": "Number" }, "example": [ "\n\nnoFill();\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\nlet steps = 6;\nfill(255);\nfor (let i = 0; i <= steps; i++) {\n let t = i / steps;\n // Get the location of the point\n let x = bezierPoint(85, 10, 90, 15, t);\n let y = bezierPoint(20, 10, 90, 80, t);\n // Get the tangent points\n let tx = bezierTangent(85, 10, 90, 15, t);\n let ty = bezierTangent(20, 10, 90, 80, t);\n // Calculate an angle from the tangent points\n let a = atan2(ty, tx);\n a += PI;\n stroke(255, 102, 0);\n line(x, y, cos(a) * 30 + x, sin(a) * 30 + y);\n // The following line of code makes a line\n // inverse of the above line\n //line(x, y, cos(a)*-30 + x, sin(a)*-30 + y);\n stroke(0);\n ellipse(x, y, 5, 5);\n}\n
\n\nnoFill();\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\nstroke(255, 102, 0);\nlet steps = 16;\nfor (let i = 0; i <= steps; i++) {\n let t = i / steps;\n let x = bezierPoint(85, 10, 90, 15, t);\n let y = bezierPoint(20, 10, 90, 80, t);\n let tx = bezierTangent(85, 10, 90, 15, t);\n let ty = bezierTangent(20, 10, 90, 80, t);\n let a = atan2(ty, tx);\n a -= HALF_PI;\n line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);\n}\n
\nDraws a curved line on the screen between two points, given as the\nmiddle four parameters. The first two parameters are a control point, as\nif the curve came from this point even though it's not drawn. The last\ntwo parameters similarly describe the other control point.
\nLonger curves can be created by putting a series of curve() functions\ntogether or using curveVertex(). An additional function called\ncurveTightness() provides control for the visual quality of the curve.\nThe curve() function is an implementation of Catmull-Rom splines.
\nnoFill();\nstroke(255, 102, 0);\ncurve(5, 26, 5, 26, 73, 24, 73, 61);\nstroke(0);\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nstroke(255, 102, 0);\ncurve(73, 24, 73, 61, 15, 65, 15, 65);\n
\n\n// Define the curve points as JavaScript objects\nlet p1 = { x: 5, y: 26 };\nlet p2 = { x: 73, y: 24 };\nlet p3 = { x: 73, y: 61 };\nlet p4 = { x: 15, y: 65 };\nnoFill();\nstroke(255, 102, 0);\ncurve(p1.x, p1.y, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);\nstroke(0);\ncurve(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y);\nstroke(255, 102, 0);\ncurve(p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, p4.x, p4.y);\n
\n\nnoFill();\nstroke(255, 102, 0);\ncurve(5, 26, 0, 5, 26, 0, 73, 24, 0, 73, 61, 0);\nstroke(0);\ncurve(5, 26, 0, 73, 24, 0, 73, 61, 0, 15, 65, 0);\nstroke(255, 102, 0);\ncurve(73, 24, 0, 73, 61, 0, 15, 65, 0, 15, 65, 0);\n
\nx-coordinate for the beginning control point
\n", "type": "Number" }, { "name": "y1", "description": "y-coordinate for the beginning control point
\n", "type": "Number" }, { "name": "x2", "description": "x-coordinate for the first point
\n", "type": "Number" }, { "name": "y2", "description": "y-coordinate for the first point
\n", "type": "Number" }, { "name": "x3", "description": "x-coordinate for the second point
\n", "type": "Number" }, { "name": "y3", "description": "y-coordinate for the second point
\n", "type": "Number" }, { "name": "x4", "description": "x-coordinate for the ending control point
\n", "type": "Number" }, { "name": "y4", "description": "y-coordinate for the ending control point
\n", "type": "Number" } ], "chainable": 1 }, { "line": 333, "params": [ { "name": "x1", "description": "", "type": "Number" }, { "name": "y1", "description": "", "type": "Number" }, { "name": "z1", "description": "z-coordinate for the beginning control point
\n", "type": "Number" }, { "name": "x2", "description": "", "type": "Number" }, { "name": "y2", "description": "", "type": "Number" }, { "name": "z2", "description": "z-coordinate for the first point
\n", "type": "Number" }, { "name": "x3", "description": "", "type": "Number" }, { "name": "y3", "description": "", "type": "Number" }, { "name": "z3", "description": "z-coordinate for the second point
\n", "type": "Number" }, { "name": "x4", "description": "", "type": "Number" }, { "name": "y4", "description": "", "type": "Number" }, { "name": "z4", "description": "z-coordinate for the ending control point
\n", "type": "Number" } ], "chainable": 1 } ] }, { "file": "src/core/shape/curves.js", "line": 359, "description": "Sets the resolution at which curves display. The default value is 20 while\nthe minimum value is 3.
\nThis function is only useful when using the WEBGL renderer\nas the default canvas renderer does not use this\ninformation.
\n", "itemtype": "method", "name": "curveDetail", "params": [ { "name": "resolution", "description": "resolution of the curves
\n", "type": "Number" } ], "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n curveDetail(5);\n}\nfunction draw() {\n background(200);\n\n curve(250, 600, 0, -30, 40, 0, 30, 30, 0, -250, 600, 0);\n}\n
\nModifies the quality of forms created with curve()\nand curveVertex().The parameter tightness\ndetermines how the curve fits to the vertex points. The value 0.0 is the\ndefault value for tightness (this value defines the curves to be Catmull-Rom\nsplines) and the value 1.0 connects all the points with straight lines.\nValues within the range -5.0 and 5.0 will deform the curves but will leave\nthem recognizable and as values increase in magnitude, they will continue to deform.
\n", "itemtype": "method", "name": "curveTightness", "params": [ { "name": "amount", "description": "amount of deformation from the original vertices
\n", "type": "Number" } ], "chainable": 1, "example": [ "\n\n// Move the mouse left and right to see the curve change\nfunction setup() {\n createCanvas(100, 100);\n noFill();\n}\n\nfunction draw() {\n background(204);\n let t = map(mouseX, 0, width, -5, 5);\n curveTightness(t);\n beginShape();\n curveVertex(10, 26);\n curveVertex(10, 26);\n curveVertex(83, 24);\n curveVertex(83, 61);\n curveVertex(25, 65);\n curveVertex(25, 65);\n endShape();\n}\n
\nEvaluates the curve at position t for points a, b, c, d.\nThe parameter t varies between 0 and 1, a and d are control points\nof the curve, and b and c are the start and end points of the curve.\nThis can be done once with the x coordinates and a second time\nwith the y coordinates to get the location of a curve at t.
\n", "itemtype": "method", "name": "curvePoint", "params": [ { "name": "a", "description": "coordinate of first control point of the curve
\n", "type": "Number" }, { "name": "b", "description": "coordinate of first point
\n", "type": "Number" }, { "name": "c", "description": "coordinate of second point
\n", "type": "Number" }, { "name": "d", "description": "coordinate of second control point
\n", "type": "Number" }, { "name": "t", "description": "value between 0 and 1
\n", "type": "Number" } ], "return": { "description": "Curve value at position t", "type": "Number" }, "example": [ "\n\nnoFill();\ncurve(5, 26, 5, 26, 73, 24, 73, 61);\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nfill(255);\nellipseMode(CENTER);\nlet steps = 6;\nfor (let i = 0; i <= steps; i++) {\n let t = i / steps;\n let x = curvePoint(5, 5, 73, 73, t);\n let y = curvePoint(26, 26, 24, 61, t);\n ellipse(x, y, 5, 5);\n x = curvePoint(5, 73, 73, 15, t);\n y = curvePoint(26, 24, 61, 65, t);\n ellipse(x, y, 5, 5);\n}\n
\nEvaluates the tangent to the curve at position t for points a, b, c, d.\nThe parameter t varies between 0 and 1, a and d are points on the curve,\nand b and c are the control points.
\n", "itemtype": "method", "name": "curveTangent", "params": [ { "name": "a", "description": "coordinate of first control point
\n", "type": "Number" }, { "name": "b", "description": "coordinate of first point on the curve
\n", "type": "Number" }, { "name": "c", "description": "coordinate of second point on the curve
\n", "type": "Number" }, { "name": "d", "description": "coordinate of second conrol point
\n", "type": "Number" }, { "name": "t", "description": "value between 0 and 1
\n", "type": "Number" } ], "return": { "description": "the tangent at position t", "type": "Number" }, "example": [ "\n\nnoFill();\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nlet steps = 6;\nfor (let i = 0; i <= steps; i++) {\n let t = i / steps;\n let x = curvePoint(5, 73, 73, 15, t);\n let y = curvePoint(26, 24, 61, 65, t);\n //ellipse(x, y, 5, 5);\n let tx = curveTangent(5, 73, 73, 15, t);\n let ty = curveTangent(26, 24, 61, 65, t);\n let a = atan2(ty, tx);\n a -= PI / 2.0;\n line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);\n}\n
\nUse the beginContour() and\nendContour() functions to create negative shapes\nwithin shapes such as the center of the letter 'O'. beginContour()\nbegins recording vertices for the shape and endContour() stops recording.\nThe vertices that define a negative shape must \"wind\" in the opposite direction\nfrom the exterior shape. First draw vertices for the exterior clockwise order, then for internal shapes, draw vertices\nshape in counter-clockwise.
\nThese functions can only be used within a beginShape()/endShape() pair and\ntransformations such as translate(), rotate(), and scale() do not work\nwithin a beginContour()/endContour() pair. It is also not possible to use\nother shapes, such as ellipse() or rect() within.
\n", "itemtype": "method", "name": "beginContour", "chainable": 1, "example": [ "\n\ntranslate(50, 50);\nstroke(255, 0, 0);\nbeginShape();\n// Exterior part of shape, clockwise winding\nvertex(-40, -40);\nvertex(40, -40);\nvertex(40, 40);\nvertex(-40, 40);\n// Interior part of shape, counter-clockwise winding\nbeginContour();\nvertex(-20, -20);\nvertex(-20, 20);\nvertex(20, 20);\nvertex(20, -20);\nendContour();\nendShape(CLOSE);\n
\nUsing the beginShape() and endShape() functions allow creating more\ncomplex forms. beginShape() begins recording vertices for a shape and\nendShape() stops recording. The value of the kind parameter tells it which\ntypes of shapes to create from the provided vertices. With no mode\nspecified, the shape can be any irregular polygon.
\nThe parameters available for beginShape() are:
\nPOINTS\nDraw a series of points
\nLINES\nDraw a series of unconnected line segments (individual lines)
\nTRIANGLES\nDraw a series of separate triangles
\nTRIANGLE_FAN\nDraw a series of connected triangles sharing the first vertex in a fan-like fashion
\nTRIANGLE_STRIP\nDraw a series of connected triangles in strip fashion
\nQUADS\nDraw a series of separate quads
\nQUAD_STRIP\nDraw quad strip using adjacent edges to form the next quad
\nTESS (WEBGL only)\nHandle irregular polygon for filling curve by explicit tessellation
\nAfter calling the beginShape() function, a series of vertex() commands must follow. To stop\ndrawing the shape, call endShape(). Each shape will be outlined with the\ncurrent stroke color and filled with the fill color.
\nTransformations such as translate(), rotate(), and scale() do not work\nwithin beginShape(). It is also not possible to use other shapes, such as\nellipse() or rect() within beginShape().
\n", "itemtype": "method", "name": "beginShape", "params": [ { "name": "kind", "description": "either POINTS, LINES, TRIANGLES, TRIANGLE_FAN\n TRIANGLE_STRIP, QUADS, QUAD_STRIP or TESS
\n", "type": "Constant", "optional": true } ], "chainable": 1, "example": [ "\n\nbeginShape();\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape(CLOSE);\n
\n\nbeginShape(POINTS);\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n
\n\nbeginShape(LINES);\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n
\n\nnoFill();\nbeginShape();\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n
\n\nnoFill();\nbeginShape();\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape(CLOSE);\n
\n\nbeginShape(TRIANGLES);\nvertex(30, 75);\nvertex(40, 20);\nvertex(50, 75);\nvertex(60, 20);\nvertex(70, 75);\nvertex(80, 20);\nendShape();\n
\n\nbeginShape(TRIANGLE_STRIP);\nvertex(30, 75);\nvertex(40, 20);\nvertex(50, 75);\nvertex(60, 20);\nvertex(70, 75);\nvertex(80, 20);\nvertex(90, 75);\nendShape();\n
\n\nbeginShape(TRIANGLE_FAN);\nvertex(57.5, 50);\nvertex(57.5, 15);\nvertex(92, 50);\nvertex(57.5, 85);\nvertex(22, 50);\nvertex(57.5, 15);\nendShape();\n
\n\nbeginShape(QUADS);\nvertex(30, 20);\nvertex(30, 75);\nvertex(50, 75);\nvertex(50, 20);\nvertex(65, 20);\nvertex(65, 75);\nvertex(85, 75);\nvertex(85, 20);\nendShape();\n
\n\nbeginShape(QUAD_STRIP);\nvertex(30, 20);\nvertex(30, 75);\nvertex(50, 20);\nvertex(50, 75);\nvertex(65, 20);\nvertex(65, 75);\nvertex(85, 20);\nvertex(85, 75);\nendShape();\n
\n\nbeginShape(TESS);\nvertex(20, 20);\nvertex(80, 20);\nvertex(80, 40);\nvertex(40, 40);\nvertex(40, 60);\nvertex(80, 60);\nvertex(80, 80);\nvertex(20, 80);\nendShape(CLOSE);\n
\nSpecifies vertex coordinates for Bezier curves. Each call to\nbezierVertex() defines the position of two control points and\none anchor point of a Bezier curve, adding a new segment to a\nline or shape. For WebGL mode bezierVertex() can be used in 2D\nas well as 3D mode. 2D mode expects 6 parameters, while 3D mode\nexpects 9 parameters (including z coordinates).
\nThe first time bezierVertex() is used within a beginShape()\ncall, it must be prefaced with a call to vertex() to set the first anchor\npoint. This function must be used between beginShape() and endShape()\nand only when there is no MODE or POINTS parameter specified to\nbeginShape().
\n", "itemtype": "method", "name": "bezierVertex", "chainable": 1, "example": [ "\n\nnoFill();\nbeginShape();\nvertex(30, 20);\nbezierVertex(80, 0, 80, 75, 30, 75);\nendShape();\n
\n\nbeginShape();\nvertex(30, 20);\nbezierVertex(80, 0, 80, 75, 30, 75);\nbezierVertex(50, 80, 60, 25, 30, 20);\nendShape();\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n setAttributes('antialias', true);\n}\nfunction draw() {\n orbitControl();\n background(50);\n strokeWeight(4);\n stroke(255);\n point(-25, 30);\n point(25, 30);\n point(25, -30);\n point(-25, -30);\n\n strokeWeight(1);\n noFill();\n\n beginShape();\n vertex(-25, 30);\n bezierVertex(25, 30, 25, -30, -25, -30);\n endShape();\n\n beginShape();\n vertex(-25, 30, 20);\n bezierVertex(25, 30, 20, 25, -30, 20, -25, -30, 20);\n endShape();\n}\n
\nx-coordinate for the first control point
\n", "type": "Number" }, { "name": "y2", "description": "y-coordinate for the first control point
\n", "type": "Number" }, { "name": "x3", "description": "x-coordinate for the second control point
\n", "type": "Number" }, { "name": "y3", "description": "y-coordinate for the second control point
\n", "type": "Number" }, { "name": "x4", "description": "x-coordinate for the anchor point
\n", "type": "Number" }, { "name": "y4", "description": "y-coordinate for the anchor point
\n", "type": "Number" } ], "chainable": 1 }, { "line": 375, "params": [ { "name": "x2", "description": "", "type": "Number" }, { "name": "y2", "description": "", "type": "Number" }, { "name": "z2", "description": "z-coordinate for the first control point (for WebGL mode)
\n", "type": "Number" }, { "name": "x3", "description": "", "type": "Number" }, { "name": "y3", "description": "", "type": "Number" }, { "name": "z3", "description": "z-coordinate for the second control point (for WebGL mode)
\n", "type": "Number" }, { "name": "x4", "description": "", "type": "Number" }, { "name": "y4", "description": "", "type": "Number" }, { "name": "z4", "description": "z-coordinate for the anchor point (for WebGL mode)
\n", "type": "Number" } ], "chainable": 1 } ] }, { "file": "src/core/shape/vertex.js", "line": 415, "description": "Specifies vertex coordinates for curves. This function may only\nbe used between beginShape() and endShape() and only when there\nis no MODE parameter specified to beginShape().\nFor WebGL mode curveVertex() can be used in 2D as well as 3D mode.\n2D mode expects 2 parameters, while 3D mode expects 3 parameters.
\nThe first and last points in a series of curveVertex() lines will be used to\nguide the beginning and end of the curve. A minimum of four\npoints is required to draw a tiny curve between the second and\nthird points. Adding a fifth point with curveVertex() will draw\nthe curve between the second, third, and fourth points. The\ncurveVertex() function is an implementation of Catmull-Rom\nsplines.
\n", "itemtype": "method", "name": "curveVertex", "chainable": 1, "example": [ "\n\nstrokeWeight(5);\npoint(84, 91);\npoint(68, 19);\npoint(21, 17);\npoint(32, 91);\nstrokeWeight(1);\n\nnoFill();\nbeginShape();\ncurveVertex(84, 91);\ncurveVertex(84, 91);\ncurveVertex(68, 19);\ncurveVertex(21, 17);\ncurveVertex(32, 91);\ncurveVertex(32, 91);\nendShape();\n
\nx-coordinate of the vertex
\n", "type": "Number" }, { "name": "y", "description": "y-coordinate of the vertex
\n", "type": "Number" } ], "chainable": 1 }, { "line": 460, "params": [ { "name": "x", "description": "", "type": "Number" }, { "name": "y", "description": "", "type": "Number" }, { "name": "z", "description": "z-coordinate of the vertex (for WebGL mode)
\n", "type": "Number", "optional": true } ], "chainable": 1 } ] }, { "file": "src/core/shape/vertex.js", "line": 524, "description": "Use the beginContour() and endContour() functions to create negative\nshapes within shapes such as the center of the letter 'O'. beginContour()\nbegins recording vertices for the shape and endContour() stops recording.\nThe vertices that define a negative shape must \"wind\" in the opposite\ndirection from the exterior shape. First draw vertices for the exterior\nclockwise order, then for internal shapes, draw vertices\nshape in counter-clockwise.
\nThese functions can only be used within a beginShape()/endShape() pair and\ntransformations such as translate(), rotate(), and scale() do not work\nwithin a beginContour()/endContour() pair. It is also not possible to use\nother shapes, such as ellipse() or rect() within.
\n", "itemtype": "method", "name": "endContour", "chainable": 1, "example": [ "\n\ntranslate(50, 50);\nstroke(255, 0, 0);\nbeginShape();\n// Exterior part of shape, clockwise winding\nvertex(-40, -40);\nvertex(40, -40);\nvertex(40, 40);\nvertex(-40, 40);\n// Interior part of shape, counter-clockwise winding\nbeginContour();\nvertex(-20, -20);\nvertex(-20, 20);\nvertex(20, 20);\nvertex(20, -20);\nendContour();\nendShape(CLOSE);\n
\nThe endShape() function is the companion to beginShape() and may only be\ncalled after beginShape(). When endShape() is called, all of the image\ndata defined since the previous call to beginShape() is written into the image\nbuffer. The constant CLOSE as the value for the mode
parameter to close\nthe shape (to connect the beginning and the end).
use CLOSE to close the shape
\n", "type": "Constant", "optional": true } ], "chainable": 1, "example": [ "\n\nnoFill();\n\nbeginShape();\nvertex(20, 20);\nvertex(45, 20);\nvertex(45, 80);\nendShape(CLOSE);\n\nbeginShape();\nvertex(50, 20);\nvertex(75, 20);\nvertex(75, 80);\nendShape();\n
\nSpecifies vertex coordinates for quadratic Bezier curves. Each call to\nquadraticVertex() defines the position of one control points and one\nanchor point of a Bezier curve, adding a new segment to a line or shape.\nThe first time quadraticVertex() is used within a beginShape() call, it\nmust be prefaced with a call to vertex() to set the first anchor point.\nFor WebGL mode quadraticVertex() can be used in 2D as well as 3D mode.\n2D mode expects 4 parameters, while 3D mode expects 6 parameters\n(including z coordinates).
\nThis function must be used between beginShape() and endShape()\nand only when there is no MODE or POINTS parameter specified to\nbeginShape().
\n", "itemtype": "method", "name": "quadraticVertex", "chainable": 1, "example": [ "\n\nstrokeWeight(5);\npoint(20, 20);\npoint(80, 20);\npoint(50, 50);\n\nnoFill();\nstrokeWeight(1);\nbeginShape();\nvertex(20, 20);\nquadraticVertex(80, 20, 50, 50);\nendShape();\n
\n\nstrokeWeight(5);\npoint(20, 20);\npoint(80, 20);\npoint(50, 50);\n\npoint(20, 80);\npoint(80, 80);\npoint(80, 60);\n\nnoFill();\nstrokeWeight(1);\nbeginShape();\nvertex(20, 20);\nquadraticVertex(80, 20, 50, 50);\nquadraticVertex(20, 80, 80, 80);\nvertex(80, 60);\nendShape();\n
\nx-coordinate for the control point
\n", "type": "Number" }, { "name": "cy", "description": "y-coordinate for the control point
\n", "type": "Number" }, { "name": "x3", "description": "x-coordinate for the anchor point
\n", "type": "Number" }, { "name": "y3", "description": "y-coordinate for the anchor point
\n", "type": "Number" } ], "chainable": 1 }, { "line": 733, "params": [ { "name": "cx", "description": "", "type": "Number" }, { "name": "cy", "description": "", "type": "Number" }, { "name": "cz", "description": "z-coordinate for the control point (for WebGL mode)
\n", "type": "Number" }, { "name": "x3", "description": "", "type": "Number" }, { "name": "y3", "description": "", "type": "Number" }, { "name": "z3", "description": "z-coordinate for the anchor point (for WebGL mode)
\n", "type": "Number" } ], "chainable": 1 } ] }, { "file": "src/core/shape/vertex.js", "line": 826, "description": "All shapes are constructed by connecting a series of vertices. vertex()\nis used to specify the vertex coordinates for points, lines, triangles,\nquads, and polygons. It is used exclusively within the beginShape() and\nendShape() functions.
\n", "itemtype": "method", "name": "vertex", "chainable": 1, "example": [ "\n\nstrokeWeight(3);\nbeginShape(POINTS);\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n
\n\ncreateCanvas(100, 100, WEBGL);\nbackground(240, 240, 240);\nfill(237, 34, 93);\nnoStroke();\nbeginShape();\nvertex(0, 35);\nvertex(35, 0);\nvertex(0, -35);\nvertex(-35, 0);\nendShape();\n
\n\ncreateCanvas(100, 100, WEBGL);\nbackground(240, 240, 240);\nfill(237, 34, 93);\nnoStroke();\nbeginShape();\nvertex(-10, 10);\nvertex(0, 35);\nvertex(10, 10);\nvertex(35, 0);\nvertex(10, -8);\nvertex(0, -35);\nvertex(-10, -8);\nvertex(-35, 0);\nendShape();\n
\n\nstrokeWeight(3);\nstroke(237, 34, 93);\nbeginShape(LINES);\nvertex(10, 35);\nvertex(90, 35);\nvertex(10, 65);\nvertex(90, 65);\nvertex(35, 10);\nvertex(35, 90);\nvertex(65, 10);\nvertex(65, 90);\nendShape();\n
\n\n// Click to change the number of sides.\n// In WebGL mode, custom shapes will only\n// display hollow fill sections when\n// all calls to vertex() use the same z-value.\n\nlet sides = 3;\nlet angle, px, py;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n setAttributes('antialias', true);\n fill(237, 34, 93);\n strokeWeight(3);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateZ(frameCount * 0.01);\n ngon(sides, 0, 0, 80);\n}\n\nfunction mouseClicked() {\n if (sides > 6) {\n sides = 3;\n } else {\n sides++;\n }\n}\n\nfunction ngon(n, x, y, d) {\n beginShape(TESS);\n for (let i = 0; i < n + 1; i++) {\n angle = TWO_PI / n * i;\n px = x + sin(angle) * d / 2;\n py = y - cos(angle) * d / 2;\n vertex(px, py, 0);\n }\n for (let i = 0; i < n + 1; i++) {\n angle = TWO_PI / n * i;\n px = x + sin(angle) * d / 4;\n py = y - cos(angle) * d / 4;\n vertex(px, py, 0);\n }\n endShape();\n}\n
\nx-coordinate of the vertex
\n", "type": "Number" }, { "name": "y", "description": "y-coordinate of the vertex
\n", "type": "Number" } ], "chainable": 1 }, { "line": 957, "params": [ { "name": "x", "description": "", "type": "Number" }, { "name": "y", "description": "", "type": "Number" }, { "name": "z", "description": "z-coordinate of the vertex.\n Defaults to 0 if not specified.
\n", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 965, "params": [ { "name": "x", "description": "", "type": "Number" }, { "name": "y", "description": "", "type": "Number" }, { "name": "z", "description": "", "type": "Number", "optional": true }, { "name": "u", "description": "the vertex's texture u-coordinate
\n", "type": "Number", "optional": true }, { "name": "v", "description": "the vertex's texture v-coordinate
\n", "type": "Number", "optional": true } ], "chainable": 1 } ] }, { "file": "src/core/shape/vertex.js", "line": 1003, "description": "Sets the 3d vertex normal to use for subsequent vertices drawn with\nvertex(). A normal is a vector that is generally\nnearly perpendicular to a shape's surface which controls how much light will\nbe reflected from that part of the surface.
\n", "itemtype": "method", "name": "normal", "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noStroke();\n}\n\nfunction draw() {\n background(255);\n rotateY(frameCount / 100);\n normalMaterial();\n beginShape(TRIANGLE_STRIP);\n normal(-0.4, 0.4, 0.8);\n vertex(-30, 30, 0);\n\n normal(0, 0, 1);\n vertex(-30, -30, 30);\n vertex(30, 30, 30);\n\n normal(0.4, -0.4, 0.8);\n vertex(30, -30, 0);\n endShape();\n}\n
\nA p5.Vector representing the vertex normal.
\n", "type": "Vector" } ], "chainable": 1 }, { "line": 1040, "params": [ { "name": "x", "description": "The x component of the vertex normal.
\n", "type": "Number" }, { "name": "y", "description": "The y component of the vertex normal.
\n", "type": "Number" }, { "name": "z", "description": "The z component of the vertex normal.
\n", "type": "Number" } ], "chainable": 1 } ] }, { "file": "src/core/constants.js", "line": 9, "description": "Version of this p5.js.
\n", "itemtype": "property", "name": "VERSION", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 18, "description": "The default, two-dimensional renderer.
\n", "itemtype": "property", "name": "P2D", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 24, "description": "One of the two render modes in p5.js: P2D (default renderer) and WEBGL\nEnables 3D render by introducing the third dimension: Z
\n", "itemtype": "property", "name": "WEBGL", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 33, "itemtype": "property", "name": "ARROW", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 38, "itemtype": "property", "name": "CROSS", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 43, "itemtype": "property", "name": "HAND", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 48, "itemtype": "property", "name": "MOVE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 53, "itemtype": "property", "name": "TEXT", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 58, "itemtype": "property", "name": "WAIT", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 66, "description": "HALF_PI is a mathematical constant with the value\n1.57079632679489661923. It is half the ratio of the\ncircumference of a circle to its diameter. It is useful in\ncombination with the trigonometric functions sin() and cos().
\n", "itemtype": "property", "name": "HALF_PI", "type": "Number", "final": 1, "example": [ "\n\narc(50, 50, 80, 80, 0, HALF_PI);\n
PI is a mathematical constant with the value\n3.14159265358979323846. It is the ratio of the circumference\nof a circle to its diameter. It is useful in combination with\nthe trigonometric functions sin() and cos().
\n", "itemtype": "property", "name": "PI", "type": "Number", "final": 1, "example": [ "\n\narc(50, 50, 80, 80, 0, PI);\n
QUARTER_PI is a mathematical constant with the value 0.7853982.\nIt is one quarter the ratio of the circumference of a circle to\nits diameter. It is useful in combination with the trigonometric\nfunctions sin() and cos().
\n", "itemtype": "property", "name": "QUARTER_PI", "type": "Number", "final": 1, "example": [ "\n\narc(50, 50, 80, 80, 0, QUARTER_PI);\n
TAU is an alias for TWO_PI, a mathematical constant with the\nvalue 6.28318530717958647693. It is twice the ratio of the\ncircumference of a circle to its diameter. It is useful in\ncombination with the trigonometric functions sin() and cos().
\n", "itemtype": "property", "name": "TAU", "type": "Number", "final": 1, "example": [ "\n\narc(50, 50, 80, 80, 0, TAU);\n
TWO_PI is a mathematical constant with the value\n6.28318530717958647693. It is twice the ratio of the\ncircumference of a circle to its diameter. It is useful in\ncombination with the trigonometric functions sin() and cos().
\n", "itemtype": "property", "name": "TWO_PI", "type": "Number", "final": 1, "example": [ "\n\narc(50, 50, 80, 80, 0, TWO_PI);\n
Constant to be used with the angleMode() function, to set the mode in\nwhich p5.js interprets and calculates angles (either DEGREES or RADIANS).
\n", "itemtype": "property", "name": "DEGREES", "type": "String", "final": 1, "example": [ "\n\nfunction setup() {\n angleMode(DEGREES);\n}\n
Constant to be used with the angleMode() function, to set the mode\nin which p5.js interprets and calculates angles (either RADIANS or DEGREES).
\n", "itemtype": "property", "name": "RADIANS", "type": "String", "final": 1, "example": [ "\n\nfunction setup() {\n angleMode(RADIANS);\n}\n
HSB (hue, saturation, brightness) is a type of color model.\nYou can learn more about it at\nHSB.
\n", "itemtype": "property", "name": "HSB", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 356, "itemtype": "property", "name": "HSL", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 363, "description": "AUTO allows us to automatically set the width or height of an element (but not both),\nbased on the current height and width of the element. Only one parameter can\nbe passed to the size function as AUTO, at a time.
\n", "itemtype": "property", "name": "AUTO", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 373, "itemtype": "property", "name": "ALT", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 379, "itemtype": "property", "name": "BACKSPACE", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 384, "itemtype": "property", "name": "CONTROL", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 389, "itemtype": "property", "name": "DELETE", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 394, "itemtype": "property", "name": "DOWN_ARROW", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 399, "itemtype": "property", "name": "ENTER", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 404, "itemtype": "property", "name": "ESCAPE", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 409, "itemtype": "property", "name": "LEFT_ARROW", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 414, "itemtype": "property", "name": "OPTION", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 419, "itemtype": "property", "name": "RETURN", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 424, "itemtype": "property", "name": "RIGHT_ARROW", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 429, "itemtype": "property", "name": "SHIFT", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 434, "itemtype": "property", "name": "TAB", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 439, "itemtype": "property", "name": "UP_ARROW", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 446, "itemtype": "property", "name": "BLEND", "type": "String", "final": 1, "default": "source-over", "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 452, "itemtype": "property", "name": "REMOVE", "type": "String", "final": 1, "default": "destination-out", "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 458, "itemtype": "property", "name": "ADD", "type": "String", "final": 1, "default": "lighter", "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 466, "itemtype": "property", "name": "DARKEST", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 471, "itemtype": "property", "name": "LIGHTEST", "type": "String", "final": 1, "default": "lighten", "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 477, "itemtype": "property", "name": "DIFFERENCE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 482, "itemtype": "property", "name": "SUBTRACT", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 487, "itemtype": "property", "name": "EXCLUSION", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 492, "itemtype": "property", "name": "MULTIPLY", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 497, "itemtype": "property", "name": "SCREEN", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 502, "itemtype": "property", "name": "REPLACE", "type": "String", "final": 1, "default": "copy", "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 508, "itemtype": "property", "name": "OVERLAY", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 513, "itemtype": "property", "name": "HARD_LIGHT", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 518, "itemtype": "property", "name": "SOFT_LIGHT", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 523, "itemtype": "property", "name": "DODGE", "type": "String", "final": 1, "default": "color-dodge", "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 529, "itemtype": "property", "name": "BURN", "type": "String", "final": 1, "default": "color-burn", "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 537, "itemtype": "property", "name": "THRESHOLD", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 542, "itemtype": "property", "name": "GRAY", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 547, "itemtype": "property", "name": "OPAQUE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 552, "itemtype": "property", "name": "INVERT", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 557, "itemtype": "property", "name": "POSTERIZE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 562, "itemtype": "property", "name": "DILATE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 567, "itemtype": "property", "name": "ERODE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 572, "itemtype": "property", "name": "BLUR", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 579, "itemtype": "property", "name": "NORMAL", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 584, "itemtype": "property", "name": "ITALIC", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 589, "itemtype": "property", "name": "BOLD", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 594, "itemtype": "property", "name": "BOLDITALIC", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 599, "itemtype": "property", "name": "CHAR", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 604, "itemtype": "property", "name": "WORD", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 616, "itemtype": "property", "name": "LINEAR", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 621, "itemtype": "property", "name": "QUADRATIC", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 626, "itemtype": "property", "name": "BEZIER", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 631, "itemtype": "property", "name": "CURVE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 638, "itemtype": "property", "name": "STROKE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 643, "itemtype": "property", "name": "FILL", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 648, "itemtype": "property", "name": "TEXTURE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 653, "itemtype": "property", "name": "IMMEDIATE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 661, "itemtype": "property", "name": "IMAGE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 669, "itemtype": "property", "name": "NEAREST", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 674, "itemtype": "property", "name": "REPEAT", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 679, "itemtype": "property", "name": "CLAMP", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 684, "itemtype": "property", "name": "MIRROR", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 691, "itemtype": "property", "name": "LANDSCAPE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 696, "itemtype": "property", "name": "PORTRAIT", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 706, "itemtype": "property", "name": "GRID", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 712, "itemtype": "property", "name": "AXES", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 718, "itemtype": "property", "name": "LABEL", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 723, "itemtype": "property", "name": "FALLBACK", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 729, "itemtype": "property", "name": "CONTAIN", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 735, "itemtype": "property", "name": "COVER", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/environment.js", "line": 20, "description": "The print() function writes to the console area of\nyour browser. This function is often helpful for looking at the data a program\nis producing. This function creates a new line of text for each call to\nthe function. Individual elements can be separated with quotes (\"\") and joined\nwith the addition operator (+).
\nNote that calling print() without any arguments invokes the window.print()\nfunction which opens the browser's print dialog. To print a blank line\nto console you can write print('\\n').
\n", "itemtype": "method", "name": "print", "params": [ { "name": "contents", "description": "any combination of Number, String, Object, Boolean,\n Array to print
\n", "type": "Any" } ], "example": [ "\n\nlet x = 10;\nprint('The value of x is ' + x);\n// prints \"The value of x is 10\"\n
The system variable frameCount contains the\nnumber of frames that have been displayed since the program started. Inside\nsetup() the value is 0, after the first iteration\nof draw() it is 1, etc.
\n", "itemtype": "property", "name": "frameCount", "type": "Integer", "readonly": "", "example": [ "\n\nfunction setup() {\n frameRate(30);\n textSize(30);\n textAlign(CENTER);\n}\n\nfunction draw() {\n background(200);\n text(frameCount, width / 2, height / 2);\n}\n
The system variable deltaTime contains the time\ndifference between the beginning of the previous frame and the beginning\nof the current frame in milliseconds.
\nThis variable is useful for creating time sensitive animation or physics\ncalculation that should stay constant regardless of frame rate.
\n", "itemtype": "property", "name": "deltaTime", "type": "Integer", "readonly": "", "example": [ "\n\nlet rectX = 0;\nlet fr = 30; //starting FPS\nlet clr;\n\nfunction setup() {\n background(200);\n frameRate(fr); // Attempt to refresh at starting FPS\n clr = color(255, 0, 0);\n}\n\nfunction draw() {\n background(200);\n rectX = rectX + 1 * (deltaTime / 50); // Move Rectangle in relation to deltaTime\n\n if (rectX >= width) {\n // If you go off screen.\n if (fr === 30) {\n clr = color(0, 0, 255);\n fr = 10;\n frameRate(fr); // make frameRate 10 FPS\n } else {\n clr = color(255, 0, 0);\n fr = 30;\n frameRate(fr); // make frameRate 30 FPS\n }\n rectX = 0;\n }\n fill(clr);\n rect(rectX, 40, 20, 20);\n}\n
Confirms if the window a p5.js program is in is \"focused,\" meaning that\nthe sketch will accept mouse or keyboard input. This variable is\n\"true\" if the window is focused and \"false\" if not.
\n", "itemtype": "property", "name": "focused", "type": "Boolean", "readonly": "", "example": [ "\n\n// To demonstrate, put two windows side by side.\n// Click on the window that the p5 sketch isn't in!\nfunction draw() {\n background(200);\n noStroke();\n fill(0, 200, 0);\n ellipse(25, 25, 50, 50);\n\n if (!focused) {\n // or \"if (focused === false)\"\n stroke(200, 0, 0);\n line(0, 0, 100, 100);\n line(100, 0, 0, 100);\n }\n}\n
Sets the cursor to a predefined symbol or an image, or makes it visible\nif already hidden. If you are trying to set an image as the cursor, the\nrecommended size is 16×16 or 32×32 pixels. The values for parameters x and y\nmust be less than the dimensions of the image.
\n", "itemtype": "method", "name": "cursor", "params": [ { "name": "type", "description": "Built-In: either ARROW, CROSS, HAND, MOVE, TEXT and WAIT\n Native CSS properties: 'grab', 'progress', 'cell' etc.\n External: path for cursor's images\n (Allowed File extensions: .cur, .gif, .jpg, .jpeg, .png)\n For more information on Native CSS cursors and url visit:\n https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
\n", "type": "String|Constant" }, { "name": "x", "description": "the horizontal active spot of the cursor (must be less than 32)
\n", "type": "Number", "optional": true }, { "name": "y", "description": "the vertical active spot of the cursor (must be less than 32)
\n", "type": "Number", "optional": true } ], "example": [ "\n\n// Move the mouse across the quadrants\n// to see the cursor change\nfunction draw() {\n line(width / 2, 0, width / 2, height);\n line(0, height / 2, width, height / 2);\n if (mouseX < 50 && mouseY < 50) {\n cursor(CROSS);\n } else if (mouseX > 50 && mouseY < 50) {\n cursor('progress');\n } else if (mouseX > 50 && mouseY > 50) {\n cursor('https://avatars0.githubusercontent.com/u/1617169?s=16');\n } else {\n cursor('grab');\n }\n}\n
Specifies the number of frames to be displayed every second. For example,\nthe function call frameRate(30) will attempt to refresh 30 times a second.\nIf the processor is not fast enough to maintain the specified rate, the\nframe rate will not be achieved. Setting the frame rate within\nsetup() is recommended. The default frame rate is\nbased on the frame rate of the display (here also called \"refresh rate\"),\nwhich is set to 60 frames per second on most computers. A frame rate of 24\nframes per second (usual for movies) or above will be enough for smooth\nanimations. This is the same as setFrameRate(val).
\nCalling frameRate() with no arguments returns\nthe current framerate. The draw function must run at least once before it will\nreturn a value. This is the same as getFrameRate().
\nCalling frameRate() with arguments that are not\nof the type Number or are non-positive also returns current framerate.
\n", "itemtype": "method", "name": "frameRate", "chainable": 1, "example": [ "\n\n\nlet rectX = 0;\nlet fr = 30; //starting FPS\nlet clr;\n\nfunction setup() {\n background(200);\n frameRate(fr); // Attempt to refresh at starting FPS\n clr = color(255, 0, 0);\n}\n\nfunction draw() {\n background(200);\n rectX += 1; // Move Rectangle\n\n if (rectX >= width) {\n // If you go off screen.\n if (fr === 30) {\n clr = color(0, 0, 255);\n fr = 10;\n frameRate(fr); // make frameRate 10 FPS\n } else {\n clr = color(255, 0, 0);\n fr = 30;\n frameRate(fr); // make frameRate 30 FPS\n }\n rectX = 0;\n }\n fill(clr);\n rect(rectX, 40, 20, 20);\n}\n
number of frames to be displayed every second
\n", "type": "Number" } ], "chainable": 1 }, { "line": 288, "params": [], "return": { "description": "current frameRate", "type": "Number" } } ] }, { "file": "src/core/environment.js", "line": 331, "description": "Hides the cursor from view.
\n", "itemtype": "method", "name": "noCursor", "example": [ "\n\nfunction setup() {\n noCursor();\n}\n\nfunction draw() {\n background(200);\n ellipse(mouseX, mouseY, 10, 10);\n}\n
System variable that stores the width of the screen display according to The\ndefault pixelDensity. This is used to run a\nfull-screen program on any display size. To return actual screen size,\nmultiply this by pixelDensity.
\n", "itemtype": "property", "name": "displayWidth", "type": "Number", "readonly": "", "example": [ "\n\ncreateCanvas(displayWidth, displayHeight);\n
System variable that stores the height of the screen display according to The\ndefault pixelDensity. This is used to run a\nfull-screen program on any display size. To return actual screen size,\nmultiply this by pixelDensity.
\n", "itemtype": "property", "name": "displayHeight", "type": "Number", "readonly": "", "example": [ "\n\ncreateCanvas(displayWidth, displayHeight);\n
System variable that stores the width of the inner window, it maps to\nwindow.innerWidth.
\n", "itemtype": "property", "name": "windowWidth", "type": "Number", "readonly": "", "example": [ "\n\ncreateCanvas(windowWidth, windowHeight);\n
System variable that stores the height of the inner window, it maps to\nwindow.innerHeight.
\n", "itemtype": "property", "name": "windowHeight", "type": "Number", "readonly": "", "example": [ "\n\ncreateCanvas(windowWidth, windowHeight);\n
The windowResized() function is called once\nevery time the browser window is resized. This is a good place to resize the\ncanvas or do any other adjustments to accommodate the new window size.
\n", "itemtype": "method", "name": "windowResized", "params": [ { "name": "event", "description": "optional Event callback argument.
\n", "type": "Object", "optional": true } ], "example": [ "\n\nfunction setup() {\n createCanvas(windowWidth, windowHeight);\n}\n\nfunction draw() {\n background(0, 100, 200);\n}\n\nfunction windowResized() {\n resizeCanvas(windowWidth, windowHeight);\n}\n
System variable that stores the width of the drawing canvas. This value\nis set by the first parameter of the createCanvas() function.\nFor example, the function call createCanvas(320, 240) sets the width\nvariable to the value 320. The value of width defaults to 100 if\ncreateCanvas() is not used in a program.
\n", "itemtype": "property", "name": "width", "type": "Number", "readonly": "", "class": "p5", "module": "Environment", "submodule": "Environment" }, { "file": "src/core/environment.js", "line": 488, "description": "System variable that stores the height of the drawing canvas. This value\nis set by the second parameter of the createCanvas() function. For\nexample, the function call createCanvas(320, 240) sets the height\nvariable to the value 240. The value of height defaults to 100 if\ncreateCanvas() is not used in a program.
\n", "itemtype": "property", "name": "height", "type": "Number", "readonly": "", "class": "p5", "module": "Environment", "submodule": "Environment" }, { "file": "src/core/environment.js", "line": 500, "description": "If argument is given, sets the sketch to fullscreen or not based on the\nvalue of the argument. If no argument is given, returns the current\nfullscreen state. Note that due to browser restrictions this can only\nbe called on user input, for example, on mouse press like the example\nbelow.
\n", "itemtype": "method", "name": "fullscreen", "params": [ { "name": "val", "description": "whether the sketch should be in fullscreen mode\nor not
\n", "type": "Boolean", "optional": true } ], "return": { "description": "current fullscreen state", "type": "Boolean" }, "example": [ "\n\n// Clicking in the box toggles fullscreen on and off.\nfunction setup() {\n background(200);\n}\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n let fs = fullscreen();\n fullscreen(!fs);\n }\n}\n
\nSets the pixel scaling for high pixel density displays. By default\npixel density is set to match display density, call pixelDensity(1)\nto turn this off. Calling pixelDensity() with no arguments returns\nthe current pixel density of the sketch.
\n", "itemtype": "method", "name": "pixelDensity", "chainable": 1, "example": [ "\n\nfunction setup() {\n pixelDensity(1);\n createCanvas(100, 100);\n background(200);\n ellipse(width / 2, height / 2, 50, 50);\n}\n
\n\nfunction setup() {\n pixelDensity(3.0);\n createCanvas(100, 100);\n background(200);\n ellipse(width / 2, height / 2, 50, 50);\n}\n
\nwhether or how much the sketch should scale
\n", "type": "Number" } ], "chainable": 1 }, { "line": 586, "params": [], "return": { "description": "current pixel density of the sketch", "type": "Number" } } ] }, { "file": "src/core/environment.js", "line": 605, "description": "Returns the pixel density of the current display the sketch is running on.
\n", "itemtype": "method", "name": "displayDensity", "return": { "description": "current pixel density of the display", "type": "Number" }, "example": [ "\n\nfunction setup() {\n let density = displayDensity();\n pixelDensity(density);\n createCanvas(100, 100);\n background(200);\n ellipse(width / 2, height / 2, 50, 50);\n}\n
\nGets the current URL. Note: when using the\np5 Editor, this will return an empty object because the sketch\nis embedded in an iframe. It will work correctly if you view the\nsketch using the editor's present or share URLs.
\n", "itemtype": "method", "name": "getURL", "return": { "description": "url", "type": "String" }, "example": [ "\n\nlet url;\nlet x = 100;\n\nfunction setup() {\n fill(0);\n noStroke();\n url = getURL();\n}\n\nfunction draw() {\n background(200);\n text(url, x, height / 2);\n x--;\n}\n
\nGets the current URL path as an array. Note: when using the\np5 Editor, this will return an empty object because the sketch\nis embedded in an iframe. It will work correctly if you view the\nsketch using the editor's present or share URLs.
\n", "itemtype": "method", "name": "getURLPath", "return": { "description": "path components", "type": "String[]" }, "example": [ "\n\nfunction setup() {\n let urlPath = getURLPath();\n for (let i = 0; i < urlPath.length; i++) {\n text(urlPath[i], 10, i * 20 + 20);\n }\n}\n
Gets the current URL params as an Object. Note: when using the\np5 Editor, this will return an empty object because the sketch\nis embedded in an iframe. It will work correctly if you view the\nsketch using the editor's present or share URLs.
\n", "itemtype": "method", "name": "getURLParams", "return": { "description": "URL params", "type": "Object" }, "example": [ "\n\n// Example: http://p5js.org?year=2014&month=May&day=15\n\nfunction setup() {\n let params = getURLParams();\n text(params.day, 10, 20);\n text(params.month, 10, 40);\n text(params.year, 10, 60);\n}\n
\nThis is our i18next \"backend\" plugin. It tries to fetch languages\nfrom a CDN.
\n", "class": "p5", "module": "Environment" }, { "file": "src/core/internationalization.js", "line": 126, "description": "Set up our translation function, with loaded languages
\n", "class": "p5", "module": "Environment" }, { "file": "src/core/internationalization.js", "line": 171, "description": "Returns a list of languages we have translations loaded for
\n", "class": "p5", "module": "Environment" }, { "file": "src/core/internationalization.js", "line": 178, "description": "Returns the current language selected for translation
\n", "class": "p5", "module": "Environment" }, { "file": "src/core/internationalization.js", "line": 185, "description": "Sets the current language for translation\nReturns a promise that resolved when loading is finished,\nor rejects if it fails.
\n", "class": "p5", "module": "Environment" }, { "file": "src/core/legacy.js", "line": 1, "requires": [ "core\nThese are functions that are part of the Processing API but are not part of\nthe p5.js API. In some cases they have a new name", "in others", "they are\nremoved completely. Not all unsupported Processing functions are listed here\nbut we try to include ones that a user coming from Processing might likely\ncall." ], "class": "p5", "module": "Environment" }, { "file": "src/core/main.js", "line": 42, "description": "Called directly before setup(), the preload() function is used to handle\nasynchronous loading of external files in a blocking way. If a preload\nfunction is defined, setup() will wait until any load calls within have\nfinished. Nothing besides load calls (loadImage, loadJSON, loadFont,\nloadStrings, etc.) should be inside the preload function. If asynchronous\nloading is preferred, the load methods can instead be called in setup()\nor anywhere else with the use of a callback parameter.
\nBy default the text \"loading...\" will be displayed. To make your own\nloading page, include an HTML element with id \"p5_loading\" in your\npage. More information here.
\n", "itemtype": "method", "name": "preload", "example": [ "\n\nlet img;\nlet c;\nfunction preload() {\n // preload() runs once\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n // setup() waits until preload() is done\n img.loadPixels();\n // get color of middle pixel\n c = img.get(img.width / 2, img.height / 2);\n}\n\nfunction draw() {\n background(c);\n image(img, 25, 25, 50, 50);\n}\n
The setup() function is called once when the program starts. It's used to\ndefine initial environment properties such as screen size and background\ncolor and to load media such as images and fonts as the program starts.\nThere can only be one setup() function for each program and it shouldn't\nbe called again after its initial execution.
\nNote: Variables declared within setup() are not accessible within other\nfunctions, including draw().
\n", "itemtype": "method", "name": "setup", "example": [ "\n\nlet a = 0;\n\nfunction setup() {\n background(0);\n noStroke();\n fill(102);\n}\n\nfunction draw() {\n rect(a++ % width, 10, 2, 80);\n}\n
Called directly after setup(), the draw() function continuously executes\nthe lines of code contained inside its block until the program is stopped\nor noLoop() is called. Note if noLoop() is called in setup(), draw() will\nstill be executed once before stopping. draw() is called automatically and\nshould never be called explicitly.
\nIt should always be controlled with noLoop(), redraw() and loop(). After\nnoLoop() stops the code in draw() from executing, redraw() causes the\ncode inside draw() to execute once, and loop() will cause the code\ninside draw() to resume executing continuously.
\nThe number of times draw() executes in each second may be controlled with\nthe frameRate() function.
\nThere can only be one draw() function for each sketch, and draw() must\nexist if you want the code to run continuously, or to process events such\nas mousePressed(). Sometimes, you might have an empty call to draw() in\nyour program, as shown in the above example.
\nIt is important to note that the drawing coordinate system will be reset\nat the beginning of each draw() call. If any transformations are performed\nwithin draw() (ex: scale, rotate, translate), their effects will be\nundone at the beginning of draw(), so transformations will not accumulate\nover time. On the other hand, styling applied (ex: fill, stroke, etc) will\nremain in effect.
\n", "itemtype": "method", "name": "draw", "example": [ "\n\nlet yPos = 0;\nfunction setup() {\n // setup() runs once\n frameRate(30);\n}\nfunction draw() {\n // draw() loops forever, until stopped\n background(204);\n yPos = yPos - 1;\n if (yPos < 0) {\n yPos = height;\n }\n line(0, yPos, width, yPos);\n}\n
Removes the entire p5 sketch. This will remove the canvas and any\nelements created by p5.js. It will also stop the draw loop and unbind\nany properties or methods from the window global scope. It will\nleave a variable p5 in case you wanted to create a new p5 sketch.\nIf you like, you can set p5 = null to erase it. While all functions and\nvariables and objects created by the p5 library will be removed, any\nother global variables created by your code will remain.
\n", "itemtype": "method", "name": "remove", "example": [ "\n\nfunction draw() {\n ellipse(50, 50, 10, 10);\n}\n\nfunction mousePressed() {\n remove(); // remove whole sketch on mouse press\n}\n
Turn off some features of the friendly error system (FES), which can give\na significant boost to performance when needed.
\nNote that this will disable the parts of the FES that cause performance\nslowdown (like argument checking). Friendly errors that have no performance\ncost (like giving a descriptive error if a file load fails, or warning you\nif you try to override p5.js functions in the global space),\nwill remain in place.
\nSee \ndisabling the friendly error system.
\n", "itemtype": "property", "name": "disableFriendlyErrors", "type": "Boolean", "example": [ "\n\np5.disableFriendlyErrors = true;\n\nfunction setup() {\n createCanvas(100, 50);\n}\n
Underlying HTML element. All normal HTML methods can be called on this.
\n", "example": [ "\n\nfunction setup() {\n let c = createCanvas(50, 50);\n c.elt.style.border = '5px solid red';\n}\n\nfunction draw() {\n background(220);\n}\n
\nAttaches the element to the parent specified. A way of setting\n the container for the element. Accepts either a string ID, DOM\n node, or p5.Element. If no arguments are given, parent node is returned.\n For more ways to position the canvas, see the\n \n positioning the canvas wiki page.
\n", "itemtype": "method", "name": "parent", "chainable": 1, "example": [ "\n\n // Add the following comment to html file.\n // <div id=\"myContainer\"></div>\n// The js code\n let cnv = createCanvas(100, 100);\n cnv.parent('myContainer');\n
\n let div0 = createDiv('this is the parent');\n let div1 = createDiv('this is the child');\n div1.parent(div0); // use p5.Element\n
\n let div0 = createDiv('this is the parent');\n div0.id('apples');\n let div1 = createDiv('this is the child');\n div1.parent('apples'); // use id\n
\n let elt = document.getElementById('myParentDiv');\n let div1 = createDiv('this is the child');\n div1.parent(elt); // use element from page\n
the ID, DOM node, or p5.Element\n of desired parent element
\n", "type": "String|p5.Element|Object" } ], "chainable": 1 }, { "line": 93, "params": [], "return": { "description": "", "type": "p5.Element" } } ] }, { "file": "src/core/p5.Element.js", "line": 114, "description": "Sets the ID of the element. If no ID argument is passed in, it instead\n returns the current ID of the element.\n Note that only one element can have a particular id in a page.\n The class() method can be used\n to identify multiple elements with the same class name.
\n", "itemtype": "method", "name": "id", "chainable": 1, "example": [ "\n\n function setup() {\n let cnv = createCanvas(100, 100);\n // Assigns a CSS selector ID to\n // the canvas element.\n cnv.id('mycanvas');\n }\n
ID of the element
\n", "type": "String" } ], "chainable": 1 }, { "line": 139, "params": [], "return": { "description": "the id of the element", "type": "String" } } ] }, { "file": "src/core/p5.Element.js", "line": 154, "description": "Adds given class to the element. If no class argument is passed in, it\n instead returns a string containing the current class(es) of the element.
\n", "itemtype": "method", "name": "class", "chainable": 1, "example": [ "\n\n function setup() {\n let cnv = createCanvas(100, 100);\n // Assigns a CSS selector class 'small'\n // to the canvas element.\n cnv.class('small');\n }\n
class to add
\n", "type": "String" } ], "chainable": 1 }, { "line": 176, "params": [], "return": { "description": "the class of the element", "type": "String" } } ] }, { "file": "src/core/p5.Element.js", "line": 189, "description": "The mousePressed() method is called\nonce after every time a mouse button is pressed over the element. Some mobile\nbrowsers may also trigger this event on a touch screen, if the user performs\na quick tap. This can be used to attach element-specific event listeners.
\n", "itemtype": "method", "name": "mousePressed", "params": [ { "name": "fxn", "description": "function to be fired when mouse is\n pressed over the element.\n if false
is passed instead, the previously\n firing function will no longer fire.
\nlet cnv, d, g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mousePressed(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any click anywhere\nfunction mousePressed() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
The doubleClicked() method is called once after every time a\nmouse button is pressed twice over the element. This can be used to\nattach element and action-specific event listeners.
\n", "itemtype": "method", "name": "doubleClicked", "params": [ { "name": "fxn", "description": "function to be fired when mouse is\n double clicked over the element.\n if false
is passed instead, the previously\n firing function will no longer fire.
\nlet cnv, d, g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.doubleClicked(changeGray); // attach listener for\n // canvas double click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any double click anywhere\nfunction doubleClicked() {\n d = d + 10;\n}\n\n// this function fires only when cnv is double clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
The mouseWheel() method is called\nonce after every time a mouse wheel is scrolled over the element. This can\nbe used to attach element-specific event listeners.
\nThe method accepts a callback function as argument which will be executed\nwhen the wheel
event is triggered on the element, the callback function is\npassed one argument event
. The event.deltaY
property returns negative\nvalues if the mouse wheel is rotated up or away from the user and positive\nin the other direction. The event.deltaX
does the same as event.deltaY
\nexcept it reads the horizontal wheel scroll of the mouse wheel.
On macOS with \"natural\" scrolling enabled, the event.deltaY
values are\nreversed.
function to be fired when mouse is\n scrolled over the element.\n if false
is passed instead, the previously\n firing function will no longer fire.
\nlet cnv, d, g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseWheel(changeSize); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with mousewheel movement\n// anywhere on screen\nfunction mouseWheel() {\n g = g + 10;\n}\n\n// this function fires with mousewheel movement\n// over canvas only\nfunction changeSize(event) {\n if (event.deltaY > 0) {\n d = d + 10;\n } else {\n d = d - 10;\n }\n}\n
The mouseReleased() method is\ncalled once after every time a mouse button is released over the element.\nSome mobile browsers may also trigger this event on a touch screen, if the\nuser performs a quick tap. This can be used to attach element-specific event listeners.
\n", "itemtype": "method", "name": "mouseReleased", "params": [ { "name": "fxn", "description": "function to be fired when mouse is\n released over the element.\n if false
is passed instead, the previously\n firing function will no longer fire.
\nlet cnv, d, g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseReleased(changeGray); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires after the mouse has been\n// released\nfunction mouseReleased() {\n d = d + 10;\n}\n\n// this function fires after the mouse has been\n// released while on canvas\nfunction changeGray() {\n g = random(0, 255);\n}\n
The mouseClicked() method is\ncalled once after a mouse button is pressed and released over the element.\nSome mobile browsers may also trigger this event on a touch screen, if the\nuser performs a quick tap. This can be used to attach element-specific event listeners.
\n", "itemtype": "method", "name": "mouseClicked", "params": [ { "name": "fxn", "description": "function to be fired when mouse is\n clicked over the element.\n if false
is passed instead, the previously\n firing function will no longer fire.
\nlet cnv, d, g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseClicked(changeGray); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires after the mouse has been\n// clicked anywhere\nfunction mouseClicked() {\n d = d + 10;\n}\n\n// this function fires after the mouse has been\n// clicked on canvas\nfunction changeGray() {\n g = random(0, 255);\n}\n
\nThe mouseMoved() method is called once every time a\nmouse moves over the element. This can be used to attach an\nelement-specific event listener.
\n", "itemtype": "method", "name": "mouseMoved", "params": [ { "name": "fxn", "description": "function to be fired when a mouse moves\n over the element.\n if false
is passed instead, the previously\n firing function will no longer fire.
\nlet cnv;\nlet d = 30;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseMoved(changeSize); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n fill(200);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires when mouse moves anywhere on\n// page\nfunction mouseMoved() {\n g = g + 5;\n if (g > 255) {\n g = 0;\n }\n}\n\n// this function fires when mouse moves over canvas\nfunction changeSize() {\n d = d + 2;\n if (d > 100) {\n d = 0;\n }\n}\n
The mouseOver() method is called once after every time a\nmouse moves onto the element. This can be used to attach an\nelement-specific event listener.
\n", "itemtype": "method", "name": "mouseOver", "params": [ { "name": "fxn", "description": "function to be fired when a mouse moves\n onto the element.\n if false
is passed instead, the previously\n firing function will no longer fire.
\nlet cnv;\nlet d;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseOver(changeGray);\n d = 10;\n}\n\nfunction draw() {\n ellipse(width / 2, height / 2, d, d);\n}\n\nfunction changeGray() {\n d = d + 10;\n if (d > 100) {\n d = 0;\n }\n}\n
The mouseOut() method is called once after every time a\nmouse moves off the element. This can be used to attach an\nelement-specific event listener.
\n", "itemtype": "method", "name": "mouseOut", "params": [ { "name": "fxn", "description": "function to be fired when a mouse\n moves off of an element.\n if false
is passed instead, the previously\n firing function will no longer fire.
\nlet cnv;\nlet d;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseOut(changeGray);\n d = 10;\n}\n\nfunction draw() {\n ellipse(width / 2, height / 2, d, d);\n}\n\nfunction changeGray() {\n d = d + 10;\n if (d > 100) {\n d = 0;\n }\n}\n
The touchStarted() method is called once after every time a touch is\nregistered. This can be used to attach element-specific event listeners.
\n", "itemtype": "method", "name": "touchStarted", "params": [ { "name": "fxn", "description": "function to be fired when a touch\n starts over the element.\n if false
is passed instead, the previously\n firing function will no longer fire.
\nlet cnv;\nlet d;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchStarted(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any touch anywhere\nfunction touchStarted() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
The touchMoved() method is called once after every time a touch move is\nregistered. This can be used to attach element-specific event listeners.
\n", "itemtype": "method", "name": "touchMoved", "params": [ { "name": "fxn", "description": "function to be fired when a touch moves over\n the element.\n if false
is passed instead, the previously\n firing function will no longer fire.
\nlet cnv;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchMoved(changeGray); // attach listener for\n // canvas click only\n g = 100;\n}\n\nfunction draw() {\n background(g);\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
The touchEnded() method is called once after every time a touch is\nregistered. This can be used to attach element-specific event listeners.
\n", "itemtype": "method", "name": "touchEnded", "params": [ { "name": "fxn", "description": "function to be fired when a touch ends\n over the element.\n if false
is passed instead, the previously\n firing function will no longer fire.
\nlet cnv;\nlet d;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchEnded(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any touch anywhere\nfunction touchEnded() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
The dragOver() method is called once after every time a\nfile is dragged over the element. This can be used to attach an\nelement-specific event listener.
\n", "itemtype": "method", "name": "dragOver", "params": [ { "name": "fxn", "description": "function to be fired when a file is\n dragged over the element.\n if false
is passed instead, the previously\n firing function will no longer fire.
\n// To test this sketch, simply drag a\n// file over the canvas\nfunction setup() {\n let c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('Drag file', width / 2, height / 2);\n c.dragOver(dragOverCallback);\n}\n\n// This function will be called whenever\n// a file is dragged over the canvas\nfunction dragOverCallback() {\n background(240);\n text('Dragged over', width / 2, height / 2);\n}\n
The dragLeave() method is called once after every time a\ndragged file leaves the element area. This can be used to attach an\nelement-specific event listener.
\n", "itemtype": "method", "name": "dragLeave", "params": [ { "name": "fxn", "description": "function to be fired when a file is\n dragged off the element.\n if false
is passed instead, the previously\n firing function will no longer fire.
\n// To test this sketch, simply drag a file\n// over and then out of the canvas area\nfunction setup() {\n let c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('Drag file', width / 2, height / 2);\n c.dragLeave(dragLeaveCallback);\n}\n\n// This function will be called whenever\n// a file is dragged out of the canvas\nfunction dragLeaveCallback() {\n background(240);\n text('Dragged off', width / 2, height / 2);\n}\n
Helper fxn for sharing pixel methods
\n", "class": "p5.Element", "module": "DOM", "submodule": "DOM" }, { "file": "src/core/p5.Graphics.js", "line": 70, "description": "Resets certain values such as those modified by functions in the Transform category\nand in the Lights category that are not automatically reset\nwith graphics buffer objects. Calling this in draw() will copy the behavior\nof the standard canvas.
\n", "itemtype": "method", "name": "reset", "example": [ "\n\n\nlet pg;\nfunction setup() {\n createCanvas(100, 100);\n background(0);\n pg = createGraphics(50, 100);\n pg.fill(0);\n frameRate(5);\n}\n\nfunction draw() {\n image(pg, width / 2, 0);\n pg.background(255);\n // p5.Graphics object behave a bit differently in some cases\n // The normal canvas on the left resets the translate\n // with every loop through draw()\n // the graphics object on the right doesn't automatically reset\n // so translate() is additive and it moves down the screen\n rect(0, 0, width / 2, 5);\n pg.rect(0, 0, width / 2, 5);\n translate(0, 5, 0);\n pg.translate(0, 5, 0);\n}\nfunction mouseClicked() {\n // if you click you will see that\n // reset() resets the translate back to the initial state\n // of the Graphics object\n pg.reset();\n}\n
Removes a Graphics object from the page and frees any resources\nassociated with it.
\n", "itemtype": "method", "name": "remove", "example": [ "\n\nlet bg;\nfunction setup() {\n bg = createCanvas(100, 100);\n bg.background(0);\n image(bg, 0, 0);\n bg.remove();\n}\n
\nlet bg;\nfunction setup() {\n pixelDensity(1);\n createCanvas(100, 100);\n stroke(255);\n fill(0);\n\n // create and draw the background image\n bg = createGraphics(100, 100);\n bg.background(200);\n bg.ellipse(50, 50, 80, 80);\n}\nfunction draw() {\n let t = millis() / 1000;\n // draw the background\n if (bg) {\n image(bg, frameCount % 100, 0);\n image(bg, frameCount % 100 - 100, 0);\n }\n // draw the foreground\n let p = p5.Vector.fromAngle(t, 35).add(50, 50);\n ellipse(p.x, p.y, 30);\n}\nfunction mouseClicked() {\n // remove the background\n if (bg) {\n bg.remove();\n bg = null;\n }\n}\n
Resize our canvas element.
\n", "class": "p5.Renderer", "module": "Rendering", "submodule": "Rendering" }, { "file": "src/core/p5.Renderer.js", "line": 461, "description": "Helper function to check font type (system or otf)
\n", "class": "p5.Renderer", "module": "Rendering", "submodule": "Rendering" }, { "file": "src/core/p5.Renderer.js", "line": 513, "description": "Helper fxn to measure ascent and descent.\nAdapted from http://stackoverflow.com/a/25355178
\n", "class": "p5.Renderer", "module": "Rendering", "submodule": "Rendering" }, { "file": "src/core/p5.Renderer2D.js", "line": 6, "description": "p5.Renderer2D\nThe 2D graphics canvas renderer class.\nextends p5.Renderer
\n", "class": "p5", "module": "Rendering" }, { "file": "src/core/p5.Renderer2D.js", "line": 444, "description": "Generate a cubic Bezier representing an arc on the unit circle of total\nangle size
radians, beginning start
radians above the x-axis. Up to\nfour of these curves are combined to make a full arc.
See ecridge.com/bezier.pdf for an explanation of the method.
\n", "class": "p5", "module": "Rendering" }, { "file": "src/core/reference.js", "line": 7, "description": "Creates and names a new variable. A variable is a container for a value.
\nVariables that are declared with let will have block-scope.\nThis means that the variable only exists within the\n\nblock that it is created within.
\nFrom the MDN entry:\nDeclares a block scope local variable, optionally initializing it to a value.
\n", "itemtype": "property", "name": "let", "example": [ "\n\nlet x = 2;\nconsole.log(x); // prints 2 to the console\nx = 1;\nconsole.log(x); // prints 1 to the console\n
\nCreates and names a new constant. Like a variable created with let,\na constant that is created with const is a container for a value,\nhowever constants cannot be reassigned once they are declared. Although it is\nnoteworthy that for non-primitive data types like objects & arrays, their\nelements can still be changeable. So if a variable is assigned an array, you\ncan still add or remove elements from the array but cannot reassign another\narray to it. Also unlike let
, you cannot declare variables without value\nusing const.
Constants have block-scope. This means that the constant only exists within\nthe \nblock that it is created within. A constant cannot be redeclared within a scope in which it\nalready exists.
\nFrom the MDN entry:\nDeclares a read-only named constant.\nConstants are block-scoped, much like variables defined using the 'let' statement.\nThe value of a constant can't be changed through reassignment, and it can't be redeclared.
\n", "itemtype": "property", "name": "const", "example": [ "\n\n// define myFavNumber as a constant and give it the value 7\nconst myFavNumber = 7;\nconsole.log('my favorite number is: ' + myFavNumber);\n
\n\nconst bigCats = ['lion', 'tiger', 'panther'];\nbigCats.push('leopard');\nconsole.log(bigCats);\n// bigCats = ['cat']; // throws error as re-assigning not allowed for const\n
\n\nconst wordFrequency = {};\nwordFrequency['hello'] = 2;\nwordFrequency['bye'] = 1;\nconsole.log(wordFrequency);\n// wordFrequency = { 'a': 2, 'b': 3}; // throws error here\n
\nThe strict equality operator ===\nchecks to see if two values are equal and of the same type.
\nA comparison expression always evaluates to a boolean.
\nFrom the MDN entry:\nThe non-identity operator returns true if the operands are not equal and/or not of the same type.
\nNote: In some examples around the web you may see a double-equals-sign\n==,\nused for comparison instead. This is the non-strict equality operator in Javascript.\nThis will convert the two values being compared to the same type before comparing them.
\n", "itemtype": "property", "name": "===", "example": [ "\n\nconsole.log(1 === 1); // prints true to the console\nconsole.log(1 === '1'); // prints false to the console\n
\nThe greater than operator \">>\nevaluates to true if the left value is greater than\nthe right value.
\n\nThere is more info on comparison operators on MDN.", "itemtype": "property", "name": ">", "example": [ "\n\nconsole.log(100 > 1); // prints true to the console\nconsole.log(1 > 100); // prints false to the console\n
\nThe greater than or equal to operator =\">>=\nevaluates to true if the left value is greater than or equal to\nthe right value.
\nThere is more info on comparison operators on MDN.
\n", "itemtype": "property", "name": ">=", "example": [ "\n\nconsole.log(100 >= 100); // prints true to the console\nconsole.log(101 >= 100); // prints true to the console\n
\nThe less than operator <\nevaluates to true if the left value is less than\nthe right value.
\nThere is more info on comparison operators on MDN.
\n", "itemtype": "property", "name": "<", "example": [ "\n\nconsole.log(1 < 100); // prints true to the console\nconsole.log(100 < 99); // prints false to the console\n
\nThe less than or equal to operator <=\nevaluates to true if the left value is less than or equal to\nthe right value.
\nThere is more info on comparison operators on MDN.
\n", "itemtype": "property", "name": "<=", "example": [ "\n\nconsole.log(100 <= 100); // prints true to the console\nconsole.log(99 <= 100); // prints true to the console\n
\nThe if-else statement helps control the flow of your code.
\nA condition is placed between the parenthesis following 'if',\nwhen that condition evalues to truthy,\nthe code between the following curly braces is run.\nAlternatively, when the condition evaluates to falsy,\nthe code between the curly braces of 'else' block is run instead. Writing an\nelse block is optional.
\nFrom the MDN entry:\nThe 'if' statement executes a statement if a specified condition is truthy.\nIf the condition is falsy, another statement can be executed
\n", "itemtype": "property", "name": "if-else", "example": [ "\n\nlet a = 4;\nif (a > 0) {\n console.log('positive');\n} else {\n console.log('negative');\n}\n
\nCreates and names a function.\nA function is a set of statements that perform a task.
\nOptionally, functions can have parameters. Parameters\nare variables that are scoped to the function, that can be assigned a value\nwhen calling the function.Multiple parameters can be given by seperating them\nwith commmas.
\nFrom the MDN entry:\nDeclares a function with the specified parameters.
\n", "itemtype": "property", "name": "function", "example": [ "\n\nlet myName = 'Hridi';\nfunction sayHello(name) {\n console.log('Hello ' + name + '!');\n}\nsayHello(myName); // calling the function, prints \"Hello Hridi!\" to console.\n
\n\nlet square = number => number * number;\nconsole.log(square(5));\n
\nSpecifies the value to be returned by a function.\nFor more info checkout \nthe MDN entry for return.
\n", "itemtype": "property", "name": "return", "example": [ "\n\nfunction calculateSquare(x) {\n return x * x;\n}\nconst result = calculateSquare(4); // returns 16\nconsole.log(result); // prints '16' to the console\n
\nA boolean is one of the 7 primitive data types in Javascript.\nA boolean can only be true
or false
.
From the MDN entry:\nBoolean represents a logical entity and can have two values: true, and false.
\n", "itemtype": "property", "name": "boolean", "example": [ "\n\nlet myBoolean = false;\nconsole.log(typeof myBoolean); // prints 'boolean' to the console\n
\nA string is one of the 7 primitive data types in Javascript.\nA string is a series of text characters. In Javascript, a string value must\nbe surrounded by either single-quotation marks(') or double-quotation marks(\").
\nFrom the MDN entry:\nA string is a sequence of characters used to represent text.
\n", "itemtype": "property", "name": "string", "example": [ "\n\nlet mood = 'chill';\nconsole.log(typeof mood); // prints 'string' to the console\n
\nA number is one of the 7 primitive data types in Javascript.\nA number can be a whole number or a decimal number.
\n\n", "itemtype": "property", "name": "number", "example": [ "\n\nlet num = 46.5;\nconsole.log(typeof num); // prints 'number' to the console\n
\nFrom MDN's object basics:\n An object is a collection of related data and/or\n functionality (which usually consists of several variables and functions —\n which are called properties and methods when they are inside objects.)
\n", "itemtype": "property", "name": "object", "example": [ "\n\n let author = {\n name: 'Ursula K Le Guin',\n books: [\n 'The Left Hand of Darkness',\n 'The Dispossessed',\n 'A Wizard of Earthsea'\n ]\n };\n console.log(author.name); // prints 'Ursula K Le Guin' to the console\n
\n Creates and names a class which is a template for\nthe creation of objects.
\nFrom the MDN entry:\nThe class declaration creates a new Class with a given name using\nprototype-based inheritance.
\n", "itemtype": "property", "name": "class", "example": [ "\n\nclass Rectangle {\n constructor(name, height, width) {\n this.name = name;\n this.height = height;\n this.width = width;\n }\n}\nlet square = new Rectangle('square', 1, 1); // creating new instance of Polygon Class.\nconsole.log(square.width); // prints '1' to the console\n
\nfor creates a loop that is useful for executing one\nsection of code multiple times.
\nA 'for loop' consists of three different expressions inside of a parenthesis,\nall of which are optional.These expressions are used to control the number of\ntimes the loop is run.The first expression is a statement that is used to set\nthe initial state for the loop.The second expression is a condition that you\nwould like to check before each loop. If this expression returns false then\nthe loop will exit.The third expression is executed at the end of each loop.\nThese expression are separated by ; (semi-colon).In case of an empty expression,\nonly a semi-colon is written.
\nThe code inside of the loop body (in between the curly braces) is executed between the evaluation of the second\nand third expression.
\nAs with any loop, it is important to ensure that the loop can 'exit', or that\nthe test condition will eventually evaluate to false. The test condition with a for loop\nis the second expression detailed above. Ensuring that this expression can eventually\nbecome false ensures that your loop doesn't attempt to run an infinite amount of times,\nwhich can crash your browser.
\nFrom the MDN entry:\nCreates a loop that executes a specified statement until the test condition evaluates to false.\nThe condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
\n", "itemtype": "property", "name": "for", "example": [ "\n\nfor (let i = 0; i < 9; i++) {\n console.log(i);\n}\n
\nwhile creates a loop that is useful for executing\none section of code multiple times.
\nWith a 'while loop', the code inside of the loop body (between the curly\nbraces) is run repeatedly until the test condition (inside of the parenthesis)\nevaluates to false. The condition is tested before executing the code body\nwith while, so if the condition is initially false\nthe loop body, or statement, will never execute.
\nAs with any loop, it is important to ensure that the loop can 'exit', or that\nthe test condition will eventually evaluate to false. This is to keep your loop\nfrom trying to run an infinite amount of times, which can crash your browser.
\nFrom the MDN entry:\nThe while statement creates a loop that executes a specified statement as long\nas the test condition evaluates to true.The condition is evaluated before\nexecuting the statement.
\n", "itemtype": "property", "name": "while", "example": [ "\n\n// This example logs the lines below to the console\n// 4\n// 3\n// 2\n// 1\n// 0\nlet num = 5;\nwhile (num > 0) {\n num = num - 1;\n console.log(num);\n}\n
\nFrom the MDN entry:\nThe JSON.stringify() method converts a JavaScript object or value to a JSON string.
\n", "itemtype": "method", "name": "stringify", "static": 1, "params": [ { "name": "object", "description": ":Javascript object that you would like to convert to JSON
\n", "type": "Object" } ], "example": [ "\n\nlet myObject = { x: 5, y: 6 };\nlet myObjectAsString = JSON.stringify(myObject);\nconsole.log(myObjectAsString); // prints \"{\"x\":5,\"y\":6}\" to the console\nconsole.log(typeof myObjectAsString); // prints 'string' to the console\n
\nPrints a message to your browser's web console. When using p5, you can use print\nand console.log interchangeably.
\nThe console is opened differently depending on which browser you are using.\nHere are links on how to open the console in Firefox\n, Chrome, Edge,\nand Safari.\nWith the online p5 editor the console\nis embedded directly in the page underneath the code editor.
\nFrom the MDN entry:\nThe Console method log() outputs a message to the web console. The message may\nbe a single string (with optional substitution values),\nor it may be any one or more JavaScript objects.
\n", "itemtype": "method", "name": "log", "static": 1, "params": [ { "name": "message", "description": ":Message that you would like to print to the console
\n", "type": "String|Expression|Object" } ], "example": [ "\n\nlet myNum = 5;\nconsole.log(myNum); // prints 5 to the console\nconsole.log(myNum + 12); // prints 17 to the console\n
\nCreates a canvas element in the document and sets its dimensions\nin pixels. This method should be called only once at the start of setup().\nCalling createCanvas more than once in a\nsketch will result in very unpredictable behavior. If you want more than\none drawing canvas you could use createGraphics()\n(hidden by default but it can be shown).
\nImportant note: in 2D mode (i.e. when p5.Renderer
is not set) the origin (0,0)\nis positioned at the top left of the screen. In 3D mode (i.e. when p5.Renderer
\nis set to WEBGL
), the origin is positioned at the center of the canvas.\nSee this issue for more information.
The system variables width and height are set by the parameters passed to this\nfunction. If createCanvas() is not used, the\nwindow will be given a default size of 100×100 pixels.
\nFor more ways to position the canvas, see the\n\npositioning the canvas wiki page.
\n", "itemtype": "method", "name": "createCanvas", "params": [ { "name": "w", "description": "width of the canvas
\n", "type": "Number" }, { "name": "h", "description": "height of the canvas
\n", "type": "Number" }, { "name": "renderer", "description": "either P2D or WEBGL
\n", "type": "Constant", "optional": true } ], "return": { "description": "pointer to p5.Renderer holding canvas", "type": "p5.Renderer" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 50);\n background(153);\n line(0, 0, width, height);\n}\n
\nResizes the canvas to given width and height. The canvas will be cleared\nand draw will be called immediately, allowing the sketch to re-render itself\nin the resized canvas.
\n", "itemtype": "method", "name": "resizeCanvas", "params": [ { "name": "w", "description": "width of the canvas
\n", "type": "Number" }, { "name": "h", "description": "height of the canvas
\n", "type": "Number" }, { "name": "noRedraw", "description": "don't redraw the canvas immediately
\n", "type": "Boolean", "optional": true } ], "example": [ "\n\nfunction setup() {\n createCanvas(windowWidth, windowHeight);\n}\n\nfunction draw() {\n background(0, 100, 200);\n}\n\nfunction windowResized() {\n resizeCanvas(windowWidth, windowHeight);\n}\n
Removes the default canvas for a p5 sketch that doesn't require a canvas
\n", "itemtype": "method", "name": "noCanvas", "example": [ "\n\nfunction setup() {\n noCanvas();\n}\n
\nCreates and returns a new p5.Renderer object. Use this class if you need\nto draw into an off-screen graphics buffer. The two parameters define the\nwidth and height in pixels.
\n", "itemtype": "method", "name": "createGraphics", "params": [ { "name": "w", "description": "width of the offscreen graphics buffer
\n", "type": "Number" }, { "name": "h", "description": "height of the offscreen graphics buffer
\n", "type": "Number" }, { "name": "renderer", "description": "either P2D or WEBGL\n undefined defaults to p2d
\n", "type": "Constant", "optional": true } ], "return": { "description": "offscreen graphics buffer", "type": "p5.Graphics" }, "example": [ "\n\nlet pg;\nfunction setup() {\n createCanvas(100, 100);\n pg = createGraphics(100, 100);\n}\n\nfunction draw() {\n background(200);\n pg.background(100);\n pg.noStroke();\n pg.ellipse(pg.width / 2, pg.height / 2, 50, 50);\n image(pg, 50, 50);\n image(pg, 0, 0, 50, 50);\n}\n
\nBlends the pixels in the display window according to the defined mode.\nThere is a choice of the following modes to blend the source pixels (A)\nwith the ones of pixels already in the display window (B):
\nBLEND
- linear interpolation of colours: C =\nA*factor + B. This is the default blending mode.ADD
- sum of A and BDARKEST
- only the darkest colour succeeds: C =\nmin(A*factor, B).LIGHTEST
- only the lightest colour succeeds: C =\nmax(A*factor, B).DIFFERENCE
- subtract colors from underlying image.\n(2D)EXCLUSION
- similar to DIFFERENCE
, but less\nextreme.MULTIPLY
- multiply the colors, result will always be\ndarker.SCREEN
- opposite multiply, uses inverse values of the\ncolors.REPLACE
- the pixels entirely replace the others and\ndon't utilize alpha (transparency) values.REMOVE
- removes pixels from B with the alpha strength of A.OVERLAY
- mix of MULTIPLY
and SCREEN\n
. Multiplies dark values, and screens light values. (2D)HARD_LIGHT
- SCREEN
when greater than 50%\ngray, MULTIPLY
when lower. (2D)SOFT_LIGHT
- mix of DARKEST
and\nLIGHTEST
. Works like OVERLAY
, but not as harsh. (2D)\nDODGE
- lightens light tones and increases contrast,\nignores darks. (2D)BURN
- darker areas are applied, increasing contrast,\nignores lights. (2D)SUBTRACT
- remainder of A and B (3D)(2D) indicates that this blend mode only works in the 2D renderer.
\n(3D) indicates that this blend mode only works in the WEBGL renderer.
blend mode to set for canvas.\n either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY,\n EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD, REMOVE or SUBTRACT
\n", "type": "Constant" } ], "example": [ "\n\nblendMode(LIGHTEST);\nstrokeWeight(30);\nstroke(80, 150, 255);\nline(25, 25, 75, 75);\nstroke(255, 50, 50);\nline(75, 25, 25, 75);\n
\n\nblendMode(MULTIPLY);\nstrokeWeight(30);\nstroke(80, 150, 255);\nline(25, 25, 75, 75);\nstroke(255, 50, 50);\nline(75, 25, 25, 75);\n
\nThe p5.js API provides a lot of functionality for creating graphics, but there is\nsome native HTML5 Canvas functionality that is not exposed by p5. You can still call\nit directly using the variable drawingContext
, as in the example shown. This is\nthe equivalent of calling canvas.getContext('2d');
or canvas.getContext('webgl');
.\nSee this\n\nreference for the native canvas API for possible drawing functions you can call.
\nfunction setup() {\n drawingContext.shadowOffsetX = 5;\n drawingContext.shadowOffsetY = -5;\n drawingContext.shadowBlur = 10;\n drawingContext.shadowColor = 'black';\n background(200);\n ellipse(width / 2, height / 2, 50, 50);\n}\n
\nshim for Uint8ClampedArray.slice\n(allows arrayCopy to work with pixels[])\nwith thanks to http://halfpapstudios.com/blog/tag/html5-canvas/\nEnumerable set to false to protect for...in from\nUint8ClampedArray.prototype pollution.
\n", "class": "p5", "module": "Rendering" }, { "file": "src/core/shim.js", "line": 39, "description": "this is implementation of Object.assign() which is unavailable in\nIE11 and (non-Chrome) Android browsers.\nThe assign() method is used to copy the values of all enumerable\nown properties from one or more source objects to a target object.\nIt will return the target object.\nModified from https://github.com/ljharb/object.assign
\n", "class": "p5", "module": "Rendering" }, { "file": "src/core/structure.js", "line": 10, "description": "Stops p5.js from continuously executing the code within draw().\nIf loop() is called, the code in draw()\nbegins to run continuously again. If using noLoop()\nin setup(), it should be the last line inside the block.
\nWhen noLoop() is used, it's not possible to manipulate\nor access the screen inside event handling functions such as\nmousePressed() or\nkeyPressed(). Instead, use those functions to\ncall redraw() or loop(),\nwhich will run draw(), which can update the screen\nproperly. This means that when noLoop() has been\ncalled, no drawing can happen, and functions like saveFrames()\nor loadPixels() may not be used.
\nNote that if the sketch is resized, redraw() will\nbe called to update the sketch, even after noLoop()\nhas been specified. Otherwise, the sketch would enter an odd state until\nloop() was called.
\nUse isLooping() to check the current state of loop().
\n", "itemtype": "method", "name": "noLoop", "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n noLoop();\n}\n\nfunction draw() {\n line(10, 10, 90, 90);\n}\n
\n\nlet x = 0;\nfunction setup() {\n createCanvas(100, 100);\n}\n\nfunction draw() {\n background(204);\n x = x + 0.1;\n if (x > width) {\n x = 0;\n }\n line(x, 0, x, height);\n}\n\nfunction mousePressed() {\n noLoop();\n}\n\nfunction mouseReleased() {\n loop();\n}\n
\nBy default, p5.js loops through draw() continuously, executing the code within\nit. However, the draw() loop may be stopped by calling\nnoLoop(). In that case, the draw()\nloop can be resumed with loop().
\nAvoid calling loop() from inside setup().
\nUse isLooping() to check the current state of loop().
\n", "itemtype": "method", "name": "loop", "example": [ "\n\nlet x = 0;\nfunction setup() {\n createCanvas(100, 100);\n noLoop();\n}\n\nfunction draw() {\n background(204);\n x = x + 0.1;\n if (x > width) {\n x = 0;\n }\n line(x, 0, x, height);\n}\n\nfunction mousePressed() {\n loop();\n}\n\nfunction mouseReleased() {\n noLoop();\n}\n
\nBy default, p5.js loops through draw() continuously,\nexecuting the code within it. If the sketch is stopped with\nnoLoop() or resumed with loop(),\nisLooping() returns the current state for use within custom event handlers.
\n", "itemtype": "method", "name": "isLooping", "return": { "description": "", "type": "Boolean" }, "example": [ "\n\nlet checkbox, button, colBG, colFill;\n\nfunction setup() {\n createCanvas(100, 100);\n\n button = createButton('Colorize if loop()');\n button.position(0, 120);\n button.mousePressed(changeBG);\n\n checkbox = createCheckbox('loop()', true);\n checkbox.changed(checkLoop);\n\n colBG = color(0);\n colFill = color(255);\n}\n\nfunction changeBG() {\n if (isLooping()) {\n colBG = color(random(255), random(255), random(255));\n colFill = color(random(255), random(255), random(255));\n }\n}\n\nfunction checkLoop() {\n if (this.checked()) {\n loop();\n } else {\n noLoop();\n }\n}\n\nfunction draw() {\n background(colBG);\n fill(colFill);\n ellipse(frameCount % width, height / 2, 50);\n}\n
\nThe push() function saves the current drawing style\nsettings and transformations, while pop() restores these\nsettings. Note that these functions are always used together. They allow you to\nchange the style and transformation settings and later return to what you had.\nWhen a new state is started with push(), it builds on\nthe current style and transform information. The push()\nand pop() functions can be embedded to provide more\ncontrol. (See the second example for a demonstration.)
\npush() stores information related to the current transformation state\nand style settings controlled by the following functions:\nfill(),\nnoFill(),\nnoStroke(),\nstroke(),\ntint(),\nnoTint(),\nstrokeWeight(),\nstrokeCap(),\nstrokeJoin(),\nimageMode(),\nrectMode(),\nellipseMode(),\ncolorMode(),\ntextAlign(),\ntextFont(),\ntextSize(),\ntextLeading(),\napplyMatrix(),\nresetMatrix(),\nrotate(),\nscale(),\nshearX(),\nshearY(),\ntranslate(),\nnoiseSeed().
\nIn WEBGL mode additional style settings are stored. These are controlled by the\nfollowing functions: setCamera(),\nambientLight(),\ndirectionalLight(),\npointLight(), texture(),\nspecularMaterial(),\nshininess(),\nnormalMaterial()\nand shader().
\n", "itemtype": "method", "name": "push", "example": [ "\n\nellipse(0, 50, 33, 33); // Left circle\n\npush(); // Start a new drawing state\nstrokeWeight(10);\nfill(204, 153, 0);\ntranslate(50, 0);\nellipse(0, 50, 33, 33); // Middle circle\npop(); // Restore original state\n\nellipse(100, 50, 33, 33); // Right circle\n
\n\nellipse(0, 50, 33, 33); // Left circle\n\npush(); // Start a new drawing state\nstrokeWeight(10);\nfill(204, 153, 0);\nellipse(33, 50, 33, 33); // Left-middle circle\n\npush(); // Start another new drawing state\nstroke(0, 102, 153);\nellipse(66, 50, 33, 33); // Right-middle circle\npop(); // Restore previous state\n\npop(); // Restore original state\n\nellipse(100, 50, 33, 33); // Right circle\n
\nThe push() function saves the current drawing style\nsettings and transformations, while pop() restores\nthese settings. Note that these functions are always used together. They allow\nyou to change the style and transformation settings and later return to what\nyou had. When a new state is started with push(), it\nbuilds on the current style and transform information. The push()\nand pop() functions can be embedded to provide more\ncontrol. (See the second example for a demonstration.)
\npush() stores information related to the current transformation state\nand style settings controlled by the following functions:\nfill(),\nnoFill(),\nnoStroke(),\nstroke(),\ntint(),\nnoTint(),\nstrokeWeight(),\nstrokeCap(),\nstrokeJoin(),\nimageMode(),\nrectMode(),\nellipseMode(),\ncolorMode(),\ntextAlign(),\ntextFont(),\ntextSize(),\ntextLeading(),\napplyMatrix(),\nresetMatrix(),\nrotate(),\nscale(),\nshearX(),\nshearY(),\ntranslate(),\nnoiseSeed().
\nIn WEBGL mode additional style settings are stored. These are controlled by\nthe following functions:\nsetCamera(),\nambientLight(),\ndirectionalLight(),\npointLight(),\ntexture(),\nspecularMaterial(),\nshininess(),\nnormalMaterial() and\nshader().
\n", "itemtype": "method", "name": "pop", "example": [ "\n\nellipse(0, 50, 33, 33); // Left circle\n\npush(); // Start a new drawing state\ntranslate(50, 0);\nstrokeWeight(10);\nfill(204, 153, 0);\nellipse(0, 50, 33, 33); // Middle circle\npop(); // Restore original state\n\nellipse(100, 50, 33, 33); // Right circle\n
\n\nellipse(0, 50, 33, 33); // Left circle\n\npush(); // Start a new drawing state\nstrokeWeight(10);\nfill(204, 153, 0);\nellipse(33, 50, 33, 33); // Left-middle circle\n\npush(); // Start another new drawing state\nstroke(0, 102, 153);\nellipse(66, 50, 33, 33); // Right-middle circle\npop(); // Restore previous state\n\npop(); // Restore original state\n\nellipse(100, 50, 33, 33); // Right circle\n
\nExecutes the code within draw() one time. This\nfunction allows the program to update the display window only when necessary,\nfor example when an event registered by mousePressed()\nor keyPressed() occurs.
\nIn structuring a program, it only makes sense to call redraw()\nwithin events such as mousePressed(). This\nis because redraw() does not run\ndraw() immediately (it only sets a flag that indicates\nan update is needed).
\nThe redraw() function does not work properly when\ncalled inside draw().To enable/disable animations,\nuse loop() and noLoop().
\nIn addition you can set the number of redraws per method call. Just\nadd an integer as single parameter for the number of redraws.
\n", "itemtype": "method", "name": "redraw", "params": [ { "name": "n", "description": "Redraw for n-times. The default value is 1.
\n", "type": "Integer", "optional": true } ], "example": [ "\n\nlet x = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n noLoop();\n}\n\nfunction draw() {\n background(204);\n line(x, 0, x, height);\n}\n\nfunction mousePressed() {\n x += 1;\n redraw();\n}\n
\n\nlet x = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n noLoop();\n}\n\nfunction draw() {\n background(204);\n x += 1;\n line(x, 0, x, height);\n}\n\nfunction mousePressed() {\n redraw(5);\n}\n
\nThe p5()
constructor enables you to activate \"instance mode\" instead of normal\n\"global mode\". This is an advanced topic. A short description and example is\nincluded below. Please see\n\nDan Shiffman's Coding Train video tutorial or this\ntutorial page\nfor more info.
By default, all p5.js functions are in the global namespace (i.e. bound to the window\nobject), meaning you can call them simply ellipse()
, fill()
, etc. However, this\nmight be inconvenient if you are mixing with other JS libraries (synchronously or\nasynchronously) or writing long programs of your own. p5.js currently supports a\nway around this problem called \"instance mode\". In instance mode, all p5 functions\nare bound up in a single variable instead of polluting your global namespace.
Optionally, you can specify a default container for the canvas and any other elements\nto append to with a second argument. You can give the ID of an element in your html,\nor an html node itself.
\nNote that creating instances like this also allows you to have more than one p5 sketch on\na single web page, as they will each be wrapped up with their own set up variables. Of\ncourse, you could also use iframes to have multiple sketches in global mode.
\n", "itemtype": "method", "name": "p5", "params": [ { "name": "sketch", "description": "a function containing a p5.js sketch
\n", "type": "Object" }, { "name": "node", "description": "ID or pointer to HTML DOM node to contain sketch in
\n", "type": "String|Object" } ], "example": [ "\n\nconst s = p => {\n let x = 100;\n let y = 100;\n\n p.setup = function() {\n p.createCanvas(700, 410);\n };\n\n p.draw = function() {\n p.background(0);\n p.fill(255);\n p.rect(x, y, 50, 50);\n };\n};\n\nnew p5(s); // invoke p5\n
Multiplies the current matrix by the one specified through the parameters.\nThis is a powerful operation that can perform the equivalent of translate,\nscale, shear and rotate all at once. You can learn more about transformation\nmatrices on \nWikipedia.
\nThe naming of the arguments here follows the naming of the \nWHATWG specification and corresponds to a\ntransformation matrix of the\nform:
\n\n\n\n
\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n let step = frameCount % 20;\n background(200);\n // Equivalent to translate(x, y);\n applyMatrix(1, 0, 0, 1, 40 + step, 50);\n rect(0, 0, 50, 50);\n}\n
\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n let step = frameCount % 20;\n background(200);\n translate(50, 50);\n // Equivalent to scale(x, y);\n applyMatrix(1 / step, 0, 0, 1 / step, 0, 0);\n rect(0, 0, 50, 50);\n}\n
\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n let step = frameCount % 20;\n let angle = map(step, 0, 20, 0, TWO_PI);\n let cos_a = cos(angle);\n let sin_a = sin(angle);\n background(200);\n translate(50, 50);\n // Equivalent to rotate(angle);\n applyMatrix(cos_a, sin_a, -sin_a, cos_a, 0, 0);\n rect(0, 0, 50, 50);\n}\n
\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n let step = frameCount % 20;\n let angle = map(step, 0, 20, -PI / 4, PI / 4);\n background(200);\n translate(50, 50);\n // equivalent to shearX(angle);\n let shear_factor = 1 / tan(PI / 2 - angle);\n applyMatrix(1, 0, shear_factor, 1, 0, 0);\n rect(0, 0, 50, 50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noFill();\n}\n\nfunction draw() {\n background(200);\n rotateY(PI / 6);\n stroke(153);\n box(35);\n let rad = millis() / 1000;\n // Set rotation angles\n let ct = cos(rad);\n let st = sin(rad);\n // Matrix for rotation around the Y axis\n applyMatrix(\n ct, 0.0, st, 0.0,\n 0.0, 1.0, 0.0, 0.0,\n -st, 0.0, ct, 0.0,\n 0.0, 0.0, 0.0, 1.0\n );\n stroke(255);\n box(50);\n}\n
\n\nfunction draw() {\n background(200);\n let testMatrix = [1, 0, 0, 1, 0, 0];\n applyMatrix(testMatrix);\n rect(0, 0, 50, 50);\n}\n
\nan array of numbers - should be 6 or 16 length (23 or 44 matrix values)
\n", "type": "Array" } ], "chainable": 1 }, { "line": 157, "params": [ { "name": "a", "description": "numbers which define the 2×3 or 4x4 matrix to be multiplied
\n", "type": "Number" }, { "name": "b", "description": "numbers which define the 2×3 or 4x4 matrix to be multiplied
\n", "type": "Number" }, { "name": "c", "description": "numbers which define the 2×3 or 4x4 matrix to be multiplied
\n", "type": "Number" }, { "name": "d", "description": "numbers which define the 2×3 or 4x4 matrix to be multiplied
\n", "type": "Number" }, { "name": "e", "description": "numbers which define the 2×3 or 4x4 matrix to be multiplied
\n", "type": "Number" }, { "name": "f", "description": "numbers which define the 2×3 or 4x4 matrix to be multiplied
\n", "type": "Number" } ], "chainable": 1 }, { "line": 167, "params": [ { "name": "a", "description": "", "type": "Number" }, { "name": "b", "description": "", "type": "Number" }, { "name": "c", "description": "", "type": "Number" }, { "name": "d", "description": "", "type": "Number" }, { "name": "e", "description": "", "type": "Number" }, { "name": "f", "description": "", "type": "Number" }, { "name": "g", "description": "numbers which define the 4x4 matrix to be multiplied
\n", "type": "Number" }, { "name": "h", "description": "numbers which define the 4x4 matrix to be multiplied
\n", "type": "Number" }, { "name": "i", "description": "numbers which define the 4x4 matrix to be multiplied
\n", "type": "Number" }, { "name": "j", "description": "numbers which define the 4x4 matrix to be multiplied
\n", "type": "Number" }, { "name": "k", "description": "numbers which define the 4x4 matrix to be multiplied
\n", "type": "Number" }, { "name": "l", "description": "numbers which define the 4x4 matrix to be multiplied
\n", "type": "Number" }, { "name": "m", "description": "numbers which define the 4x4 matrix to be multiplied
\n", "type": "Number" }, { "name": "n", "description": "numbers which define the 4x4 matrix to be multiplied
\n", "type": "Number" }, { "name": "o", "description": "numbers which define the 4x4 matrix to be multiplied
\n", "type": "Number" }, { "name": "p", "description": "numbers which define the 4x4 matrix to be multiplied
\n", "type": "Number" } ], "chainable": 1 } ] }, { "file": "src/core/transform.js", "line": 197, "description": "Replaces the current matrix with the identity matrix.
\n", "itemtype": "method", "name": "resetMatrix", "chainable": 1, "example": [ "\n\ntranslate(50, 50);\napplyMatrix(0.5, 0.5, -0.5, 0.5, 0, 0);\nrect(0, 0, 20, 20);\n// Note that the translate is also reset.\nresetMatrix();\nrect(0, 0, 20, 20);\n
\nRotates a shape by the amount specified by the angle parameter. This\nfunction accounts for angleMode, so angles\ncan be entered in either RADIANS or DEGREES.
\nObjects are always rotated around their relative position to the\norigin and positive numbers rotate objects in a clockwise direction.\nTransformations apply to everything that happens after and subsequent\ncalls to the function accumulate the effect. For example, calling\nrotate(HALF_PI) and then rotate(HALF_PI) is the same as rotate(PI).\nAll transformations are reset when draw() begins again.
\nTechnically, rotate() multiplies the current transformation matrix\nby a rotation matrix. This function can be further controlled by\npush() and pop().
\n", "itemtype": "method", "name": "rotate", "params": [ { "name": "angle", "description": "the angle of rotation, specified in radians\n or degrees, depending on current angleMode
\n", "type": "Number" }, { "name": "axis", "description": "(in 3d) the axis to rotate around
\n", "type": "p5.Vector|Number[]", "optional": true } ], "chainable": 1, "example": [ "\n\ntranslate(width / 2, height / 2);\nrotate(PI / 3.0);\nrect(-26, -26, 52, 52);\n
\nRotates a shape around X axis by the amount specified in angle parameter.\nThe angles can be entered in either RADIANS or DEGREES.
\nObjects are always rotated around their relative position to the\norigin and positive numbers rotate objects in a clockwise direction.\nAll transformations are reset when draw() begins again.
\n", "itemtype": "method", "name": "rotateX", "params": [ { "name": "angle", "description": "the angle of rotation, specified in radians\n or degrees, depending on current angleMode
\n", "type": "Number" } ], "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(255);\n rotateX(millis() / 1000);\n box();\n}\n
\nRotates a shape around Y axis by the amount specified in angle parameter.\nThe angles can be entered in either RADIANS or DEGREES.
\nObjects are always rotated around their relative position to the\norigin and positive numbers rotate objects in a clockwise direction.\nAll transformations are reset when draw() begins again.
\n", "itemtype": "method", "name": "rotateY", "params": [ { "name": "angle", "description": "the angle of rotation, specified in radians\n or degrees, depending on current angleMode
\n", "type": "Number" } ], "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(255);\n rotateY(millis() / 1000);\n box();\n}\n
\nRotates a shape around Z axis by the amount specified in angle parameter.\nThe angles can be entered in either RADIANS or DEGREES.
\nThis method works in WEBGL mode only.
\nObjects are always rotated around their relative position to the\norigin and positive numbers rotate objects in a clockwise direction.\nAll transformations are reset when draw() begins again.
\n", "itemtype": "method", "name": "rotateZ", "params": [ { "name": "angle", "description": "the angle of rotation, specified in radians\n or degrees, depending on current angleMode
\n", "type": "Number" } ], "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(255);\n rotateZ(millis() / 1000);\n box();\n}\n
\nIncreases or decreases the size of a shape by expanding or contracting\nvertices. Objects always scale from their relative origin to the\ncoordinate system. Scale values are specified as decimal percentages.\nFor example, the function call scale(2.0) increases the dimension of a\nshape by 200%.
\nTransformations apply to everything that happens after and subsequent\ncalls to the function multiply the effect. For example, calling scale(2.0)\nand then scale(1.5) is the same as scale(3.0). If scale() is called\nwithin draw(), the transformation is reset when the loop begins again.
\nUsing this function with the z parameter is only available in WEBGL mode.\nThis function can be further controlled with push() and pop().
\n", "itemtype": "method", "name": "scale", "chainable": 1, "example": [ "\n\nrect(30, 20, 50, 50);\nscale(0.5);\nrect(30, 20, 50, 50);\n
\n\nrect(30, 20, 50, 50);\nscale(0.5, 1.3);\nrect(30, 20, 50, 50);\n
\npercent to scale the object, or percentage to\n scale the object in the x-axis if multiple arguments\n are given
\n", "type": "Number|p5.Vector|Number[]" }, { "name": "y", "description": "percent to scale the object in the y-axis
\n", "type": "Number", "optional": true }, { "name": "z", "description": "percent to scale the object in the z-axis (webgl only)
\n", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 415, "params": [ { "name": "scales", "description": "per-axis percents to scale the object
\n", "type": "p5.Vector|Number[]" } ], "chainable": 1 } ] }, { "file": "src/core/transform.js", "line": 445, "description": "Shears a shape around the x-axis by the amount specified by the angle\nparameter. Angles should be specified in the current angleMode.\nObjects are always sheared around their relative position to the origin\nand positive numbers shear objects in a clockwise direction.
\nTransformations apply to everything that happens after and subsequent\ncalls to the function accumulates the effect. For example, calling\nshearX(PI/2) and then shearX(PI/2) is the same as shearX(PI).\nIf shearX() is called within the draw(),\nthe transformation is reset when the loop begins again.
\nTechnically, shearX() multiplies the current\ntransformation matrix by a rotation matrix. This function can be further\ncontrolled by the push() and pop() functions.
\n", "itemtype": "method", "name": "shearX", "params": [ { "name": "angle", "description": "angle of shear specified in radians or degrees,\n depending on current angleMode
\n", "type": "Number" } ], "chainable": 1, "example": [ "\n\ntranslate(width / 4, height / 4);\nshearX(PI / 4.0);\nrect(0, 0, 30, 30);\n
\nShears a shape around the y-axis the amount specified by the angle\nparameter. Angles should be specified in the current angleMode. Objects\nare always sheared around their relative position to the origin and\npositive numbers shear objects in a clockwise direction.
\nTransformations apply to everything that happens after and subsequent\ncalls to the function accumulates the effect. For example, calling\nshearY(PI/2) and then shearY(PI/2) is the same as shearY(PI). If\nshearY() is called within the draw(), the transformation is reset when\nthe loop begins again.
\nTechnically, shearY() multiplies the current transformation matrix by a\nrotation matrix. This function can be further controlled by the\npush() and pop() functions.
\n", "itemtype": "method", "name": "shearY", "params": [ { "name": "angle", "description": "angle of shear specified in radians or degrees,\n depending on current angleMode
\n", "type": "Number" } ], "chainable": 1, "example": [ "\n\ntranslate(width / 4, height / 4);\nshearY(PI / 4.0);\nrect(0, 0, 30, 30);\n
\nSpecifies an amount to displace objects within the display window.\nThe x parameter specifies left/right translation, the y parameter\nspecifies up/down translation.
\nTransformations are cumulative and apply to everything that happens after\nand subsequent calls to the function accumulates the effect. For example,\ncalling translate(50, 0) and then translate(20, 0) is the same as\ntranslate(70, 0). If translate() is called within draw(), the\ntransformation is reset when the loop begins again. This function can be\nfurther controlled by using push() and pop().
\n", "itemtype": "method", "name": "translate", "chainable": 1, "example": [ "\n\ntranslate(30, 20);\nrect(0, 0, 55, 55);\n
\n\nrect(0, 0, 55, 55); // Draw rect at original 0,0\ntranslate(30, 20);\nrect(0, 0, 55, 55); // Draw rect at new 0,0\ntranslate(14, 14);\nrect(0, 0, 55, 55); // Draw rect at new 0,0\n
\n\nfunction draw() {\n background(200);\n rectMode(CENTER);\n translate(width / 2, height / 2);\n translate(p5.Vector.fromAngle(millis() / 1000, 40));\n rect(0, 0, 20, 20);\n}\n
\nleft/right translation
\n", "type": "Number" }, { "name": "y", "description": "up/down translation
\n", "type": "Number" }, { "name": "z", "description": "forward/backward translation (WEBGL only)
\n", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 576, "params": [ { "name": "vector", "description": "the vector to translate by
\n", "type": "p5.Vector" } ], "chainable": 1 } ] }, { "file": "src/data/local_storage.js", "line": 10, "description": "Stores a value in local storage under the key name.\n Local storage is saved in the browser and persists\n between browsing sessions and page reloads.\n The key can be the name of the variable but doesn't\n have to be. To retrieve stored items\n see getItem.\nSensitive data such as passwords or personal information\n should not be stored in local storage.
\n", "itemtype": "method", "name": "storeItem", "params": [ { "name": "key", "description": "", "type": "String" }, { "name": "value", "description": "", "type": "String|Number|Object|Boolean|p5.Color|p5.Vector" } ], "example": [ "\n\n // Type to change the letter in the\n // center of the canvas.\n // If you reload the page, it will\n // still display the last key you entered\nlet myText;\nfunction setup() {\n createCanvas(100, 100);\n myText = getItem('myText');\n if (myText === null) {\n myText = '';\n }\n describe(`When you type the key name is displayed as black text on white background.\n If you reload the page, the last letter typed is still displaying.`);\n }\nfunction draw() {\n textSize(40);\n background(255);\n text(myText, width / 2, height / 2);\n }\nfunction keyPressed() {\n myText = key;\n storeItem('myText', myText);\n }\n
Returns the value of an item that was stored in local storage\n using storeItem()
\n", "itemtype": "method", "name": "getItem", "params": [ { "name": "key", "description": "name that you wish to use to store in local storage
\n", "type": "String" } ], "return": { "description": "Value of stored item", "type": "Number|Object|String|Boolean|p5.Color|p5.Vector" }, "example": [ "\n\n // Click the mouse to change\n // the color of the background\n // Once you have changed the color\n // it will stay changed even when you\n // reload the page.\nlet myColor;\nfunction setup() {\n createCanvas(100, 100);\n myColor = getItem('myColor');\n }\nfunction draw() {\n if (myColor !== null) {\n background(myColor);\n }\n describe(`If you click, the canvas changes to a random color.·\n If you reload the page, the canvas is still the color it was when the\n page was previously loaded.`);\n }\nfunction mousePressed() {\n myColor = color(random(255), random(255), random(255));\n storeItem('myColor', myColor);\n }\n
Clears all local storage items set with storeItem()\n for the current domain.
\n", "itemtype": "method", "name": "clearStorage", "example": [ "\n\n function setup() {\n let myNum = 10;\n let myBool = false;\n storeItem('myNum', myNum);\n storeItem('myBool', myBool);\n print(getItem('myNum')); // logs 10 to the console\n print(getItem('myBool')); // logs false to the console\n clearStorage();\n print(getItem('myNum')); // logs null to the console\n print(getItem('myBool')); // logs null to the console\n }\n
Removes an item that was stored with storeItem()
\n", "itemtype": "method", "name": "removeItem", "params": [ { "name": "key", "description": "", "type": "String" } ], "example": [ "\n\n function setup() {\n let myVar = 10;\n storeItem('myVar', myVar);\n print(getItem('myVar')); // logs 10 to the console\n removeItem('myVar');\n print(getItem('myVar')); // logs null to the console\n }\n
Creates a new instance of p5.StringDict using the key-value pair\n or the object you provide.
\n", "itemtype": "method", "name": "createStringDict", "return": { "description": "", "type": "p5.StringDict" }, "example": [ "\n\n function setup() {\n let myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // logs true to console\n let anotherDictionary = createStringDict({ happy: 'coding' });\n print(anotherDictionary.hasKey('happy')); // logs true to console\n }\n
object
\n", "type": "Object" } ], "return": { "description": "", "type": "p5.StringDict" } } ] }, { "file": "src/data/p5.TypedDict.js", "line": 48, "description": "Creates a new instance of p5.NumberDict using the key-value pair\n or object you provide.
\n", "itemtype": "method", "name": "createNumberDict", "return": { "description": "", "type": "p5.NumberDict" }, "example": [ "\n\n function setup() {\n let myDictionary = createNumberDict(100, 42);\n print(myDictionary.hasKey(100)); // logs true to console\n let anotherDictionary = createNumberDict({ 200: 84 });\n print(anotherDictionary.hasKey(200)); // logs true to console\n }\n
object
\n", "type": "Object" } ], "return": { "description": "", "type": "p5.NumberDict" } } ] }, { "file": "src/data/p5.TypedDict.js", "line": 101, "description": "Returns the number of key-value pairs currently stored in the Dictionary.
\n", "itemtype": "method", "name": "size", "return": { "description": "the number of key-value pairs in the Dictionary", "type": "Integer" }, "example": [ "\n\nfunction setup() {\n let myDictionary = createNumberDict(1, 10);\n myDictionary.create(2, 20);\n myDictionary.create(3, 30);\n print(myDictionary.size()); // logs 3 to the console\n}\n
Returns true if the given key exists in the Dictionary,\notherwise returns false.
\n", "itemtype": "method", "name": "hasKey", "params": [ { "name": "key", "description": "that you want to look up
\n", "type": "Number|String" } ], "return": { "description": "whether that key exists in Dictionary", "type": "Boolean" }, "example": [ "\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // logs true to console\n}\n
Returns the value stored at the given key.
\n", "itemtype": "method", "name": "get", "params": [ { "name": "the", "description": "key you want to access
\n", "type": "Number|String" } ], "return": { "description": "the value stored at that key", "type": "Number|String" }, "example": [ "\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n let myValue = myDictionary.get('p5');\n print(myValue === 'js'); // logs true to console\n}\n
Updates the value associated with the given key in case it already exists\nin the Dictionary. Otherwise a new key-value pair is added.
\n", "itemtype": "method", "name": "set", "params": [ { "name": "key", "description": "", "type": "Number|String" }, { "name": "value", "description": "", "type": "Number|String" } ], "example": [ "\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.set('p5', 'JS');\n myDictionary.print(); // logs \"key: p5 - value: JS\" to console\n}\n
private helper function to handle the user passing in objects\nduring construction or calls to create()
\n", "class": "p5.TypedDict", "module": "Data", "submodule": "Dictionary" }, { "file": "src/data/p5.TypedDict.js", "line": 208, "description": "Creates a new key-value pair in the Dictionary.
\n", "itemtype": "method", "name": "create", "example": [ "\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n}\n
key/value pair
\n", "type": "Object" } ] } ] }, { "file": "src/data/p5.TypedDict.js", "line": 244, "description": "Removes all previously stored key-value pairs from the Dictionary.
\n", "itemtype": "method", "name": "clear", "example": [ "\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // prints 'true'\n myDictionary.clear();\n print(myDictionary.hasKey('p5')); // prints 'false'\n}\n
\nRemoves the key-value pair stored at the given key from the Dictionary.
\n", "itemtype": "method", "name": "remove", "params": [ { "name": "key", "description": "for the pair to remove
\n", "type": "Number|String" } ], "example": [ "\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n myDictionary.remove('p5');\n myDictionary.print();\n // above logs \"key: happy value: coding\" to console\n}\n
Logs the set of items currently stored in the Dictionary to the console.
\n", "itemtype": "method", "name": "print", "example": [ "\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n}\n
\nConverts the Dictionary into a CSV file for local download.
\n", "itemtype": "method", "name": "saveTable", "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n}\n\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n createStringDict({\n john: 1940,\n paul: 1942,\n george: 1943,\n ringo: 1940\n }).saveTable('beatles');\n }\n}\n
\nConverts the Dictionary into a JSON file for local download.
\n", "itemtype": "method", "name": "saveJSON", "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n}\n\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n createStringDict({\n john: 1940,\n paul: 1942,\n george: 1943,\n ringo: 1940\n }).saveJSON('beatles');\n }\n}\n
\nprivate helper function to ensure that the user passed in valid\nvalues for the Dictionary type
\n", "class": "p5.TypedDict", "module": "Data", "submodule": "Dictionary" }, { "file": "src/data/p5.TypedDict.js", "line": 425, "description": "private helper function to ensure that the user passed in valid\nvalues for the Dictionary type
\n", "class": "p5.NumberDict", "module": "Data", "submodule": "Dictionary" }, { "file": "src/data/p5.TypedDict.js", "line": 432, "description": "Add the given number to the value currently stored at the given key.\nThe sum then replaces the value previously stored in the Dictionary.
\n", "itemtype": "method", "name": "add", "params": [ { "name": "Key", "description": "for the value you wish to add to
\n", "type": "Number" }, { "name": "Number", "description": "to add to the value
\n", "type": "Number" } ], "example": [ "\n\nfunction setup() {\n let myDictionary = createNumberDict(2, 5);\n myDictionary.add(2, 2);\n print(myDictionary.get(2)); // logs 7 to console.\n}\n
Subtract the given number from the value currently stored at the given key.\nThe difference then replaces the value previously stored in the Dictionary.
\n", "itemtype": "method", "name": "sub", "params": [ { "name": "Key", "description": "for the value you wish to subtract from
\n", "type": "Number" }, { "name": "Number", "description": "to subtract from the value
\n", "type": "Number" } ], "example": [ "\n\nfunction setup() {\n let myDictionary = createNumberDict(2, 5);\n myDictionary.sub(2, 2);\n print(myDictionary.get(2)); // logs 3 to console.\n}\n
Multiply the given number with the value currently stored at the given key.\nThe product then replaces the value previously stored in the Dictionary.
\n", "itemtype": "method", "name": "mult", "params": [ { "name": "Key", "description": "for value you wish to multiply
\n", "type": "Number" }, { "name": "Amount", "description": "to multiply the value by
\n", "type": "Number" } ], "example": [ "\n\nfunction setup() {\n let myDictionary = createNumberDict(2, 4);\n myDictionary.mult(2, 2);\n print(myDictionary.get(2)); // logs 8 to console.\n}\n
Divide the given number with the value currently stored at the given key.\nThe quotient then replaces the value previously stored in the Dictionary.
\n", "itemtype": "method", "name": "div", "params": [ { "name": "Key", "description": "for value you wish to divide
\n", "type": "Number" }, { "name": "Amount", "description": "to divide the value by
\n", "type": "Number" } ], "example": [ "\n\nfunction setup() {\n let myDictionary = createNumberDict(2, 8);\n myDictionary.div(2, 2);\n print(myDictionary.get(2)); // logs 4 to console.\n}\n
private helper function for finding lowest or highest value\nthe argument 'flip' is used to flip the comparison arrow\nfrom 'less than' to 'greater than'
\n", "class": "p5.NumberDict", "module": "Data", "submodule": "Dictionary" }, { "file": "src/data/p5.TypedDict.js", "line": 560, "description": "Return the lowest number currently stored in the Dictionary.
\n", "itemtype": "method", "name": "minValue", "return": { "description": "", "type": "Number" }, "example": [ "\n\nfunction setup() {\n let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });\n let lowestValue = myDictionary.minValue(); // value is -10\n print(lowestValue);\n}\n
Return the highest number currently stored in the Dictionary.
\n", "itemtype": "method", "name": "maxValue", "return": { "description": "", "type": "Number" }, "example": [ "\n\nfunction setup() {\n let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });\n let highestValue = myDictionary.maxValue(); // value is 3\n print(highestValue);\n}\n
private helper function for finding lowest or highest key\nthe argument 'flip' is used to flip the comparison arrow\nfrom 'less than' to 'greater than'
\n", "class": "p5.NumberDict", "module": "Data", "submodule": "Dictionary" }, { "file": "src/data/p5.TypedDict.js", "line": 622, "description": "Return the lowest key currently used in the Dictionary.
\n", "itemtype": "method", "name": "minKey", "return": { "description": "", "type": "Number" }, "example": [ "\n\nfunction setup() {\n let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });\n let lowestKey = myDictionary.minKey(); // value is 1.2\n print(lowestKey);\n}\n
Return the highest key currently used in the Dictionary.
\n", "itemtype": "method", "name": "maxKey", "return": { "description": "", "type": "Number" }, "example": [ "\n\nfunction setup() {\n let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });\n let highestKey = myDictionary.maxKey(); // value is 4\n print(highestKey);\n}\n
Searches the page for the first element that matches the given CSS selector string (can be an\nID, class, tag name or a combination) and returns it as a p5.Element.\nThe DOM node itself can be accessed with .elt.\nReturns null if none found. You can also specify a container to search within.
\n", "itemtype": "method", "name": "select", "params": [ { "name": "selectors", "description": "CSS selector string of element to search for
\n", "type": "String" }, { "name": "container", "description": "CSS selector string, p5.Element, or\n HTML element to search within
\n", "type": "String|p5.Element|HTMLElement", "optional": true } ], "return": { "description": "p5.Element containing node found", "type": "p5.Element|null" }, "example": [ "\n\nfunction setup() {\n createCanvas(50, 50);\n background(30);\n // move canvas down and right\n select('canvas').position(10, 30);\n}\n
\n// select using ID\nlet a = select('#container');\nlet b = select('#beep', '#container');\nlet c;\nif (a) {\n // select using class\n c = select('.boop', a);\n}\n// select using CSS selector string\nlet d = select('#container #bleep');\nlet e = select('#container p');\n[a, b, c, d, e]; // unused\n
Searches the page for elements that match the given CSS selector string (can be an ID a class,\ntag name or a combination) and returns them as p5.Elements in\nan array.\nThe DOM node itself can be accessed with .elt.\nReturns an empty array if none found.\nYou can also specify a container to search within.
\n", "itemtype": "method", "name": "selectAll", "params": [ { "name": "selectors", "description": "CSS selector string of elements to search for
\n", "type": "String" }, { "name": "container", "description": "CSS selector string, p5.Element\n , or HTML element to search within
\n", "type": "String|p5.Element|HTMLElement", "optional": true } ], "return": { "description": "Array of p5.Elements containing nodes found", "type": "p5.Element[]" }, "example": [ "\n\nfunction setup() {\n createButton('btn');\n createButton('2nd btn');\n createButton('3rd btn');\n let buttons = selectAll('button');\n\n for (let i = 0; i < 3; i++) {\n buttons[i].size(100);\n buttons[i].position(0, i * 30);\n }\n}\n
\n// these are all valid calls to selectAll()\nlet a = selectAll('.beep');\na = selectAll('div');\na = selectAll('button', '#container');\n\nlet b = createDiv();\nb.id('container');\nlet c = select('#container');\na = selectAll('p', c);\na = selectAll('#container p');\n\nlet d = document.getElementById('container');\na = selectAll('.boop', d);\na = selectAll('#container .boop');\nconsole.log(a);\n
Helper function for select and selectAll
\n", "class": "p5", "module": "DOM", "submodule": "DOM" }, { "file": "src/dom/dom.js", "line": 142, "description": "Helper function for getElement and getElements.
\n", "class": "p5", "module": "DOM", "submodule": "DOM" }, { "file": "src/dom/dom.js", "line": 176, "description": "Removes all elements created by p5, except any canvas / graphics\nelements created by createCanvas or createGraphics.\nEvent handlers are removed, and element is removed from the DOM.
\n", "itemtype": "method", "name": "removeElements", "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n background('grey');\n let div = createDiv('this is some text');\n let p = createP('this is a paragraph');\n div.style('font-size', '16px');\n p.style('font-size', '16px');\n}\nfunction mousePressed() {\n removeElements(); // this will remove the div and p, not canvas\n}\n
The .changed() function is called when the value of an\nelement changes.\nThis can be used to attach an element specific event listener.
\n", "itemtype": "method", "name": "changed", "params": [ { "name": "fxn", "description": "function to be fired when the value of\n an element changes.\n if false
is passed instead, the previously\n firing function will no longer fire.
\nlet sel;\n\nfunction setup() {\n textAlign(CENTER);\n background(200);\n sel = createSelect();\n sel.position(10, 10);\n sel.option('pear');\n sel.option('kiwi');\n sel.option('grape');\n sel.changed(mySelectEvent);\n}\n\nfunction mySelectEvent() {\n let item = sel.value();\n background(200);\n text(\"it's a \" + item + '!', 50, 50);\n}\n
\nlet checkbox;\nlet cnv;\n\nfunction setup() {\n checkbox = createCheckbox(' fill');\n checkbox.changed(changeFill);\n cnv = createCanvas(100, 100);\n cnv.position(0, 30);\n noFill();\n}\n\nfunction draw() {\n background(200);\n ellipse(50, 50, 50, 50);\n}\n\nfunction changeFill() {\n if (checkbox.checked()) {\n fill(0);\n } else {\n noFill();\n }\n}\n
The .input() function is called when any user input is\ndetected with an element. The input event is often used\nto detect keystrokes in a input element, or changes on a\nslider element. This can be used to attach an element specific\nevent listener.
\n", "itemtype": "method", "name": "input", "params": [ { "name": "fxn", "description": "function to be fired when any user input is\n detected within the element.\n if false
is passed instead, the previously\n firing function will no longer fire.
\n// Open your console to see the output\nfunction setup() {\n createCanvas(100, 100);\n background('grey');\n let inp = createInput('');\n inp.position(0, 0);\n inp.size(100);\n inp.input(myInputEvent);\n}\n\nfunction myInputEvent() {\n console.log('you are typing: ', this.value());\n}\n
Helpers for create methods.
\n", "class": "p5", "module": "DOM", "submodule": "DOM" }, { "file": "src/dom/dom.js", "line": 322, "description": "Creates a <div></div>
element in the DOM with given inner HTML.
inner HTML for element created
\n", "type": "String", "optional": true } ], "return": { "description": "pointer to p5.Element holding created node", "type": "p5.Element" }, "example": [ "\n\nlet div = createDiv('this is some text');\ndiv.style('font-size', '16px');\ndiv.position(10, 0);\n
Creates a <p></p>
element in the DOM with given inner HTML. Used\nfor paragraph length text.
inner HTML for element created
\n", "type": "String", "optional": true } ], "return": { "description": "pointer to p5.Element holding created node", "type": "p5.Element" }, "example": [ "\n\nlet p = createP('this is some text');\np.style('font-size', '16px');\np.position(10, 0);\n
Creates a <span></span>
element in the DOM with given inner HTML.
inner HTML for element created
\n", "type": "String", "optional": true } ], "return": { "description": "pointer to p5.Element holding created node", "type": "p5.Element" }, "example": [ "\n\nlet span = createSpan('this is some text');\nspan.position(0, 0);\n
Creates an <img>
element in the DOM with given src and\nalternate text.
\nlet img = createImg(\n 'https://p5js.org/assets/img/asterisk-01.png',\n 'the p5 magenta asterisk'\n);\nimg.position(0, -10);\n
src path or url for image
\n", "type": "String" }, { "name": "alt", "description": "alternate text to be used if image does not load. You can use also an empty string (\"\"
) if that an image is not intended to be viewed.
crossOrigin property of the img
element; use either 'anonymous' or 'use-credentials' to retrieve the image with cross-origin access (for later use with canvas
. if an empty string(\"\"
) is passed, CORS is not used
callback to be called once image data is loaded with the p5.Element as argument
\n", "type": "Function", "optional": true } ], "return": { "description": "pointer to p5.Element holding created node", "type": "p5.Element" } } ] }, { "file": "src/dom/dom.js", "line": 426, "description": "Creates an <a></a>
element in the DOM for including a hyperlink.
url of page to link to
\n", "type": "String" }, { "name": "html", "description": "inner html of link element to display
\n", "type": "String" }, { "name": "target", "description": "target where new link should open,\n could be _blank, _self, _parent, _top.
\n", "type": "String", "optional": true } ], "return": { "description": "pointer to p5.Element holding created node", "type": "p5.Element" }, "example": [ "\n\nlet a = createA('http://p5js.org/', 'this is a link');\na.position(0, 0);\n
Creates a slider <input></input>
element in the DOM.\nUse .size() to set the display length of the slider.
minimum value of the slider
\n", "type": "Number" }, { "name": "max", "description": "maximum value of the slider
\n", "type": "Number" }, { "name": "value", "description": "default value of the slider
\n", "type": "Number", "optional": true }, { "name": "step", "description": "step size for each tick of the slider (if step is set to 0, the slider will move continuously from the minimum to the maximum value)
\n", "type": "Number", "optional": true } ], "return": { "description": "pointer to p5.Element holding the created node", "type": "p5.Element" }, "example": [ "\n\nlet slider;\nfunction setup() {\n slider = createSlider(0, 255, 100);\n slider.position(10, 10);\n slider.style('width', '80px');\n}\n\nfunction draw() {\n let val = slider.value();\n background(val);\n}\n
\nlet slider;\nfunction setup() {\n colorMode(HSB);\n slider = createSlider(0, 360, 60, 40);\n slider.position(10, 10);\n slider.style('width', '80px');\n}\n\nfunction draw() {\n let val = slider.value();\n background(val, 100, 100, 1);\n}\n
Creates a <button></button>
element in the DOM.\nUse .size() to set the display size of the button.\nUse .mousePressed() to specify behavior on press.
label displayed on the button
\n", "type": "String" }, { "name": "value", "description": "value of the button
\n", "type": "String", "optional": true } ], "return": { "description": "pointer to p5.Element holding created node", "type": "p5.Element" }, "example": [ "\n\nlet button;\nfunction setup() {\n createCanvas(100, 100);\n background(0);\n button = createButton('click me');\n button.position(0, 0);\n button.mousePressed(changeBG);\n}\n\nfunction changeBG() {\n let val = random(255);\n background(val);\n}\n
Creates a checkbox <input></input>
element in the DOM.\nCalling .checked() on a checkbox returns a boolean indicating whether\nit is checked or not.
label displayed after checkbox
\n", "type": "String", "optional": true }, { "name": "value", "description": "value of the checkbox; checked is true, unchecked is false
\n", "type": "Boolean", "optional": true } ], "return": { "description": "pointer to p5.Element holding created node", "type": "p5.Element" }, "example": [ "\n\nlet checkbox;\n\nfunction setup() {\n checkbox = createCheckbox('label', false);\n checkbox.changed(myCheckedEvent);\n}\n\nfunction myCheckedEvent() {\n if (checkbox.checked()) {\n console.log('Checking!');\n } else {\n console.log('Unchecking!');\n }\n}\n
Creates a dropdown menu <select></select>
element in the DOM.\nIt also assigns select-related methods to p5.Element when selecting an existing select box. Options in the menu are unique by name
(the display text).
.option(name, [value])
can be used to add an option with name
(the display text) and value
to the select element. If an option with name
already exists within the select element, this method will change its value to value
..value()
will return the currently selected option..selected()
will return the current dropdown element which is an instance of p5.Element..selected(value)
can be used to make given option selected by default when the page first loads..disable()
marks the whole dropdown element as disabled..disable(value)
marks a given option as disabled.\nlet sel;\n\nfunction setup() {\n textAlign(CENTER);\n background(200);\n sel = createSelect();\n sel.position(10, 10);\n sel.option('pear');\n sel.option('kiwi');\n sel.option('grape');\n sel.selected('kiwi');\n sel.changed(mySelectEvent);\n}\n\nfunction mySelectEvent() {\n let item = sel.value();\n background(200);\n text('It is a ' + item + '!', 50, 50);\n}\n
\nlet sel;\n\nfunction setup() {\n textAlign(CENTER);\n background(200);\n sel = createSelect();\n sel.position(10, 10);\n sel.option('oil');\n sel.option('milk');\n sel.option('bread');\n sel.disable('milk');\n}\n
true if dropdown should support multiple selections
\n", "type": "Boolean", "optional": true } ], "return": { "description": "pointer to p5.Element holding created node", "type": "p5.Element" } }, { "line": 674, "params": [ { "name": "existing", "description": "DOM select element
\n", "type": "Object" } ], "return": { "description": "", "type": "p5.Element" } } ] }, { "file": "src/dom/dom.js", "line": 771, "description": "Creates a radio button element in the DOM. It also helps existing radio buttons\nassign methods of p5.Element.
\n.option(value, [label])
can be used to create a new option for the\nelement. If an option with a value already exists, it will be returned.\nIt is recommended to use string values as input for value
.\nOptionally, a label can be provided as second argument for the option..remove(value)
can be used to remove an option for the element. String\nvalues recommended as input for value
..value()
method will return the currently selected value..selected()
method will return the currently selected input element..selected(value)
method will select the option and return it. String\nvalues recommended as input for value
..disable(Boolean)
method will enable/disable the whole radio button element.\nlet radio;\n\nfunction setup() {\n radio = createRadio();\n radio.option('black');\n radio.option('white');\n radio.option('gray');\n radio.style('width', '60px');\n textAlign(CENTER);\n fill(255, 0, 0);\n}\n\nfunction draw() {\n let val = radio.value();\n background(val);\n text(val, width / 2, height / 2);\n}\n
\nlet radio;\n\nfunction setup() {\n radio = createRadio();\n radio.option('1', 'apple');\n radio.option('2', 'bread');\n radio.option('3', 'juice');\n radio.style('width', '30px');\n radio.selected('2');\n textAlign(CENTER);\n}\n\nfunction draw() {\n background(200);\n let val = radio.value();\n if (val) {\n text('item cost is $' + val, width / 2, height / 2);\n }\n}\n
A container HTML Element, either a div\nor span, inside which all existing radio inputs will be considered as options.
\n", "type": "Object" }, { "name": "name", "description": "A name parameter for each Input Element.
\n", "type": "String", "optional": true } ], "return": { "description": "pointer to p5.Element holding created node", "type": "p5.Element" } }, { "line": 833, "params": [ { "name": "name", "description": "", "type": "String" } ], "return": { "description": "pointer to p5.Element holding created node", "type": "p5.Element" } }, { "line": 838, "params": [], "return": { "description": "pointer to p5.Element holding created node", "type": "p5.Element" } } ] }, { "file": "src/dom/dom.js", "line": 1000, "description": "Creates a colorPicker element in the DOM for color input.\nThe .value() method will return a hex string (#rrggbb) of the color.\nThe .color() method will return a p5.Color\nobject with the current chosen color.
\n", "itemtype": "method", "name": "createColorPicker", "params": [ { "name": "value", "description": "default color of element
\n", "type": "String|p5.Color", "optional": true } ], "return": { "description": "pointer to p5.Element holding created node", "type": "p5.Element" }, "example": [ "\n\nlet colorPicker;\nfunction setup() {\n createCanvas(100, 100);\n colorPicker = createColorPicker('#ed225d');\n colorPicker.position(0, height + 5);\n}\n\nfunction draw() {\n background(colorPicker.color());\n}\n
\nlet inp1, inp2;\nfunction setup() {\n createCanvas(100, 100);\n background('grey');\n inp1 = createColorPicker('#ff0000');\n inp1.position(0, height + 5);\n inp1.input(setShade1);\n inp2 = createColorPicker(color('yellow'));\n inp2.position(0, height + 30);\n inp2.input(setShade2);\n setMidShade();\n}\n\nfunction setMidShade() {\n // Finding a shade between the two\n let commonShade = lerpColor(inp1.color(), inp2.color(), 0.5);\n fill(commonShade);\n rect(20, 20, 60, 60);\n}\n\nfunction setShade1() {\n setMidShade();\n console.log('You are choosing shade 1 to be : ', this.value());\n}\nfunction setShade2() {\n setMidShade();\n console.log('You are choosing shade 2 to be : ', this.value());\n}\n
Creates an <input></input>
element in the DOM for text input.\nUse .size() to set the display length of the box.
\nfunction setup() {\n createCanvas(100, 100);\n background('grey');\n let inp = createInput('');\n inp.position(0, 0);\n inp.size(100);\n inp.input(myInputEvent);\n}\n\nfunction myInputEvent() {\n console.log('you are typing: ', this.value());\n}\n
default value of the input box
\n", "type": "String" }, { "name": "type", "description": "type of text, ie text, password etc. Defaults to text.\n Needs a value to be specified first.
\n", "type": "String", "optional": true } ], "return": { "description": "pointer to p5.Element holding created node", "type": "p5.Element" } }, { "line": 1114, "params": [ { "name": "value", "description": "", "type": "String", "optional": true } ], "return": { "description": "", "type": "p5.Element" } } ] }, { "file": "src/dom/dom.js", "line": 1127, "description": "Creates an <input></input>
element in the DOM of type 'file'.\nThis allows users to select local files for use in a sketch.
callback function for when a file is loaded
\n", "type": "Function" }, { "name": "multiple", "description": "optional, to allow multiple files to be selected
\n", "type": "Boolean", "optional": true } ], "return": { "description": "pointer to p5.Element holding created DOM element", "type": "p5.Element" }, "example": [ "\n\nlet input;\nlet img;\n\nfunction setup() {\n input = createFileInput(handleFile);\n input.position(0, 0);\n}\n\nfunction draw() {\n background(255);\n if (img) {\n image(img, 0, 0, width, height);\n }\n}\n\nfunction handleFile(file) {\n print(file);\n if (file.type === 'image') {\n img = createImg(file.data, '');\n img.hide();\n } else {\n img = null;\n }\n}\n
Creates an HTML5 <video>
element in the DOM for simple playback\nof audio/video. Shown by default, can be hidden with .hide()\nand drawn into canvas using image(). The first parameter\ncan be either a single string path to a video file, or an array of string\npaths to different formats of the same video. This is useful for ensuring\nthat your video can play across different browsers, as each supports\ndifferent formats. See this\npage for further information about supported formats.
path to a video file, or array of paths for\n supporting different browsers
\n", "type": "String|String[]" }, { "name": "callback", "description": "callback function to be called upon\n 'canplaythrough' event fire, that is, when the\n browser can play the media, and estimates that\n enough data has been loaded to play the media\n up to its end without having to stop for\n further buffering of content
\n", "type": "Function", "optional": true } ], "return": { "description": "pointer to video p5.MediaElement", "type": "p5.MediaElement" }, "example": [ "\n\nlet vid;\nfunction setup() {\n noCanvas();\n\n vid = createVideo(\n ['assets/small.mp4', 'assets/small.ogv', 'assets/small.webm'],\n vidLoad\n );\n\n vid.size(100, 100);\n}\n\n// This function is called when the video loads\nfunction vidLoad() {\n vid.loop();\n vid.volume(0);\n}\n
Creates a hidden HTML5 <audio>
element in the DOM for simple audio\nplayback. The first parameter can be either a single string path to a\naudio file, or an array of string paths to different formats of the same\naudio. This is useful for ensuring that your audio can play across\ndifferent browsers, as each supports different formats.\nSee this\npage for further information about supported formats.
path to an audio file, or array of paths\n for supporting different browsers
\n", "type": "String|String[]", "optional": true }, { "name": "callback", "description": "callback function to be called upon\n 'canplaythrough' event fire, that is, when the\n browser can play the media, and estimates that\n enough data has been loaded to play the media\n up to its end without having to stop for\n further buffering of content
\n", "type": "Function", "optional": true } ], "return": { "description": "pointer to audio p5.MediaElement", "type": "p5.MediaElement" }, "example": [ "\n\nlet ele;\nfunction setup() {\n ele = createAudio('assets/beat.mp3');\n\n // here we set the element to autoplay\n // The element will play as soon\n // as it is able to do so.\n ele.autoplay(true);\n}\n
Creates a new HTML5 <video>
element that contains the audio/video feed\nfrom a webcam. The element is separate from the canvas and is displayed by\ndefault. The element can be hidden using .hide().\nThe feed can be drawn onto the canvas using image().\nThe loadedmetadata property can be used to detect when the element has fully\nloaded (see second example).
More specific properties of the feed can be passing in a Constraints object.\nSee the \nW3C spec for possible properties. Note that not all of these are supported\nby all browsers.
\nSecurity note: A new browser security specification requires that\ngetUserMedia, which is behind createCapture(),\nonly works when you're running the code locally, or on HTTPS. Learn more\nhere\nand here.
\n", "itemtype": "method", "name": "createCapture", "params": [ { "name": "type", "description": "type of capture, either VIDEO or\n AUDIO if none specified, default both,\n or a Constraints object
\n", "type": "String|Constant|Object" }, { "name": "callback", "description": "function to be called once\n stream has loaded
\n", "type": "Function", "optional": true } ], "return": { "description": "capture video p5.Element", "type": "p5.Element" }, "example": [ "\n\nlet capture;\n\nfunction setup() {\n createCanvas(100, 100);\n capture = createCapture(VIDEO);\n capture.hide();\n}\n\nfunction draw() {\n image(capture, 0, 0, width, width * capture.height / capture.width);\n filter(INVERT);\n}\n
\n\nfunction setup() {\n createCanvas(480, 120);\n let constraints = {\n video: {\n mandatory: {\n minWidth: 1280,\n minHeight: 720\n },\n optional: [{ maxFrameRate: 10 }]\n },\n audio: true\n };\n createCapture(constraints, function(stream) {\n console.log(stream);\n });\n}\n
\n\nlet capture;\n\nfunction setup() {\n createCanvas(640, 480);\n capture = createCapture(VIDEO);\n}\nfunction draw() {\n background(0);\n if (capture.loadedmetadata) {\n let c = capture.get(0, 0, 100, 100);\n image(c, 0, 0);\n }\n}\n
\nCreates element with given tag in the DOM with given content.
\n", "itemtype": "method", "name": "createElement", "params": [ { "name": "tag", "description": "tag for the new element
\n", "type": "String" }, { "name": "content", "description": "html content to be inserted into the element
\n", "type": "String", "optional": true } ], "return": { "description": "pointer to p5.Element holding created node", "type": "p5.Element" }, "example": [ "\n\nlet h5 = createElement('h5', 'im an h5 p5.element!');\nh5.style('color', '#00a1d3');\nh5.position(0, 0);\n
Adds specified class to the element.
\n", "itemtype": "method", "name": "addClass", "params": [ { "name": "class", "description": "name of class to add
\n", "type": "String" } ], "chainable": 1, "example": [ "\n\n let div = createDiv('div');\n div.addClass('myClass');\n
Removes specified class from the element.
\n", "itemtype": "method", "name": "removeClass", "params": [ { "name": "class", "description": "name of class to remove
\n", "type": "String" } ], "chainable": 1, "example": [ "\n\n // In this example, a class is set when the div is created\n // and removed when mouse is pressed. This could link up\n // with a CSS style rule to toggle style properties.\nlet div;\nfunction setup() {\n div = createDiv('div');\n div.addClass('myClass');\n }\nfunction mousePressed() {\n div.removeClass('myClass');\n }\n
Checks if specified class is already applied to element.
\n", "itemtype": "method", "name": "hasClass", "return": { "description": "a boolean value if element has specified class", "type": "Boolean" }, "params": [ { "name": "c", "description": "class name of class to check
\n", "type": "String" } ], "example": [ "\n\n let div;\nfunction setup() {\n div = createDiv('div');\n div.addClass('show');\n }\nfunction mousePressed() {\n if (div.hasClass('show')) {\n div.addClass('show');\n } else {\n div.removeClass('show');\n }\n }\n
Toggles element class.
\n", "itemtype": "method", "name": "toggleClass", "params": [ { "name": "c", "description": "class name to toggle
\n", "type": "String" } ], "chainable": 1, "example": [ "\n\n let div;\nfunction setup() {\n div = createDiv('div');\n div.addClass('show');\n }\nfunction mousePressed() {\n div.toggleClass('show');\n }\n
Attaches the element as a child to the parent specified.\n Accepts either a string ID, DOM node, or p5.Element.\n If no argument is specified, an array of children DOM nodes is returned.
\n", "itemtype": "method", "name": "child", "return": { "description": "an array of child nodes", "type": "Node[]" }, "example": [ "\n\n let div0 = createDiv('this is the parent');\n let div1 = createDiv('this is the child');\n div0.child(div1); // use p5.Element\n
\n let div0 = createDiv('this is the parent');\n let div1 = createDiv('this is the child');\n div1.id('apples');\n div0.child('apples'); // use id\n
\n // this example assumes there is a div already on the page\n // with id \"myChildDiv\"\n let div0 = createDiv('this is the parent');\n let elt = document.getElementById('myChildDiv');\n div0.child(elt); // use element from page\n
the ID, DOM node, or p5.Element\n to add to the current element
\n", "type": "String|p5.Element", "optional": true } ], "chainable": 1 } ] }, { "file": "src/dom/dom.js", "line": 1689, "description": "Centers a p5.Element either vertically, horizontally,\nor both, relative to its parent or according to\nthe body if the p5.Element has no parent. If no argument is passed\nthe p5.Element is aligned both vertically and horizontally.
\n", "itemtype": "method", "name": "center", "params": [ { "name": "align", "description": "passing 'vertical', 'horizontal' aligns element accordingly
\n", "type": "String", "optional": true } ], "chainable": 1, "example": [ "\n\nfunction setup() {\n let div = createDiv('').size(10, 10);\n div.style('background-color', 'orange');\n div.center();\n}\n
If an argument is given, sets the inner HTML of the element,\n replacing any existing HTML. If true is included as a second\n argument, HTML is appended instead of replacing existing HTML.\n If no arguments are given, returns\n the inner HTML of the element.
\n", "itemtype": "method", "name": "html", "return": { "description": "the inner HTML of the element", "type": "String" }, "example": [ "\n\n let div = createDiv('').size(100, 100);\n div.html('hi');\n
\n let div = createDiv('Hello ').size(100, 100);\n div.html('World', true);\n
the HTML to be placed inside the element
\n", "type": "String", "optional": true }, { "name": "append", "description": "whether to append HTML to existing
\n", "type": "Boolean", "optional": true } ], "chainable": 1 } ] }, { "file": "src/dom/dom.js", "line": 1779, "description": "Sets the position of the element. If no position type argument is given, the\n position will be relative to (0, 0) of the window.\n Essentially, this sets position:absolute and left and top\n properties of style. If an optional third argument specifying position type is given,\n the x and y-coordinates will be interpreted based on the positioning scheme.\n If no arguments given, the function returns the x and y position of the element.\nfound documentation on how to be more specific with object type\n https://stackoverflow.com/questions/14714314/how-do-i-comment-object-literals-in-yuidoc
\n", "itemtype": "method", "name": "position", "return": { "description": "object of form { x: 0, y: 0 } containing the position of the element in an object", "type": "Object" }, "example": [ "\n\n function setup() {\n let cnv = createCanvas(100, 100);\n // positions canvas 50px to the right and 100px\n // below upper left corner of the window\n cnv.position(50, 100);\n }\n
\n function setup() {\n let cnv = createCanvas(100, 100);\n // positions canvas at upper left corner of the window\n // with a 'fixed' position type\n cnv.position(0, 0, 'fixed');\n }\n
x-position relative to upper left of window (optional)
\n", "type": "Number", "optional": true }, { "name": "y", "description": "y-position relative to upper left of window (optional)
\n", "type": "Number", "optional": true }, { "name": "positionType", "description": "it can be static, fixed, relative, sticky, initial or inherit (optional)
\n", "type": "String", "optional": true } ], "chainable": 1 } ] }, { "file": "src/dom/dom.js", "line": 1899, "description": "Sets the given style (CSS) property (1st arg) of the element with the\ngiven value (2nd arg). If a single argument is given, .style()\nreturns the value of the given property; however, if a single argument\nis given in CSS syntax ('text-align:center'), .style() sets the CSS\nappropriately.
\n", "itemtype": "method", "name": "style", "return": { "description": "value of property", "type": "String" }, "example": [ "\n\nlet myDiv = createDiv('I like pandas.');\nmyDiv.style('font-size', '18px');\nmyDiv.style('color', '#ff0000');\nmyDiv.position(0, 0);\n
\nlet col = color(25, 23, 200, 50);\nlet button = createButton('button');\nbutton.style('background-color', col);\nbutton.position(0, 0);\n
\nlet myDiv, fontSize;\nfunction setup() {\n background(200);\n myDiv = createDiv('I like gray.');\n myDiv.position(0, 0);\n myDiv.style('z-index', 10);\n}\n\nfunction draw() {\n fontSize = min(mouseX, 90);\n myDiv.style('font-size', fontSize + 'px');\n}\n
property to be set
\n", "type": "String" } ], "return": { "description": "value of property", "type": "String" } }, { "line": 1937, "params": [ { "name": "property", "description": "", "type": "String" }, { "name": "value", "description": "value to assign to property
\n", "type": "String|p5.Color" } ], "chainable": 1, "return": { "description": "current value of property, if no value is given as second argument", "type": "String" } } ] }, { "file": "src/dom/dom.js", "line": 1994, "description": "Adds a new attribute or changes the value of an existing attribute\n on the specified element. If no value is specified, returns the\n value of the given attribute, or null if the attribute is not set.
\n", "itemtype": "method", "name": "attribute", "return": { "description": "value of attribute", "type": "String" }, "example": [ "\n\n let myDiv = createDiv('I like pandas.');\n myDiv.attribute('align', 'center');\n
attribute to set
\n", "type": "String" }, { "name": "value", "description": "value to assign to attribute
\n", "type": "String" } ], "chainable": 1 } ] }, { "file": "src/dom/dom.js", "line": 2038, "description": "Removes an attribute on the specified element.
\n", "itemtype": "method", "name": "removeAttribute", "params": [ { "name": "attr", "description": "attribute to remove
\n", "type": "String" } ], "chainable": 1, "example": [ "\n\n let button;\n let checkbox;\nfunction setup() {\n checkbox = createCheckbox('enable', true);\n checkbox.changed(enableButton);\n button = createButton('button');\n button.position(10, 10);\n }\nfunction enableButton() {\n if (this.checked()) {\n // Re-enable the button\n button.removeAttribute('disabled');\n } else {\n // Disable the button\n button.attribute('disabled', '');\n }\n }\n
Either returns the value of the element if no arguments\ngiven, or sets the value of the element.
\n", "itemtype": "method", "name": "value", "return": { "description": "value of the element", "type": "String|Number" }, "example": [ "\n\n// gets the value\nlet inp;\nfunction setup() {\n inp = createInput('');\n}\n\nfunction mousePressed() {\n print(inp.value());\n}\n
\n// sets the value\nlet inp;\nfunction setup() {\n inp = createInput('myValue');\n}\n\nfunction mousePressed() {\n inp.value('myValue');\n}\n
Shows the current element. Essentially, setting display:block for the style.
\n", "itemtype": "method", "name": "show", "chainable": 1, "example": [ "\n\n let div = createDiv('div');\n div.style('display', 'none');\n div.show(); // turns display to block\n
Hides the current element. Essentially, setting display:none for the style.
\n", "itemtype": "method", "name": "hide", "chainable": 1, "example": [ "\n\nlet div = createDiv('this is a div');\ndiv.hide();\n
Sets the width and height of the element. AUTO can be used to\n only adjust one dimension at a time. If no arguments are given, it\n returns the width and height of the element in an Object. In the case of\n elements that need to be loaded, such as images, it is recommended\n to call the function after the element has finished loading.
\n", "itemtype": "method", "name": "size", "return": { "description": "the width and height of the element in an object", "type": "Object" }, "example": [ "\n\n let div = createDiv('this is a div');\n div.size(100, 100);\n let img = createImg(\n 'assets/rockies.jpg',\n 'A tall mountain with a small forest and field in front of it on a sunny day',\n '',\n () => {\n img.size(10, AUTO);\n }\n );\n
width of the element, either AUTO, or a number
\n", "type": "Number|Constant" }, { "name": "h", "description": "height of the element, either AUTO, or a number
\n", "type": "Number|Constant", "optional": true } ], "chainable": 1 } ] }, { "file": "src/dom/dom.js", "line": 2244, "description": "Removes the element, stops all media streams, and deregisters all listeners.
\n", "itemtype": "method", "name": "remove", "example": [ "\n\nlet myDiv = createDiv('this is some text');\nmyDiv.remove();\n
Registers a callback that gets called every time a file that is\ndropped on the element has been loaded.\np5 will load every dropped file into memory and pass it as a p5.File object to the callback.\nMultiple files dropped at the same time will result in multiple calls to the callback.
\nYou can optionally pass a second callback which will be registered to the raw\ndrop event.\nThe callback will thus be provided the original\nDragEvent.\nDropping multiple files at the same time will trigger the second callback once per drop,\nwhereas the first callback will trigger for each loaded file.
\n", "itemtype": "method", "name": "drop", "params": [ { "name": "callback", "description": "callback to receive loaded file, called for each file dropped.
\n", "type": "Function" }, { "name": "fxn", "description": "callback triggered once when files are dropped with the drop event.
\n", "type": "Function", "optional": true } ], "chainable": 1, "example": [ "\n\nfunction setup() {\n let c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('drop file', width / 2, height / 2);\n c.drop(gotFile);\n}\n\nfunction gotFile(file) {\n background(200);\n text('received file:', width / 2, height / 2);\n text(file.name, width / 2, height / 2 + 50);\n}\n
\nlet img;\n\nfunction setup() {\n let c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('drop image', width / 2, height / 2);\n c.drop(gotFile);\n}\n\nfunction draw() {\n if (img) {\n image(img, 0, 0, width, height);\n }\n}\n\nfunction gotFile(file) {\n img = createImg(file.data, '').hide();\n}\n
Path to the media element source.
\n", "itemtype": "property", "name": "src", "return": { "description": "src", "type": "String" }, "example": [ "\n\nlet ele;\n\nfunction setup() {\n background(250);\n\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n\n //In this example we create\n //a new p5.MediaElement via createAudio().\n ele = createAudio('assets/beat.mp3');\n\n //We'll set up our example so that\n //when you click on the text,\n //an alert box displays the MediaElement's\n //src field.\n textAlign(CENTER);\n text('Click Me!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n //Show our p5.MediaElement's src field\n alert(ele.src);\n }\n}\n
Play an HTML5 media element.
\n", "itemtype": "method", "name": "play", "chainable": 1, "example": [ "\n\nlet ele;\n\nfunction setup() {\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n\n //In this example we create\n //a new p5.MediaElement via createAudio().\n ele = createAudio('assets/beat.mp3');\n\n background(250);\n textAlign(CENTER);\n text('Click to Play!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n //Here we call the play() function on\n //the p5.MediaElement we created above.\n //This will start the audio sample.\n ele.play();\n\n background(200);\n text('You clicked Play!', width / 2, height / 2);\n }\n}\n
Stops an HTML5 media element (sets current time to zero).
\n", "itemtype": "method", "name": "stop", "chainable": 1, "example": [ "\n\n//This example both starts\n//and stops a sound sample\n//when the user clicks the canvas\n\n//We will store the p5.MediaElement\n//object in here\nlet ele;\n\n//while our audio is playing,\n//this will be set to true\nlet sampleIsPlaying = false;\n\nfunction setup() {\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio('assets/beat.mp3');\n background(200);\n textAlign(CENTER);\n text('Click to play!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n background(200);\n\n if (sampleIsPlaying) {\n //if the sample is currently playing\n //calling the stop() function on\n //our p5.MediaElement will stop\n //it and reset its current\n //time to 0 (i.e. it will start\n //at the beginning the next time\n //you play it)\n ele.stop();\n\n sampleIsPlaying = false;\n text('Click to play!', width / 2, height / 2);\n } else {\n //loop our sound element until we\n //call ele.stop() on it.\n ele.loop();\n\n sampleIsPlaying = true;\n text('Click to stop!', width / 2, height / 2);\n }\n }\n}\n
Pauses an HTML5 media element.
\n", "itemtype": "method", "name": "pause", "chainable": 1, "example": [ "\n\n//This example both starts\n//and pauses a sound sample\n//when the user clicks the canvas\n\n//We will store the p5.MediaElement\n//object in here\nlet ele;\n\n//while our audio is playing,\n//this will be set to true\nlet sampleIsPlaying = false;\n\nfunction setup() {\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio('assets/lucky_dragons.mp3');\n background(200);\n textAlign(CENTER);\n text('Click to play!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n background(200);\n\n if (sampleIsPlaying) {\n //Calling pause() on our\n //p5.MediaElement will stop it\n //playing, but when we call the\n //loop() or play() functions\n //the sample will start from\n //where we paused it.\n ele.pause();\n\n sampleIsPlaying = false;\n text('Click to resume!', width / 2, height / 2);\n } else {\n //loop our sound element until we\n //call ele.pause() on it.\n ele.loop();\n\n sampleIsPlaying = true;\n text('Click to pause!', width / 2, height / 2);\n }\n }\n}\n
Set 'loop' to true for an HTML5 media element, and starts playing.
\n", "itemtype": "method", "name": "loop", "chainable": 1, "example": [ "\n\n//Clicking the canvas will loop\n//the audio sample until the user\n//clicks again to stop it\n\n//We will store the p5.MediaElement\n//object in here\nlet ele;\n\n//while our audio is playing,\n//this will be set to true\nlet sampleIsLooping = false;\n\nfunction setup() {\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio('assets/lucky_dragons.mp3');\n background(200);\n textAlign(CENTER);\n text('Click to loop!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n background(200);\n\n if (!sampleIsLooping) {\n //loop our sound element until we\n //call ele.stop() on it.\n ele.loop();\n\n sampleIsLooping = true;\n text('Click to stop!', width / 2, height / 2);\n } else {\n ele.stop();\n\n sampleIsLooping = false;\n text('Click to loop!', width / 2, height / 2);\n }\n }\n}\n
Set 'loop' to false for an HTML5 media element. Element will stop\nwhen it reaches the end.
\n", "itemtype": "method", "name": "noLoop", "chainable": 1, "example": [ "\n\n//This example both starts\n//and stops loop of sound sample\n//when the user clicks the canvas\n\n//We will store the p5.MediaElement\n//object in here\nlet ele;\n//while our audio is playing,\n//this will be set to true\nlet sampleIsPlaying = false;\n\nfunction setup() {\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio('assets/beat.mp3');\n background(200);\n textAlign(CENTER);\n text('Click to play!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n background(200);\n\n if (sampleIsPlaying) {\n ele.noLoop();\n sampleIsPlaying = false;\n text('No more Loops!', width / 2, height / 2);\n } else {\n ele.loop();\n sampleIsPlaying = true;\n text('Click to stop looping!', width / 2, height / 2);\n }\n }\n}\n
Set HTML5 media element to autoplay or not. If no argument is specified, by\ndefault it will autoplay.
\n", "itemtype": "method", "name": "autoplay", "params": [ { "name": "shouldAutoplay", "description": "whether the element should autoplay
\n", "type": "Boolean" } ], "chainable": 1, "example": [ "\n\nlet videoElement;\nfunction setup() {\n noCanvas();\n videoElement = createVideo(['assets/small.mp4'], onVideoLoad);\n}\nfunction onVideoLoad() {\n // The media will play as soon as it is loaded.\n videoElement.autoplay();\n videoElement.volume(0);\n videoElement.size(100, 100);\n}\n
\nlet videoElement;\nfunction setup() {\n noCanvas();\n videoElement = createVideo(['assets/small.mp4'], onVideoLoad);\n}\nfunction onVideoLoad() {\n // The media will not play until some explicitly triggered.\n videoElement.autoplay(false);\n videoElement.volume(0);\n videoElement.size(100, 100);\n}\n\nfunction mouseClicked() {\n videoElement.play();\n}\n
Sets volume for this HTML5 media element. If no argument is given,\nreturns the current volume.
\n", "itemtype": "method", "name": "volume", "return": { "description": "current volume", "type": "Number" }, "example": [ "\n\nlet ele;\nfunction setup() {\n // p5.MediaElement objects are usually created\n // by calling the createAudio(), createVideo(),\n // and createCapture() functions.\n // In this example we create\n // a new p5.MediaElement via createAudio().\n ele = createAudio('assets/lucky_dragons.mp3');\n background(250);\n textAlign(CENTER);\n text('Click to Play!', width / 2, height / 2);\n}\nfunction mouseClicked() {\n // Here we call the volume() function\n // on the sound element to set its volume\n // Volume must be between 0.0 and 1.0\n ele.volume(0.2);\n ele.play();\n background(200);\n text('You clicked Play!', width / 2, height / 2);\n}\n
\nlet audio;\nlet counter = 0;\n\nfunction loaded() {\n audio.play();\n}\n\nfunction setup() {\n audio = createAudio('assets/lucky_dragons.mp3', loaded);\n textAlign(CENTER);\n}\n\nfunction draw() {\n if (counter === 0) {\n background(0, 255, 0);\n text('volume(0.9)', width / 2, height / 2);\n } else if (counter === 1) {\n background(255, 255, 0);\n text('volume(0.5)', width / 2, height / 2);\n } else if (counter === 2) {\n background(255, 0, 0);\n text('volume(0.1)', width / 2, height / 2);\n }\n}\n\nfunction mousePressed() {\n counter++;\n if (counter === 0) {\n audio.volume(0.9);\n } else if (counter === 1) {\n audio.volume(0.5);\n } else if (counter === 2) {\n audio.volume(0.1);\n } else {\n counter = 0;\n audio.volume(0.9);\n }\n}\n
\nvolume between 0.0 and 1.0
\n", "type": "Number" } ], "chainable": 1 } ] }, { "file": "src/dom/dom.js", "line": 2945, "description": "If no arguments are given, returns the current playback speed of the\nelement. The speed parameter sets the speed where 2.0 will play the\nelement twice as fast, 0.5 will play at half the speed, and -1 will play\nthe element in normal speed in reverse.(Note that not all browsers support\nbackward playback and even if they do, playback might not be smooth.)
\n", "itemtype": "method", "name": "speed", "return": { "description": "current playback speed of the element", "type": "Number" }, "example": [ "\n\n//Clicking the canvas will loop\n//the audio sample until the user\n//clicks again to stop it\n\n//We will store the p5.MediaElement\n//object in here\nlet ele;\nlet button;\n\nfunction setup() {\n createCanvas(710, 400);\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio('assets/beat.mp3');\n ele.loop();\n background(200);\n\n button = createButton('2x speed');\n button.position(100, 68);\n button.mousePressed(twice_speed);\n\n button = createButton('half speed');\n button.position(200, 68);\n button.mousePressed(half_speed);\n\n button = createButton('reverse play');\n button.position(300, 68);\n button.mousePressed(reverse_speed);\n\n button = createButton('STOP');\n button.position(400, 68);\n button.mousePressed(stop_song);\n\n button = createButton('PLAY!');\n button.position(500, 68);\n button.mousePressed(play_speed);\n}\n\nfunction twice_speed() {\n ele.speed(2);\n}\n\nfunction half_speed() {\n ele.speed(0.5);\n}\n\nfunction reverse_speed() {\n ele.speed(-1);\n}\n\nfunction stop_song() {\n ele.stop();\n}\n\nfunction play_speed() {\n ele.play();\n}\n
speed multiplier for element playback
\n", "type": "Number" } ], "chainable": 1 } ] }, { "file": "src/dom/dom.js", "line": 3034, "description": "If no arguments are given, returns the current time of the element.\nIf an argument is given the current time of the element is set to it.
\n", "itemtype": "method", "name": "time", "return": { "description": "current time (in seconds)", "type": "Number" }, "example": [ "\n\nlet ele;\nlet beginning = true;\nfunction setup() {\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n\n //In this example we create\n //a new p5.MediaElement via createAudio().\n ele = createAudio('assets/lucky_dragons.mp3');\n background(250);\n textAlign(CENTER);\n text('start at beginning', width / 2, height / 2);\n}\n\n// this function fires with click anywhere\nfunction mousePressed() {\n if (beginning === true) {\n // here we start the sound at the beginning\n // time(0) is not necessary here\n // as this produces the same result as\n // play()\n ele.play().time(0);\n background(200);\n text('jump 2 sec in', width / 2, height / 2);\n beginning = false;\n } else {\n // here we jump 2 seconds into the sound\n ele.play().time(2);\n background(250);\n text('start at beginning', width / 2, height / 2);\n beginning = true;\n }\n}\n
time to jump to (in seconds)
\n", "type": "Number" } ], "chainable": 1 } ] }, { "file": "src/dom/dom.js", "line": 3093, "description": "Returns the duration of the HTML5 media element.
\n", "itemtype": "method", "name": "duration", "return": { "description": "duration", "type": "Number" }, "example": [ "\n\nlet ele;\nfunction setup() {\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n //In this example we create\n //a new p5.MediaElement via createAudio().\n ele = createAudio('assets/doorbell.mp3');\n background(250);\n textAlign(CENTER);\n text('Click to know the duration!', 10, 25, 70, 80);\n}\nfunction mouseClicked() {\n ele.play();\n background(200);\n //ele.duration dislpays the duration\n text(ele.duration() + ' seconds', width / 2, height / 2);\n}\n
Schedule an event to be called when the audio or video\nelement reaches the end. If the element is looping,\nthis will not be called. The element is passed in\nas the argument to the onended callback.
\n", "itemtype": "method", "name": "onended", "params": [ { "name": "callback", "description": "function to call when the\n soundfile has ended. The\n media element will be passed\n in as the argument to the\n callback.
\n", "type": "Function" } ], "chainable": 1, "example": [ "\n\nfunction setup() {\n let audioEl = createAudio('assets/beat.mp3');\n audioEl.showControls();\n audioEl.onended(sayDone);\n}\n\nfunction sayDone(elt) {\n alert('done playing ' + elt.src);\n}\n
Send the audio output of this element to a specified audioNode or\np5.sound object. If no element is provided, connects to p5's main\noutput. That connection is established when this method is first called.\nAll connections are removed by the .disconnect() method.
\nThis method is meant to be used with the p5.sound.js addon library.
\n", "itemtype": "method", "name": "connect", "params": [ { "name": "audioNode", "description": "AudioNode from the Web Audio API,\nor an object from the p5.sound library
\n", "type": "AudioNode|Object" } ], "class": "p5.MediaElement", "module": "DOM", "submodule": "DOM" }, { "file": "src/dom/dom.js", "line": 3297, "description": "Disconnect all Web Audio routing, including to main output.\nThis is useful if you want to re-route the output through\naudio effects, for example.
\n", "itemtype": "method", "name": "disconnect", "class": "p5.MediaElement", "module": "DOM", "submodule": "DOM" }, { "file": "src/dom/dom.js", "line": 3312, "class": "p5.MediaElement", "module": "DOM", "submodule": "DOM" }, { "file": "src/dom/dom.js", "line": 3314, "description": "Show the default MediaElement controls, as determined by the web browser.
\n", "itemtype": "method", "name": "showControls", "example": [ "\n\nlet ele;\nfunction setup() {\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n //In this example we create\n //a new p5.MediaElement via createAudio()\n ele = createAudio('assets/lucky_dragons.mp3');\n background(200);\n textAlign(CENTER);\n text('Click to Show Controls!', 10, 25, 70, 80);\n}\nfunction mousePressed() {\n ele.showControls();\n background(200);\n text('Controls Shown', width / 2, height / 2);\n}\n
Hide the default mediaElement controls.
\n", "itemtype": "method", "name": "hideControls", "example": [ "\n\nlet ele;\nfunction setup() {\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n //In this example we create\n //a new p5.MediaElement via createAudio()\n ele = createAudio('assets/lucky_dragons.mp3');\n ele.showControls();\n background(200);\n textAlign(CENTER);\n text('Click to hide Controls!', 10, 25, 70, 80);\n}\nfunction mousePressed() {\n ele.hideControls();\n background(200);\n text('Controls hidden', width / 2, height / 2);\n}\n
Schedule events to trigger every time a MediaElement\n(audio/video) reaches a playback cue point.
\nAccepts a callback function, a time (in seconds) at which to trigger\nthe callback, and an optional parameter for the callback.
\nTime will be passed as the first parameter to the callback function,\nand param will be the second parameter.
\n", "itemtype": "method", "name": "addCue", "params": [ { "name": "time", "description": "Time in seconds, relative to this media\n element's playback. For example, to trigger\n an event every time playback reaches two\n seconds, pass in the number 2. This will be\n passed as the first parameter to\n the callback function.
\n", "type": "Number" }, { "name": "callback", "description": "Name of a function that will be\n called at the given time. The callback will\n receive time and (optionally) param as its\n two parameters.
\n", "type": "Function" }, { "name": "value", "description": "An object to be passed as the\n second parameter to the\n callback function.
\n", "type": "Object", "optional": true } ], "return": { "description": "id ID of this cue,\n useful for removeCue(id)", "type": "Number" }, "example": [ "\n\n//\n//\nfunction setup() {\n createCanvas(200, 200);\n\n let audioEl = createAudio('assets/beat.mp3');\n audioEl.showControls();\n\n // schedule three calls to changeBackground\n audioEl.addCue(0.5, changeBackground, color(255, 0, 0));\n audioEl.addCue(1.0, changeBackground, color(0, 255, 0));\n audioEl.addCue(2.5, changeBackground, color(0, 0, 255));\n audioEl.addCue(3.0, changeBackground, color(0, 255, 255));\n audioEl.addCue(4.2, changeBackground, color(255, 255, 0));\n audioEl.addCue(5.0, changeBackground, color(255, 255, 0));\n}\n\nfunction changeBackground(val) {\n background(val);\n}\n
Remove a callback based on its ID. The ID is returned by the\naddCue method.
\n", "itemtype": "method", "name": "removeCue", "params": [ { "name": "id", "description": "ID of the cue, as returned by addCue
\n", "type": "Number" } ], "example": [ "\n\nlet audioEl, id1, id2;\nfunction setup() {\n background(255, 255, 255);\n audioEl = createAudio('assets/beat.mp3');\n audioEl.showControls();\n // schedule five calls to changeBackground\n id1 = audioEl.addCue(0.5, changeBackground, color(255, 0, 0));\n audioEl.addCue(1.0, changeBackground, color(0, 255, 0));\n audioEl.addCue(2.5, changeBackground, color(0, 0, 255));\n audioEl.addCue(3.0, changeBackground, color(0, 255, 255));\n id2 = audioEl.addCue(4.2, changeBackground, color(255, 255, 0));\n text('Click to remove first and last Cue!', 10, 25, 70, 80);\n}\nfunction mousePressed() {\n audioEl.removeCue(id1);\n audioEl.removeCue(id2);\n}\nfunction changeBackground(val) {\n background(val);\n}\n
Remove all of the callbacks that had originally been scheduled\nvia the addCue method.
\n", "itemtype": "method", "name": "clearCues", "params": [ { "name": "id", "description": "ID of the cue, as returned by addCue
\n", "type": "Number" } ], "example": [ "\n\nlet audioEl;\nfunction setup() {\n background(255, 255, 255);\n audioEl = createAudio('assets/beat.mp3');\n //Show the default MediaElement controls, as determined by the web browser\n audioEl.showControls();\n // schedule calls to changeBackground\n background(200);\n text('Click to change Cue!', 10, 25, 70, 80);\n audioEl.addCue(0.5, changeBackground, color(255, 0, 0));\n audioEl.addCue(1.0, changeBackground, color(0, 255, 0));\n audioEl.addCue(2.5, changeBackground, color(0, 0, 255));\n audioEl.addCue(3.0, changeBackground, color(0, 255, 255));\n audioEl.addCue(4.2, changeBackground, color(255, 255, 0));\n}\nfunction mousePressed() {\n // here we clear the scheduled callbacks\n audioEl.clearCues();\n // then we add some more callbacks\n audioEl.addCue(1, changeBackground, color(2, 2, 2));\n audioEl.addCue(3, changeBackground, color(255, 255, 0));\n}\nfunction changeBackground(val) {\n background(val);\n}\n
Underlying File object. All normal File methods can be called on this.
\n", "itemtype": "property", "name": "file", "class": "p5.File", "module": "DOM", "submodule": "DOM" }, { "file": "src/dom/dom.js", "line": 3568, "description": "File type (image, text, etc.)
\n", "itemtype": "property", "name": "type", "class": "p5.File", "module": "DOM", "submodule": "DOM" }, { "file": "src/dom/dom.js", "line": 3574, "description": "File subtype (usually the file extension jpg, png, xml, etc.)
\n", "itemtype": "property", "name": "subtype", "class": "p5.File", "module": "DOM", "submodule": "DOM" }, { "file": "src/dom/dom.js", "line": 3580, "description": "File name
\n", "itemtype": "property", "name": "name", "class": "p5.File", "module": "DOM", "submodule": "DOM" }, { "file": "src/dom/dom.js", "line": 3586, "description": "File size
\n", "itemtype": "property", "name": "size", "class": "p5.File", "module": "DOM", "submodule": "DOM" }, { "file": "src/dom/dom.js", "line": 3593, "description": "URL string containing either image data, the text contents of the file or\na parsed object if file is JSON and p5.XML if XML
\n", "itemtype": "property", "name": "data", "class": "p5.File", "module": "DOM", "submodule": "DOM" }, { "file": "src/events/acceleration.js", "line": 11, "description": "The system variable deviceOrientation always contains the orientation of\nthe device. The value of this variable will either be set 'landscape'\nor 'portrait'. If no data is available it will be set to 'undefined'.\neither LANDSCAPE or PORTRAIT.
\n", "itemtype": "property", "name": "deviceOrientation", "type": "Constant", "readonly": "", "class": "p5", "module": "Events", "submodule": "Acceleration" }, { "file": "src/events/acceleration.js", "line": 23, "description": "The system variable accelerationX always contains the acceleration of the\ndevice along the x axis. Value is represented as meters per second squared.
\n", "itemtype": "property", "name": "accelerationX", "type": "Number", "readonly": "", "example": [ "\n\n// Move a touchscreen device to register\n// acceleration changes.\nfunction draw() {\n background(220, 50);\n fill('magenta');\n ellipse(width / 2, height / 2, accelerationX);\n describe('Magnitude of device acceleration is displayed as ellipse size.');\n}\n
\nThe system variable accelerationY always contains the acceleration of the\ndevice along the y axis. Value is represented as meters per second squared.
\n", "itemtype": "property", "name": "accelerationY", "type": "Number", "readonly": "", "example": [ "\n\n// Move a touchscreen device to register\n// acceleration changes.\nfunction draw() {\n background(220, 50);\n fill('magenta');\n ellipse(width / 2, height / 2, accelerationY);\n describe('Magnitude of device acceleration is displayed as ellipse size');\n}\n
\nThe system variable accelerationZ always contains the acceleration of the\ndevice along the z axis. Value is represented as meters per second squared.
\n", "itemtype": "property", "name": "accelerationZ", "type": "Number", "readonly": "", "example": [ "\n\n// Move a touchscreen device to register\n// acceleration changes.\nfunction draw() {\n background(220, 50);\n fill('magenta');\n ellipse(width / 2, height / 2, accelerationZ);\n describe('Magnitude of device acceleration is displayed as ellipse size');\n}\n
\nThe system variable pAccelerationX always contains the acceleration of the\ndevice along the x axis in the frame previous to the current frame. Value\nis represented as meters per second squared.
\n", "itemtype": "property", "name": "pAccelerationX", "type": "Number", "readonly": "", "class": "p5", "module": "Events", "submodule": "Acceleration" }, { "file": "src/events/acceleration.js", "line": 100, "description": "The system variable pAccelerationY always contains the acceleration of the\ndevice along the y axis in the frame previous to the current frame. Value\nis represented as meters per second squared.
\n", "itemtype": "property", "name": "pAccelerationY", "type": "Number", "readonly": "", "class": "p5", "module": "Events", "submodule": "Acceleration" }, { "file": "src/events/acceleration.js", "line": 110, "description": "The system variable pAccelerationZ always contains the acceleration of the\ndevice along the z axis in the frame previous to the current frame. Value\nis represented as meters per second squared.
\n", "itemtype": "property", "name": "pAccelerationZ", "type": "Number", "readonly": "", "class": "p5", "module": "Events", "submodule": "Acceleration" }, { "file": "src/events/acceleration.js", "line": 131, "description": "The system variable rotationX always contains the rotation of the\ndevice along the x axis. If the sketch \nangleMode() is set to DEGREES, the value will be -180 to 180. If\nit is set to RADIANS, the value will be -PI to PI.
\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.
\n", "itemtype": "property", "name": "rotationX", "type": "Number", "readonly": "", "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n //rotateZ(radians(rotationZ));\n rotateX(radians(rotationX));\n //rotateY(radians(rotationY));\n box(200, 200, 200);\n describe(`red horizontal line right, green vertical line bottom.\n black background.`);\n}\n
\nThe system variable rotationY always contains the rotation of the\ndevice along the y axis. If the sketch \nangleMode() is set to DEGREES, the value will be -90 to 90. If\nit is set to RADIANS, the value will be -PI/2 to PI/2.
\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.
\n", "itemtype": "property", "name": "rotationY", "type": "Number", "readonly": "", "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n //rotateZ(radians(rotationZ));\n //rotateX(radians(rotationX));\n rotateY(radians(rotationY));\n box(200, 200, 200);\n describe(`red horizontal line right, green vertical line bottom.\n black background.`);\n}\n
\nThe system variable rotationZ always contains the rotation of the\ndevice along the z axis. If the sketch \nangleMode() is set to DEGREES, the value will be 0 to 360. If\nit is set to RADIANS, the value will be 0 to 2*PI.
\nUnlike rotationX and rotationY, this variable is available for devices\nwith a built-in compass only.
\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.
\n", "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateZ(radians(rotationZ));\n //rotateX(radians(rotationX));\n //rotateY(radians(rotationY));\n box(200, 200, 200);\n describe(`red horizontal line right, green vertical line bottom.\n black background.`);\n}\n
\nThe system variable pRotationX always contains the rotation of the\ndevice along the x axis in the frame previous to the current frame.\nIf the sketch angleMode() is set to DEGREES,\nthe value will be -180 to 180. If it is set to RADIANS, the value will\nbe -PI to PI.
\npRotationX can also be used with rotationX to determine the rotate\ndirection of the device along the X-axis.
\n", "example": [ "\n\n// A simple if statement looking at whether\n// rotationX - pRotationX < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nlet rotateDirection = 'clockwise';\n\n// Simple range conversion to make things simpler.\n// This is not absolutely necessary but the logic\n// will be different in that case.\n\nlet rX = rotationX + 180;\nlet pRX = pRotationX + 180;\n\nif ((rX - pRX > 0 && rX - pRX < 270) || rX - pRX < -270) {\n rotateDirection = 'clockwise';\n} else if (rX - pRX < 0 || rX - pRX > 270) {\n rotateDirection = 'counter-clockwise';\n}\n\nprint(rotateDirection);\ndescribe('no image to display.');\n
\nThe system variable pRotationY always contains the rotation of the\ndevice along the y axis in the frame previous to the current frame.\nIf the sketch angleMode() is set to DEGREES,\nthe value will be -90 to 90. If it is set to RADIANS, the value will\nbe -PI/2 to PI/2.
\npRotationY can also be used with rotationY to determine the rotate\ndirection of the device along the Y-axis.
\n", "example": [ "\n\n// A simple if statement looking at whether\n// rotationY - pRotationY < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nlet rotateDirection = 'clockwise';\n\n// Simple range conversion to make things simpler.\n// This is not absolutely necessary but the logic\n// will be different in that case.\n\nlet rY = rotationY + 180;\nlet pRY = pRotationY + 180;\n\nif ((rY - pRY > 0 && rY - pRY < 270) || rY - pRY < -270) {\n rotateDirection = 'clockwise';\n} else if (rY - pRY < 0 || rY - pRY > 270) {\n rotateDirection = 'counter-clockwise';\n}\nprint(rotateDirection);\ndescribe('no image to display.');\n
\nThe system variable pRotationZ always contains the rotation of the\ndevice along the z axis in the frame previous to the current frame.\nIf the sketch angleMode() is set to DEGREES,\nthe value will be 0 to 360. If it is set to RADIANS, the value will\nbe 0 to 2*PI.
\npRotationZ can also be used with rotationZ to determine the rotate\ndirection of the device along the Z-axis.
\n", "example": [ "\n\n// A simple if statement looking at whether\n// rotationZ - pRotationZ < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nlet rotateDirection = 'clockwise';\n\nif (\n (rotationZ - pRotationZ > 0 && rotationZ - pRotationZ < 270) ||\n rotationZ - pRotationZ < -270\n) {\n rotateDirection = 'clockwise';\n} else if (rotationZ - pRotationZ < 0 || rotationZ - pRotationZ > 270) {\n rotateDirection = 'counter-clockwise';\n}\nprint(rotateDirection);\ndescribe('no image to display.');\n
\nWhen a device is rotated, the axis that triggers the deviceTurned()\nmethod is stored in the turnAxis variable. The turnAxis variable is only defined within\nthe scope of deviceTurned().
\n", "itemtype": "property", "name": "turnAxis", "type": "String", "readonly": "", "example": [ "\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees in the\n// X-axis to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when device turns`);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when x-axis turns`);\n}\nfunction deviceTurned() {\n if (turnAxis === 'X') {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n }\n}\n
\nThe setMoveThreshold() function is used to set the movement threshold for\nthe deviceMoved() function. The default threshold is set to 0.5.
\n", "itemtype": "method", "name": "setMoveThreshold", "params": [ { "name": "value", "description": "The threshold value
\n", "type": "Number" } ], "example": [ "\n\n// Run this example on a mobile device\n// You will need to move the device incrementally further\n// the closer the square's color gets to white in order to change the value.\n\nlet value = 0;\nlet threshold = 0.5;\nfunction setup() {\n setMoveThreshold(threshold);\n}\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when device moves`);\n}\nfunction deviceMoved() {\n value = value + 5;\n threshold = threshold + 0.1;\n if (value > 255) {\n value = 0;\n threshold = 30;\n }\n setMoveThreshold(threshold);\n}\n
\nThe setShakeThreshold() function is used to set the movement threshold for\nthe deviceShaken() function. The default threshold is set to 30.
\n", "itemtype": "method", "name": "setShakeThreshold", "params": [ { "name": "value", "description": "The threshold value
\n", "type": "Number" } ], "example": [ "\n\n// Run this example on a mobile device\n// You will need to shake the device more firmly\n// the closer the box's fill gets to white in order to change the value.\n\nlet value = 0;\nlet threshold = 30;\nfunction setup() {\n setShakeThreshold(threshold);\n}\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when device is being shaked`);\n}\nfunction deviceMoved() {\n value = value + 5;\n threshold = threshold + 5;\n if (value > 255) {\n value = 0;\n threshold = 30;\n }\n setShakeThreshold(threshold);\n}\n
\nThe deviceMoved() function is called when the device is moved by more than\nthe threshold value along X, Y or Z axis. The default threshold is set to 0.5.\nThe threshold value can be changed using setMoveThreshold().
\n", "itemtype": "method", "name": "deviceMoved", "example": [ "\n\n// Run this example on a mobile device\n// Move the device around\n// to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when device moves`);\n}\nfunction deviceMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n
\nThe deviceTurned() function is called when the device rotates by\nmore than 90 degrees continuously.
\nThe axis that triggers the deviceTurned() method is stored in the turnAxis\nvariable. The deviceTurned() method can be locked to trigger on any axis:\nX, Y or Z by comparing the turnAxis variable to 'X', 'Y' or 'Z'.
\n", "itemtype": "method", "name": "deviceTurned", "example": [ "\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees\n// to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when device turns`);\n}\nfunction deviceTurned() {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n}\n
\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees in the\n// X-axis to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when x-axis turns`);\n}\nfunction deviceTurned() {\n if (turnAxis === 'X') {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n }\n}\n
\nThe deviceShaken() function is called when the device total acceleration\nchanges of accelerationX and accelerationY values is more than\nthe threshold value. The default threshold is set to 30.\nThe threshold value can be changed using setShakeThreshold().
\n", "itemtype": "method", "name": "deviceShaken", "example": [ "\n\n// Run this example on a mobile device\n// Shake the device to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when device shakes`);\n}\nfunction deviceShaken() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n
\nThe boolean system variable keyIsPressed is true if any key is pressed\nand false if no keys are pressed.
\n", "itemtype": "property", "name": "keyIsPressed", "type": "Boolean", "readonly": "", "example": [ "\n\nfunction draw() {\n if (keyIsPressed === true) {\n fill(0);\n } else {\n fill(255);\n }\n rect(25, 25, 50, 50);\n describe('50-by-50 white rect that turns black on keypress.');\n}\n
\nThe system variable key always contains the value of the most recent\nkey on the keyboard that was typed. To get the proper capitalization, it\nis best to use it within keyTyped(). For non-ASCII keys, use the keyCode\nvariable.
\n", "itemtype": "property", "name": "key", "type": "String", "readonly": "", "example": [ "\n\n// Click any key to display it!\n// (Not Guaranteed to be Case Sensitive)\nfunction setup() {\n fill(245, 123, 158);\n textSize(50);\n}\n\nfunction draw() {\n background(200);\n text(key, 33, 65); // Display last key pressed.\n describe('canvas displays any key value that is pressed in pink font.');\n}\n
The variable keyCode is used to detect special keys such as BACKSPACE,\nDELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL, OPTION, ALT, UP_ARROW,\nDOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.\nYou can also check for custom keys by looking up the keyCode of any key\non a site like this: keycode.info.
\n", "itemtype": "property", "name": "keyCode", "type": "Integer", "readonly": "", "example": [ "\n\nlet fillVal = 126;\nfunction draw() {\n fill(fillVal);\n rect(25, 25, 50, 50);\n describe(`Grey rect center. turns white when up arrow pressed and black when down.\n Display key pressed and its keyCode in a yellow box.`);\n}\n\nfunction keyPressed() {\n if (keyCode === UP_ARROW) {\n fillVal = 255;\n } else if (keyCode === DOWN_ARROW) {\n fillVal = 0;\n }\n}\n
\nfunction draw() {}\nfunction keyPressed() {\n background('yellow');\n text(`${key} ${keyCode}`, 10, 40);\n print(key, ' ', keyCode);\n}\n
The keyPressed() function is called once every time a key is pressed. The\nkeyCode for the key that was pressed is stored in the keyCode variable.
\nFor non-ASCII keys, use the keyCode variable. You can check if the keyCode\nequals BACKSPACE, DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL,\nOPTION, ALT, UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.
\nFor ASCII keys, the key that was pressed is stored in the key variable. However, it\ndoes not distinguish between uppercase and lowercase. For this reason, it\nis recommended to use keyTyped() to read the key variable, in which the\ncase of the variable will be distinguished.
\nBecause of how operating systems handle key repeats, holding down a key\nmay cause multiple calls to keyTyped() (and keyReleased() as well). The\nrate of repeat is set by the operating system and how each computer is\nconfigured.
\nBrowsers may have different default\nbehaviors attached to various key events. To prevent any default\nbehavior for this event, add \"return false\" to the end of the method.
optional KeyboardEvent callback argument.
\n", "type": "Object", "optional": true } ], "example": [ "\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`black rect center. turns white when key pressed and black\n when released.`);\n}\nfunction keyPressed() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`black rect center. turns white when left arrow pressed and\n black when right.`);\n}\nfunction keyPressed() {\n if (keyCode === LEFT_ARROW) {\n value = 255;\n } else if (keyCode === RIGHT_ARROW) {\n value = 0;\n }\n}\n
\n\nfunction keyPressed() {\n // Do something\n return false; // prevent any default behaviour\n}\n
\nThe keyReleased() function is called once every time a key is released.\nSee key and keyCode for more information.
\nBrowsers may have different default\nbehaviors attached to various key events. To prevent any default\nbehavior for this event, add \"return false\" to the end of the function.
optional KeyboardEvent callback argument.
\n", "type": "Object", "optional": true } ], "example": [ "\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`black rect center. turns white when key pressed and black\n when pressed again`);\n}\nfunction keyReleased() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n return false; // prevent any default behavior\n}\n
\nThe keyTyped() function is called once every time a key is pressed, but\naction keys such as Backspace, Delete, Ctrl, Shift, and Alt are ignored. If you are trying to detect\na keyCode for one of these keys, use the keyPressed() function instead.\nThe most recent key typed will be stored in the key variable.
\nBecause of how operating systems handle key repeats, holding down a key\nwill cause multiple calls to keyTyped() (and keyReleased() as well). The\nrate of repeat is set by the operating system and how each computer is\nconfigured.
\nBrowsers may have different default behaviors attached to various key\nevents. To prevent any default behavior for this event, add \"return false\"\nto the end of the function.
optional KeyboardEvent callback argument.
\n", "type": "Object", "optional": true } ], "example": [ "\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`black rect center. turns white when 'a' key typed and\n black when 'b' pressed`);\n}\nfunction keyTyped() {\n if (key === 'a') {\n value = 255;\n } else if (key === 'b') {\n value = 0;\n }\n // uncomment to prevent any default behavior\n // return false;\n}\n
\nThe onblur function is called when the user is no longer focused\non the p5 element. Because the keyup events will not fire if the user is\nnot focused on the element we must assume all keys currently down have\nbeen released.
\n", "class": "p5", "module": "Events", "submodule": "Keyboard" }, { "file": "src/events/keyboard.js", "line": 301, "description": "The keyIsDown() function checks if the key is currently down, i.e. pressed.\nIt can be used if you have an object that moves, and you want several keys\nto be able to affect its behaviour simultaneously, such as moving a\nsprite diagonally. You can put in any number representing the keyCode of\nthe key, or use any of the variable keyCode names listed\nhere.
\n", "itemtype": "method", "name": "keyIsDown", "params": [ { "name": "code", "description": "The key to check for.
\n", "type": "Number" } ], "return": { "description": "whether key is down or not", "type": "Boolean" }, "example": [ "\n\nlet x = 100;\nlet y = 100;\n\nfunction setup() {\n createCanvas(512, 512);\n fill(255, 0, 0);\n}\n\nfunction draw() {\n if (keyIsDown(LEFT_ARROW)) {\n x -= 5;\n }\n\n if (keyIsDown(RIGHT_ARROW)) {\n x += 5;\n }\n\n if (keyIsDown(UP_ARROW)) {\n y -= 5;\n }\n\n if (keyIsDown(DOWN_ARROW)) {\n y += 5;\n }\n\n clear();\n ellipse(x, y, 50, 50);\n describe(`50-by-50 red ellipse moves left, right, up, and\n down with arrow presses.`);\n}\n
\nlet diameter = 50;\n\nfunction setup() {\n createCanvas(512, 512);\n}\n\nfunction draw() {\n // 107 and 187 are keyCodes for \"+\"\n if (keyIsDown(107) || keyIsDown(187)) {\n diameter += 1;\n }\n\n // 109 and 189 are keyCodes for \"-\"\n if (keyIsDown(109) || keyIsDown(189)) {\n diameter -= 1;\n }\n\n clear();\n fill(255, 0, 0);\n ellipse(50, 50, diameter, diameter);\n describe(`50-by-50 red ellipse gets bigger or smaller when\n + or - are pressed.`);\n}\n
The variable movedX contains the horizontal movement of the mouse since the last frame
\n", "itemtype": "property", "name": "movedX", "type": "Number", "readonly": "", "example": [ "\n\n let x = 50;\n function setup() {\n rectMode(CENTER);\n }\nfunction draw() {\n if (x > 48) {\n x -= 2;\n } else if (x < 48) {\n x += 2;\n }\n x += floor(movedX / 5);\n background(237, 34, 93);\n fill(0);\n rect(x, 50, 50, 50);\n describe(`box moves left and right according to mouse movement\n then slowly back towards the center`);\n }\n
\n The variable movedY contains the vertical movement of the mouse since the last frame
\n", "itemtype": "property", "name": "movedY", "type": "Number", "readonly": "", "example": [ "\n\nlet y = 50;\nfunction setup() {\n rectMode(CENTER);\n}\n\nfunction draw() {\n if (y > 48) {\n y -= 2;\n } else if (y < 48) {\n y += 2;\n }\n y += floor(movedY / 5);\n background(237, 34, 93);\n fill(0);\n rect(y, 50, 50, 50);\n describe(`box moves up and down according to mouse movement then\n slowly back towards the center`);\n}\n
\nThe system variable mouseX always contains the current horizontal\nposition of the mouse, relative to (0, 0) of the canvas. The value at\nthe top-left corner is (0, 0) for 2-D and (-width/2, -height/2) for WebGL.\nIf touch is used instead of mouse input, mouseX will hold the x value\nof the most recent touch point.
\n", "itemtype": "property", "name": "mouseX", "type": "Number", "readonly": "", "example": [ "\n\n// Move the mouse across the canvas\nfunction draw() {\n background(244, 248, 252);\n line(mouseX, 0, mouseX, 100);\n describe('horizontal black line moves left and right with mouse x-position');\n}\n
\nThe system variable mouseY always contains the current vertical\nposition of the mouse, relative to (0, 0) of the canvas. The value at\nthe top-left corner is (0, 0) for 2-D and (-width/2, -height/2) for WebGL.\nIf touch is used instead of mouse input, mouseY will hold the y value\nof the most recent touch point.
\n", "itemtype": "property", "name": "mouseY", "type": "Number", "readonly": "", "example": [ "\n\n// Move the mouse across the canvas\nfunction draw() {\n background(244, 248, 252);\n line(0, mouseY, 100, mouseY);\n describe('vertical black line moves up and down with mouse y-position');\n}\n
\nThe system variable pmouseX always contains the horizontal position of\nthe mouse or finger in the frame previous to the current frame, relative to\n(0, 0) of the canvas. The value at the top-left corner is (0, 0) for 2-D and\n(-width/2, -height/2) for WebGL. Note: pmouseX will be reset to the current mouseX\nvalue at the start of each touch event.
\n", "itemtype": "property", "name": "pmouseX", "type": "Number", "readonly": "", "example": [ "\n\n// Move the mouse across the canvas to leave a trail\nfunction setup() {\n //slow down the frameRate to make it more visible\n frameRate(10);\n}\n\nfunction draw() {\n background(244, 248, 252);\n line(mouseX, mouseY, pmouseX, pmouseY);\n print(pmouseX + ' -> ' + mouseX);\n describe(`line trail is created from cursor movements.\n faster movement make longer line.`);\n}\n
\nThe system variable pmouseY always contains the vertical position of\nthe mouse or finger in the frame previous to the current frame, relative to\n(0, 0) of the canvas. The value at the top-left corner is (0, 0) for 2-D and\n(-width/2, -height/2) for WebGL. Note: pmouseY will be reset to the current mouseY\nvalue at the start of each touch event.
\n", "itemtype": "property", "name": "pmouseY", "type": "Number", "readonly": "", "example": [ "\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n //draw a square only if the mouse is not moving\n if (mouseY === pmouseY && mouseX === pmouseX) {\n rect(20, 20, 60, 60);\n }\n\n print(pmouseY + ' -> ' + mouseY);\n describe(`60-by-60 black rect center, fuchsia background.\n rect flickers on mouse movement`);\n}\n
\nThe system variable winMouseX always contains the current horizontal\nposition of the mouse, relative to (0, 0) of the window.
\n", "itemtype": "property", "name": "winMouseX", "type": "Number", "readonly": "", "example": [ "\n\nlet myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n let body = document.getElementsByTagName('body')[0];\n myCanvas.parent(body);\n}\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n //move the canvas to the horizontal mouse position\n //relative to the window\n myCanvas.position(winMouseX + 1, windowHeight / 2);\n\n //the y of the square is relative to the canvas\n rect(20, mouseY, 60, 60);\n describe(`60-by-60 black rect y moves with mouse y and fuchsia\n canvas moves with mouse x`);\n}\n
\nThe system variable winMouseY always contains the current vertical\nposition of the mouse, relative to (0, 0) of the window.
\n", "itemtype": "property", "name": "winMouseY", "type": "Number", "readonly": "", "example": [ "\n\nlet myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n let body = document.getElementsByTagName('body')[0];\n myCanvas.parent(body);\n}\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n //move the canvas to the vertical mouse position\n //relative to the window\n myCanvas.position(windowWidth / 2, winMouseY + 1);\n\n //the x of the square is relative to the canvas\n rect(mouseX, 20, 60, 60);\n describe(`60-by-60 black rect x moves with mouse x and\n fuchsia canvas y moves with mouse y`);\n}\n
\nThe system variable pwinMouseX always contains the horizontal position\nof the mouse in the frame previous to the current frame, relative to\n(0, 0) of the window. Note: pwinMouseX will be reset to the current winMouseX\nvalue at the start of each touch event.
\n", "itemtype": "property", "name": "pwinMouseX", "type": "Number", "readonly": "", "example": [ "\n\nlet myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n noStroke();\n fill(237, 34, 93);\n}\n\nfunction draw() {\n clear();\n //the difference between previous and\n //current x position is the horizontal mouse speed\n let speed = abs(winMouseX - pwinMouseX);\n //change the size of the circle\n //according to the horizontal speed\n ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);\n //move the canvas to the mouse position\n myCanvas.position(winMouseX + 1, winMouseY + 1);\n describe(`fuchsia ellipse moves with mouse x and y.\n Grows and shrinks with mouse speed`);\n}\n
\nThe system variable pwinMouseY always contains the vertical position of\nthe mouse in the frame previous to the current frame, relative to (0, 0)\nof the window. Note: pwinMouseY will be reset to the current winMouseY\nvalue at the start of each touch event.
\n", "itemtype": "property", "name": "pwinMouseY", "type": "Number", "readonly": "", "example": [ "\n\nlet myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n noStroke();\n fill(237, 34, 93);\n}\n\nfunction draw() {\n clear();\n //the difference between previous and\n //current y position is the vertical mouse speed\n let speed = abs(winMouseY - pwinMouseY);\n //change the size of the circle\n //according to the vertical speed\n ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);\n //move the canvas to the mouse position\n myCanvas.position(winMouseX + 1, winMouseY + 1);\n describe(`fuchsia ellipse moves with mouse x and y.\n Grows and shrinks with mouse speed`);\n}\n
\np5 automatically tracks if the mouse button is pressed and which\nbutton is pressed. The value of the system variable mouseButton is either\nLEFT, RIGHT, or CENTER depending on which button was pressed last.\nWarning: different browsers may track mouseButton differently.
\n", "itemtype": "property", "name": "mouseButton", "type": "Constant", "readonly": "", "example": [ "\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n if (mouseIsPressed === true) {\n if (mouseButton === LEFT) {\n ellipse(50, 50, 50, 50);\n }\n if (mouseButton === RIGHT) {\n rect(25, 25, 50, 50);\n }\n if (mouseButton === CENTER) {\n triangle(23, 75, 50, 20, 78, 75);\n }\n }\n\n print(mouseButton);\n describe(`50-by-50 black ellipse appears on center of fuchsia\n canvas on mouse click/press.`);\n}\n
\nThe boolean system variable mouseIsPressed is true if the mouse is pressed\nand false if not.
\n", "itemtype": "property", "name": "mouseIsPressed", "type": "Boolean", "readonly": "", "example": [ "\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n if (mouseIsPressed === true) {\n ellipse(50, 50, 50, 50);\n } else {\n rect(25, 25, 50, 50);\n }\n\n print(mouseIsPressed);\n describe(`black 50-by-50 rect becomes ellipse with mouse click/press.\n fuchsia background.`);\n}\n
\nThe mouseMoved() function is called every time the mouse moves and a mouse\nbutton is not pressed.
\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add \"return false\" to the end of the method.
optional MouseEvent callback argument.
\n", "type": "Object", "optional": true } ], "example": [ "\n\n// Move the mouse across the page\n// to change its value\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`black 50-by-50 rect becomes lighter with mouse movements until\n white then resets no image displayed`);\n}\nfunction mouseMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n
\n\nfunction mouseMoved() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// returns a MouseEvent object\n// as a callback argument\nfunction mouseMoved(event) {\n console.log(event);\n}\n
\nThe mouseDragged() function is called once every time the mouse moves and\na mouse button is pressed. If no mouseDragged() function is defined, the\ntouchMoved() function will be called instead if it is defined.
\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add \"return false\" to the end of the function.
optional MouseEvent callback argument.
\n", "type": "Object", "optional": true } ], "example": [ "\n\n// Drag the mouse across the page\n// to change its value\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`black 50-by-50 rect turns lighter with mouse click and\n drag until white, resets`);\n}\nfunction mouseDragged() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n
\n\nfunction mouseDragged() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// returns a MouseEvent object\n// as a callback argument\nfunction mouseDragged(event) {\n console.log(event);\n}\n
\nThe mousePressed() function is called once after every time a mouse button\nis pressed. The mouseButton variable (see the related reference entry)\ncan be used to determine which button has been pressed. If no\nmousePressed() function is defined, the touchStarted() function will be\ncalled instead if it is defined.
\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add \"return false\" to the end of the function.
optional MouseEvent callback argument.
\n", "type": "Object", "optional": true } ], "example": [ "\n\n// Click within the image to change\n// the value of the rectangle\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe('black 50-by-50 rect turns white with mouse click/press.');\n}\nfunction mousePressed() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\n\nfunction mousePressed() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// returns a MouseEvent object\n// as a callback argument\nfunction mousePressed(event) {\n console.log(event);\n}\n
\nThe mouseReleased() function is called every time a mouse button is\nreleased. If no mouseReleased() function is defined, the touchEnded()\nfunction will be called instead if it is defined.
\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add \"return false\" to the end of the function.
optional MouseEvent callback argument.
\n", "type": "Object", "optional": true } ], "example": [ "\n\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been clicked\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe('black 50-by-50 rect turns white with mouse click/press.');\n}\nfunction mouseReleased() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\n\nfunction mouseReleased() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// returns a MouseEvent object\n// as a callback argument\nfunction mouseReleased(event) {\n console.log(event);\n}\n
\nThe mouseClicked() function is called once after a mouse button has been\npressed and then released.
\nBrowsers handle clicks differently, so this function is only guaranteed to be\nrun when the left mouse button is clicked. To handle other mouse buttons\nbeing pressed or released, see mousePressed() or mouseReleased().
\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add \"return false\" to the end of the function.
optional MouseEvent callback argument.
\n", "type": "Object", "optional": true } ], "example": [ "\n\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been clicked\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe('black 50-by-50 rect turns white with mouse click/press.');\n}\n\nfunction mouseClicked() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\n\nfunction mouseClicked() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// returns a MouseEvent object\n// as a callback argument\nfunction mouseClicked(event) {\n console.log(event);\n}\n
\nThe doubleClicked() function is executed every time a event\nlistener has detected a dblclick event which is a part of the\nDOM L3 specification. The doubleClicked event is fired when a\npointing device button (usually a mouse's primary button)\nis clicked twice on a single element. For more info on the\ndblclick event refer to mozilla's documentation here:\nhttps://developer.mozilla.org/en-US/docs/Web/Events/dblclick
\n", "itemtype": "method", "name": "doubleClicked", "params": [ { "name": "event", "description": "optional MouseEvent callback argument.
\n", "type": "Object", "optional": true } ], "example": [ "\n\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been double clicked\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe('black 50-by-50 rect turns white with mouse doubleClick/press.');\n}\n\nfunction doubleClicked() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\n\nfunction doubleClicked() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// returns a MouseEvent object\n// as a callback argument\nfunction doubleClicked(event) {\n console.log(event);\n}\n
\nThe function mouseWheel() is executed every time a vertical mouse wheel\nevent is detected either triggered by an actual mouse wheel or by a\ntouchpad.
\nThe event.delta property returns the amount the mouse wheel\nhave scrolled. The values can be positive or negative depending on the\nscroll direction (on macOS with \"natural\" scrolling enabled, the signs\nare inverted).
\nBrowsers may have different default behaviors attached to various\nmouse events. To prevent any default behavior for this event, add\n\"return false\" to the end of the method.
\nDue to the current support of the \"wheel\" event on Safari, the function\nmay only work as expected if \"return false\" is included while using Safari.
optional WheelEvent callback argument.
\n", "type": "Object", "optional": true } ], "example": [ "\n\nlet pos = 25;\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n rect(25, pos, 50, 50);\n describe(`black 50-by-50 rect moves up and down with vertical scroll.\n fuchsia background`);\n}\n\nfunction mouseWheel(event) {\n print(event.delta);\n //move the square according to the vertical scroll amount\n pos += event.delta;\n //uncomment to block page scrolling\n //return false;\n}\n
\nThe function requestPointerLock()\nlocks the pointer to its current position and makes it invisible.\nUse movedX and movedY to get the difference the mouse was moved since\nthe last call of draw.\nNote that not all browsers support this feature.\nThis enables you to create experiences that aren't limited by the mouse moving out of the screen\neven if it is repeatedly moved into one direction.\nFor example, a first person perspective experience.
\n", "itemtype": "method", "name": "requestPointerLock", "example": [ "\n\nlet cam;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n requestPointerLock();\n cam = createCamera();\n}\n\nfunction draw() {\n background(255);\n cam.pan(-movedX * 0.001);\n cam.tilt(movedY * 0.001);\n sphere(25);\n describe(`3D scene moves according to mouse mouse movement in a\n first person perspective`);\n}\n
\nThe function exitPointerLock()\nexits a previously triggered pointer Lock\nfor example to make ui elements usable etc
\n", "itemtype": "method", "name": "exitPointerLock", "example": [ "\n\n//click the canvas to lock the pointer\n//click again to exit (otherwise escape)\nlet locked = false;\nfunction draw() {\n background(237, 34, 93);\n describe('cursor gets locked / unlocked on mouse-click');\n}\nfunction mouseClicked() {\n if (!locked) {\n locked = true;\n requestPointerLock();\n } else {\n exitPointerLock();\n locked = false;\n }\n}\n
\nThe system variable touches[] contains an array of the positions of all\ncurrent touch points, relative to (0, 0) of the canvas, and IDs identifying a\nunique touch as it moves. Each element in the array is an object with x, y,\nand id properties.
\nThe touches[] array is not supported on Safari and IE on touch-based\ndesktops (laptops).
\n", "itemtype": "property", "name": "touches", "type": "Object[]", "readonly": "", "example": [ "\n\n// On a touchscreen device, touch\n// the canvas using one or more fingers\n// at the same time\nfunction draw() {\n clear();\n let display = touches.length + ' touches';\n text(display, 5, 10);\n describe(`Number of touches currently registered are displayed\n on the canvas`);\n}\n
\nThe touchStarted() function is called once after every time a touch is\nregistered. If no touchStarted() function is defined, the mousePressed()\nfunction will be called instead if it is defined.
\nBrowsers may have different default behaviors attached to various touch\nevents. To prevent any default behavior for this event, add \"return false\"\nto the end of the method.
optional TouchEvent callback argument.
\n", "type": "Object", "optional": true } ], "example": [ "\n\n// Touch within the image to change\n// the value of the rectangle\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe('50-by-50 black rect turns white with touch event.');\n}\nfunction touchStarted() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\n\nfunction touchStarted() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\ndescribe('no image displayed');\n
\n\n// returns a TouchEvent object\n// as a callback argument\nfunction touchStarted(event) {\n console.log(event);\n}\ndescribe('no image displayed');\n
\nThe touchMoved() function is called every time a touch move is registered.\nIf no touchMoved() function is defined, the mouseDragged() function will\nbe called instead if it is defined.
\nBrowsers may have different default behaviors attached to various touch\nevents. To prevent any default behavior for this event, add \"return false\"\nto the end of the method.
optional TouchEvent callback argument.
\n", "type": "Object", "optional": true } ], "example": [ "\n\n// Move your finger across the page\n// to change its value\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe('50-by-50 black rect turns lighter with touch until white. resets');\n}\nfunction touchMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n
\n\nfunction touchMoved() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\ndescribe('no image displayed');\n
\n\n// returns a TouchEvent object\n// as a callback argument\nfunction touchMoved(event) {\n console.log(event);\n}\ndescribe('no image displayed');\n
\nThe touchEnded() function is called every time a touch ends. If no\ntouchEnded() function is defined, the mouseReleased() function will be\ncalled instead if it is defined.
\nBrowsers may have different default behaviors attached to various touch\nevents. To prevent any default behavior for this event, add \"return false\"\nto the end of the method.
optional TouchEvent callback argument.
\n", "type": "Object", "optional": true } ], "example": [ "\n\n// Release touch within the image to\n// change the value of the rectangle\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe('50-by-50 black rect turns white with touch.');\n}\nfunction touchEnded() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\n\nfunction touchEnded() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\ndescribe('no image displayed');\n
\n\n// returns a TouchEvent object\n// as a callback argument\nfunction touchEnded(event) {\n console.log(event);\n}\ndescribe('no image displayed');\n
\nThis module defines the filters for use with image buffers.
\nThis module is basically a collection of functions stored in an object\nas opposed to modules. The functions are destructive, modifying\nthe passed in canvas rather than creating a copy.
\nGenerally speaking users of this module will use the Filters.apply method\non a canvas to create an effect.
\nA number of functions are borrowed/adapted from\nhttp://www.html5rocks.com/en/tutorials/canvas/imagefilters/\nor the java processing implementation.
\n", "class": "p5", "module": "Events" }, { "file": "src/image/image.js", "line": 8, "description": "This module defines the p5 methods for the p5.Image class\nfor drawing images to the main display canvas.
\n", "class": "p5", "module": "Image", "submodule": "Image" }, { "file": "src/image/image.js", "line": 15, "description": "Creates a new p5.Image (the datatype for storing images). This provides a\nfresh buffer of pixels to play with. Set the size of the buffer with the\nwidth and height parameters.
\n.pixels gives access to an array containing the values for all the pixels\nin the display window.\nThese values are numbers. This array is the size (including an appropriate\nfactor for the pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. See .pixels for\nmore info. It may also be simpler to use set() or get().
\nBefore accessing the pixels of an image, the data must loaded with the\nloadPixels() function. After the array data has been modified, the\nupdatePixels() function must be run to update the changes.
\n", "itemtype": "method", "name": "createImage", "params": [ { "name": "width", "description": "width in pixels
\n", "type": "Integer" }, { "name": "height", "description": "height in pixels
\n", "type": "Integer" } ], "return": { "description": "the p5.Image object", "type": "p5.Image" }, "example": [ "\n\nlet img = createImage(66, 66);\nimg.loadPixels();\nfor (let i = 0; i < img.width; i++) {\n for (let j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\n
\n\nlet img = createImage(66, 66);\nimg.loadPixels();\nfor (let i = 0; i < img.width; i++) {\n for (let j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102, (i % img.width) * 2));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\nimage(img, 34, 34);\n
\n\nlet pink = color(255, 102, 204);\nlet img = createImage(66, 66);\nimg.loadPixels();\nlet d = pixelDensity();\nlet halfImage = 4 * (img.width * d) * (img.height / 2 * d);\nfor (let i = 0; i < halfImage; i += 4) {\n img.pixels[i] = red(pink);\n img.pixels[i + 1] = green(pink);\n img.pixels[i + 2] = blue(pink);\n img.pixels[i + 3] = alpha(pink);\n}\nimg.updatePixels();\nimage(img, 17, 17);\n
\nSave the current canvas as an image. The browser will either save the\nfile immediately, or prompt the user with a dialogue window.
\n", "itemtype": "method", "name": "saveCanvas", "example": [ "\n\n function setup() {\n let c = createCanvas(100, 100);\n background(255, 0, 0);\n saveCanvas(c, 'myCanvas', 'jpg');\n }\n
\n // note that this example has the same result as above\n // if no canvas is specified, defaults to main canvas\n function setup() {\n let c = createCanvas(100, 100);\n background(255, 0, 0);\n saveCanvas('myCanvas', 'jpg');\n\n // all of the following are valid\n saveCanvas(c, 'myCanvas', 'jpg');\n saveCanvas(c, 'myCanvas.jpg');\n saveCanvas(c, 'myCanvas');\n saveCanvas(c);\n saveCanvas('myCanvas', 'png');\n saveCanvas('myCanvas');\n saveCanvas();\n }\n
a variable\n representing a specific html5 canvas (optional)
\n", "type": "p5.Element|HTMLCanvasElement" }, { "name": "filename", "description": "", "type": "String", "optional": true }, { "name": "extension", "description": "'jpg' or 'png'
\n", "type": "String", "optional": true } ] }, { "line": 136, "params": [ { "name": "filename", "description": "", "type": "String", "optional": true }, { "name": "extension", "description": "", "type": "String", "optional": true } ] } ] }, { "file": "src/image/image.js", "line": 416, "description": "Capture a sequence of frames that can be used to create a movie.\nAccepts a callback. For example, you may wish to send the frames\nto a server where they can be stored or converted into a movie.\nIf no callback is provided, the browser will pop up save dialogues in an\nattempt to download all of the images that have just been created. With the\ncallback provided the image data isn't saved by default but instead passed\nas an argument to the callback function as an array of objects, with the\nsize of array equal to the total number of frames.
\nThe arguments duration
and framerate
are constrained to be less or equal to 15 and 22, respectively, which means you\ncan only download a maximum of 15 seconds worth of frames at 22 frames per second, adding up to 330 frames.\nThis is done in order to avoid memory problems since a large enough canvas can fill up the memory in your computer\nvery easily and crash your program or even your browser.
To export longer animations, you might look into a library like\nccapture.js.
\n", "itemtype": "method", "name": "saveFrames", "params": [ { "name": "filename", "description": "", "type": "String" }, { "name": "extension", "description": "'jpg' or 'png'
\n", "type": "String" }, { "name": "duration", "description": "Duration in seconds to save the frames for. This parameter will be constrained to be less or equal to 15.
\n", "type": "Number" }, { "name": "framerate", "description": "Framerate to save the frames in. This parameter will be constrained to be less or equal to 22.
\n", "type": "Number" }, { "name": "callback", "description": "A callback function that will be executed\n to handle the image data. This function\n should accept an array as argument. The\n array will contain the specified number of\n frames of objects. Each object has three\n properties: imageData - an\n image/octet-stream, filename and extension.
\n", "type": "Function(Array)", "optional": true } ], "example": [ "\n\n function draw() {\n background(mouseX);\n }\n\n function mousePressed() {\n saveFrames('out', 'png', 1, 25, data => {\n print(data);\n });\n }\n
Loads an image from a path and creates a p5.Image from it.
\nThe image may not be immediately available for rendering.\nIf you want to ensure that the image is ready before doing\nanything with it, place the loadImage() call in preload().\nYou may also supply a callback function to handle the image when it's ready.
\nThe path to the image should be relative to the HTML file\nthat links in your sketch. Loading an image from a URL or other\nremote location may be blocked due to your browser's built-in\nsecurity.
\nYou can also pass in a string of a base64 encoded image as an alternative to the file path.\nRemember to add \"data:image/png;base64,\" in front of the string.
\n", "itemtype": "method", "name": "loadImage", "params": [ { "name": "path", "description": "Path of the image to be loaded
\n", "type": "String" }, { "name": "successCallback", "description": "Function to be called once\n the image is loaded. Will be passed the\n p5.Image.
\n", "type": "function(p5.Image)", "optional": true }, { "name": "failureCallback", "description": "called with event error if\n the image fails to load.
\n", "type": "Function(Event)", "optional": true } ], "return": { "description": "the p5.Image object", "type": "p5.Image" }, "example": [ "\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n}\n
\n\nfunction setup() {\n // here we use a callback to display the image after loading\n loadImage('assets/laDefense.jpg', img => {\n image(img, 0, 0);\n });\n}\n
\nGenerates a gif of your current animation and downloads it to your computer!
\nThe duration argument specifies how many seconds you want to record from your animation.\nThis value is then converted to the necessary number of frames to generate it, depending\non the value of units. More on that on the next paragraph.
\nAn optional object that can contain two more arguments: delay (number) and units (string).
\ndelay
, specifying how much time we should wait before recording
units
, a string that can be either 'seconds' or 'frames'. By default it's 'seconds'.
units
specifies how the duration and delay arguments will behave.\nIf 'seconds', these arguments will correspond to seconds, meaning that 3 seconds worth of animation\nwill be created. If 'frames', the arguments now correspond to the number of frames you want your\nanimation to be, if you are very sure of this number.
It is not recommended to write this function inside setup, since it won't work properly.\nThe recommended use can be seen in the example, where we use it inside an event function,\nlike keyPressed or mousePressed.
\n", "itemtype": "method", "name": "saveGif", "params": [ { "name": "filename", "description": "File name of your gif
\n", "type": "String" }, { "name": "duration", "description": "Duration in seconds that you wish to capture from your sketch
\n", "type": "Number" }, { "name": "options", "description": "An optional object that can contain two more arguments: delay, specifying\nhow much time we should wait before recording, and units, a string that can be either 'seconds' or\n'frames'. By default it's 'seconds'.
\n", "type": "Object" } ], "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n}\n\nfunction draw() {\n colorMode(RGB);\n background(30);\n\n // create a bunch of circles that move in... circles!\n for (let i = 0; i < 10; i++) {\n let opacity = map(i, 0, 10, 0, 255);\n noStroke();\n fill(230, 250, 90, opacity);\n circle(\n 30 * sin(frameCount / (30 - i)) + width / 2,\n 30 * cos(frameCount / (30 - i)) + height / 2,\n 10\n );\n }\n}\n\n// you can put it in the mousePressed function,\n// or keyPressed for example\nfunction keyPressed() {\n // this will download the first 5 seconds of the animation!\n if (key === 's') {\n saveGif('mySketch', 5);\n }\n}\n
\nHelper function for loading GIF-based images
\n", "class": "p5", "module": "Image", "submodule": "Loading & Displaying" }, { "file": "src/image/loading_displaying.js", "line": 796, "description": "Draw an image to the p5.js canvas.
\nThis function can be used with different numbers of parameters. The\nsimplest use requires only three parameters: img, x, and y—where (x, y) is\nthe position of the image. Two more parameters can optionally be added to\nspecify the width and height of the image.
\nThis function can also be used with eight Number parameters. To\ndifferentiate between all these parameters, p5.js uses the language of\n\"destination rectangle\" (which corresponds to \"dx\", \"dy\", etc.) and \"source\nimage\" (which corresponds to \"sx\", \"sy\", etc.) below. Specifying the\n\"source image\" dimensions can be useful when you want to display a\nsubsection of the source image instead of the whole thing. Here's a diagram\nto explain further:\n
This function can also be used to draw images without distorting the orginal aspect ratio,\nby adding 9th parameter, fit, which can either be COVER or CONTAIN.\nCONTAIN, as the name suggests, contains the whole image within the specified destination box\nwithout distorting the image ratio.\nCOVER covers the entire destination box.
\n", "itemtype": "method", "name": "image", "example": [ "\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n // Top-left corner of the img is at (0, 0)\n // Width and height are the img's original width and height\n image(img, 0, 0);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n background(50);\n // Top-left corner of the img is at (10, 10)\n // Width and height are 50×50\n image(img, 10, 10, 50, 50);\n}\n
\n\nfunction setup() {\n // Here, we use a callback to display the image after loading\n loadImage('assets/laDefense.jpg', img => {\n image(img, 0, 0);\n });\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/gradient.png');\n}\nfunction setup() {\n // 1. Background image\n // Top-left corner of the img is at (0, 0)\n // Width and height are the img's original width and height, 100×100\n image(img, 0, 0);\n // 2. Top right image\n // Top-left corner of destination rectangle is at (50, 0)\n // Destination rectangle width and height are 40×20\n // The next parameters are relative to the source image:\n // - Starting at position (50, 50) on the source image, capture a 50×50\n // subsection\n // - Draw this subsection to fill the dimensions of the destination rectangle\n image(img, 50, 0, 40, 20, 50, 50, 50, 50);\n}\n
\n\nlet img;\nfunction preload() {\n // dimensions of image are 780 x 440\n // dimensions of canvas are 100 x 100\n img = loadImage('assets/moonwalk.jpg');\n}\nfunction setup() {\n // CONTAIN the whole image without distorting the image's aspect ratio\n // CONTAIN the image within the specified destination box and display at LEFT,CENTER position\n background(color('green'));\n image(img, 0, 0, width, height, 0, 0, img.width, img.height, CONTAIN, LEFT);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense50.png'); // dimensions of image are 50 x 50\n}\nfunction setup() {\n // COVER the whole destination box without distorting the image's aspect ratio\n // COVER the specified destination box which is of dimension 100 x 100\n // Without specifying xAlign or yAlign, the image will be\n // centered in the destination box in both axes\n image(img, 0, 0, width, height, 0, 0, img.width, img.height, COVER);\n}\n
\nthe image to display
\n", "type": "p5.Image|p5.Element|p5.Texture" }, { "name": "x", "description": "the x-coordinate of the top-left corner of the image
\n", "type": "Number" }, { "name": "y", "description": "the y-coordinate of the top-left corner of the image
\n", "type": "Number" }, { "name": "width", "description": "the width to draw the image
\n", "type": "Number", "optional": true }, { "name": "height", "description": "the height to draw the image
\n", "type": "Number", "optional": true } ] }, { "line": 922, "params": [ { "name": "img", "description": "", "type": "p5.Image|p5.Element|p5.Texture" }, { "name": "dx", "description": "the x-coordinate of the destination\n rectangle in which to draw the source image
\n", "type": "Number" }, { "name": "dy", "description": "the y-coordinate of the destination\n rectangle in which to draw the source image
\n", "type": "Number" }, { "name": "dWidth", "description": "the width of the destination rectangle
\n", "type": "Number" }, { "name": "dHeight", "description": "the height of the destination rectangle
\n", "type": "Number" }, { "name": "sx", "description": "the x-coordinate of the subsection of the source\nimage to draw into the destination rectangle
\n", "type": "Number" }, { "name": "sy", "description": "the y-coordinate of the subsection of the source\nimage to draw into the destination rectangle
\n", "type": "Number" }, { "name": "sWidth", "description": "the width of the subsection of the\n source image to draw into the destination\n rectangle
\n", "type": "Number", "optional": true }, { "name": "sHeight", "description": "the height of the subsection of the\n source image to draw into the destination rectangle
\n", "type": "Number", "optional": true }, { "name": "fit", "description": "either CONTAIN or COVER
\n", "type": "Constant", "optional": true }, { "name": "xAlign", "description": "either LEFT, RIGHT or CENTER default is CENTER
\n", "type": "Constant", "optional": true }, { "name": "yAlign", "description": "either TOP, BOTTOM or CENTER default is CENTER
\n", "type": "Constant", "optional": true } ] } ] }, { "file": "src/image/loading_displaying.js", "line": 1036, "description": "Sets the fill value for displaying images. Images can be tinted to\nspecified colors or made transparent by including an alpha value.
\nTo apply transparency to an image without affecting its color, use\nwhite as the tint color and specify an alpha value. For instance,\ntint(255, 128) will make an image 50% transparent (assuming the default\nalpha range of 0-255, which can be changed with colorMode()).
\nThe value for the gray parameter must be less than or equal to the current\nmaximum value as specified by colorMode(). The default maximum value is\n255.
\n", "itemtype": "method", "name": "tint", "example": [ "\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n tint(0, 153, 204); // Tint blue\n image(img, 50, 0);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n tint(0, 153, 204, 126); // Tint blue and set transparency\n image(img, 50, 0);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n tint(255, 126); // Apply transparency without changing color\n image(img, 50, 0);\n}\n
\nred or hue value relative to\n the current color range
\n", "type": "Number" }, { "name": "v2", "description": "green or saturation value\n relative to the current color range
\n", "type": "Number" }, { "name": "v3", "description": "blue or brightness value\n relative to the current color range
\n", "type": "Number" }, { "name": "alpha", "description": "", "type": "Number", "optional": true } ] }, { "line": 1107, "params": [ { "name": "value", "description": "a color string
\n", "type": "String" } ] }, { "line": 1112, "params": [ { "name": "gray", "description": "a gray value
\n", "type": "Number" }, { "name": "alpha", "description": "", "type": "Number", "optional": true } ] }, { "line": 1118, "params": [ { "name": "values", "description": "an array containing the red,green,blue &\n and alpha components of the color
\n", "type": "Number[]" } ] }, { "line": 1124, "params": [ { "name": "color", "description": "the tint color
\n", "type": "p5.Color" } ] } ] }, { "file": "src/image/loading_displaying.js", "line": 1134, "description": "Removes the current fill value for displaying images and reverts to\ndisplaying images with their original hues.
\n", "itemtype": "method", "name": "noTint", "example": [ "\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n tint(0, 153, 204); // Tint blue\n image(img, 0, 0);\n noTint(); // Disable tint\n image(img, 50, 0);\n}\n
\nSet image mode. Modifies the location from which images are drawn by\nchanging the way in which parameters given to image() are interpreted.\nThe default mode is imageMode(CORNER), which interprets the second and\nthird parameters of image() as the upper-left corner of the image. If\ntwo additional parameters are specified, they are used to set the image's\nwidth and height.
\nimageMode(CORNERS) interprets the second and third parameters of image()\nas the location of one corner, and the fourth and fifth parameters as the\nopposite corner.
\nimageMode(CENTER) interprets the second and third parameters of image()\nas the image's center point. If two additional parameters are specified,\nthey are used to set the image's width and height.
\n", "itemtype": "method", "name": "imageMode", "params": [ { "name": "mode", "description": "either CORNER, CORNERS, or CENTER
\n", "type": "Constant" } ], "example": [ "\n\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n imageMode(CORNER);\n image(img, 10, 10, 50, 50);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n imageMode(CORNERS);\n image(img, 10, 10, 90, 40);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n imageMode(CENTER);\n image(img, 50, 50, 80, 80);\n}\n
\nThis module defines the p5.Image class and P5 methods for\ndrawing images to the main display canvas.
\n", "class": "p5.Image", "module": "Image", "submodule": "Image" }, { "file": "src/image/p5.Image.js", "line": 88, "description": "Image width.
\n", "itemtype": "property", "name": "width", "type": "Number", "readonly": "", "example": [ "\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n image(img, 0, 0);\n for (let i = 0; i < img.width; i++) {\n let c = img.get(i, img.height / 2);\n stroke(c);\n line(i, height / 2, i, height);\n }\n}\n
Image height.
\n", "itemtype": "property", "name": "height", "type": "Number", "readonly": "", "example": [ "\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n image(img, 0, 0);\n for (let i = 0; i < img.height; i++) {\n let c = img.get(img.width / 2, i);\n stroke(c);\n line(0, i, width / 2, i);\n }\n}\n
Array containing the values for all the pixels in the display window.\nThese values are numbers. This array is the size (include an appropriate\nfactor for pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. Retina and other\nhigh density displays may have more pixels (by a factor of\npixelDensity^2).\nFor example, if the image is 100×100 pixels, there will be 40,000. With\npixelDensity = 2, there will be 160,000. The first four values\n(indices 0-3) in the array will be the R, G, B, A values of the pixel at\n(0, 0). The second four values (indices 4-7) will contain the R, G, B, A\nvalues of the pixel at (1, 0). More generally, to set values for a pixel\nat (x, y):
\nlet d = pixelDensity();\nfor (let i = 0; i < d; i++) {\n for (let j = 0; j < d; j++) {\n // loop over\n index = 4 * ((y * d + j) * width * d + (x * d + i));\n pixels[index] = r;\n pixels[index+1] = g;\n pixels[index+2] = b;\n pixels[index+3] = a;\n }\n}\n
\nBefore accessing this array, the data must loaded with the loadPixels()\nfunction. After the array data has been modified, the updatePixels()\nfunction must be run to update the changes.
\n", "itemtype": "property", "name": "pixels", "type": "Number[]", "example": [ "\n\nlet img = createImage(66, 66);\nimg.loadPixels();\nfor (let i = 0; i < img.width; i++) {\n for (let j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\n
\n\nlet pink = color(255, 102, 204);\nlet img = createImage(66, 66);\nimg.loadPixels();\nfor (let i = 0; i < 4 * (width * height / 2); i += 4) {\n img.pixels[i] = red(pink);\n img.pixels[i + 1] = green(pink);\n img.pixels[i + 2] = blue(pink);\n img.pixels[i + 3] = alpha(pink);\n}\nimg.updatePixels();\nimage(img, 17, 17);\n
\nHelper function for animating GIF-based images with time
\n", "class": "p5.Image", "module": "Image", "submodule": "Image" }, { "file": "src/image/p5.Image.js", "line": 253, "description": "Helper fxn for sharing pixel methods
\n", "class": "p5.Image", "module": "Image", "submodule": "Image" }, { "file": "src/image/p5.Image.js", "line": 261, "description": "Loads the pixels data for this image into the [pixels] attribute.
\n", "itemtype": "method", "name": "loadPixels", "example": [ "\n\nlet myImage;\nlet halfImage;\n\nfunction preload() {\n myImage = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n myImage.loadPixels();\n halfImage = 4 * myImage.width * myImage.height / 2;\n for (let i = 0; i < halfImage; i++) {\n myImage.pixels[i + halfImage] = myImage.pixels[i];\n }\n myImage.updatePixels();\n}\n\nfunction draw() {\n image(myImage, 0, 0, width, height);\n}\n
Updates the backing canvas for this image with the contents of\nthe [pixels] array.
\nIf this image is an animated GIF then the pixels will be updated\nin the frame that is currently displayed.
\n", "itemtype": "method", "name": "updatePixels", "example": [ "\n\nlet myImage;\nlet halfImage;\n\nfunction preload() {\n myImage = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n myImage.loadPixels();\n halfImage = 4 * myImage.width * myImage.height / 2;\n for (let i = 0; i < halfImage; i++) {\n myImage.pixels[i + halfImage] = myImage.pixels[i];\n }\n myImage.updatePixels();\n}\n\nfunction draw() {\n image(myImage, 0, 0, width, height);\n}\n
x-offset of the target update area for the\n underlying canvas
\n", "type": "Integer" }, { "name": "y", "description": "y-offset of the target update area for the\n underlying canvas
\n", "type": "Integer" }, { "name": "w", "description": "width of the target update area for the\n underlying canvas
\n", "type": "Integer" }, { "name": "h", "description": "height of the target update area for the\n underlying canvas
\n", "type": "Integer" } ] }, { "line": 338, "params": [] } ] }, { "file": "src/image/p5.Image.js", "line": 346, "description": "Get a region of pixels from an image.
\nIf no params are passed, the whole image is returned.\nIf x and y are the only params passed a single pixel is extracted.\nIf all params are passed a rectangle region is extracted and a p5.Image\nis returned.
\n", "itemtype": "method", "name": "get", "return": { "description": "the rectangle p5.Image", "type": "p5.Image" }, "example": [ "\n\nlet myImage;\nlet c;\n\nfunction preload() {\n myImage = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n background(myImage);\n noStroke();\n c = myImage.get(60, 90);\n fill(c);\n rect(25, 25, 50, 50);\n}\n\n//get() returns color here\n
x-coordinate of the pixel
\n", "type": "Number" }, { "name": "y", "description": "y-coordinate of the pixel
\n", "type": "Number" }, { "name": "w", "description": "width
\n", "type": "Number" }, { "name": "h", "description": "height
\n", "type": "Number" } ], "return": { "description": "the rectangle p5.Image", "type": "p5.Image" } }, { "line": 383, "params": [], "return": { "description": "the whole p5.Image", "type": "p5.Image" } }, { "line": 387, "params": [ { "name": "x", "description": "", "type": "Number" }, { "name": "y", "description": "", "type": "Number" } ], "return": { "description": "color of pixel at x,y in array format [R, G, B, A]", "type": "Number[]" } } ] }, { "file": "src/image/p5.Image.js", "line": 400, "description": "Set the color of a single pixel or write an image into\nthis p5.Image.
\nNote that for a large number of pixels this will\nbe slower than directly manipulating the pixels array\nand then calling updatePixels().
\n", "itemtype": "method", "name": "set", "params": [ { "name": "x", "description": "x-coordinate of the pixel
\n", "type": "Number" }, { "name": "y", "description": "y-coordinate of the pixel
\n", "type": "Number" }, { "name": "a", "description": "grayscale value | pixel array |\n a p5.Color | image to copy
\n", "type": "Number|Number[]|Object" } ], "example": [ "\n\nlet img = createImage(66, 66);\nimg.loadPixels();\nfor (let i = 0; i < img.width; i++) {\n for (let j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102, (i % img.width) * 2));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\nimage(img, 34, 34);\n
\nResize the image to a new width and height. To make the image scale\nproportionally, use 0 as the value for the wide or high parameter.\nFor instance, to make the width of an image 150 pixels, and change\nthe height using the same proportion, use resize(150, 0).
\n", "itemtype": "method", "name": "resize", "params": [ { "name": "width", "description": "the resized image width
\n", "type": "Number" }, { "name": "height", "description": "the resized image height
\n", "type": "Number" } ], "example": [ "\n\nlet img;\n\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction draw() {\n image(img, 0, 0);\n}\n\nfunction mousePressed() {\n img.resize(50, 100);\n}\n
Copies a region of pixels from one image to another. If no\nsrcImage is specified this is used as the source. If the source\nand destination regions aren't the same size, it will\nautomatically resize source pixels to fit the specified\ntarget region.
\n", "itemtype": "method", "name": "copy", "example": [ "\n\nlet photo;\nlet bricks;\nlet x;\nlet y;\n\nfunction preload() {\n photo = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n x = bricks.width / 2;\n y = bricks.height / 2;\n photo.copy(bricks, 0, 0, x, y, 0, 0, x, y);\n image(photo, 0, 0);\n}\n
source image
\n", "type": "p5.Image|p5.Element" }, { "name": "sx", "description": "X coordinate of the source's upper left corner
\n", "type": "Integer" }, { "name": "sy", "description": "Y coordinate of the source's upper left corner
\n", "type": "Integer" }, { "name": "sw", "description": "source image width
\n", "type": "Integer" }, { "name": "sh", "description": "source image height
\n", "type": "Integer" }, { "name": "dx", "description": "X coordinate of the destination's upper left corner
\n", "type": "Integer" }, { "name": "dy", "description": "Y coordinate of the destination's upper left corner
\n", "type": "Integer" }, { "name": "dw", "description": "destination image width
\n", "type": "Integer" }, { "name": "dh", "description": "destination image height
\n", "type": "Integer" } ] }, { "line": 585, "params": [ { "name": "sx", "description": "", "type": "Integer" }, { "name": "sy", "description": "", "type": "Integer" }, { "name": "sw", "description": "", "type": "Integer" }, { "name": "sh", "description": "", "type": "Integer" }, { "name": "dx", "description": "", "type": "Integer" }, { "name": "dy", "description": "", "type": "Integer" }, { "name": "dw", "description": "", "type": "Integer" }, { "name": "dh", "description": "", "type": "Integer" } ] } ] }, { "file": "src/image/p5.Image.js", "line": 600, "description": "Masks part of an image from displaying by loading another\nimage and using its alpha channel as an alpha channel for\nthis image. Masks are cumulative, once applied to an image\nobject, they cannot be removed.
\n", "itemtype": "method", "name": "mask", "params": [ { "name": "srcImage", "description": "source image
\n", "type": "p5.Image" } ], "example": [ "\n\nlet photo, maskImage;\nfunction preload() {\n photo = loadImage('assets/rockies.jpg');\n maskImage = loadImage('assets/mask2.png');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n photo.mask(maskImage);\n image(photo, 0, 0);\n}\n
Applies an image filter to a p5.Image
\nTHRESHOLD\nConverts the image to black and white pixels depending if they are above or\nbelow the threshold defined by the level parameter. The parameter must be\nbetween 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used.
\nGRAY\nConverts any colors in the image to grayscale equivalents. No parameter\nis used.
\nOPAQUE\nSets the alpha channel to entirely opaque. No parameter is used.
\nINVERT\nSets each pixel to its inverse value. No parameter is used.
\nPOSTERIZE\nLimits each channel of the image to the number of colors specified as the\nparameter. The parameter can be set to values between 2 and 255, but\nresults are most noticeable in the lower ranges.
\nBLUR\nExecutes a Gaussian blur with the level parameter specifying the extent\nof the blurring. If no parameter is used, the blur is equivalent to\nGaussian blur of radius 1. Larger values increase the blur.
\nERODE\nReduces the light areas. No parameter is used.
\nDILATE\nIncreases the light areas. No parameter is used.
\nfilter() does not work in WEBGL mode.\nA similar effect can be achieved in WEBGL mode using custom\nshaders. Adam Ferriss has written\na selection of shader examples that contains many\nof the effects present in the filter examples.
\n", "itemtype": "method", "name": "filter", "params": [ { "name": "filterType", "description": "either THRESHOLD, GRAY, OPAQUE, INVERT,\n POSTERIZE, ERODE, DILATE or BLUR.\n See Filters.js for docs on\n each available filter
\n", "type": "Constant" }, { "name": "filterParam", "description": "an optional parameter unique\n to each filter, see above
\n", "type": "Number", "optional": true } ], "example": [ "\n\nlet photo1;\nlet photo2;\n\nfunction preload() {\n photo1 = loadImage('assets/rockies.jpg');\n photo2 = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n photo2.filter(GRAY);\n image(photo1, 0, 0);\n image(photo2, width / 2, 0);\n}\n
Copies a region of pixels from one image to another, using a specified\nblend mode to do the operation.
\n", "itemtype": "method", "name": "blend", "example": [ "\n\nlet mountains;\nlet bricks;\n\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n
\nlet mountains;\nlet bricks;\n\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n
\nlet mountains;\nlet bricks;\n\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n
source image
\n", "type": "p5.Image" }, { "name": "sx", "description": "X coordinate of the source's upper left corner
\n", "type": "Integer" }, { "name": "sy", "description": "Y coordinate of the source's upper left corner
\n", "type": "Integer" }, { "name": "sw", "description": "source image width
\n", "type": "Integer" }, { "name": "sh", "description": "source image height
\n", "type": "Integer" }, { "name": "dx", "description": "X coordinate of the destination's upper left corner
\n", "type": "Integer" }, { "name": "dy", "description": "Y coordinate of the destination's upper left corner
\n", "type": "Integer" }, { "name": "dw", "description": "destination image width
\n", "type": "Integer" }, { "name": "dh", "description": "destination image height
\n", "type": "Integer" }, { "name": "blendMode", "description": "the blend mode. either\n BLEND, DARKEST, LIGHTEST, DIFFERENCE,\n MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.
\nAvailable blend modes are: normal | multiply | screen | overlay |\n darken | lighten | color-dodge | color-burn | hard-light |\n soft-light | difference | exclusion | hue | saturation |\n color | luminosity
\nhttp://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/
\n", "type": "Constant" } ] }, { "line": 830, "params": [ { "name": "sx", "description": "", "type": "Integer" }, { "name": "sy", "description": "", "type": "Integer" }, { "name": "sw", "description": "", "type": "Integer" }, { "name": "sh", "description": "", "type": "Integer" }, { "name": "dx", "description": "", "type": "Integer" }, { "name": "dy", "description": "", "type": "Integer" }, { "name": "dw", "description": "", "type": "Integer" }, { "name": "dh", "description": "", "type": "Integer" }, { "name": "blendMode", "description": "", "type": "Constant" } ] } ] }, { "file": "src/image/p5.Image.js", "line": 874, "description": "Saves the image to a file and force the browser to download it.\nAccepts two strings for filename and file extension\nSupports png (default), jpg, and gif\n
\nNote that the file will only be downloaded as an animated GIF\nif the p5.Image was loaded from a GIF file.
give your file a name
\n", "type": "String" }, { "name": "extension", "description": "'png' or 'jpg'
\n", "type": "String" } ], "example": [ "\n\nlet photo;\n\nfunction preload() {\n photo = loadImage('assets/rockies.jpg');\n}\n\nfunction draw() {\n image(photo, 0, 0);\n}\n\nfunction keyTyped() {\n if (key === 's') {\n photo.save('photo', 'png');\n }\n}\n
Starts an animated GIF over at the beginning state.
\n", "itemtype": "method", "name": "reset", "example": [ "\n\nlet gif;\n\nfunction preload() {\n gif = loadImage('assets/arnott-wallace-wink-loop-once.gif');\n}\n\nfunction draw() {\n background(255);\n // The GIF file that we loaded only loops once\n // so it freezes on the last frame after playing through\n image(gif, 0, 0);\n}\n\nfunction mousePressed() {\n // Click to reset the GIF and begin playback from start\n gif.reset();\n}\n
Gets the index for the frame that is currently visible in an animated GIF.
\n", "itemtype": "method", "name": "getCurrentFrame", "return": { "description": "The index for the currently displaying frame in animated GIF", "type": "Number" }, "example": [ "\n\nlet gif;\n\nfunction preload() {\n gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif');\n}\n\nfunction draw() {\n let frame = gif.getCurrentFrame();\n image(gif, 0, 0);\n text(frame, 10, 90);\n}\n
Sets the index of the frame that is currently visible in an animated GIF
\n", "itemtype": "method", "name": "setFrame", "params": [ { "name": "index", "description": "the index for the frame that should be displayed
\n", "type": "Number" } ], "example": [ "\n\nlet gif;\n\nfunction preload() {\n gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif');\n}\n\n// Move your mouse up and down over canvas to see the GIF\n// frames animate\nfunction draw() {\n gif.pause();\n image(gif, 0, 0);\n // Get the highest frame number which is the number of frames - 1\n let maxFrame = gif.numFrames() - 1;\n // Set the current frame that is mapped to be relative to mouse position\n let frameNumber = floor(map(mouseY, 0, height, 0, maxFrame, true));\n gif.setFrame(frameNumber);\n}\n
Returns the number of frames in an animated GIF
\n", "itemtype": "method", "name": "numFrames", "return": { "description": "", "type": "Number" }, "example": [ " The number of frames in the animated GIF\n\nlet gif;\n\nfunction preload() {\n gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif');\n}\n\n// Move your mouse up and down over canvas to see the GIF\n// frames animate\nfunction draw() {\n gif.pause();\n image(gif, 0, 0);\n // Get the highest frame number which is the number of frames - 1\n let maxFrame = gif.numFrames() - 1;\n // Set the current frame that is mapped to be relative to mouse position\n let frameNumber = floor(map(mouseY, 0, height, 0, maxFrame, true));\n gif.setFrame(frameNumber);\n}\n
Plays an animated GIF that was paused with\npause()
\n", "itemtype": "method", "name": "play", "example": [ "\n\nlet gif;\n\nfunction preload() {\n gif = loadImage('assets/nancy-liang-wind-loop-forever.gif');\n}\n\nfunction draw() {\n background(255);\n image(gif, 0, 0);\n}\n\nfunction mousePressed() {\n gif.pause();\n}\n\nfunction mouseReleased() {\n gif.play();\n}\n
Pauses an animated GIF.
\n", "itemtype": "method", "name": "pause", "example": [ "\n\nlet gif;\n\nfunction preload() {\n gif = loadImage('assets/nancy-liang-wind-loop-forever.gif');\n}\n\nfunction draw() {\n background(255);\n image(gif, 0, 0);\n}\n\nfunction mousePressed() {\n gif.pause();\n}\n\nfunction mouseReleased() {\n gif.play();\n}\n
Changes the delay between frames in an animated GIF. There is an optional second parameter that\nindicates an index for a specific frame that should have its delay modified. If no index is given, all frames\nwill have the new delay.
\n", "itemtype": "method", "name": "delay", "params": [ { "name": "d", "description": "the amount in milliseconds to delay between switching frames
\n", "type": "Number" }, { "name": "index", "description": "the index of the frame that should have the new delay value {optional}
\n", "type": "Number", "optional": true } ], "example": [ "\n\nlet gifFast, gifSlow;\n\nfunction preload() {\n gifFast = loadImage('assets/arnott-wallace-eye-loop-forever.gif');\n gifSlow = loadImage('assets/arnott-wallace-eye-loop-forever.gif');\n}\n\nfunction setup() {\n gifFast.resize(width / 2, height / 2);\n gifSlow.resize(width / 2, height / 2);\n\n //Change the delay here\n gifFast.delay(10);\n gifSlow.delay(100);\n}\n\nfunction draw() {\n background(255);\n image(gifFast, 0, 0);\n image(gifSlow, width / 2, 0);\n}\n
Uint8ClampedArray\ncontaining the values for all the pixels in the display window.\nThese values are numbers. This array is the size (include an appropriate\nfactor for pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. Retina and other\nhigh density displays will have more pixels[] (by a factor of\npixelDensity^2).\nFor example, if the image is 100×100 pixels, there will be 40,000. On a\nretina display, there will be 160,000.
\nThe first four values (indices 0-3) in the array will be the R, G, B, A\nvalues of the pixel at (0, 0). The second four values (indices 4-7) will\ncontain the R, G, B, A values of the pixel at (1, 0). More generally, to\nset values for a pixel at (x, y):
\nlet d = pixelDensity();\nfor (let i = 0; i < d; i++) {\n for (let j = 0; j < d; j++) {\n // loop over\n index = 4 * ((y * d + j) * width * d + (x * d + i));\n pixels[index] = r;\n pixels[index+1] = g;\n pixels[index+2] = b;\n pixels[index+3] = a;\n }\n}\n
\nWhile the above method is complex, it is flexible enough to work with\nany pixelDensity. Note that set() will automatically take care of\nsetting all the appropriate values in pixels[] for a given (x, y) at\nany pixelDensity, but the performance may not be as fast when lots of\nmodifications are made to the pixel array.
\nBefore accessing this array, the data must loaded with the loadPixels()\nfunction. After the array data has been modified, the updatePixels()\nfunction must be run to update the changes.
\nNote that this is not a standard javascript array. This means that\nstandard javascript functions such as slice() or\narrayCopy() do not\nwork.
\n", "itemtype": "property", "name": "pixels", "type": "Number[]", "example": [ "\n\nlet pink = color(255, 102, 204);\nloadPixels();\nlet d = pixelDensity();\nlet halfImage = 4 * (width * d) * (height / 2 * d);\nfor (let i = 0; i < halfImage; i += 4) {\n pixels[i] = red(pink);\n pixels[i + 1] = green(pink);\n pixels[i + 2] = blue(pink);\n pixels[i + 3] = alpha(pink);\n}\nupdatePixels();\n
\nCopies a region of pixels from one image to another, using a specified\nblend mode to do the operation.
\n", "itemtype": "method", "name": "blend", "example": [ "\n\nlet img0;\nlet img1;\n\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n}\n
\nlet img0;\nlet img1;\n\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n}\n
\nlet img0;\nlet img1;\n\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n}\n
source image
\n", "type": "p5.Image" }, { "name": "sx", "description": "X coordinate of the source's upper left corner
\n", "type": "Integer" }, { "name": "sy", "description": "Y coordinate of the source's upper left corner
\n", "type": "Integer" }, { "name": "sw", "description": "source image width
\n", "type": "Integer" }, { "name": "sh", "description": "source image height
\n", "type": "Integer" }, { "name": "dx", "description": "X coordinate of the destination's upper left corner
\n", "type": "Integer" }, { "name": "dy", "description": "Y coordinate of the destination's upper left corner
\n", "type": "Integer" }, { "name": "dw", "description": "destination image width
\n", "type": "Integer" }, { "name": "dh", "description": "destination image height
\n", "type": "Integer" }, { "name": "blendMode", "description": "the blend mode. either\n BLEND, DARKEST, LIGHTEST, DIFFERENCE,\n MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.
\n", "type": "Constant" } ] }, { "line": 152, "params": [ { "name": "sx", "description": "", "type": "Integer" }, { "name": "sy", "description": "", "type": "Integer" }, { "name": "sw", "description": "", "type": "Integer" }, { "name": "sh", "description": "", "type": "Integer" }, { "name": "dx", "description": "", "type": "Integer" }, { "name": "dy", "description": "", "type": "Integer" }, { "name": "dw", "description": "", "type": "Integer" }, { "name": "dh", "description": "", "type": "Integer" }, { "name": "blendMode", "description": "", "type": "Constant" } ] } ] }, { "file": "src/image/pixels.js", "line": 173, "description": "Copies a region of the canvas to another region of the canvas\nand copies a region of pixels from an image used as the srcImg parameter\ninto the canvas srcImage is specified this is used as the source. If\nthe source and destination regions aren't the same size, it will\nautomatically resize source pixels to fit the specified\ntarget region.
\n", "itemtype": "method", "name": "copy", "example": [ "\n\nlet img;\n\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n background(img);\n copy(img, 7, 22, 10, 10, 35, 25, 50, 50);\n stroke(255);\n noFill();\n // Rectangle shows area being copied\n rect(7, 22, 10, 10);\n}\n
source image
\n", "type": "p5.Image|p5.Element" }, { "name": "sx", "description": "X coordinate of the source's upper left corner
\n", "type": "Integer" }, { "name": "sy", "description": "Y coordinate of the source's upper left corner
\n", "type": "Integer" }, { "name": "sw", "description": "source image width
\n", "type": "Integer" }, { "name": "sh", "description": "source image height
\n", "type": "Integer" }, { "name": "dx", "description": "X coordinate of the destination's upper left corner
\n", "type": "Integer" }, { "name": "dy", "description": "Y coordinate of the destination's upper left corner
\n", "type": "Integer" }, { "name": "dw", "description": "destination image width
\n", "type": "Integer" }, { "name": "dh", "description": "destination image height
\n", "type": "Integer" } ] }, { "line": 215, "params": [ { "name": "sx", "description": "", "type": "Integer" }, { "name": "sy", "description": "", "type": "Integer" }, { "name": "sw", "description": "", "type": "Integer" }, { "name": "sh", "description": "", "type": "Integer" }, { "name": "dx", "description": "", "type": "Integer" }, { "name": "dy", "description": "", "type": "Integer" }, { "name": "dw", "description": "", "type": "Integer" }, { "name": "dh", "description": "", "type": "Integer" } ] } ] }, { "file": "src/image/pixels.js", "line": 307, "description": "Applies a filter to the canvas. The presets options are:
\nTHRESHOLD\nConverts the image to black and white pixels depending if they are above or\nbelow the threshold defined by the level parameter. The parameter must be\nbetween 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used.
\nGRAY\nConverts any colors in the image to grayscale equivalents. No parameter\nis used.
\nOPAQUE\nSets the alpha channel to entirely opaque. No parameter is used.
\nINVERT\nSets each pixel to its inverse value. No parameter is used.
\nPOSTERIZE\nLimits each channel of the image to the number of colors specified as the\nparameter. The parameter can be set to values between 2 and 255, but\nresults are most noticeable in the lower ranges.
\nBLUR\nExecutes a Gaussian blur with the level parameter specifying the extent\nof the blurring. If no parameter is used, the blur is equivalent to\nGaussian blur of radius 1. Larger values increase the blur.
\nERODE\nReduces the light areas. No parameter is used.
\nDILATE\nIncreases the light areas. No parameter is used.
\nfilter() does not work in WEBGL mode.\nA similar effect can be achieved in WEBGL mode using custom\nshaders. Adam Ferriss has written\na selection of shader examples that contains many\nof the effects present in the filter examples.
\n", "itemtype": "method", "name": "filter", "params": [ { "name": "filterType", "description": "either THRESHOLD, GRAY, OPAQUE, INVERT,\n POSTERIZE, BLUR, ERODE, DILATE or BLUR.\n See Filters.js for docs on\n each available filter
\n", "type": "Constant" }, { "name": "filterParam", "description": "an optional parameter unique\n to each filter, see above
\n", "type": "Number", "optional": true } ], "example": [ "\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(THRESHOLD);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(GRAY);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(OPAQUE);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(INVERT);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(POSTERIZE, 3);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(DILATE);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(BLUR, 3);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(ERODE);\n}\n
\nGet a region of pixels, or a single pixel, from the canvas.
\nReturns an array of [R,G,B,A] values for any pixel or grabs a section of\nan image. If no parameters are specified, the entire image is returned.\nUse the x and y parameters to get the value of one pixel. Get a section of\nthe display window by specifying additional w and h parameters. When\ngetting an image, the x and y parameters define the coordinates for the\nupper-left corner of the image, regardless of the current imageMode().
\nGetting the color of a single pixel with get(x, y) is easy, but not as fast\nas grabbing the data directly from pixels[]. The equivalent statement to\nget(x, y) using pixels[] with pixel density d is
\nlet x, y, d; // set these to the coordinates\nlet off = (y * width + x) * d * 4;\nlet components = [\n pixels[off],\n pixels[off + 1],\n pixels[off + 2],\n pixels[off + 3]\n];\nprint(components);\n
\nSee the reference for pixels[] for more information.
\nIf you want to extract an array of colors or a subimage from an p5.Image object,\ntake a look at p5.Image.get()
\n", "itemtype": "method", "name": "get", "return": { "description": "the rectangle p5.Image", "type": "p5.Image" }, "example": [ "\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n let c = get();\n image(c, width / 2, 0);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n let c = get(50, 90);\n fill(c);\n noStroke();\n rect(25, 25, 50, 50);\n}\n
\nx-coordinate of the pixel
\n", "type": "Number" }, { "name": "y", "description": "y-coordinate of the pixel
\n", "type": "Number" }, { "name": "w", "description": "width
\n", "type": "Number" }, { "name": "h", "description": "height
\n", "type": "Number" } ], "return": { "description": "the rectangle p5.Image", "type": "p5.Image" } }, { "line": 551, "params": [], "return": { "description": "the whole p5.Image", "type": "p5.Image" } }, { "line": 555, "params": [ { "name": "x", "description": "", "type": "Number" }, { "name": "y", "description": "", "type": "Number" } ], "return": { "description": "color of pixel at x,y in array format [R, G, B, A]", "type": "Number[]" } } ] }, { "file": "src/image/pixels.js", "line": 566, "description": "Loads the pixel data for the display window into the pixels[] array. This\nfunction must always be called before reading from or writing to pixels[].\nNote that only changes made with set() or direct manipulation of pixels[]\nwill occur.
\n", "itemtype": "method", "name": "loadPixels", "example": [ "\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n image(img, 0, 0, width, height);\n let d = pixelDensity();\n let halfImage = 4 * (width * d) * (height * d / 2);\n loadPixels();\n for (let i = 0; i < halfImage; i++) {\n pixels[i + halfImage] = pixels[i];\n }\n updatePixels();\n}\n
\nChanges the color of any pixel, or writes an image directly to the\ndisplay window.\nThe x and y parameters specify the pixel to change and the c parameter\nspecifies the color value. This can be a p5.Color object, or [R, G, B, A]\npixel array. It can also be a single grayscale value.\nWhen setting an image, the x and y parameters define the coordinates for\nthe upper-left corner of the image, regardless of the current imageMode().
\nAfter using set(), you must call updatePixels() for your changes to appear.\nThis should be called once all pixels have been set, and must be called before\ncalling .get() or drawing the image.
\nSetting the color of a single pixel with set(x, y) is easy, but not as\nfast as putting the data directly into pixels[]. Setting the pixels[]\nvalues directly may be complicated when working with a retina display,\nbut will perform better when lots of pixels need to be set directly on\nevery loop. See the reference for pixels[] for more information.
\n", "itemtype": "method", "name": "set", "params": [ { "name": "x", "description": "x-coordinate of the pixel
\n", "type": "Number" }, { "name": "y", "description": "y-coordinate of the pixel
\n", "type": "Number" }, { "name": "c", "description": "insert a grayscale value | a pixel array |\n a p5.Color object | a p5.Image to copy
\n", "type": "Number|Number[]|Object" } ], "example": [ "\n\nlet black = color(0);\nset(30, 20, black);\nset(85, 20, black);\nset(85, 75, black);\nset(30, 75, black);\nupdatePixels();\n
\n\nfor (let i = 30; i < width - 15; i++) {\n for (let j = 20; j < height - 25; j++) {\n let c = color(204 - j, 153 - i, 0);\n set(i, j, c);\n }\n}\nupdatePixels();\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n set(0, 0, img);\n updatePixels();\n line(0, 0, width, height);\n line(0, height, width, 0);\n}\n
\nUpdates the display window with the data in the pixels[] array.\nUse in conjunction with loadPixels(). If you're only reading pixels from\nthe array, there's no need to call updatePixels() — updating is only\nnecessary to apply changes. updatePixels() should be called anytime the\npixels array is manipulated or set() is called, and only changes made with\nset() or direct changes to pixels[] will occur.
\n", "itemtype": "method", "name": "updatePixels", "params": [ { "name": "x", "description": "x-coordinate of the upper-left corner of region\n to update
\n", "type": "Number", "optional": true }, { "name": "y", "description": "y-coordinate of the upper-left corner of region\n to update
\n", "type": "Number", "optional": true }, { "name": "w", "description": "width of region to update
\n", "type": "Number", "optional": true }, { "name": "h", "description": "height of region to update
\n", "type": "Number", "optional": true } ], "example": [ "\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n image(img, 0, 0, width, height);\n let d = pixelDensity();\n let halfImage = 4 * (width * d) * (height * d / 2);\n loadPixels();\n for (let i = 0; i < halfImage; i++) {\n pixels[i + halfImage] = pixels[i];\n }\n updatePixels();\n}\n
\nLoads a JSON file from a file or a URL, and returns an Object.\nNote that even if the JSON file contains an Array, an Object will be\nreturned with index numbers as keys.
\nThis method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed. JSONP is supported via a polyfill and you\ncan pass in as the second argument an object with definitions of the json\ncallback following the syntax specified here.
\nThis method is suitable for fetching files up to size of 64MB.
\n", "itemtype": "method", "name": "loadJSON", "return": { "description": "JSON data", "type": "Object|Array" }, "example": [ "\n\nCalling loadJSON() inside preload() guarantees to complete the\noperation before setup() and draw() are called.\n\n\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\nlet earthquakes;\nfunction preload() {\n // Get the most recent earthquake in the database\n let url =\n 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +\n 'summary/all_day.geojson';\n earthquakes = loadJSON(url);\n}\n\nfunction setup() {\n noLoop();\n}\n\nfunction draw() {\n background(200);\n // Get the magnitude and name of the earthquake out of the loaded JSON\n let earthquakeMag = earthquakes.features[0].properties.mag;\n let earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n describe(`50×50 ellipse that changes from black to white\n depending on the current humidity`);\n}\n
\nfunction setup() {\n noLoop();\n let url =\n 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +\n 'summary/all_day.geojson';\n loadJSON(url, drawEarthquake);\n}\n\nfunction draw() {\n background(200);\n describe(`50×50 ellipse that changes from black to white\n depending on the current humidity`);\n}\n\nfunction drawEarthquake(earthquakes) {\n // Get the magnitude and name of the earthquake out of the loaded JSON\n let earthquakeMag = earthquakes.features[0].properties.mag;\n let earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n}\n
name of the file or url to load
\n", "type": "String" }, { "name": "jsonpOptions", "description": "options object for jsonp related settings
\n", "type": "Object", "optional": true }, { "name": "datatype", "description": "\"json\" or \"jsonp\"
\n", "type": "String", "optional": true }, { "name": "callback", "description": "function to be executed after\n loadJSON() completes, data is passed\n in as first argument
\n", "type": "Function", "optional": true }, { "name": "errorCallback", "description": "function to be executed if\n there is an error, response is passed\n in as first argument
\n", "type": "Function", "optional": true } ], "return": { "description": "JSON data", "type": "Object|Array" } }, { "line": 101, "params": [ { "name": "path", "description": "", "type": "String" }, { "name": "datatype", "description": "", "type": "String" }, { "name": "callback", "description": "", "type": "Function", "optional": true }, { "name": "errorCallback", "description": "", "type": "Function", "optional": true } ], "return": { "description": "", "type": "Object|Array" } }, { "line": 109, "params": [ { "name": "path", "description": "", "type": "String" }, { "name": "callback", "description": "", "type": "Function" }, { "name": "errorCallback", "description": "", "type": "Function", "optional": true } ], "return": { "description": "", "type": "Object|Array" } } ] }, { "file": "src/io/files.js", "line": 180, "description": "Reads the contents of a file and creates a String array of its individual\nlines. If the name of the file is used as the parameter, as in the above\nexample, the file must be located in the sketch directory/folder.
\nAlternatively, the file maybe be loaded from anywhere on the local\ncomputer using an absolute path (something that starts with / on Unix and\nLinux, or a drive letter on Windows), or the filename parameter can be a\nURL for a file found on a network.
\nThis method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed.
\nThis method is suitable for fetching files up to size of 64MB.
\n", "itemtype": "method", "name": "loadStrings", "params": [ { "name": "filename", "description": "name of the file or url to load
\n", "type": "String" }, { "name": "callback", "description": "function to be executed after loadStrings()\n completes, Array is passed in as first\n argument
\n", "type": "Function", "optional": true }, { "name": "errorCallback", "description": "function to be executed if\n there is an error, response is passed\n in as first argument
\n", "type": "Function", "optional": true } ], "return": { "description": "Array of Strings", "type": "String[]" }, "example": [ "\n\nCalling loadStrings() inside preload() guarantees to complete the\noperation before setup() and draw() are called.\n\n\nlet result;\nfunction preload() {\n result = loadStrings('assets/test.txt');\n}\n\nfunction setup() {\n background(200);\n text(random(result), 10, 10, 80, 80);\n describe(`randomly generated text from a file,\n for example \"i smell like butter\"`);\n}\n
\nfunction setup() {\n loadStrings('assets/test.txt', pickString);\n describe(`randomly generated text from a file,\n for example \"i have three feet\"`);\n}\n\nfunction pickString(result) {\n background(200);\n text(random(result), 10, 10, 80, 80);\n}\n
Reads the contents of a file or URL and creates a p5.Table object with\nits values. If a file is specified, it must be located in the sketch's\n\"data\" folder. The filename parameter can also be a URL to a file found\nonline. By default, the file is assumed to be comma-separated (in CSV\nformat). Table only looks for a header row if the 'header' option is\nincluded.
\nThis method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed. Calling loadTable() inside preload()\nguarantees to complete the operation before setup() and draw() are called.\nOutside of preload(), you may supply a callback function to handle the\nobject:
\nAll files loaded and saved use UTF-8 encoding. This method is suitable for fetching files up to size of 64MB.
\n", "itemtype": "method", "name": "loadTable", "params": [ { "name": "filename", "description": "name of the file or URL to load
\n", "type": "String" }, { "name": "extension", "description": "parse the table by comma-separated values \"csv\", semicolon-separated\n values \"ssv\", or tab-separated values \"tsv\"
\n", "type": "String", "optional": true }, { "name": "header", "description": "\"header\" to indicate table has header row
\n", "type": "String", "optional": true }, { "name": "callback", "description": "function to be executed after\n loadTable() completes. On success, the\n Table object is passed in as the\n first argument.
\n", "type": "Function", "optional": true }, { "name": "errorCallback", "description": "function to be executed if\n there is an error, response is passed\n in as first argument
\n", "type": "Function", "optional": true } ], "return": { "description": "Table object containing data", "type": "Object" }, "example": [ "\n\n// Given the following CSV file called \"mammals.csv\"\n// located in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n //the file can be remote\n //table = loadTable(\"http://p5js.org/reference/assets/mammals.csv\",\n // \"csv\", \"header\");\n}\n\nfunction setup() {\n //count the columns\n print(table.getRowCount() + ' total rows in table');\n print(table.getColumnCount() + ' total columns in table');\n\n print(table.getColumn('name'));\n //[\"Goat\", \"Leopard\", \"Zebra\"]\n\n //cycle through the table\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++) {\n print(table.getString(r, c));\n }\n describe(`randomly generated text from a file,\n for example \"i smell like butter\"`);\n}\n
\nReads the contents of a file and creates an XML object with its values.\nIf the name of the file is used as the parameter, as in the above example,\nthe file must be located in the sketch directory/folder.
\nAlternatively, the file maybe be loaded from anywhere on the local\ncomputer using an absolute path (something that starts with / on Unix and\nLinux, or a drive letter on Windows), or the filename parameter can be a\nURL for a file found on a network.
\nThis method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed. Calling loadXML() inside preload()\nguarantees to complete the operation before setup() and draw() are called.
\nOutside of preload(), you may supply a callback function to handle the\nobject.
\nThis method is suitable for fetching files up to size of 64MB.
\n", "itemtype": "method", "name": "loadXML", "params": [ { "name": "filename", "description": "name of the file or URL to load
\n", "type": "String" }, { "name": "callback", "description": "function to be executed after loadXML()\n completes, XML object is passed in as\n first argument
\n", "type": "Function", "optional": true }, { "name": "errorCallback", "description": "function to be executed if\n there is an error, response is passed\n in as first argument
\n", "type": "Function", "optional": true } ], "return": { "description": "XML object containing data", "type": "Object" }, "example": [ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let children = xml.getChildren('animal');\n\n for (let i = 0; i < children.length; i++) {\n let id = children[i].getNum('id');\n let coloring = children[i].getString('species');\n let name = children[i].getContent();\n print(id + ', ' + coloring + ', ' + name);\n }\n describe('no image displayed');\n}\n\n// Sketch prints:\n// 0, Capra hircus, Goat\n// 1, Panthera pardus, Leopard\n// 2, Equus zebra, Zebra\n
This method is suitable for fetching files up to size of 64MB.
\n", "itemtype": "method", "name": "loadBytes", "params": [ { "name": "file", "description": "name of the file or URL to load
\n", "type": "String" }, { "name": "callback", "description": "function to be executed after loadBytes()\n completes
\n", "type": "Function", "optional": true }, { "name": "errorCallback", "description": "function to be executed if there\n is an error
\n", "type": "Function", "optional": true } ], "return": { "description": "an object whose 'bytes' property will be the loaded buffer", "type": "Object" }, "example": [ "\n\nlet data;\n\nfunction preload() {\n data = loadBytes('assets/mammals.xml');\n}\n\nfunction setup() {\n for (let i = 0; i < 5; i++) {\n console.log(data.bytes[i].toString(16));\n }\n describe('no image displayed');\n}\n
Method for executing an HTTP GET request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text. This is equivalent to\ncalling httpDo(path, 'GET')
. The 'binary' datatype will return\na Blob object, and the 'arrayBuffer' datatype will return an ArrayBuffer\nwhich can be used to initialize typed arrays (such as Uint8Array).
\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\nlet earthquakes;\nfunction preload() {\n // Get the most recent earthquake in the database\n let url =\n 'https://earthquake.usgs.gov/fdsnws/event/1/query?' +\n 'format=geojson&limit=1&orderby=time';\n httpGet(url, 'jsonp', false, function(response) {\n // when the HTTP request completes, populate the variable that holds the\n // earthquake data used in the visualization.\n earthquakes = response;\n });\n}\n\nfunction draw() {\n if (!earthquakes) {\n // Wait until the earthquake data has loaded before drawing.\n return;\n }\n background(200);\n // Get the magnitude and name of the earthquake out of the loaded JSON\n let earthquakeMag = earthquakes.features[0].properties.mag;\n let earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n noLoop();\n}\n
name of the file or url to load
\n", "type": "String" }, { "name": "datatype", "description": "\"json\", \"jsonp\", \"binary\", \"arrayBuffer\",\n \"xml\", or \"text\"
\n", "type": "String", "optional": true }, { "name": "data", "description": "param data passed sent with request
\n", "type": "Object|Boolean", "optional": true }, { "name": "callback", "description": "function to be executed after\n httpGet() completes, data is passed in\n as first argument
\n", "type": "Function", "optional": true }, { "name": "errorCallback", "description": "function to be executed if\n there is an error, response is passed\n in as first argument
\n", "type": "Function", "optional": true } ], "return": { "description": "A promise that resolves with the data when the operation\n completes successfully or rejects with the error after\n one occurs.", "type": "Promise" } }, { "line": 797, "params": [ { "name": "path", "description": "", "type": "String" }, { "name": "data", "description": "", "type": "Object|Boolean" }, { "name": "callback", "description": "", "type": "Function", "optional": true }, { "name": "errorCallback", "description": "", "type": "Function", "optional": true } ], "return": { "description": "", "type": "Promise" } }, { "line": 805, "params": [ { "name": "path", "description": "", "type": "String" }, { "name": "callback", "description": "", "type": "Function" }, { "name": "errorCallback", "description": "", "type": "Function", "optional": true } ], "return": { "description": "", "type": "Promise" } } ] }, { "file": "src/io/files.js", "line": 820, "description": "Method for executing an HTTP POST request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text. This is equivalent to\ncalling httpDo(path, 'POST')
.
\n// Examples use jsonplaceholder.typicode.com for a Mock Data API\n\nlet url = 'https://jsonplaceholder.typicode.com/posts';\nlet postData = { userId: 1, title: 'p5 Clicked!', body: 'p5.js is very cool.' };\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n}\n\nfunction mousePressed() {\n httpPost(url, 'json', postData, function(result) {\n strokeWeight(2);\n text(result.body, mouseX, mouseY);\n });\n}\n
\n\nlet url = 'ttps://invalidURL'; // A bad URL that will cause errors\nlet postData = { title: 'p5 Clicked!', body: 'p5.js is very cool.' };\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n}\n\nfunction mousePressed() {\n httpPost(\n url,\n 'json',\n postData,\n function(result) {\n // ... won't be called\n },\n function(error) {\n strokeWeight(2);\n text(error.toString(), mouseX, mouseY);\n }\n );\n}\n
name of the file or url to load
\n", "type": "String" }, { "name": "datatype", "description": "\"json\", \"jsonp\", \"xml\", or \"text\".\n If omitted, httpPost() will guess.
\n", "type": "String", "optional": true }, { "name": "data", "description": "param data passed sent with request
\n", "type": "Object|Boolean", "optional": true }, { "name": "callback", "description": "function to be executed after\n httpPost() completes, data is passed in\n as first argument
\n", "type": "Function", "optional": true }, { "name": "errorCallback", "description": "function to be executed if\n there is an error, response is passed\n in as first argument
\n", "type": "Function", "optional": true } ], "return": { "description": "A promise that resolves with the data when the operation\n completes successfully or rejects with the error after\n one occurs.", "type": "Promise" } }, { "line": 887, "params": [ { "name": "path", "description": "", "type": "String" }, { "name": "data", "description": "", "type": "Object|Boolean" }, { "name": "callback", "description": "", "type": "Function", "optional": true }, { "name": "errorCallback", "description": "", "type": "Function", "optional": true } ], "return": { "description": "", "type": "Promise" } }, { "line": 895, "params": [ { "name": "path", "description": "", "type": "String" }, { "name": "callback", "description": "", "type": "Function" }, { "name": "errorCallback", "description": "", "type": "Function", "optional": true } ], "return": { "description": "", "type": "Promise" } } ] }, { "file": "src/io/files.js", "line": 910, "description": "Method for executing an HTTP request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text.
\nFor more advanced use, you may also pass in the path as the first argument\nand a object as the second argument, the signature follows the one specified\nin the Fetch API specification.\nThis method is suitable for fetching files up to size of 64MB when \"GET\" is used.
\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\n\n// displays an animation of all USGS earthquakes\nlet earthquakes;\nlet eqFeatureIndex = 0;\n\nfunction preload() {\n let url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson';\n httpDo(\n url,\n {\n method: 'GET',\n // Other Request options, like special headers for apis\n headers: { authorization: 'Bearer secretKey' }\n },\n function(res) {\n earthquakes = res;\n }\n );\n}\n\nfunction draw() {\n // wait until the data is loaded\n if (!earthquakes || !earthquakes.features[eqFeatureIndex]) {\n return;\n }\n clear();\n\n let feature = earthquakes.features[eqFeatureIndex];\n let mag = feature.properties.mag;\n let rad = mag / 11 * ((width + height) / 2);\n fill(255, 0, 0, 100);\n ellipse(width / 2 + random(-2, 2), height / 2 + random(-2, 2), rad, rad);\n\n if (eqFeatureIndex >= earthquakes.features.length) {\n eqFeatureIndex = 0;\n } else {\n eqFeatureIndex += 1;\n }\n}\n
\nname of the file or url to load
\n", "type": "String" }, { "name": "method", "description": "either \"GET\", \"POST\", or \"PUT\",\n defaults to \"GET\"
\n", "type": "String", "optional": true }, { "name": "datatype", "description": "\"json\", \"jsonp\", \"xml\", or \"text\"
\n", "type": "String", "optional": true }, { "name": "data", "description": "param data passed sent with request
\n", "type": "Object", "optional": true }, { "name": "callback", "description": "function to be executed after\n httpGet() completes, data is passed in\n as first argument
\n", "type": "Function", "optional": true }, { "name": "errorCallback", "description": "function to be executed if\n there is an error, response is passed\n in as first argument
\n", "type": "Function", "optional": true } ], "return": { "description": "A promise that resolves with the data when the operation\n completes successfully or rejects with the error after\n one occurs.", "type": "Promise" } }, { "line": 981, "params": [ { "name": "path", "description": "", "type": "String" }, { "name": "options", "description": "Request object options as documented in the\n \"fetch\" API\nreference
\n", "type": "Object" }, { "name": "callback", "description": "", "type": "Function", "optional": true }, { "name": "errorCallback", "description": "", "type": "Function", "optional": true } ], "return": { "description": "", "type": "Promise" } } ] }, { "file": "src/io/files.js", "line": 1146, "itemtype": "method", "name": "createWriter", "params": [ { "name": "name", "description": "name of the file to be created
\n", "type": "String" }, { "name": "extension", "description": "", "type": "String", "optional": true } ], "return": { "description": "", "type": "p5.PrintWriter" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n}\n\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n const writer = createWriter('squares.txt');\n for (let i = 0; i < 10; i++) {\n writer.print(i * i);\n }\n writer.close();\n writer.clear();\n }\n}\n
\nWrites data to the PrintWriter stream
\n", "itemtype": "method", "name": "write", "params": [ { "name": "data", "description": "all data to be written by the PrintWriter
\n", "type": "Array" } ], "example": [ "\n\n// creates a file called 'newFile.txt'\nlet writer = createWriter('newFile.txt');\n// write 'Hello world!'' to the file\nwriter.write(['Hello world!']);\n// close the PrintWriter and save the file\nwriter.close();\n
\n\n// creates a file called 'newFile2.txt'\nlet writer = createWriter('newFile2.txt');\n// write 'apples,bananas,123' to the file\nwriter.write(['apples', 'bananas', 123]);\n// close the PrintWriter and save the file\nwriter.close();\n
\n\n// creates a file called 'newFile3.txt'\nlet writer = createWriter('newFile3.txt');\n// write 'My name is: Teddy' to the file\nwriter.write('My name is:');\nwriter.write(' Teddy');\n// close the PrintWriter and save the file\nwriter.close();\n
\n\nfunction setup() {\n createCanvas(100, 100);\n button = createButton('SAVE FILE');\n button.position(21, 40);\n button.mousePressed(createFile);\n}\n\nfunction createFile() {\n // creates a file called 'newFile.txt'\n let writer = createWriter('newFile.txt');\n // write 'Hello world!'' to the file\n writer.write(['Hello world!']);\n // close the PrintWriter and save the file\n writer.close();\n}\n
\nWrites data to the PrintWriter stream, and adds a new line at the end
\n", "itemtype": "method", "name": "print", "params": [ { "name": "data", "description": "all data to be printed by the PrintWriter
\n", "type": "Array" } ], "example": [ "\n\n// creates a file called 'newFile.txt'\nlet writer = createWriter('newFile.txt');\n// creates a file containing\n// My name is:\n// Teddy\nwriter.print('My name is:');\nwriter.print('Teddy');\n// close the PrintWriter and save the file\nwriter.close();\n
\n\nlet writer;\n\nfunction setup() {\n createCanvas(400, 400);\n // create a PrintWriter\n writer = createWriter('newFile.txt');\n}\n\nfunction draw() {\n writer.print([mouseX, mouseY]);\n}\n\nfunction mouseClicked() {\n writer.close();\n}\n
\nClears the data already written to the PrintWriter object
\n", "itemtype": "method", "name": "clear", "example": [ "\n\n// create writer object\nlet writer = createWriter('newFile.txt');\nwriter.write(['clear me']);\n// clear writer object here\nwriter.clear();\n// close writer\nwriter.close();\n
\nfunction setup() {\n button = createButton('CLEAR ME');\n button.position(21, 40);\n button.mousePressed(createFile);\n}\n\nfunction createFile() {\n let writer = createWriter('newFile.txt');\n writer.write(['clear me']);\n writer.clear();\n writer.close();\n}\n
\nCloses the PrintWriter
\n", "itemtype": "method", "name": "close", "example": [ "\n\n// create a file called 'newFile.txt'\nlet writer = createWriter('newFile.txt');\n// close the PrintWriter and save the file\nwriter.close();\n
\n\n// create a file called 'newFile2.txt'\nlet writer = createWriter('newFile2.txt');\n// write some data to the file\nwriter.write([100, 101, 102]);\n// close the PrintWriter and save the file\nwriter.close();\n
\nSaves a given element(image, text, json, csv, wav, or html) to the client's\ncomputer. The first parameter can be a pointer to element we want to save.\nThe element can be one of p5.Element,an Array of\nStrings, an Array of JSON, a JSON object, a p5.Table\n, a p5.Image, or a p5.SoundFile (requires\np5.sound). The second parameter is a filename (including extension).The\nthird parameter is for options specific to this type of object. This method\nwill save a file that fits the given parameters.\nIf it is called without specifying an element, by default it will save the\nwhole canvas as an image file. You can optionally specify a filename as\nthe first parameter in such a case.\nNote that it is not recommended to\ncall this method within draw, as it will open a new save dialog on every\nrender.
\n", "itemtype": "method", "name": "save", "params": [ { "name": "objectOrFilename", "description": "If filename is provided, will\n save canvas as an image with\n either png or jpg extension\n depending on the filename.\n If object is provided, will\n save depending on the object\n and filename (see examples\n above).
\n", "type": "Object|String", "optional": true }, { "name": "filename", "description": "If an object is provided as the first\n parameter, then the second parameter\n indicates the filename,\n and should include an appropriate\n file extension (see examples above).
\n", "type": "String", "optional": true }, { "name": "options", "description": "Additional options depend on\n filetype. For example, when saving JSON,\n true
indicates that the\n output will be optimized for filesize,\n rather than readability.
\n // Saves the canvas as an image\n cnv = createCanvas(300, 300);\n save(cnv, 'myCanvas.jpg');\n\n // Saves the canvas as an image by default\n save('myCanvas.jpg');\n describe('An example for saving a canvas as an image.');\n
\n // Saves p5.Image as an image\n img = createImage(10, 10);\n save(img, 'myImage.png');\n describe('An example for saving a p5.Image element as an image.');\n
\n // Saves p5.Renderer object as an image\n obj = createGraphics(100, 100);\n save(obj, 'myObject.png');\n describe('An example for saving a p5.Renderer element.');\n
\n let myTable = new p5.Table();\n // Saves table as html file\n save(myTable, 'myTable.html');\n\n // Comma Separated Values\n save(myTable, 'myTable.csv');\n\n // Tab Separated Values\n save(myTable, 'myTable.tsv');\n\n describe(`An example showing how to save a table in formats of\n HTML, CSV and TSV.`);\n
\n let myJSON = { a: 1, b: true };\n\n // Saves pretty JSON\n save(myJSON, 'my.json');\n\n // Optimizes JSON filesize\n save(myJSON, 'my.json', true);\n\n describe('An example for saving JSON to a txt file with some extra arguments.');\n
\n // Saves array of strings to text file with line breaks after each item\n let arrayOfStrings = ['a', 'b'];\n save(arrayOfStrings, 'my.txt');\n describe(`An example for saving an array of strings to text file\n with line breaks.`);\n
Writes the contents of an Array or a JSON object to a .json file.\nThe file saving process and location of the saved file will\nvary between web browsers.
\n", "itemtype": "method", "name": "saveJSON", "params": [ { "name": "json", "description": "", "type": "Array|Object" }, { "name": "filename", "description": "", "type": "String" }, { "name": "optimize", "description": "If true, removes line breaks\n and spaces from the output\n file to optimize filesize\n (but not readability).
\n", "type": "Boolean", "optional": true } ], "example": [ "\n\n let json = {}; // new JSON Object\n\n json.id = 0;\n json.species = 'Panthera leo';\n json.name = 'Lion';\n\n function setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n describe('no image displayed');\n }\n\n function mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n saveJSON(json, 'lion.json');\n }\n }\n\n // saves the following to a file called \"lion.json\":\n // {\n // \"id\": 0,\n // \"species\": \"Panthera leo\",\n // \"name\": \"Lion\"\n // }\n
Writes an array of Strings to a text file, one line per String.\nThe file saving process and location of the saved file will\nvary between web browsers.
\n", "itemtype": "method", "name": "saveStrings", "params": [ { "name": "list", "description": "string array to be written
\n", "type": "String[]" }, { "name": "filename", "description": "filename for output
\n", "type": "String" }, { "name": "extension", "description": "the filename's extension
\n", "type": "String", "optional": true }, { "name": "isCRLF", "description": "if true, change line-break to CRLF
\n", "type": "Boolean", "optional": true } ], "example": [ "\n\n let words = 'apple bear cat dog';\n\n // .split() outputs an Array\n let list = split(words, ' ');\n\n function setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n describe('no image displayed');\n }\n\n function mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n saveStrings(list, 'nouns.txt');\n }\n }\n\n // Saves the following to a file called 'nouns.txt':\n //\n // apple\n // bear\n // cat\n // dog\n
Writes the contents of a Table object to a file. Defaults to a\ntext file with comma-separated-values ('csv') but can also\nuse tab separation ('tsv'), or generate an HTML table ('html').\nThe file saving process and location of the saved file will\nvary between web browsers.
\n", "itemtype": "method", "name": "saveTable", "params": [ { "name": "Table", "description": "the Table object to save to a file
\n", "type": "p5.Table" }, { "name": "filename", "description": "the filename to which the Table should be saved
\n", "type": "String" }, { "name": "options", "description": "can be one of \"tsv\", \"csv\", or \"html\"
\n", "type": "String", "optional": true } ], "example": [ "\n\n let table;\n\n function setup() {\n table = new p5.Table();\n\n table.addColumn('id');\n table.addColumn('species');\n table.addColumn('name');\n\n let newRow = table.addRow();\n newRow.setNum('id', table.getRowCount() - 1);\n newRow.setString('species', 'Panthera leo');\n newRow.setString('name', 'Lion');\n\n // To save, un-comment next line then click 'run'\n // saveTable(table, 'new.csv');\n\n describe('no image displayed');\n }\n\n // Saves the following to a file called 'new.csv':\n // id,species,name\n // 0,Panthera leo,Lion\n
Table Options\nGeneric class for handling tabular data, typically from a\nCSV, TSV, or other sort of spreadsheet file.\nCSV files are\n\ncomma separated values, often with the data in quotes. TSV\nfiles use tabs as separators, and usually don't bother with the\nquotes.\nFile names should end with .csv if they're comma separated.\nA rough \"spec\" for CSV can be found\nhere.\nTo load files, use the loadTable method.\nTo save tables to your computer, use the save method\n or the saveTable method.
\nPossible options include:
\nAn array containing the names of the columns in the table, if the \"header\" the table is\nloaded with the \"header\" parameter.
\n", "itemtype": "property", "name": "columns", "type": "String[]", "example": [ "\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //print the column names\n for (let c = 0; c < table.getColumnCount(); c++) {\n print('column ' + c + ' is named ' + table.columns[c]);\n }\n}\n
\nAn array containing the p5.TableRow objects that make up the\nrows of the table. The same result as calling getRows()
\n", "itemtype": "property", "name": "rows", "type": "p5.TableRow[]", "class": "p5.Table", "module": "IO", "submodule": "Table" }, { "file": "src/io/p5.Table.js", "line": 85, "description": "Use addRow() to add a new row of data to a p5.Table object. By default,\nan empty row is created. Typically, you would store a reference to\nthe new row in a TableRow object (see newRow in the example above),\nand then set individual values using set().
\nIf a p5.TableRow object is included as a parameter, then that row is\nduplicated and added to the table.
\n", "itemtype": "method", "name": "addRow", "params": [ { "name": "row", "description": "row to be added to the table
\n", "type": "p5.TableRow", "optional": true } ], "return": { "description": "the row that was added", "type": "p5.TableRow" }, "example": [ "\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //add a row\n let newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Canis Lupus');\n newRow.setString('name', 'Wolf');\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n\n describe('no image displayed');\n }\n
\n Removes a row from the table object.
\n", "itemtype": "method", "name": "removeRow", "params": [ { "name": "id", "description": "ID number of the row to remove
\n", "type": "Integer" } ], "example": [ "\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //remove the first row\n table.removeRow(0);\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n\n describe('no image displayed');\n}\n
\nReturns a reference to the specified p5.TableRow. The reference\ncan then be used to get and set values of the selected row.
\n", "itemtype": "method", "name": "getRow", "params": [ { "name": "rowID", "description": "ID number of the row to get
\n", "type": "Integer" } ], "return": { "description": "p5.TableRow object", "type": "p5.TableRow" }, "example": [ "\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n let row = table.getRow(1);\n //print it column by column\n //note: a row is an object, not an array\n for (let c = 0; c < table.getColumnCount(); c++) {\n print(row.getString(c));\n }\n\n describe('no image displayed');\n}\n
\nGets all rows from the table. Returns an array of p5.TableRows.
\n", "itemtype": "method", "name": "getRows", "return": { "description": "Array of p5.TableRows", "type": "p5.TableRow[]" }, "example": [ "\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n\n //warning: rows is an array of objects\n for (let r = 0; r < rows.length; r++) {\n rows[r].set('name', 'Unicorn');\n }\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n\n describe('no image displayed');\n }\n
\n Finds the first row in the Table that contains the value\nprovided, and returns a reference to that row. Even if\nmultiple rows are possible matches, only the first matching\nrow is returned. The column to search may be specified by\neither its ID or title.
\n", "itemtype": "method", "name": "findRow", "params": [ { "name": "value", "description": "The value to match
\n", "type": "String" }, { "name": "column", "description": "ID number or title of the\n column to search
\n", "type": "Integer|String" } ], "return": { "description": "", "type": "p5.TableRow" }, "example": [ "\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //find the animal named zebra\n let row = table.findRow('Zebra', 'name');\n //find the corresponding species\n print(row.getString('species'));\n describe('no image displayed');\n }\n
\n Finds the rows in the Table that contain the value\nprovided, and returns references to those rows. Returns an\nArray, so for must be used to iterate through all the rows,\nas shown in the example above. The column to search may be\nspecified by either its ID or title.
\n", "itemtype": "method", "name": "findRows", "params": [ { "name": "value", "description": "The value to match
\n", "type": "String" }, { "name": "column", "description": "ID number or title of the\n column to search
\n", "type": "Integer|String" } ], "return": { "description": "An Array of TableRow objects", "type": "p5.TableRow[]" }, "example": [ "\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //add another goat\n let newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Scape Goat');\n newRow.setString('name', 'Goat');\n\n //find the rows containing animals named Goat\n let rows = table.findRows('Goat', 'name');\n print(rows.length + ' Goats found');\n describe('no image displayed');\n }\n
\n Finds the first row in the Table that matches the regular\nexpression provided, and returns a reference to that row.\nEven if multiple rows are possible matches, only the first\nmatching row is returned. The column to search may be\nspecified by either its ID or title.
\n", "itemtype": "method", "name": "matchRow", "params": [ { "name": "regexp", "description": "The regular expression to match
\n", "type": "String|RegExp" }, { "name": "column", "description": "The column ID (number) or\n title (string)
\n", "type": "String|Integer" } ], "return": { "description": "TableRow object", "type": "p5.TableRow" }, "example": [ "\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //Search using specified regex on a given column, return TableRow object\n let mammal = table.matchRow(new RegExp('ant'), 1);\n print(mammal.getString(1));\n //Output \"Panthera pardus\"\n}\n
\nFinds the rows in the Table that match the regular expression provided,\nand returns references to those rows. Returns an array, so for must be\nused to iterate through all the rows, as shown in the example. The\ncolumn to search may be specified by either its ID or title.
\n", "itemtype": "method", "name": "matchRows", "params": [ { "name": "regexp", "description": "The regular expression to match
\n", "type": "String" }, { "name": "column", "description": "The column ID (number) or\n title (string)
\n", "type": "String|Integer", "optional": true } ], "return": { "description": "An Array of TableRow objects", "type": "p5.TableRow[]" }, "example": [ "\n\nlet table;\n\nfunction setup() {\n table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n let newRow = table.addRow();\n newRow.setString('name', 'Lion');\n newRow.setString('type', 'Mammal');\n\n newRow = table.addRow();\n newRow.setString('name', 'Snake');\n newRow.setString('type', 'Reptile');\n\n newRow = table.addRow();\n newRow.setString('name', 'Mosquito');\n newRow.setString('type', 'Insect');\n\n newRow = table.addRow();\n newRow.setString('name', 'Lizard');\n newRow.setString('type', 'Reptile');\n\n let rows = table.matchRows('R.*', 'type');\n for (let i = 0; i < rows.length; i++) {\n print(rows[i].getString('name') + ': ' + rows[i].getString('type'));\n }\n}\n// Sketch prints:\n// Snake: Reptile\n// Lizard: Reptile\n
\nRetrieves all values in the specified column, and returns them\nas an array. The column may be specified by either its ID or title.
\n", "itemtype": "method", "name": "getColumn", "params": [ { "name": "column", "description": "String or Number of the column to return
\n", "type": "String|Number" } ], "return": { "description": "Array of column values", "type": "Array" }, "example": [ "\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //getColumn returns an array that can be printed directly\n print(table.getColumn('species'));\n //outputs [\"Capra hircus\", \"Panthera pardus\", \"Equus zebra\"]\n describe('no image displayed');\n }\n
\n Removes all rows from a Table. While all rows are removed,\ncolumns and column titles are maintained.
\n", "itemtype": "method", "name": "clearRows", "example": [ "\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.clearRows();\n print(table.getRowCount() + ' total rows in table');\n print(table.getColumnCount() + ' total columns in table');\n describe('no image displayed');\n }\n
\n Use addColumn() to add a new column to a Table object.\nTypically, you will want to specify a title, so the column\nmay be easily referenced later by name. (If no title is\nspecified, the new column's title will be null.)
\n", "itemtype": "method", "name": "addColumn", "params": [ { "name": "title", "description": "title of the given column
\n", "type": "String", "optional": true } ], "example": [ "\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.addColumn('carnivore');\n table.set(0, 'carnivore', 'no');\n table.set(1, 'carnivore', 'yes');\n table.set(2, 'carnivore', 'no');\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n\n describe('no image displayed');\n }\n
\n Returns the total number of columns in a Table.
\n", "itemtype": "method", "name": "getColumnCount", "return": { "description": "Number of columns in this table", "type": "Integer" }, "example": [ "\n\n // given the cvs file \"blobs.csv\" in /assets directory\n // ID, Name, Flavor, Shape, Color\n // Blob1, Blobby, Sweet, Blob, Pink\n // Blob2, Saddy, Savory, Blob, Blue\n\n let table;\n\n function preload() {\n table = loadTable('assets/blobs.csv');\n }\n\n function setup() {\n createCanvas(200, 100);\n textAlign(CENTER);\n background(255);\n }\n\n function draw() {\n let numOfColumn = table.getColumnCount();\n text('There are ' + numOfColumn + ' columns in the table.', 100, 50);\n }\n
\n Returns the total number of rows in a Table.
\n", "itemtype": "method", "name": "getRowCount", "return": { "description": "Number of rows in this table", "type": "Integer" }, "example": [ "\n\n // given the cvs file \"blobs.csv\" in /assets directory\n //\n // ID, Name, Flavor, Shape, Color\n // Blob1, Blobby, Sweet, Blob, Pink\n // Blob2, Saddy, Savory, Blob, Blue\n\n let table;\n\n function preload() {\n table = loadTable('assets/blobs.csv');\n }\n\n function setup() {\n createCanvas(200, 100);\n textAlign(CENTER);\n background(255);\n }\n\n function draw() {\n text('There are ' + table.getRowCount() + ' rows in the table.', 100, 50);\n }\n
\n Removes any of the specified characters (or \"tokens\").
\nIf no column is specified, then the values in all columns and\nrows are processed. A specific column may be referenced by\neither its ID or title.
\n", "itemtype": "method", "name": "removeTokens", "params": [ { "name": "chars", "description": "String listing characters to be removed
\n", "type": "String" }, { "name": "column", "description": "Column ID (number)\n or name (string)
\n", "type": "String|Integer", "optional": true } ], "example": [ "\n\n function setup() {\n let table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n let newRow = table.addRow();\n newRow.setString('name', ' $Lion ,');\n newRow.setString('type', ',,,Mammal');\n\n newRow = table.addRow();\n newRow.setString('name', '$Snake ');\n newRow.setString('type', ',,,Reptile');\n\n table.removeTokens(',$ ');\n print(table.getArray());\n }\n\n // prints:\n // 0 \"Lion\" \"Mamal\"\n // 1 \"Snake\" \"Reptile\"\n
Trims leading and trailing whitespace, such as spaces and tabs,\nfrom String table values. If no column is specified, then the\nvalues in all columns and rows are trimmed. A specific column\nmay be referenced by either its ID or title.
\n", "itemtype": "method", "name": "trim", "params": [ { "name": "column", "description": "Column ID (number)\n or name (string)
\n", "type": "String|Integer", "optional": true } ], "example": [ "\n\n function setup() {\n let table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n let newRow = table.addRow();\n newRow.setString('name', ' Lion ,');\n newRow.setString('type', ' Mammal ');\n\n newRow = table.addRow();\n newRow.setString('name', ' Snake ');\n newRow.setString('type', ' Reptile ');\n\n table.trim();\n print(table.getArray());\n }\n\n // prints:\n // 0 \"Lion\" \"Mamal\"\n // 1 \"Snake\" \"Reptile\"\n
Use removeColumn() to remove an existing column from a Table\nobject. The column to be removed may be identified by either\nits title (a String) or its index value (an int).\nremoveColumn(0) would remove the first column, removeColumn(1)\nwould remove the second column, and so on.
\n", "itemtype": "method", "name": "removeColumn", "params": [ { "name": "column", "description": "columnName (string) or ID (number)
\n", "type": "String|Integer" } ], "example": [ "\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.removeColumn('id');\n print(table.getColumnCount());\n describe('no image displayed');\n }\n
\n Stores a value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
\n", "itemtype": "method", "name": "set", "params": [ { "name": "row", "description": "row ID
\n", "type": "Integer" }, { "name": "column", "description": "column ID (Number)\n or title (String)
\n", "type": "String|Integer" }, { "name": "value", "description": "value to assign
\n", "type": "String|Number" } ], "example": [ "\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n table.set(0, 'species', 'Canis Lupus');\n table.set(0, 'name', 'Wolf');\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n\n describe('no image displayed');\n}\n
\nStores a Float value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
\n", "itemtype": "method", "name": "setNum", "params": [ { "name": "row", "description": "row ID
\n", "type": "Integer" }, { "name": "column", "description": "column ID (Number)\n or title (String)
\n", "type": "String|Integer" }, { "name": "value", "description": "value to assign
\n", "type": "Number" } ], "example": [ "\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n table.setNum(1, 'id', 1);\n\n print(table.getColumn(0));\n //[\"0\", 1, \"2\"]\n\n describe('no image displayed');\n}\n
\nStores a String value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
\n", "itemtype": "method", "name": "setString", "params": [ { "name": "row", "description": "row ID
\n", "type": "Integer" }, { "name": "column", "description": "column ID (Number)\n or title (String)
\n", "type": "String|Integer" }, { "name": "value", "description": "value to assign
\n", "type": "String" } ], "example": [ "\n\n// Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //add a row\n let newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Canis Lupus');\n newRow.setString('name', 'Wolf');\n\n print(table.getArray());\n\n describe('no image displayed');\n}\n
Retrieves a value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n", "itemtype": "method", "name": "get", "params": [ { "name": "row", "description": "row ID
\n", "type": "Integer" }, { "name": "column", "description": "columnName (string) or\n ID (number)
\n", "type": "String|Integer" } ], "return": { "description": "", "type": "String|Number" }, "example": [ "\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.get(0, 1));\n //Capra hircus\n print(table.get(0, 'species'));\n //Capra hircus\n describe('no image displayed');\n}\n
\nRetrieves a Float value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n", "itemtype": "method", "name": "getNum", "params": [ { "name": "row", "description": "row ID
\n", "type": "Integer" }, { "name": "column", "description": "columnName (string) or\n ID (number)
\n", "type": "String|Integer" } ], "return": { "description": "", "type": "Number" }, "example": [ "\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.getNum(1, 0) + 100);\n //id 1 + 100 = 101\n describe('no image displayed');\n}\n
\nRetrieves a String value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n", "itemtype": "method", "name": "getString", "params": [ { "name": "row", "description": "row ID
\n", "type": "Integer" }, { "name": "column", "description": "columnName (string) or\n ID (number)
\n", "type": "String|Integer" } ], "return": { "description": "", "type": "String" }, "example": [ "\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n // table is comma separated value \"CSV\"\n // and has specifiying header for column labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.getString(0, 0)); // 0\n print(table.getString(0, 1)); // Capra hircus\n print(table.getString(0, 2)); // Goat\n print(table.getString(1, 0)); // 1\n print(table.getString(1, 1)); // Panthera pardus\n print(table.getString(1, 2)); // Leopard\n print(table.getString(2, 0)); // 2\n print(table.getString(2, 1)); // Equus zebra\n print(table.getString(2, 2)); // Zebra\n describe('no image displayed');\n}\n
\nRetrieves all table data and returns as an object. If a column name is\npassed in, each row object will be stored with that attribute as its\ntitle.
\n", "itemtype": "method", "name": "getObject", "params": [ { "name": "headerColumn", "description": "Name of the column which should be used to\n title each row object (optional)
\n", "type": "String", "optional": true } ], "return": { "description": "", "type": "Object" }, "example": [ "\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n let tableObject = table.getObject();\n\n print(tableObject);\n //outputs an object\n\n describe('no image displayed');\n}\n
\nRetrieves all table data and returns it as a multidimensional array.
\n", "itemtype": "method", "name": "getArray", "return": { "description": "", "type": "Array" }, "example": [ "\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leoperd\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n // table is comma separated value \"CSV\"\n // and has specifiying header for column labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n let tableArray = table.getArray();\n for (let i = 0; i < tableArray.length; i++) {\n print(tableArray[i]);\n }\n describe('no image displayed');\n}\n
\nStores a value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n", "itemtype": "method", "name": "set", "params": [ { "name": "column", "description": "Column ID (Number)\n or Title (String)
\n", "type": "String|Integer" }, { "name": "value", "description": "The value to be stored
\n", "type": "String|Number" } ], "example": [ "\n\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n rows[r].set('name', 'Unicorn');\n }\n\n //print the results\n print(table.getArray());\n\n describe('no image displayed');\n }\n
Stores a Float value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n", "itemtype": "method", "name": "setNum", "params": [ { "name": "column", "description": "Column ID (Number)\n or Title (String)
\n", "type": "String|Integer" }, { "name": "value", "description": "The value to be stored\n as a Float
\n", "type": "Number|String" } ], "example": [ "\n\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n rows[r].setNum('id', r + 10);\n }\n\n print(table.getArray());\n\n describe('no image displayed');\n }\n
Stores a String value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n", "itemtype": "method", "name": "setString", "params": [ { "name": "column", "description": "Column ID (Number)\n or Title (String)
\n", "type": "String|Integer" }, { "name": "value", "description": "The value to be stored\n as a String
\n", "type": "String|Number|Boolean|Object" } ], "example": [ "\n\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n let name = rows[r].getString('name');\n rows[r].setString('name', 'A ' + name + ' named George');\n }\n\n print(table.getArray());\n\n describe('no image displayed');\n }\n
Retrieves a value from the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n", "itemtype": "method", "name": "get", "params": [ { "name": "column", "description": "columnName (string) or\n ID (number)
\n", "type": "String|Integer" } ], "return": { "description": "", "type": "String|Number" }, "example": [ "\n\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let names = [];\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n names.push(rows[r].get('name'));\n }\n\n print(names);\n\n describe('no image displayed');\n }\n
Retrieves a Float value from the TableRow's specified\ncolumn. The column may be specified by either its ID or\ntitle.
\n", "itemtype": "method", "name": "getNum", "params": [ { "name": "column", "description": "columnName (string) or\n ID (number)
\n", "type": "String|Integer" } ], "return": { "description": "Float Floating point number", "type": "Number" }, "example": [ "\n\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n let minId = Infinity;\n let maxId = -Infinity;\n for (let r = 0; r < rows.length; r++) {\n let id = rows[r].getNum('id');\n minId = min(minId, id);\n maxId = min(maxId, id);\n }\n print('minimum id = ' + minId + ', maximum id = ' + maxId);\n describe('no image displayed');\n }\n
Retrieves an String value from the TableRow's specified\ncolumn. The column may be specified by either its ID or\ntitle.
\n", "itemtype": "method", "name": "getString", "params": [ { "name": "column", "description": "columnName (string) or\n ID (number)
\n", "type": "String|Integer" } ], "return": { "description": "String", "type": "String" }, "example": [ "\n\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n let longest = '';\n for (let r = 0; r < rows.length; r++) {\n let species = rows[r].getString('species');\n if (longest.length < species.length) {\n longest = species;\n }\n }\n\n print('longest: ' + longest);\n\n describe('no image displayed');\n }\n
Gets a copy of the element's parent. Returns the parent as another\np5.XML object.
\n", "itemtype": "method", "name": "getParent", "return": { "description": "element parent", "type": "p5.XML" }, "example": [ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let children = xml.getChildren('animal');\n let parent = children[1].getParent();\n print(parent.getName());\n}\n\n// Sketch prints:\n// mammals\n
Gets the element's full name, which is returned as a String.
\n", "itemtype": "method", "name": "getName", "return": { "description": "the name of the node", "type": "String" }, "example": [ "<animal\n\n // The following short XML file called \"mammals.xml\" is parsed\n // in the code below.\n //\n // \n // <mammals>\n // <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n // <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n // <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n // </mammals>\n\n let xml;\n\n function preload() {\n xml = loadXML('assets/mammals.xml');\n }\n\n function setup() {\n print(xml.getName());\n }\n\n // Sketch prints:\n // mammals\n
Sets the element's name, which is specified as a String.
\n", "itemtype": "method", "name": "setName", "params": [ { "name": "the", "description": "new name of the node
\n", "type": "String" } ], "example": [ "<animal\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.getName());\n xml.setName('fish');\n print(xml.getName());\n}\n\n// Sketch prints:\n// mammals\n// fish\n
Checks whether or not the element has any children, and returns the result\nas a boolean.
\n", "itemtype": "method", "name": "hasChildren", "return": { "description": "", "type": "Boolean" }, "example": [ "<animal\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.hasChildren());\n}\n\n// Sketch prints:\n// true\n
Get the names of all of the element's children, and returns the names as an\narray of Strings. This is the same as looping through and calling getName()\non each child element individually.
\n", "itemtype": "method", "name": "listChildren", "return": { "description": "names of the children of the element", "type": "String[]" }, "example": [ "<animal\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.listChildren());\n}\n\n// Sketch prints:\n// [\"animal\", \"animal\", \"animal\"]\n
Returns all of the element's children as an array of p5.XML objects. When\nthe name parameter is specified, then it will return all children that match\nthat name.
\n", "itemtype": "method", "name": "getChildren", "params": [ { "name": "name", "description": "element name
\n", "type": "String", "optional": true } ], "return": { "description": "children of the element", "type": "p5.XML[]" }, "example": [ "<animal\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let animals = xml.getChildren('animal');\n\n for (let i = 0; i < animals.length; i++) {\n print(animals[i].getContent());\n }\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Leopard\"\n// \"Zebra\"\n
Returns the first of the element's children that matches the name parameter\nor the child of the given index.It returns undefined if no matching\nchild is found.
\n", "itemtype": "method", "name": "getChild", "params": [ { "name": "name", "description": "element name or index
\n", "type": "String|Integer" } ], "return": { "description": "", "type": "p5.XML" }, "example": [ "<animal\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n
\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let secondChild = xml.getChild(1);\n print(secondChild.getContent());\n}\n\n// Sketch prints:\n// \"Leopard\"\n
Appends a new child to the element. The child can be specified with\neither a String, which will be used as the new tag's name, or as a\nreference to an existing p5.XML object.\nA reference to the newly created child is returned as an p5.XML object.
\n", "itemtype": "method", "name": "addChild", "params": [ { "name": "node", "description": "a p5.XML Object which will be the child to be added
\n", "type": "p5.XML" } ], "example": [ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let child = new p5.XML();\n child.setName('animal');\n child.setAttribute('id', '3');\n child.setAttribute('species', 'Ornithorhynchus anatinus');\n child.setContent('Platypus');\n xml.addChild(child);\n\n let animals = xml.getChildren('animal');\n print(animals[animals.length - 1].getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Leopard\"\n// \"Zebra\"\n
Removes the element specified by name or index.
\n", "itemtype": "method", "name": "removeChild", "params": [ { "name": "name", "description": "element name or index
\n", "type": "String|Integer" } ], "example": [ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n xml.removeChild('animal');\n let children = xml.getChildren();\n for (let i = 0; i < children.length; i++) {\n print(children[i].getContent());\n }\n}\n\n// Sketch prints:\n// \"Leopard\"\n// \"Zebra\"\n
\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n xml.removeChild(1);\n let children = xml.getChildren();\n for (let i = 0; i < children.length; i++) {\n print(children[i].getContent());\n }\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Zebra\"\n
Counts the specified element's number of attributes, returned as an Number.
\n", "itemtype": "method", "name": "getAttributeCount", "return": { "description": "", "type": "Integer" }, "example": [ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.getAttributeCount());\n}\n\n// Sketch prints:\n// 2\n
Gets all of the specified element's attributes, and returns them as an\narray of Strings.
\n", "itemtype": "method", "name": "listAttributes", "return": { "description": "an array of strings containing the names of attributes", "type": "String[]" }, "example": [ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.listAttributes());\n}\n\n// Sketch prints:\n// [\"id\", \"species\"]\n
Checks whether or not an element has the specified attribute.
\n", "itemtype": "method", "name": "hasAttribute", "params": [ { "name": "the", "description": "attribute to be checked
\n", "type": "String" } ], "return": { "description": "true if attribute found else false", "type": "Boolean" }, "example": [ "\n\n // The following short XML file called \"mammals.xml\" is parsed\n // in the code below.\n //\n // \n // <mammals>\n // <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n // <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n // <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n // </mammals>\n\n let xml;\n\n function preload() {\n xml = loadXML('assets/mammals.xml');\n }\n\n function setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.hasAttribute('species'));\n print(firstChild.hasAttribute('color'));\n }\n\n // Sketch prints:\n // true\n // false\n
Returns an attribute value of the element as an Number. If the defaultValue\nparameter is specified and the attribute doesn't exist, then defaultValue\nis returned. If no defaultValue is specified and the attribute doesn't\nexist, the value 0 is returned.
\n", "itemtype": "method", "name": "getNum", "params": [ { "name": "name", "description": "the non-null full name of the attribute
\n", "type": "String" }, { "name": "defaultValue", "description": "the default value of the attribute
\n", "type": "Number", "optional": true } ], "return": { "description": "", "type": "Number" }, "example": [ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.getNum('id'));\n}\n\n// Sketch prints:\n// 0\n
Returns an attribute value of the element as an String. If the defaultValue\nparameter is specified and the attribute doesn't exist, then defaultValue\nis returned. If no defaultValue is specified and the attribute doesn't\nexist, null is returned.
\n", "itemtype": "method", "name": "getString", "params": [ { "name": "name", "description": "the non-null full name of the attribute
\n", "type": "String" }, { "name": "defaultValue", "description": "the default value of the attribute
\n", "type": "Number", "optional": true } ], "return": { "description": "", "type": "String" }, "example": [ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.getString('species'));\n}\n\n// Sketch prints:\n// \"Capra hircus\"\n
Sets the content of an element's attribute. The first parameter specifies\nthe attribute name, while the second specifies the new content.
\n", "itemtype": "method", "name": "setAttribute", "params": [ { "name": "name", "description": "the full name of the attribute
\n", "type": "String" }, { "name": "value", "description": "the value of the attribute
\n", "type": "Number|String|Boolean" } ], "example": [ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.getString('species'));\n firstChild.setAttribute('species', 'Jamides zebra');\n print(firstChild.getString('species'));\n}\n\n// Sketch prints:\n// \"Capra hircus\"\n// \"Jamides zebra\"\n
Returns the content of an element. If there is no such content,\ndefaultValue is returned if specified, otherwise null is returned.
\n", "itemtype": "method", "name": "getContent", "params": [ { "name": "defaultValue", "description": "value returned if no content is found
\n", "type": "String", "optional": true } ], "return": { "description": "", "type": "String" }, "example": [ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n
Sets the element's content.
\n", "itemtype": "method", "name": "setContent", "params": [ { "name": "text", "description": "the new content
\n", "type": "String" } ], "example": [ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.getContent());\n firstChild.setContent('Mountain Goat');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Mountain Goat\"\n
Serializes the element into a string. This function is useful for preparing\nthe content to be sent over a http request or saved to file.
\n", "itemtype": "method", "name": "serialize", "return": { "description": "Serialized string of the element", "type": "String" }, "example": [ "\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.serialize());\n}\n\n// Sketch prints:\n// \n// Goat \n// Leopard \n// Zebra \n// \n
Calculates the absolute value (magnitude) of a number. Maps to Math.abs().\nThe absolute value of a number is always positive.
\n", "itemtype": "method", "name": "abs", "params": [ { "name": "n", "description": "number to compute
\n", "type": "Number" } ], "return": { "description": "absolute value of given number", "type": "Number" }, "example": [ "\n\nfunction setup() {\n let x = -3;\n let y = abs(x);\n\n print(x); // -3\n print(y); // 3\n\n describe('no image displayed');\n}\n
Calculates the closest int value that is greater than or equal to the\nvalue of the parameter. Maps to Math.ceil(). For example, ceil(9.03)\nreturns the value 10.
\n", "itemtype": "method", "name": "ceil", "params": [ { "name": "n", "description": "number to round up
\n", "type": "Number" } ], "return": { "description": "rounded up number", "type": "Integer" }, "example": [ "\n\nfunction draw() {\n background(200);\n // map, mouseX between 0 and 5.\n let ax = map(mouseX, 0, 100, 0, 5);\n let ay = 66;\n\n //Get the ceiling of the mapped number.\n let bx = ceil(map(mouseX, 0, 100, 0, 5));\n let by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n\n describe(`2 horizontal lines & number sets. increase with\n mouse x. bottom to 2 decimals`);\n}\n
Constrains a value between a minimum and maximum value.
\n", "itemtype": "method", "name": "constrain", "params": [ { "name": "n", "description": "number to constrain
\n", "type": "Number" }, { "name": "low", "description": "minimum limit
\n", "type": "Number" }, { "name": "high", "description": "maximum limit
\n", "type": "Number" } ], "return": { "description": "constrained number", "type": "Number" }, "example": [ "\n\nfunction draw() {\n background(200);\n\n let leftWall = 25;\n let rightWall = 75;\n\n // xm is just the mouseX, while\n // xc is the mouseX, but constrained\n // between the leftWall and rightWall!\n let xm = mouseX;\n let xc = constrain(mouseX, leftWall, rightWall);\n\n // Draw the walls.\n stroke(150);\n line(leftWall, 0, leftWall, height);\n line(rightWall, 0, rightWall, height);\n\n // Draw xm and xc as circles.\n noStroke();\n fill(150);\n ellipse(xm, 33, 9, 9); // Not Constrained\n fill(0);\n ellipse(xc, 66, 9, 9); // Constrained\n\n describe(`2 vertical lines. 2 ellipses move with mouse X,\n 1 does not move past lines`);\n}\n
Calculates the distance between two points, in either two or three dimensions.\nIf you looking for distance between two vectors see p5.Vector.dist()
\n", "itemtype": "method", "name": "dist", "return": { "description": "distance between the two points", "type": "Number" }, "example": [ "\n\n// Move your mouse inside the canvas to see the\n// change in distance between two points!\nfunction draw() {\n background(200);\n fill(0);\n\n let x1 = 10;\n let y1 = 90;\n let x2 = mouseX;\n let y2 = mouseY;\n\n line(x1, y1, x2, y2);\n ellipse(x1, y1, 7, 7);\n ellipse(x2, y2, 7, 7);\n\n // d is the length of the line\n // the distance from point 1 to point 2.\n let d = dist(x1, y1, x2, y2);\n\n // Let's write d along the line we are drawing!\n push();\n translate((x1 + x2) / 2, (y1 + y2) / 2);\n rotate(atan2(y2 - y1, x2 - x1));\n text(nfc(d, 1), 0, -5);\n pop();\n // Fancy!\n\n describe(`2 ellipses joined by line. 1 ellipse moves with\n mouse X&Y. Distance displayed.`);\n}\n
x-coordinate of the first point
\n", "type": "Number" }, { "name": "y1", "description": "y-coordinate of the first point
\n", "type": "Number" }, { "name": "x2", "description": "x-coordinate of the second point
\n", "type": "Number" }, { "name": "y2", "description": "y-coordinate of the second point
\n", "type": "Number" } ], "return": { "description": "distance between the two points", "type": "Number" } }, { "line": 160, "params": [ { "name": "x1", "description": "", "type": "Number" }, { "name": "y1", "description": "", "type": "Number" }, { "name": "z1", "description": "z-coordinate of the first point
\n", "type": "Number" }, { "name": "x2", "description": "", "type": "Number" }, { "name": "y2", "description": "", "type": "Number" }, { "name": "z2", "description": "z-coordinate of the second point
\n", "type": "Number" } ], "return": { "description": "distance between the two points", "type": "Number" } } ] }, { "file": "src/math/calculation.js", "line": 181, "description": "Returns Euler's number e (2.71828...) raised to the power of the n\nparameter. Maps to Math.exp().
\n", "itemtype": "method", "name": "exp", "params": [ { "name": "n", "description": "exponent to raise
\n", "type": "Number" } ], "return": { "description": "e^n", "type": "Number" }, "example": [ "\n\nfunction draw() {\n background(200);\n\n // Compute the exp() function with a value between 0 and 2\n let xValue = map(mouseX, 0, width, 0, 2);\n let yValue = exp(xValue);\n\n let y = map(yValue, 0, 8, height, 0);\n\n let legend = 'exp (' + nfc(xValue, 3) + ')\\n= ' + nf(yValue, 1, 4);\n stroke(150);\n line(mouseX, y, mouseX, height);\n fill(0);\n text(legend, 5, 15);\n noStroke();\n ellipse(mouseX, y, 7, 7);\n\n // Draw the exp(x) curve,\n // over the domain of x from 0 to 2\n noFill();\n stroke(0);\n beginShape();\n for (let x = 0; x < width; x++) {\n xValue = map(x, 0, width, 0, 2);\n yValue = exp(xValue);\n y = map(yValue, 0, 8, height, 0);\n vertex(x, y);\n }\n\n endShape();\n line(0, 0, 0, height);\n line(0, height - 1, width, height - 1);\n\n describe('ellipse moves along a curve with mouse x. e^n displayed.');\n}\n
Calculates the closest int value that is less than or equal to the\nvalue of the parameter. Maps to Math.floor().
\n", "itemtype": "method", "name": "floor", "params": [ { "name": "n", "description": "number to round down
\n", "type": "Number" } ], "return": { "description": "rounded down number", "type": "Integer" }, "example": [ "\n\nfunction draw() {\n background(200);\n //map, mouseX between 0 and 5.\n let ax = map(mouseX, 0, 100, 0, 5);\n let ay = 66;\n\n //Get the floor of the mapped number.\n let bx = floor(map(mouseX, 0, 100, 0, 5));\n let by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n\n describe(`2 horizontal lines & number sets.\n increase with mouse x. bottom to 2 decimals`);\n}\n
Calculates a number between two numbers at a specific increment. The amt\nparameter is the amount to interpolate between the two values where 0.0\nis equal to the first point, 0.1 is very near the first point, 0.5 is\nhalf-way in between, and 1.0 is equal to the second point. If the\nvalue of amt is more than 1.0 or less than 0.0, the number will be\ncalculated accordingly in the ratio of the two given numbers. The lerp()\nfunction is convenient for creating motion along a straight\npath and for drawing dotted lines.
\n", "itemtype": "method", "name": "lerp", "params": [ { "name": "start", "description": "first value
\n", "type": "Number" }, { "name": "stop", "description": "second value
\n", "type": "Number" }, { "name": "amt", "description": "number
\n", "type": "Number" } ], "return": { "description": "lerped value", "type": "Number" }, "example": [ "\n\nfunction setup() {\n background(200);\n let a = 20;\n let b = 80;\n let c = lerp(a, b, 0.2);\n let d = lerp(a, b, 0.5);\n let e = lerp(a, b, 0.8);\n\n let y = 50;\n\n strokeWeight(5);\n stroke(0); // Draw the original points in black\n point(a, y);\n point(b, y);\n\n stroke(100); // Draw the lerp points in gray\n point(c, y);\n point(d, y);\n point(e, y);\n\n describe(`5 points horizontally staggered mid-canvas.\n mid 3 are grey, outer black`);\n}\n
Calculates the natural logarithm (the base-e logarithm) of a number. This\nfunction expects the n parameter to be a value greater than 0.0. Maps to\nMath.log().
\n", "itemtype": "method", "name": "log", "params": [ { "name": "n", "description": "number greater than 0
\n", "type": "Number" } ], "return": { "description": "natural logarithm of n", "type": "Number" }, "example": [ "\n\nfunction draw() {\n background(200);\n let maxX = 2.8;\n let maxY = 1.5;\n\n // Compute the natural log of a value between 0 and maxX\n let xValue = map(mouseX, 0, width, 0, maxX);\n let yValue, y;\n if (xValue > 0) {\n // Cannot take the log of a negative number.\n yValue = log(xValue);\n y = map(yValue, -maxY, maxY, height, 0);\n\n // Display the calculation occurring.\n let legend = 'log(' + nf(xValue, 1, 2) + ')\\n= ' + nf(yValue, 1, 3);\n stroke(150);\n line(mouseX, y, mouseX, height);\n fill(0);\n text(legend, 5, 15);\n noStroke();\n ellipse(mouseX, y, 7, 7);\n }\n\n // Draw the log(x) curve,\n // over the domain of x from 0 to maxX\n noFill();\n stroke(0);\n beginShape();\n for (let x = 0; x < width; x++) {\n xValue = map(x, 0, width, 0, maxX);\n yValue = log(xValue);\n y = map(yValue, -maxY, maxY, height, 0);\n vertex(x, y);\n }\n endShape();\n line(0, 0, 0, height);\n line(0, height / 2, width, height / 2);\n\n describe(`ellipse moves along a curve with mouse x.\n natural logarithm of n displayed.`);\n}\n
Calculates the magnitude (or length) of a vector. A vector is a direction\nin space commonly used in computer graphics and linear algebra. Because it\nhas no \"start\" position, the magnitude of a vector can be thought of as\nthe distance from the coordinate 0,0 to its x,y value. Therefore, mag() is\na shortcut for writing dist(0, 0, x, y).
\n", "itemtype": "method", "name": "mag", "params": [ { "name": "a", "description": "first value
\n", "type": "Number" }, { "name": "b", "description": "second value
\n", "type": "Number" } ], "return": { "description": "magnitude of vector from (0,0) to (a,b)", "type": "Number" }, "example": [ "\n\nfunction setup() {\n let x1 = 20;\n let x2 = 80;\n let y1 = 30;\n let y2 = 70;\n\n line(0, 0, x1, y1);\n print(mag(x1, y1)); // Prints \"36.05551275463989\"\n line(0, 0, x2, y1);\n print(mag(x2, y1)); // Prints \"85.44003745317531\"\n line(0, 0, x1, y2);\n print(mag(x1, y2)); // Prints \"72.80109889280519\"\n line(0, 0, x2, y2);\n print(mag(x2, y2)); // Prints \"106.3014581273465\"\n\n describe('4 lines of different length radiate from top left of canvas.');\n}\n
Re-maps a number from one range to another.
\nIn the first example above, the number 25 is converted from a value in the\nrange of 0 to 100 into a value that ranges from the left edge of the\nwindow (0) to the right edge (width).
\n", "itemtype": "method", "name": "map", "params": [ { "name": "value", "description": "the incoming value to be converted
\n", "type": "Number" }, { "name": "start1", "description": "lower bound of the value's current range
\n", "type": "Number" }, { "name": "stop1", "description": "upper bound of the value's current range
\n", "type": "Number" }, { "name": "start2", "description": "lower bound of the value's target range
\n", "type": "Number" }, { "name": "stop2", "description": "upper bound of the value's target range
\n", "type": "Number" }, { "name": "withinBounds", "description": "constrain the value to the newly mapped range
\n", "type": "Boolean", "optional": true } ], "return": { "description": "remapped number", "type": "Number" }, "example": [ "\n\nlet value = 25;\nlet m = map(value, 0, 100, 0, width);\nellipse(m, 50, 10, 10);\ndescribe('10×10 white ellipse with in mid left canvas');\n
\nfunction setup() {\n noStroke();\n}\n\nfunction draw() {\n background(204);\n let x1 = map(mouseX, 0, width, 25, 75);\n ellipse(x1, 25, 25, 25);\n //This ellipse is constrained to the 0-100 range\n //after setting withinBounds to true\n let x2 = map(mouseX, 0, width, 0, 100, true);\n ellipse(x2, 75, 25, 25);\n\n describe(`Two 25×25 white ellipses move with mouse x.\n Bottom has more range from X`);\n}\n
Determines the largest value in a sequence of numbers, and then returns\nthat value. max() accepts any number of Number parameters, or an Array\nof any length.
\n", "itemtype": "method", "name": "max", "return": { "description": "maximum Number", "type": "Number" }, "example": [ "\n\nfunction setup() {\n // Change the elements in the array and run the sketch\n // to show how max() works!\n let numArray = [2, 1, 5, 4, 8, 9];\n fill(0);\n noStroke();\n text('Array Elements', 0, 10);\n // Draw all numbers in the array\n let spacing = 15;\n let elemsY = 25;\n for (let i = 0; i < numArray.length; i++) {\n text(numArray[i], i * spacing, elemsY);\n }\n let maxX = 33;\n let maxY = 80;\n // Draw the Maximum value in the array.\n textSize(32);\n text(max(numArray), maxX, maxY);\n\n describe(`Small text at top reads: Array Elements 2 1 5 4 8 9.\n Large text at center: 9`);\n}\n
Number to compare
\n", "type": "Number" }, { "name": "n1", "description": "Number to compare
\n", "type": "Number" } ], "return": { "description": "maximum Number", "type": "Number" } }, { "line": 496, "params": [ { "name": "nums", "description": "Numbers to compare
\n", "type": "Number[]" } ], "return": { "description": "", "type": "Number" } } ] }, { "file": "src/math/calculation.js", "line": 509, "description": "Determines the smallest value in a sequence of numbers, and then returns\nthat value. min() accepts any number of Number parameters, or an Array\nof any length.
\n", "itemtype": "method", "name": "min", "return": { "description": "minimum Number", "type": "Number" }, "example": [ "\n\nfunction setup() {\n // Change the elements in the array and run the sketch\n // to show how min() works!\n let numArray = [2, 1, 5, 4, 8, 9];\n fill(0);\n noStroke();\n text('Array Elements', 0, 10);\n // Draw all numbers in the array\n let spacing = 15;\n let elemsY = 25;\n for (let i = 0; i < numArray.length; i++) {\n text(numArray[i], i * spacing, elemsY);\n }\n let maxX = 33;\n let maxY = 80;\n // Draw the Minimum value in the array.\n textSize(32);\n text(min(numArray), maxX, maxY);\n\n describe(`Small text at top reads: Array Elements 2 1 5 4 8 9.\n Large text at center: 1`);\n}\n
Number to compare
\n", "type": "Number" }, { "name": "n1", "description": "Number to compare
\n", "type": "Number" } ], "return": { "description": "minimum Number", "type": "Number" } }, { "line": 544, "params": [ { "name": "nums", "description": "Numbers to compare
\n", "type": "Number[]" } ], "return": { "description": "", "type": "Number" } } ] }, { "file": "src/math/calculation.js", "line": 557, "description": "Normalizes a number from another range into a value between 0 and 1.\nIdentical to map(value, low, high, 0, 1).\nNumbers outside of the range are not clamped to 0 and 1, because\nout-of-range values are often intentional and useful. (See the example above.)
\n", "itemtype": "method", "name": "norm", "params": [ { "name": "value", "description": "incoming value to be normalized
\n", "type": "Number" }, { "name": "start", "description": "lower bound of the value's current range
\n", "type": "Number" }, { "name": "stop", "description": "upper bound of the value's current range
\n", "type": "Number" } ], "return": { "description": "normalized number", "type": "Number" }, "example": [ "\n\nfunction draw() {\n background(200);\n let currentNum = mouseX;\n let lowerBound = 0;\n let upperBound = width; //100;\n let normalized = norm(currentNum, lowerBound, upperBound);\n let lineY = 70;\n stroke(3);\n line(0, lineY, width, lineY);\n //Draw an ellipse mapped to the non-normalized value.\n noStroke();\n fill(50);\n let s = 7; // ellipse size\n ellipse(currentNum, lineY, s, s);\n\n // Draw the guide\n let guideY = lineY + 15;\n text('0', 0, guideY);\n textAlign(RIGHT);\n text('100', width, guideY);\n\n // Draw the normalized value\n textAlign(LEFT);\n fill(0);\n textSize(32);\n let normalY = 40;\n let normalX = 20;\n text(normalized, normalX, normalY);\n\n describe(`ellipse moves with mouse. 0 shown left, 100 right,\n and updating values center`);\n}\n
Facilitates exponential expressions. The pow() function is an efficient\nway of multiplying numbers by themselves (or their reciprocals) in large\nquantities. For example, pow(3, 5) is equivalent to the expression\n3 × 3 × 3 × 3 × 3 and pow(3, -5) is equivalent to 1 /\n3 × 3 × 3 × 3 × 3. Maps to\nMath.pow().
\n", "itemtype": "method", "name": "pow", "params": [ { "name": "n", "description": "base of the exponential expression
\n", "type": "Number" }, { "name": "e", "description": "power by which to raise the base
\n", "type": "Number" } ], "return": { "description": "n^e", "type": "Number" }, "example": [ "\n\nfunction setup() {\n //Exponentially increase the size of an ellipse.\n let eSize = 3; // Original Size\n let eLoc = 10; // Original Location\n\n ellipse(eLoc, eLoc, eSize, eSize);\n\n ellipse(eLoc * 2, eLoc * 2, pow(eSize, 2), pow(eSize, 2));\n\n ellipse(eLoc * 4, eLoc * 4, pow(eSize, 3), pow(eSize, 3));\n\n ellipse(eLoc * 8, eLoc * 8, pow(eSize, 4), pow(eSize, 4));\n\n describe('small to large ellipses radiating from top left of canvas');\n}\n
Calculates the integer closest to the n parameter. For example,\nround(133.8) returns the value 134. Maps to Math.round().
\n", "itemtype": "method", "name": "round", "params": [ { "name": "n", "description": "number to round
\n", "type": "Number" }, { "name": "decimals", "description": "number of decimal places to round to, default is 0
\n", "type": "Number", "optional": true } ], "return": { "description": "rounded number", "type": "Integer" }, "example": [ "\n\nlet x = round(3.7);\ntext(x, width / 2, height / 2);\ndescribe('\"4\" written in middle of canvas');\n
\nlet x = round(12.782383, 2);\ntext(x, width / 2, height / 2);\ndescribe('\"12.78\" written in middle of canvas');\n
\nfunction draw() {\n background(200);\n //map, mouseX between 0 and 5.\n let ax = map(mouseX, 0, 100, 0, 5);\n let ay = 66;\n\n // Round the mapped number.\n let bx = round(map(mouseX, 0, 100, 0, 5));\n let by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n\n describe('two horizontal lines rounded values displayed on top.');\n}\n
Squares a number (multiplies a number by itself). The result is always a\npositive number, as multiplying two negative numbers always yields a\npositive result. For example, -1 * -1 = 1.
\n", "itemtype": "method", "name": "sq", "params": [ { "name": "n", "description": "number to square
\n", "type": "Number" } ], "return": { "description": "squared number", "type": "Number" }, "example": [ "\n\nfunction draw() {\n background(200);\n let eSize = 7;\n let x1 = map(mouseX, 0, width, 0, 10);\n let y1 = 80;\n let x2 = sq(x1);\n let y2 = 20;\n\n // Draw the non-squared.\n line(0, y1, width, y1);\n ellipse(x1, y1, eSize, eSize);\n\n // Draw the squared.\n line(0, y2, width, y2);\n ellipse(x2, y2, eSize, eSize);\n\n // Draw dividing line.\n stroke(100);\n line(0, height / 2, width, height / 2);\n\n // Draw text.\n let spacing = 15;\n noStroke();\n fill(0);\n text('x = ' + x1, 0, y1 + spacing);\n text('sq(x) = ' + x2, 0, y2 + spacing);\n\n describe(`horizontal center line squared values displayed on\n top and regular on bottom.`);\n}\n
Calculates the square root of a number. The square root of a number is\nalways positive, even though there may be a valid negative root. The\nsquare root s of number a is such that s*s = a. It is the opposite of\nsquaring. Maps to Math.sqrt().
\n", "itemtype": "method", "name": "sqrt", "params": [ { "name": "n", "description": "non-negative number to square root
\n", "type": "Number" } ], "return": { "description": "square root of number", "type": "Number" }, "example": [ "\n\nfunction draw() {\n background(200);\n let eSize = 7;\n let x1 = mouseX;\n let y1 = 80;\n let x2 = sqrt(x1);\n let y2 = 20;\n\n // Draw the non-squared.\n line(0, y1, width, y1);\n ellipse(x1, y1, eSize, eSize);\n\n // Draw the squared.\n line(0, y2, width, y2);\n ellipse(x2, y2, eSize, eSize);\n\n // Draw dividing line.\n stroke(100);\n line(0, height / 2, width, height / 2);\n\n // Draw text.\n noStroke();\n fill(0);\n let spacing = 15;\n text('x = ' + x1, 0, y1 + spacing);\n text('sqrt(x) = ' + x2, 0, y2 + spacing);\n\n describe(`horizontal center line squareroot values displayed on\n top and regular on bottom.`);\n}\n
Calculates the fractional part of a number.
\n", "itemtype": "method", "name": "fract", "params": [ { "name": "num", "description": "Number whose fractional part needs to be found out
\n", "type": "Number" } ], "return": { "description": "fractional part of x, i.e, {x}", "type": "Number" }, "example": [ "\n\ntext(7345.73472742, 10, 25);\ntext(fract(7345.73472742), 10, 75);\ndescribe(`first row having a number and the second having\n the fractional part of the number`);\n
\ntext(1.4215e-15, 10, 25);\ntext(fract(1.4215e-15), 10, 75);\ndescribe(`first row having a number expressed in scientific\n notation and the second having the fractional part of the number`);\n
Creates a new p5.Vector (the datatype for storing vectors). This provides a\ntwo or three-dimensional vector, specifically a Euclidean (also known as\ngeometric) vector. A vector is an entity that has both magnitude and\ndirection.
\n", "itemtype": "method", "name": "createVector", "params": [ { "name": "x", "description": "x component of the vector
\n", "type": "Number", "optional": true }, { "name": "y", "description": "y component of the vector
\n", "type": "Number", "optional": true }, { "name": "z", "description": "z component of the vector
\n", "type": "Number", "optional": true } ], "return": { "description": "", "type": "p5.Vector" }, "example": [ "\n\nlet v1;\nfunction setup() {\n createCanvas(100, 100);\n stroke(255, 0, 255);\n v1 = createVector(width / 2, height / 2);\n}\n\nfunction draw() {\n background(255);\n line(v1.x, v1.y, mouseX, mouseY);\n describe('draws a line from center of canvas to mouse pointer position.');\n}\n
Returns the Perlin noise value at specified coordinates. Perlin noise is\na random sequence generator producing a more naturally ordered, harmonic\nsuccession of numbers compared to the standard random() function.\nIt was invented by Ken Perlin in the 1980s and been used since in\ngraphical applications to produce procedural textures, natural motion,\nshapes, terrains etc.
The main difference to the\nrandom() function is that Perlin noise is defined in an infinite\nn-dimensional space where each pair of coordinates corresponds to a\nfixed semi-random value (fixed only for the lifespan of the program; see\nthe noiseSeed() function). p5.js can compute 1D, 2D and 3D noise,\ndepending on the number of coordinates given. The resulting value will\nalways be between 0.0 and 1.0. The noise value can be animated by moving\nthrough the noise space as demonstrated in the example above. The 2nd\nand 3rd dimensions can also be interpreted as time.
The actual\nnoise is structured similar to an audio signal, in respect to the\nfunction's use of frequencies. Similar to the concept of harmonics in\nphysics, Perlin noise is computed over several octaves which are added\ntogether for the final result.
Another way to adjust the\ncharacter of the resulting sequence is the scale of the input\ncoordinates. As the function works within an infinite space the value of\nthe coordinates doesn't matter as such, only the distance between\nsuccessive coordinates does (eg. when using noise() within a\nloop). As a general rule the smaller the difference between coordinates,\nthe smoother the resulting noise sequence will be. Steps of 0.005-0.03\nwork best for most applications, but this will differ depending on use.
x-coordinate in noise space
\n", "type": "Number" }, { "name": "y", "description": "y-coordinate in noise space
\n", "type": "Number", "optional": true }, { "name": "z", "description": "z-coordinate in noise space
\n", "type": "Number", "optional": true } ], "return": { "description": "Perlin noise value (between 0 and 1) at specified\n coordinates", "type": "Number" }, "example": [ "\n\nlet xoff = 0.0;\n\nfunction draw() {\n background(204);\n xoff = xoff + 0.01;\n let n = noise(xoff) * width;\n line(n, 0, n, height);\n describe(`vertical line moves left to right with updating\n noise values.`);\n}\n
\nlet noiseScale=0.02;\n\nfunction draw() {\n background(0);\n for (let x=0; x < width; x++) {\n let noiseVal = noise((mouseX+x)*noiseScale, mouseY*noiseScale);\n stroke(noiseVal*255);\n line(x, mouseY+noiseVal*80, x, height);\n }\n describe(`horizontal wave pattern effected by mouse x-position\n & updating noise values.`);\n}\n
\nAdjusts the character and level of detail produced by the Perlin noise\n function. Similar to harmonics in physics, noise is computed over\n several octaves. Lower octaves contribute more to the output signal and\n as such define the overall intensity of the noise, whereas higher octaves\n create finer-grained details in the noise sequence.\nBy default, noise is computed over 4 octaves with each octave contributing\n exactly half as much as its predecessor, starting at 50% strength for the 1st\n octave. This falloff amount can be changed by adding an additional function\n parameter. Eg. a falloff factor of 0.75 means each octave will now have\n 75% impact (25% less) of the previous lower octave. Any value between\n 0.0 and 1.0 is valid, however, note that values greater than 0.5 might\n result in greater than 1.0 values returned by noise().\nBy changing these parameters, the signal created by the noise()\n function can be adapted to fit very specific needs and characteristics.
\n", "itemtype": "method", "name": "noiseDetail", "params": [ { "name": "lod", "description": "number of octaves to be used by the noise
\n", "type": "Number" }, { "name": "falloff", "description": "falloff factor for each octave
\n", "type": "Number" } ], "example": [ "\n\n let noiseVal;\n let noiseScale = 0.02;\nfunction setup() {\n createCanvas(100, 100);\n }\nfunction draw() {\n background(0);\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width / 2; x++) {\n noiseDetail(2, 0.2);\n noiseVal = noise((mouseX + x) * noiseScale, (mouseY + y) * noiseScale);\n stroke(noiseVal * 255);\n point(x, y);\n noiseDetail(8, 0.65);\n noiseVal = noise(\n (mouseX + x + width / 2) * noiseScale,\n (mouseY + y) * noiseScale\n );\n stroke(noiseVal * 255);\n point(x + width / 2, y);\n }\n }\n describe(`2 vertical grey smokey patterns affected by\n mouse x-position and noise.`);\n }\n
\n Sets the seed value for noise(). By default,\nnoise() produces different results each time\nthe program is run. Set the seed
parameter to a constant to return\nthe same pseudo-random numbers each time the software is run.
the seed value
\n", "type": "Number" } ], "example": [ "\nlet xoff = 0.0;\n\nfunction setup() {\n noiseSeed(99);\n stroke(0, 10);\n}\n\nfunction draw() {\n xoff = xoff + .01;\n let n = noise(xoff) * width;\n line(n, 0, n, height);\n describe(`vertical grey lines drawing in pattern affected by noise.`);\n}\n
\nThe x component of the vector
\n", "itemtype": "property", "name": "x", "type": "Number", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 74, "description": "The y component of the vector
\n", "itemtype": "property", "name": "y", "type": "Number", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 79, "description": "The z component of the vector
\n", "itemtype": "property", "name": "z", "type": "Number", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 86, "description": "Returns a string representation of a vector v
by calling String(v)
\nor v.toString()
. This method is useful for logging vectors in the\nconsole.
\nfunction setup() {\n let v = createVector(20, 30);\n print(String(v)); // prints \"p5.Vector Object : [20, 30, 0]\"\n}\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'black');\n\n noStroke();\n text(v1.toString(), 10, 25, 90, 75);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nSets the x
, y
, and z
components of the vector using two or three separate\nvariables, the data from a p5.Vector, or the values from a float array.
\nfunction setup() {\n let v = createVector(1, 2, 3);\n v.set(4, 5, 6); // Sets vector to [4, 5, 6]\n\n let v1 = createVector(0, 0, 0);\n let arr = [1, 2, 3];\n v1.set(arr); // Sets vector to [1, 2, 3]\n}\n
\n\nlet v0, v1;\nfunction setup() {\n createCanvas(100, 100);\n\n v0 = createVector(0, 0);\n v1 = createVector(50, 50);\n}\n\nfunction draw() {\n background(240);\n\n drawArrow(v0, v1, 'black');\n v1.set(v1.x + random(-1, 1), v1.y + random(-1, 1));\n\n noStroke();\n text('x: ' + round(v1.x) + ' y: ' + round(v1.y), 20, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nThe x component of the vector
\n", "type": "Number", "optional": true }, { "name": "y", "description": "The y component of the vector
\n", "type": "Number", "optional": true }, { "name": "z", "description": "The z component of the vector
\n", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 195, "params": [ { "name": "value", "description": "The vector to set
\n", "type": "p5.Vector|Number[]" } ], "chainable": 1 } ] }, { "file": "src/math/p5.Vector.js", "line": 219, "description": "Gets a copy of the vector, returns a p5.Vector object.
\n", "itemtype": "method", "name": "copy", "return": { "description": "A copy of the p5.Vector object", "type": "p5.Vector" }, "example": [ "\n\nlet v1 = createVector(1, 2, 3);\nlet v2 = v1.copy();\nprint(v1.x === v2.x && v1.y === v2.y && v1.z === v2.z);\n// Prints \"true\"\n
\nAdds x
, y
, and z
components to a vector, adds one vector to another, or\nadds two independent vectors together. The version of the method that adds\ntwo vectors together is a static method and returns a p5.Vector, the others\nact directly on the vector. Additionally, you may provide arguments to this method as an array.\nSee the examples for more context.
\nlet v = createVector(1, 2, 3);\nv.add(4, 5, 6);\n// v's components are set to [5, 7, 9]\n
\n\nlet v = createVector(1, 2, 3);\n// Provide arguments as an array\nlet arr = [4, 5, 6];\nv.add(arr);\n// v's components are set to [5, 7, 9]\n
\n\n// Static method\nlet v1 = createVector(1, 2, 3);\nlet v2 = createVector(2, 3, 4);\n\nlet v3 = p5.Vector.add(v1, v2);\n// v3 has components [3, 5, 7]\nprint(v3);\n
\n\n// red vector + blue vector = purple vector\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'red');\n\n let v2 = createVector(-30, 20);\n drawArrow(v1, v2, 'blue');\n\n let v3 = p5.Vector.add(v1, v2);\n drawArrow(v0, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nThe x component of the vector to be added
\n", "type": "Number" }, { "name": "y", "description": "The y component of the vector to be added
\n", "type": "Number", "optional": true }, { "name": "z", "description": "The z component of the vector to be added
\n", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 325, "params": [ { "name": "value", "description": "The vector to add
\n", "type": "p5.Vector|Number[]" } ], "chainable": 1 }, { "line": 2061, "params": [ { "name": "v1", "description": "A p5.Vector to add
\n", "type": "p5.Vector" }, { "name": "v2", "description": "A p5.Vector to add
\n", "type": "p5.Vector" }, { "name": "target", "description": "The vector to receive the result
\n", "type": "p5.Vector", "optional": true } ], "static": 1, "return": { "description": "The resulting p5.Vector", "type": "p5.Vector" } } ] }, { "file": "src/math/p5.Vector.js", "line": 372, "description": "Gives the remainder of a vector when it is divided by another vector.\nSee examples for more context.
\n", "itemtype": "method", "name": "rem", "chainable": 1, "example": [ "\n\nlet v = createVector(3, 4, 5);\nv.rem(2, 3, 4);\n// v's components are set to [1, 1, 1]\n
\n\n// Static method\nlet v1 = createVector(3, 4, 5);\nlet v2 = createVector(2, 3, 4);\n\nlet v3 = p5.Vector.rem(v1, v2);\n// v3 has components [1, 1, 1]\nprint(v3);\n
\nThe x component of divisor vector
\n", "type": "Number" }, { "name": "y", "description": "The y component of divisor vector
\n", "type": "Number" }, { "name": "z", "description": "The z component of divisor vector
\n", "type": "Number" } ], "chainable": 1 }, { "line": 401, "params": [ { "name": "value", "description": "The divisor vector
\n", "type": "p5.Vector | Number[]" } ], "chainable": 1 }, { "line": 2087, "params": [ { "name": "v1", "description": "The dividend p5.Vector
\n", "type": "p5.Vector" }, { "name": "v2", "description": "The divisor p5.Vector
\n", "type": "p5.Vector" } ], "static": 1 }, { "line": 2093, "params": [ { "name": "v1", "description": "", "type": "p5.Vector" }, { "name": "v2", "description": "", "type": "p5.Vector" } ], "static": 1, "return": { "description": "The resulting p5.Vector", "type": "p5.Vector" } } ] }, { "file": "src/math/p5.Vector.js", "line": 461, "description": "Subtracts x
, y
, and z
components from a vector, subtracts one vector from\nanother, or subtracts two independent vectors. The version of the method\nthat subtracts two vectors is a static method and returns a p5.Vector, the\nothers act directly on the vector. Additionally, you may provide arguments to this method as an array.\nSee the examples for more context.
\nlet v = createVector(4, 5, 6);\nv.sub(1, 1, 1);\n// v's components are set to [3, 4, 5]\n
\n\nlet v = createVector(4, 5, 6);\n// Provide arguments as an array\nlet arr = [1, 1, 1];\nv.sub(arr);\n// v's components are set to [3, 4, 5]\n
\n\n// Static method\nlet v1 = createVector(2, 3, 4);\nlet v2 = createVector(1, 2, 3);\n\nlet v3 = p5.Vector.sub(v1, v2);\n// v3 has components [1, 1, 1]\nprint(v3);\n
\n\n// red vector - blue vector = purple vector\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(70, 50);\n drawArrow(v0, v1, 'red');\n\n let v2 = createVector(mouseX, mouseY);\n drawArrow(v0, v2, 'blue');\n\n let v3 = p5.Vector.sub(v1, v2);\n drawArrow(v2, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nThe x component of the vector to subtract
\n", "type": "Number" }, { "name": "y", "description": "The y component of the vector to subtract
\n", "type": "Number", "optional": true }, { "name": "z", "description": "The z component of the vector to subtract
\n", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 538, "params": [ { "name": "value", "description": "the vector to subtract
\n", "type": "p5.Vector|Number[]" } ], "chainable": 1 }, { "line": 2112, "params": [ { "name": "v1", "description": "A p5.Vector to subtract from
\n", "type": "p5.Vector" }, { "name": "v2", "description": "A p5.Vector to subtract
\n", "type": "p5.Vector" }, { "name": "target", "description": "The vector to receive the result
\n", "type": "p5.Vector", "optional": true } ], "static": 1, "return": { "description": "The resulting p5.Vector", "type": "p5.Vector" } } ] }, { "file": "src/math/p5.Vector.js", "line": 562, "description": "Multiplies the vector by a scalar, multiplies the x
, y
, and z
components from a vector, or multiplies\nthe x
, y
, and z
components of two independent vectors. When multiplying a vector by a scalar, the x
, y
,\nand z
components of the vector are all multiplied by the scalar. When multiplying a vector by a vector,\nthe x
, y
, z
components of both vectors are multiplied by each other\n(for example, with two vectors a
and b
: a.x * b.x
, a.y * b.y
, a.z * b.z
). The static version of this method\ncreates a new p5.Vector while the non-static version acts on the vector\ndirectly. Additionally, you may provide arguments to this function as an array.\nSee the examples for more context.
\nlet v = createVector(1, 2, 3);\nv.mult(2);\n// v's components are set to [2, 4, 6]\n
\n\nlet v0 = createVector(1, 2, 3);\nlet v1 = createVector(2, 3, 4);\nv0.mult(v1); // v0's components are set to [2, 6, 12]\n
\n\nlet v0 = createVector(1, 2, 3);\n// Provide arguments as an array\nlet arr = [2, 3, 4];\nv0.mult(arr); // v0's components are set to [2, 6, 12]\n
\n\nlet v0 = createVector(1, 2, 3);\nlet v1 = createVector(2, 3, 4);\nconst result = p5.Vector.mult(v0, v1);\nprint(result); // result's components are set to [2, 6, 12]\n
\n\n// Static method\nlet v1 = createVector(1, 2, 3);\nlet v2 = p5.Vector.mult(v1, 2);\n// v2 has components [2, 4, 6]\nprint(v2);\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = createVector(25, -25);\n drawArrow(v0, v1, 'red');\n\n let num = map(mouseX, 0, width, -2, 2, true);\n let v2 = p5.Vector.mult(v1, num);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('multiplied by ' + num.toFixed(2), 5, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nThe number to multiply with the vector
\n", "type": "Number" } ], "chainable": 1 }, { "line": 655, "params": [ { "name": "x", "description": "The number to multiply with the x component of the vector
\n", "type": "Number" }, { "name": "y", "description": "The number to multiply with the y component of the vector
\n", "type": "Number" }, { "name": "z", "description": "The number to multiply with the z component of the vector
\n", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 663, "params": [ { "name": "arr", "description": "The array to multiply with the components of the vector
\n", "type": "Number[]" } ], "chainable": 1 }, { "line": 669, "params": [ { "name": "v", "description": "The vector to multiply with the components of the original vector
\n", "type": "p5.Vector" } ], "chainable": 1 }, { "line": 2141, "params": [ { "name": "x", "description": "", "type": "Number" }, { "name": "y", "description": "", "type": "Number" }, { "name": "z", "description": "", "type": "Number", "optional": true } ], "static": 1, "return": { "description": "The resulting new p5.Vector", "type": "p5.Vector" } }, { "line": 2150, "params": [ { "name": "v", "description": "", "type": "p5.Vector" }, { "name": "n", "description": "", "type": "Number" }, { "name": "target", "description": "the vector to receive the result
\n", "type": "p5.Vector", "optional": true } ], "static": 1 }, { "line": 2158, "params": [ { "name": "v0", "description": "", "type": "p5.Vector" }, { "name": "v1", "description": "", "type": "p5.Vector" }, { "name": "target", "description": "", "type": "p5.Vector", "optional": true } ], "static": 1 }, { "line": 2166, "params": [ { "name": "v0", "description": "", "type": "p5.Vector" }, { "name": "arr", "description": "", "type": "Number[]" }, { "name": "target", "description": "", "type": "p5.Vector", "optional": true } ], "static": 1 } ] }, { "file": "src/math/p5.Vector.js", "line": 754, "description": "Divides the vector by a scalar, divides a vector by the x
, y
, and z
arguments, or divides the x
, y
, and\nz
components of two vectors against each other. When dividing a vector by a scalar, the x
, y
,\nand z
components of the vector are all divided by the scalar. When dividing a vector by a vector,\nthe x
, y
, z
components of the source vector are treated as the dividend, and the x
, y
, z
components\nof the argument is treated as the divisor. (For example, with two vectors\na
and b
: a.x / b.x
, a.y / b.y
, a.z / b.z
.)\nThe static version of this method creates a\nnew p5.Vector while the non-static version acts on the vector directly.\nAdditionally, you may provide arguments to this method as an array.\nSee the examples for more context.
\nlet v = createVector(6, 4, 2);\nv.div(2); //v's components are set to [3, 2, 1]\n
\n\nlet v0 = createVector(9, 4, 2);\nlet v1 = createVector(3, 2, 4);\nv0.div(v1); // v0's components are set to [3, 2, 0.5]\n
\n\nlet v0 = createVector(9, 4, 2);\n// Provide arguments as an array\nlet arr = [3, 2, 4];\nv0.div(arr); // v0's components are set to [3, 2, 0.5]\n
\n\nlet v0 = createVector(9, 4, 2);\nlet v1 = createVector(3, 2, 4);\nlet result = p5.Vector.div(v0, v1);\nprint(result); // result's components are set to [3, 2, 0.5]\n
\n\n// Static method\nlet v1 = createVector(6, 4, 2);\nlet v2 = p5.Vector.div(v1, 2);\n// v2 has components [3, 2, 1]\nprint(v2);\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 100);\n let v1 = createVector(50, -50);\n drawArrow(v0, v1, 'red');\n\n let num = map(mouseX, 0, width, 10, 0.5, true);\n let v2 = p5.Vector.div(v1, num);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('divided by ' + num.toFixed(2), 10, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nThe number to divide the vector by
\n", "type": "Number" } ], "chainable": 1 }, { "line": 848, "params": [ { "name": "x", "description": "The number to divide with the x component of the vector
\n", "type": "Number" }, { "name": "y", "description": "The number to divide with the y component of the vector
\n", "type": "Number" }, { "name": "z", "description": "The number to divide with the z component of the vector
\n", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 856, "params": [ { "name": "arr", "description": "The array to divide the components of the vector by
\n", "type": "Number[]" } ], "chainable": 1 }, { "line": 862, "params": [ { "name": "v", "description": "The vector to divide the components of the original vector by
\n", "type": "p5.Vector" } ], "chainable": 1 }, { "line": 2220, "params": [ { "name": "x", "description": "", "type": "Number" }, { "name": "y", "description": "", "type": "Number" }, { "name": "z", "description": "", "type": "Number", "optional": true } ], "static": 1, "return": { "description": "The resulting new p5.Vector", "type": "p5.Vector" } }, { "line": 2229, "params": [ { "name": "v", "description": "", "type": "p5.Vector" }, { "name": "n", "description": "", "type": "Number" }, { "name": "target", "description": "The vector to receive the result
\n", "type": "p5.Vector", "optional": true } ], "static": 1 }, { "line": 2237, "params": [ { "name": "v0", "description": "", "type": "p5.Vector" }, { "name": "v1", "description": "", "type": "p5.Vector" }, { "name": "target", "description": "", "type": "p5.Vector", "optional": true } ], "static": 1 }, { "line": 2245, "params": [ { "name": "v0", "description": "", "type": "p5.Vector" }, { "name": "arr", "description": "", "type": "Number[]" }, { "name": "target", "description": "", "type": "p5.Vector", "optional": true } ], "static": 1 } ] }, { "file": "src/math/p5.Vector.js", "line": 960, "description": "Calculates the magnitude (length) of the vector and returns the result as\na float. (This is simply the equation sqrt(x*x + y*y + z*z)
.)
\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'black');\n\n noStroke();\n text('vector length: ' + v1.mag().toFixed(2), 10, 70, 90, 30);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nlet v = createVector(20.0, 30.0, 40.0);\nlet m = v.mag();\nprint(m); // Prints \"53.85164807134504\"\n
\nThe vector to return the magnitude of
\n", "type": "p5.Vector" } ], "static": 1, "return": { "description": "The magnitude of vecT", "type": "Number" } } ] }, { "file": "src/math/p5.Vector.js", "line": 1008, "description": "Calculates the squared magnitude of the vector and returns the result\nas a float. (This is simply the equation x*x + y*y + z*z
.)\nFaster if the real length is not required in the\ncase of comparing vectors, etc.
\n// Static method\nlet v1 = createVector(6, 4, 2);\nprint(v1.magSq()); // Prints \"56\"\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'black');\n\n noStroke();\n text('vector length squared: ' + v1.magSq().toFixed(2), 10, 45, 90, 55);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nCalculates the dot product of two vectors. The version of the method\nthat computes the dot product of two independent vectors is a static\nmethod. See the examples for more context.
\n", "itemtype": "method", "name": "dot", "return": { "description": "The dot product", "type": "Number" }, "example": [ "\n\nlet v1 = createVector(1, 2, 3);\nlet v2 = createVector(2, 3, 4);\n\nprint(v1.dot(v2)); // Prints \"20\"\n
\n\n//Static method\nlet v1 = createVector(1, 2, 3);\nlet v2 = createVector(3, 2, 1);\nprint(p5.Vector.dot(v1, v2)); // Prints \"10\"\n
\nThe x component of the vector
\n", "type": "Number" }, { "name": "y", "description": "The y component of the vector
\n", "type": "Number", "optional": true }, { "name": "z", "description": "The z component of the vector
\n", "type": "Number", "optional": true } ], "return": { "description": "The dot product", "type": "Number" } }, { "line": 1092, "params": [ { "name": "value", "description": "value component of the vector or a p5.Vector
\n", "type": "p5.Vector" } ], "return": { "description": "", "type": "Number" } }, { "line": 2272, "params": [ { "name": "v1", "description": "The first p5.Vector
\n", "type": "p5.Vector" }, { "name": "v2", "description": "The second p5.Vector
\n", "type": "p5.Vector" } ], "static": 1, "return": { "description": "The dot product", "type": "Number" } } ] }, { "file": "src/math/p5.Vector.js", "line": 1104, "description": "Calculates and returns a vector composed of the cross product between\ntwo vectors. Both the static and non-static methods return a new p5.Vector.\nSee the examples for more context.
\n", "itemtype": "method", "name": "cross", "return": { "description": "p5.Vector composed of cross product", "type": "p5.Vector" }, "example": [ "\n\nlet v1 = createVector(1, 2, 3);\nlet v2 = createVector(1, 2, 3);\n\nlet v = v1.cross(v2); // v's components are [0, 0, 0]\nprint(v);\n
\n\n// Static method\nlet v1 = createVector(1, 0, 0);\nlet v2 = createVector(0, 1, 0);\n\nlet crossProduct = p5.Vector.cross(v1, v2);\n// crossProduct has components [0, 0, 1]\nprint(crossProduct);\n
\np5.Vector to be crossed
\n", "type": "p5.Vector" } ], "return": { "description": "p5.Vector composed of cross product", "type": "p5.Vector" } }, { "line": 2286, "params": [ { "name": "v1", "description": "The first p5.Vector
\n", "type": "p5.Vector" }, { "name": "v2", "description": "The second p5.Vector
\n", "type": "p5.Vector" } ], "static": 1, "return": { "description": "The cross product", "type": "Number" } } ] }, { "file": "src/math/p5.Vector.js", "line": 1146, "description": "Calculates the Euclidean distance between two points (considering a\npoint as a vector object).\nIf you are looking to calculate distance between 2 points see dist()
\n", "itemtype": "method", "name": "dist", "return": { "description": "The distance", "type": "Number" }, "example": [ "\n\nlet v1 = createVector(1, 0, 0);\nlet v2 = createVector(0, 1, 0);\n\nlet distance = v1.dist(v2); // distance is 1.4142...\nprint(distance);\n
\n\n// Static method\nlet v1 = createVector(1, 0, 0);\nlet v2 = createVector(0, 1, 0);\n\nlet distance = p5.Vector.dist(v1, v2);\n// distance is 1.4142...\nprint(distance);\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n\n let v1 = createVector(70, 50);\n drawArrow(v0, v1, 'red');\n\n let v2 = createVector(mouseX, mouseY);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('distance between vectors: ' + v2.dist(v1).toFixed(2), 5, 50, 95, 50);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nThe x, y, and z coordinates of a p5.Vector
\n", "type": "p5.Vector" } ], "return": { "description": "The distance", "type": "Number" } }, { "line": 2301, "params": [ { "name": "v1", "description": "The first p5.Vector
\n", "type": "p5.Vector" }, { "name": "v2", "description": "The second p5.Vector
\n", "type": "p5.Vector" } ], "static": 1, "return": { "description": "The distance", "type": "Number" } } ] }, { "file": "src/math/p5.Vector.js", "line": 1218, "description": "Normalize the vector to length 1 (make it a unit vector).
\n", "itemtype": "method", "name": "normalize", "return": { "description": "The normalized p5.Vector", "type": "p5.Vector" }, "example": [ "\n\nlet v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.normalize();\n// v's components are set to\n// [0.4454354, 0.8908708, 0.089087084]\n
\n\n// Static method\nlet v_initial = createVector(10, 20, 2);\n// v_initial has components [10.0, 20.0, 2.0]\nlet v_normalized = p5.Vector.normalize(v_initial);\nprint(v_normalized);\n// returns a new vector with components set to\n// [0.4454354, 0.8908708, 0.089087084]\n// v_initial remains unchanged\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'red');\n v1.normalize();\n drawArrow(v0, v1.mult(35), 'blue');\n\n noFill();\n ellipse(50, 50, 35 * 2);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nThe vector to normalize
\n", "type": "p5.Vector" }, { "name": "target", "description": "The vector to receive the result
\n", "type": "p5.Vector", "optional": true } ], "static": 1, "return": { "description": "The vector v, normalized to a length of 1", "type": "p5.Vector" } } ] }, { "file": "src/math/p5.Vector.js", "line": 1288, "description": "Limit the magnitude of this vector to the value used for the max
\nparameter.
The maximum magnitude for the vector
\n", "type": "Number" } ], "chainable": 1, "example": [ "\n\nlet v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.limit(5);\n// v's components are set to\n// [2.2271771, 4.4543543, 0.4454354]\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'red');\n drawArrow(v0, v1.limit(35), 'blue');\n\n noFill();\n ellipse(50, 50, 35 * 2);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nSet the magnitude of this vector to the value used for the len
\nparameter.
The new length for this vector
\n", "type": "Number" } ], "chainable": 1, "example": [ "\n\nlet v = createVector(3, 4, 0);\n// v has components [3.0, 4.0, 0.0]\nv.setMag(10);\n// v's components are set to [6.0, 8.0, 0.0]\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(50, 50);\n\n drawArrow(v0, v1, 'red');\n\n let length = map(mouseX, 0, width, 0, 141, true);\n v1.setMag(length);\n drawArrow(v0, v1, 'blue');\n\n noStroke();\n text('magnitude set to: ' + length.toFixed(2), 10, 70, 90, 30);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nCalculate the angle of rotation for this vector (only 2D vectors).\np5.Vectors created using createVector()\nwill take the current angleMode() into\nconsideration, and give the angle in radians or degree accordingly.
\n", "itemtype": "method", "name": "heading", "return": { "description": "The angle of rotation", "type": "Number" }, "example": [ "\n\nfunction setup() {\n let v1 = createVector(30, 50);\n print(v1.heading()); // 1.0303768265243125\n\n v1 = createVector(40, 50);\n print(v1.heading()); // 0.8960553845713439\n\n v1 = createVector(30, 70);\n print(v1.heading()); // 1.1659045405098132\n}\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'black');\n\n let myHeading = v1.heading();\n noStroke();\n text(\n 'vector heading: ' +\n myHeading.toFixed(2) +\n ' radians or ' +\n degrees(myHeading).toFixed(2) +\n ' degrees',\n 10,\n 50,\n 90,\n 50\n );\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nRotate the vector to a specific angle (only 2D vectors); magnitude remains the\nsame.
\n", "itemtype": "method", "name": "setHeading", "params": [ { "name": "angle", "description": "The angle of rotation
\n", "type": "Number" } ], "chainable": 1, "example": [ "\n\nlet v = createVector(10.0, 20.0);\n// result of v.heading() is 1.1071487177940904\nv.setHeading(Math.PI);\n// result of v.heading() is now 3.141592653589793\n
\nRotate the vector by an angle (only 2D vectors); magnitude remains the\nsame.
\n", "itemtype": "method", "name": "rotate", "chainable": 1, "example": [ "\n\nlet v = createVector(10.0, 20.0);\n// v has components [10.0, 20.0, 0.0]\nv.rotate(HALF_PI);\n// v's components are set to [-20.0, 9.999999, 0.0]\n
\n\n// static function implementation\nlet v = createVector(10.0, 20.0);\n// v has components [10.0, 20.0, 0.0]\nlet rotated_v = p5.Vector.rotate(v, HALF_PI);\nconsole.log(rotated_v);\n// rotated_v's components are set to [-20.0, 9.999999, 0.0]\nconsole.log(v);\n// v's components remains the same (i.e, [10.0, 20.0, 0.0])\n
\n\nlet angle = 0;\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = createVector(50, 0);\n\n drawArrow(v0, v1.rotate(angle), 'black');\n angle += 0.01;\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nThe angle of rotation
\n", "type": "Number" } ], "chainable": 1 }, { "line": 2193, "params": [ { "name": "v", "description": "", "type": "p5.Vector" }, { "name": "angle", "description": "", "type": "Number" }, { "name": "target", "description": "The vector to receive the result
\n", "type": "p5.Vector", "optional": true } ], "static": 1 } ] }, { "file": "src/math/p5.Vector.js", "line": 1569, "description": "Calculates and returns the angle between two vectors. This method will take\nthe current angleMode into consideration, and\ngive the angle in radians or degree accordingly.
\n", "itemtype": "method", "name": "angleBetween", "params": [ { "name": "value", "description": "The x, y, and z components of a p5.Vector
\n", "type": "p5.Vector" } ], "return": { "description": "The angle between (in radians)", "type": "Number" }, "example": [ "\n\nlet v1 = createVector(1, 0, 0);\nlet v2 = createVector(0, 1, 0);\n\nlet angle = v1.angleBetween(v2);\n// angle is PI/2\nprint(angle);\n
\n\nfunction draw() {\n background(240);\n let v0 = createVector(50, 50);\n\n let v1 = createVector(50, 0);\n drawArrow(v0, v1, 'red');\n\n let v2 = createVector(mouseX - 50, mouseY - 50);\n drawArrow(v0, v2, 'blue');\n\n let angleBetween = v1.angleBetween(v2);\n noStroke();\n text(\n 'angle between: ' +\n angleBetween.toFixed(2) +\n ' radians or ' +\n degrees(angleBetween).toFixed(2) +\n ' degrees',\n 10,\n 50,\n 90,\n 50\n );\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nLinear interpolate the vector to another vector.
\n", "itemtype": "method", "name": "lerp", "chainable": 1, "example": [ "\n\nlet v = createVector(1, 1, 0);\n\nv.lerp(3, 3, 0, 0.5); // v now has components [2,2,0]\n
\n\nlet v1 = createVector(0, 0, 0);\nlet v2 = createVector(100, 100, 0);\n\nlet v3 = p5.Vector.lerp(v1, v2, 0.5);\n// v3 has components [50,50,0]\nprint(v3);\n
\n\nlet step = 0.01;\nlet amount = 0;\n\nfunction draw() {\n background(240);\n let v0 = createVector(0, 0);\n\n let v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'red');\n\n let v2 = createVector(90, 90);\n drawArrow(v0, v2, 'blue');\n\n if (amount > 1 || amount < 0) {\n step *= -1;\n }\n amount += step;\n let v3 = p5.Vector.lerp(v1, v2, amount);\n\n drawArrow(v0, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nThe x component
\n", "type": "Number" }, { "name": "y", "description": "The y component
\n", "type": "Number" }, { "name": "z", "description": "The z component
\n", "type": "Number" }, { "name": "amt", "description": "The amount of interpolation; some value between 0.0\n (old vector) and 1.0 (new vector). 0.9 is very near\n the new vector. 0.5 is halfway in between.
\n", "type": "Number" } ], "chainable": 1 }, { "line": 1722, "params": [ { "name": "v", "description": "The p5.Vector to lerp to
\n", "type": "p5.Vector" }, { "name": "amt", "description": "", "type": "Number" } ], "chainable": 1 }, { "line": 2316, "params": [ { "name": "v1", "description": "", "type": "p5.Vector" }, { "name": "v2", "description": "", "type": "p5.Vector" }, { "name": "amt", "description": "", "type": "Number" }, { "name": "target", "description": "The vector to receive the result
\n", "type": "p5.Vector", "optional": true } ], "static": 1, "return": { "description": "The lerped value", "type": "p5.Vector" } } ] }, { "file": "src/math/p5.Vector.js", "line": 1738, "description": "Reflect the incoming vector about a normal to a line in 2D, or about a normal to a plane in 3D.\nThis method acts on the vector directly.
\n", "itemtype": "method", "name": "reflect", "params": [ { "name": "surfaceNormal", "description": "The p5.Vector to reflect about; will be normalized by this method.
\n", "type": "p5.Vector" } ], "chainable": 1, "example": [ "\n\nlet v = createVector(4, 6); // incoming vector, this example vector is heading to the right and downward\nlet n = createVector(0, -1); // surface normal to a plane (this example normal points directly upwards)\nv.reflect(n); // v is reflected about the surface normal n. v's components are now set to [4, -6]\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'red');\n\n let n = createVector(0, -30);\n drawArrow(v1, n, 'blue');\n\n let r = v1.copy();\n r.reflect(n);\n drawArrow(v1, r, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nReturn a representation of this vector as a float array. This is only\nfor temporary use. If used in any other fashion, the contents should be\ncopied by using the p5.Vector.copy() method to copy into your own\narray.
\n", "itemtype": "method", "name": "array", "return": { "description": "An Array with the 3 values", "type": "Number[]" }, "example": [ "\n\nfunction setup() {\n let v = createVector(20, 30);\n print(v.array()); // Prints : Array [20, 30, 0]\n}\n
\n\nlet v = createVector(10.0, 20.0, 30.0);\nlet f = v.array();\nprint(f[0]); // Prints \"10.0\"\nprint(f[1]); // Prints \"20.0\"\nprint(f[2]); // Prints \"30.0\"\n
\nEquality check against a p5.Vector.
\n", "itemtype": "method", "name": "equals", "return": { "description": "Whether the vectors are equal", "type": "Boolean" }, "example": [ "\n\nlet v1 = createVector(5, 10, 20);\nlet v2 = createVector(5, 10, 20);\nlet v3 = createVector(13, 10, 19);\n\nprint(v1.equals(v2.x, v2.y, v2.z)); // true\nprint(v1.equals(v3.x, v3.y, v3.z)); // false\n
\n\nlet v1 = createVector(10.0, 20.0, 30.0);\nlet v2 = createVector(10.0, 20.0, 30.0);\nlet v3 = createVector(0.0, 0.0, 0.0);\nprint(v1.equals(v2)); // true\nprint(v1.equals(v3)); // false\n
\nThe x component of the vector
\n", "type": "Number", "optional": true }, { "name": "y", "description": "The y component of the vector
\n", "type": "Number", "optional": true }, { "name": "z", "description": "The z component of the vector
\n", "type": "Number", "optional": true } ], "return": { "description": "Whether the vectors are equal", "type": "Boolean" } }, { "line": 1855, "params": [ { "name": "value", "description": "The vector to compare
\n", "type": "p5.Vector|Array" } ], "return": { "description": "", "type": "Boolean" } } ] }, { "file": "src/math/p5.Vector.js", "line": 1880, "description": "Make a new 2D vector from an angle.
\n", "itemtype": "method", "name": "fromAngle", "static": 1, "params": [ { "name": "angle", "description": "The desired angle, in radians (unaffected by angleMode)
\n", "type": "Number" }, { "name": "length", "description": "The length of the new vector (defaults to 1)
\n", "type": "Number", "optional": true } ], "return": { "description": "The new p5.Vector object", "type": "p5.Vector" }, "example": [ "\n\nfunction draw() {\n background(200);\n\n // Create a variable, proportional to the mouseX,\n // varying from 0-360, to represent an angle in degrees.\n let myDegrees = map(mouseX, 0, width, 0, 360);\n\n // Display that variable in an onscreen text.\n // (Note the nfc() function to truncate additional decimal places,\n // and the \"\\xB0\" character for the degree symbol.)\n let readout = 'angle = ' + nfc(myDegrees, 1) + '\\xB0';\n noStroke();\n fill(0);\n text(readout, 5, 15);\n\n // Create a p5.Vector using the fromAngle function,\n // and extract its x and y components.\n let v = p5.Vector.fromAngle(radians(myDegrees), 30);\n let vx = v.x;\n let vy = v.y;\n\n push();\n translate(width / 2, height / 2);\n noFill();\n stroke(150);\n line(0, 0, 30, 0);\n stroke(0);\n line(0, 0, vx, vy);\n pop();\n}\n
\nMake a new 3D vector from a pair of ISO spherical angles.
\n", "itemtype": "method", "name": "fromAngles", "static": 1, "params": [ { "name": "theta", "description": "The polar angle, in radians (zero is up)
\n", "type": "Number" }, { "name": "phi", "description": "The azimuthal angle, in radians\n (zero is out of the screen)
\n", "type": "Number" }, { "name": "length", "description": "The length of the new vector (defaults to 1)
\n", "type": "Number", "optional": true } ], "return": { "description": "A new p5.Vector object", "type": "p5.Vector" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n fill(255);\n noStroke();\n}\nfunction draw() {\n background(255);\n\n let t = millis() / 1000;\n\n // add three point lights\n pointLight(color('#f00'), p5.Vector.fromAngles(t * 1.0, t * 1.3, 100));\n pointLight(color('#0f0'), p5.Vector.fromAngles(t * 1.1, t * 1.2, 100));\n pointLight(color('#00f'), p5.Vector.fromAngles(t * 1.2, t * 1.1, 100));\n\n sphere(35);\n}\n
\nMake a new 2D unit vector from a random angle.
\n", "itemtype": "method", "name": "random2D", "static": 1, "return": { "description": "A new p5.Vector object", "type": "p5.Vector" }, "example": [ "\n\nlet v = p5.Vector.random2D();\n// May make v's attributes something like:\n// [0.61554617, -0.51195765, 0.0] or\n// [-0.4695841, -0.14366731, 0.0] or\n// [0.6091097, -0.22805278, 0.0]\nprint(v);\n
\n\nfunction setup() {\n frameRate(1);\n}\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = p5.Vector.random2D();\n drawArrow(v0, v1.mult(50), 'black');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nMake a new random 3D unit vector.
\n", "itemtype": "method", "name": "random3D", "static": 1, "return": { "description": "A new p5.Vector object", "type": "p5.Vector" }, "example": [ "\n\nlet v = p5.Vector.random3D();\n// May make v's attributes something like:\n// [0.61554617, -0.51195765, 0.599168] or\n// [-0.4695841, -0.14366731, -0.8711202] or\n// [0.6091097, -0.22805278, -0.7595902]\nprint(v);\n
\nMultiplies a vector by a scalar and returns a new vector.
\n", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 2189, "description": "Rotates the vector (only 2D vectors) by the given angle; magnitude remains the same. Returns a new vector.
\n", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 2216, "description": "Divides a vector by a scalar and returns a new vector.
\n", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 2269, "description": "Calculates the dot product of two vectors.
\n", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 2283, "description": "Calculates the cross product of two vectors.
\n", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 2297, "description": "Calculates the Euclidean distance between two points (considering a\npoint as a vector object).
\n", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 2312, "description": "Linear interpolate a vector to another vector and return the result as a\nnew vector.
\n", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 2341, "description": "Calculates the magnitude (length) of the vector and returns the result as\na float (this is simply the equation sqrt(x*x + y*y + z*z)
.)
Normalize the vector to length 1 (make it a unit vector).
\n", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/random.js", "line": 37, "description": "Sets the seed value for random().
\nBy default, random() produces different results each time the program\nis run. Set the seed parameter to a constant to return the same\npseudo-random numbers each time the software is run.
\n", "itemtype": "method", "name": "randomSeed", "params": [ { "name": "seed", "description": "the seed value
\n", "type": "Number" } ], "example": [ "\n\nrandomSeed(99);\nfor (let i = 0; i < 100; i++) {\n let r = random(0, 255);\n stroke(r);\n line(i, 0, i, 100);\n}\ndescribe('many vertical lines drawn in white, black, or grey.');\n
\nReturn a random floating-point number.
\nTakes either 0, 1 or 2 arguments.
\nIf no argument is given, returns a random number from 0\nup to (but not including) 1.
\nIf one argument is given and it is a number, returns a random number from 0\nup to (but not including) the number.
\nIf one argument is given and it is an array, returns a random element from\nthat array.
\nIf two arguments are given, returns a random number from the\nfirst argument up to (but not including) the second argument.
\n", "itemtype": "method", "name": "random", "return": { "description": "the random number", "type": "Number" }, "example": [ "\n\nfor (let i = 0; i < 100; i++) {\n let r = random(50);\n stroke(r * 5);\n line(50, i, 50 + r, i);\n}\ndescribe(`100 horizontal lines from center canvas to right.\n The size and fill change each time.`);\n
\n\nfor (let i = 0; i < 100; i++) {\n let r = random(-50, 50);\n line(50, i, 50 + r, i);\n}\ndescribe(`100 horizontal lines from center of canvas.\n The height & side change each render.`);\n
\n\n// Get a random element from an array using the random(Array) syntax\nlet words = ['apple', 'bear', 'cat', 'dog'];\nlet word = random(words); // select random word\ntext(word, 10, 50); // draw the word\ndescribe('word displayed at random. Either apple, bear, cat, or dog.');\n
\nthe lower bound (inclusive)
\n", "type": "Number", "optional": true }, { "name": "max", "description": "the upper bound (exclusive)
\n", "type": "Number", "optional": true } ], "return": { "description": "the random number", "type": "Number" } }, { "line": 117, "params": [ { "name": "choices", "description": "the array to choose from
\n", "type": "Array" } ], "return": { "description": "the random element from the array", "type": "*" } } ] }, { "file": "src/math/random.js", "line": 151, "description": "Returns a random number fitting a Gaussian, or\n normal, distribution. There is theoretically no minimum or maximum\n value that randomGaussian() might return. Rather, there is\n just a very low probability that values far from the mean will be\n returned; and a higher probability that numbers near the mean will\n be returned.\nTakes either 0, 1 or 2 arguments.
\n If no args, the mean is 0 and the standard deviation is 1.
\n If one arg, that arg is the mean and the standard deviation is 1.
\n If two args, the first arg is the mean and the second is the standard deviation.
the mean
\n", "type": "Number", "optional": true }, { "name": "sd", "description": "the standard deviation
\n", "type": "Number", "optional": true } ], "return": { "description": "the random number", "type": "Number" }, "example": [ "\n\n for (let y = 0; y < 100; y++) {\n let x = randomGaussian(50, 15);\n line(50, y, x, y);\n }\n describe(`100 horizontal lines from center of canvas.\n The height & side change each render.`);\n
\n \n let distribution = new Array(360);\nfunction setup() {\n createCanvas(100, 100);\n for (let i = 0; i < distribution.length; i++) {\n distribution[i] = floor(randomGaussian(0, 15));\n }\n }\nfunction draw() {\n background(204);\n translate(width / 2, width / 2);\n for (let i = 0; i < distribution.length; i++) {\n rotate(TWO_PI / distribution.length);\n stroke(0);\n let dist = abs(distribution[i]);\n line(0, 0, dist, 0);\n }\n describe(`black lines radiate from center of canvas.\n The size changes each render.`);\n }\n
\n The inverse of cos(), returns the arc cosine of a value.\nThis function expects the values in the range of -1 to 1 and values are returned in\nthe range 0 to PI (3.1415927) if the angleMode() is RADIANS\nor 0 to 180 if the angleMode() is DEGREES.
\n", "itemtype": "method", "name": "acos", "params": [ { "name": "value", "description": "the value whose arc cosine is to be returned
\n", "type": "Number" } ], "return": { "description": "the arc cosine of the given value", "type": "Number" }, "example": [ "\n\nlet a = PI;\nlet c = cos(a);\nlet ac = acos(c);\n// Prints: \"3.1415927 : -1.0 : 3.1415927\"\nprint(a + ' : ' + c + ' : ' + ac);\n
\n\nlet a = PI + PI / 4.0;\nlet c = cos(a);\nlet ac = acos(c);\n// Prints: \"3.926991 : -0.70710665 : 2.3561943\"\nprint(a + ' : ' + c + ' : ' + ac);\n
\nThe inverse of sin(), returns the arc sine of a value.\nThis function expects the values in the range of -1 to 1 and values are returned\nin the range -PI/2 to PI/2 if the angleMode is RADIANS or -90 to 90 if the angle\nmode is DEGREES.
\n", "itemtype": "method", "name": "asin", "params": [ { "name": "value", "description": "the value whose arc sine is to be returned
\n", "type": "Number" } ], "return": { "description": "the arc sine of the given value", "type": "Number" }, "example": [ "\n\nlet a = PI / 3.0;\nlet s = sin(a);\nlet as = asin(s);\n// Prints: \"1.0471975 : 0.86602540 : 1.0471975\"\nprint(a + ' : ' + s + ' : ' + as);\n
\n\nlet a = PI + PI / 3.0;\nlet s = sin(a);\nlet as = asin(s);\n// Prints: \"4.1887902 : -0.86602540 : -1.0471975\"\nprint(a + ' : ' + s + ' : ' + as);\n
\nThe inverse of tan(), returns the arc tangent of a value.\nThis function expects the values in the range of -Infinity to Infinity (exclusive) and\nvalues are returned in the range -PI/2 to PI/2 if the angleMode is RADIANS or\n-90 to 90 if the angle mode is DEGREES.
\n", "itemtype": "method", "name": "atan", "params": [ { "name": "value", "description": "the value whose arc tangent is to be returned
\n", "type": "Number" } ], "return": { "description": "the arc tangent of the given value", "type": "Number" }, "example": [ "\n\nlet a = PI / 3.0;\nlet t = tan(a);\nlet at = atan(t);\n// Prints: \"1.0471975 : 1.7320508 : 1.0471975\"\nprint(a + ' : ' + t + ' : ' + at);\n
\n\nlet a = PI + PI / 3.0;\nlet t = tan(a);\nlet at = atan(t);\n// Prints: \"4.1887902 : 1.7320508 : 1.0471975\"\nprint(a + ' : ' + t + ' : ' + at);\n
\nCalculates the angle (in radians) from a specified point to the coordinate\norigin as measured from the positive x-axis. Values are returned as a\nfloat in the range from PI to -PI if the angleMode()\nis RADIANS or 180 to -180 if the angleMode() is DEGREES.\nThe atan2() function is most often used for orienting geometry\nto the position of the cursor.
\nNote: The y-coordinate of the point is the first parameter, and the\nx-coordinate is the second parameter, due to the structure of calculating\nthe tangent.
\n", "itemtype": "method", "name": "atan2", "params": [ { "name": "y", "description": "y-coordinate of the point
\n", "type": "Number" }, { "name": "x", "description": "x-coordinate of the point
\n", "type": "Number" } ], "return": { "description": "the arc tangent of the given point", "type": "Number" }, "example": [ "\n\nfunction draw() {\n background(204);\n translate(width / 2, height / 2);\n let a = atan2(mouseY - height / 2, mouseX - width / 2);\n rotate(a);\n rect(-30, -5, 60, 10);\n describe('60×10 rect at center of canvas rotates with mouse movements');\n}\n
\nCalculates the cosine of an angle. This function takes into account the\ncurrent angleMode. Values are returned in the range -1 to 1.
\n", "itemtype": "method", "name": "cos", "params": [ { "name": "angle", "description": "the angle
\n", "type": "Number" } ], "return": { "description": "the cosine of the angle", "type": "Number" }, "example": [ "\n\nlet a = 0.0;\nlet inc = TWO_PI / 25.0;\nfor (let i = 0; i < 25; i++) {\n line(i * 4, 50, i * 4, 50 + cos(a) * 40.0);\n a = a + inc;\n}\ndescribe(`vertical black lines form wave patterns, extend-down on\n left and right side`);\n
\nCalculates the sine of an angle. This function takes into account the\ncurrent angleMode. Values are returned in the range -1 to 1.
\n", "itemtype": "method", "name": "sin", "params": [ { "name": "angle", "description": "the angle
\n", "type": "Number" } ], "return": { "description": "the sine of the angle", "type": "Number" }, "example": [ "\n\nlet a = 0.0;\nlet inc = TWO_PI / 25.0;\nfor (let i = 0; i < 25; i++) {\n line(i * 4, 50, i * 4, 50 + sin(a) * 40.0);\n a = a + inc;\n}\ndescribe(`vertical black lines extend down and up from center\n to form wave pattern.`);\n
\nCalculates the tangent of an angle. This function takes into account\nthe current angleMode. Values are returned in the range of all real numbers.
\n", "itemtype": "method", "name": "tan", "params": [ { "name": "angle", "description": "the angle
\n", "type": "Number" } ], "return": { "description": "the tangent of the angle", "type": "Number" }, "example": [ "\n\nlet a = 0.0;\nlet inc = TWO_PI / 50.0;\nfor (let i = 0; i < 100; i = i + 2) {\n line(i, 50, i, 50 + tan(a) * 2.0);\n a = a + inc;\n}\ndescribe(`vertical black lines end down and up from center to\n form spike pattern.`);\n
"
],
"class": "p5",
"module": "Math",
"submodule": "Trigonometry"
},
{
"file": "src/math/trigonometry.js",
"line": 235,
"description": "Converts a radian measurement to its corresponding value in degrees.\nRadians and degrees are two ways of measuring the same thing. There are\n360 degrees in a circle and 2*PI radians in a circle. For example,\n90° = PI/2 = 1.5707964. This function does not take into account the\ncurrent angleMode().
\n", "itemtype": "method", "name": "degrees", "params": [ { "name": "radians", "description": "the radians value to convert to degrees
\n", "type": "Number" } ], "return": { "description": "the converted angle", "type": "Number" }, "example": [ "\n\nlet rad = PI / 4;\nlet deg = degrees(rad);\nprint(rad + ' radians is ' + deg + ' degrees');\n// Prints: 0.7853981633974483 radians is 45 degrees\n
\nConverts a degree measurement to its corresponding value in radians.\nRadians and degrees are two ways of measuring the same thing. There are\n360 degrees in a circle and 2*PI radians in a circle. For example,\n90° = PI/2 = 1.5707964. This function does not take into account the\ncurrent angleMode.
\n", "itemtype": "method", "name": "radians", "params": [ { "name": "degrees", "description": "the degree value to convert to radians
\n", "type": "Number" } ], "return": { "description": "the converted angle", "type": "Number" }, "example": [ "\n\nlet deg = 45.0;\nlet rad = radians(deg);\nprint(deg + ' degrees is ' + rad + ' radians');\n// Prints: 45 degrees is 0.7853981633974483 radians\n
\nSets the current mode of p5 to the given mode. Default mode is RADIANS.
\nCalling angleMode() with no arguments returns current anglemode.
\n", "itemtype": "method", "name": "angleMode", "example": [ "\n\nfunction draw() {\n background(204);\n angleMode(DEGREES); // Change the mode to DEGREES\n let a = atan2(mouseY - height / 2, mouseX - width / 2);\n translate(width / 2, height / 2);\n push();\n rotate(a);\n rect(-20, -5, 40, 10); // Larger rectangle is rotating in degrees\n pop();\n angleMode(RADIANS); // Change the mode to RADIANS\n rotate(a); // variable a stays the same\n rect(-40, -5, 20, 10); // Smaller rectangle is rotating in radians\n describe(`40×10 rect in center rotates with mouse moves.\n 20×10 rect moves faster.`);\n}\n
\neither RADIANS or DEGREES
\n", "type": "Constant" } ] }, { "line": 309, "params": [], "return": { "description": "mode either RADIANS or DEGREES", "type": "Constant" } } ] }, { "file": "src/typography/attributes.js", "line": 11, "description": "Sets the current alignment for drawing text. Accepts two\narguments: horizAlign (LEFT, CENTER, or RIGHT) and\nvertAlign (TOP, BOTTOM, CENTER, or BASELINE).
\nThe horizAlign parameter is in reference to the x value\nof the text() function, while the vertAlign parameter\nis in reference to the y value.
\nSo if you write textAlign(LEFT), you are aligning the left\nedge of your text to the x value you give in text().\nIf you write textAlign(RIGHT, TOP), you are aligning the right edge\nof your text to the x value and the top edge of the text\nto the y value.
\n", "itemtype": "method", "name": "textAlign", "chainable": 1, "example": [ "\n\ntextSize(16);\ntextAlign(RIGHT);\ntext('ABCD', 50, 30);\ntextAlign(CENTER);\ntext('EFGH', 50, 50);\ntextAlign(LEFT);\ntext('IJKL', 50, 70);\ndescribe(`Letters ABCD displayed at top left, EFGH at center, and\n IJKL at bottom right.`);\n
\n\ntextSize(16);\nstrokeWeight(0.5);\n\nline(0, 12, width, 12);\ntextAlign(CENTER, TOP);\ntext('TOP', 0, 12, width);\n\nline(0, 37, width, 37);\ntextAlign(CENTER, CENTER);\ntext('CENTER', 0, 37, width);\n\nline(0, 62, width, 62);\ntextAlign(CENTER, BASELINE);\ntext('BASELINE', 0, 62, width);\n\nline(0, 87, width, 87);\ntextAlign(CENTER, BOTTOM);\ntext('BOTTOM', 0, 87, width);\n\ndescribe(`The names of the four vertical alignments (TOP, CENTER, BASELINE,\n and BOTTOM) rendered each showing that alignment's placement relative to a\n horizontal line.`);\n
\nhorizontal alignment, either LEFT,\n CENTER, or RIGHT
\n", "type": "Constant" }, { "name": "vertAlign", "description": "vertical alignment, either TOP,\n BOTTOM, CENTER, or BASELINE
\n", "type": "Constant", "optional": true } ], "chainable": 1 }, { "line": 74, "params": [], "return": { "description": "", "type": "Object" } } ] }, { "file": "src/typography/attributes.js", "line": 83, "description": "Sets/gets the spacing, in pixels, between lines of text. This setting will be\nused in all subsequent calls to the text() function.
\n", "itemtype": "method", "name": "textLeading", "chainable": 1, "example": [ "\n\nlet lines = 'L1\\nL2\\nL3'; // \"\\n\" is a \"new line\" character\ntextSize(12);\n\ntextLeading(10);\ntext(lines, 10, 25);\n\ntextLeading(20);\ntext(lines, 40, 25);\n\ntextLeading(30);\ntext(lines, 70, 25);\n\ndescribe(`A set of L1, L2, and L3, displayed vertically 3 times.\n Spacing increases for each set.`);\n
\nthe size in pixels for spacing between lines
\n", "type": "Number" } ], "chainable": 1 }, { "line": 111, "params": [], "return": { "description": "", "type": "Number" } } ] }, { "file": "src/typography/attributes.js", "line": 120, "description": "Sets/gets the current font size. This size will be used in all subsequent\ncalls to the text() function. Font size is measured in pixels.
\n", "itemtype": "method", "name": "textSize", "chainable": 1, "example": [ "\n\ntextSize(12);\ntext('Font Size 12', 10, 30);\ntextSize(14);\ntext('Font Size 14', 10, 60);\ntextSize(16);\ntext('Font Size 16', 10, 90);\n\ndescribe(`'Font Size 12' displayed small,\n 'Font Size 14' medium, and\n 'Font Size 16' large`);\n
\nthe size of the letters in units of pixels
\n", "type": "Number" } ], "chainable": 1 }, { "line": 144, "params": [], "return": { "description": "", "type": "Number" } } ] }, { "file": "src/typography/attributes.js", "line": 153, "description": "Sets/gets the style of the text for system fonts to NORMAL, ITALIC, BOLD or BOLDITALIC.\nNote: this may be is overridden by CSS styling. For non-system fonts\n(opentype, truetype, etc.) please load styled fonts instead.
\n", "itemtype": "method", "name": "textStyle", "chainable": 1, "example": [ "\n\nstrokeWeight(0);\ntextSize(12);\ntextStyle(NORMAL);\ntext('Font Style Normal', 10, 15);\ntextStyle(ITALIC);\ntext('Font Style Italic', 10, 40);\ntextStyle(BOLD);\ntext('Font Style Bold', 10, 65);\ntextStyle(BOLDITALIC);\ntext('Font Style Bold Italic', 10, 90);\ndescribe(`The words “Font Style Normal” displayed normally,\n “Font Style Italic” in italic,\n “Font Style Bold” in bold, and\n “Font Style Bold Italic” in bold italics.`);\n
\nstyling for text, either NORMAL,\n ITALIC, BOLD or BOLDITALIC
\n", "type": "Constant" } ], "chainable": 1 }, { "line": 182, "params": [], "return": { "description": "", "type": "String" } } ] }, { "file": "src/typography/attributes.js", "line": 191, "description": "Calculates and returns the width of any character or text string.
\n", "itemtype": "method", "name": "textWidth", "params": [ { "name": "theText", "description": "the String of characters to measure
\n", "type": "String" } ], "return": { "description": "the calculated width", "type": "Number" }, "example": [ "\n\ntextSize(28);\n\nlet aChar = 'P';\nlet cWidth = textWidth(aChar);\ntext(aChar, 0, 40);\nline(cWidth, 0, cWidth, 50);\n\nlet aString = 'p5.js';\nlet sWidth = textWidth(aString);\ntext(aString, 0, 85);\nline(sWidth, 50, sWidth, 100);\n\ndescribe('Letter P and p5.js are displayed with vertical lines at end.');\n
\nReturns the ascent of the current font at its current size. The ascent\nrepresents the distance, in pixels, of the tallest character above\nthe baseline.
\n", "itemtype": "method", "name": "textAscent", "return": { "description": "", "type": "Number" }, "example": [ "\n\nlet base = height * 0.75;\nlet scalar = 0.8; // Different for each font\n\ntextSize(32); // Set initial text size\nlet asc = textAscent() * scalar; // Calc ascent\nline(0, base - asc, width, base - asc);\ntext('dp', 0, base); // Draw text on baseline\n\ntextSize(64); // Increase text size\nasc = textAscent() * scalar; // Recalc ascent\nline(40, base - asc, width, base - asc);\ntext('dp', 40, base); // Draw text on baseline\n
\nReturns the descent of the current font at its current size. The descent\nrepresents the distance, in pixels, of the character with the longest\ndescender below the baseline.
\n", "itemtype": "method", "name": "textDescent", "return": { "description": "", "type": "Number" }, "example": [ "\n\nlet base = height * 0.75;\nlet scalar = 0.8; // Different for each font\n\ntextSize(32); // Set initial text size\nlet desc = textDescent() * scalar; // Calc descent\nline(0, base + desc, width, base + desc);\ntext('dp', 0, base); // Draw text on baseline\n\ntextSize(64); // Increase text size\ndesc = textDescent() * scalar; // Recalc descent\nline(40, base + desc, width, base + desc);\ntext('dp', 40, base); // Draw text on baseline\n
\nHelper function to measure ascent and descent.
\n", "class": "p5", "module": "Typography", "submodule": "Attributes" }, { "file": "src/typography/attributes.js", "line": 290, "description": "Specifies how lines of text are wrapped within a text box. This requires a max-width set on the text area, specified in text() as parameter x2
.
WORD wrap style only breaks lines at spaces. A single string without spaces that exceeds the boundaries of the canvas or text area is not truncated, and will overflow the desired area, disappearing at the canvas edge.
\nCHAR wrap style breaks lines wherever needed to stay within the text box.
\nWORD is the default wrap style, and both styles will still break lines at any line breaks (\\n
) specified in the original text. The text area max-height parameter (y2
) also still applies to wrapped text in both styles, lines of text that do not fit within the text area will not be drawn to the screen.
text wrapping style, either WORD or CHAR
\n", "type": "Constant" } ], "return": { "description": "wrapStyle", "type": "String" }, "example": [ "\n\ntextSize(20);\ntextWrap(WORD);\ntext('Have a wonderful day', 0, 10, 100);\n
\n\ntextSize(20);\ntextWrap(CHAR);\ntext('Have a wonderful day', 0, 10, 100);\n
\n\ntextSize(20);\ntextWrap(CHAR);\ntext('祝你有美好的一天', 0, 10, 100);\n
\n\nconst scream = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA';\ntextSize(20);\ntextWrap(WORD);\ntext(scream, 0, 0, 100);\nfill(0, 0, 0, 75);\ntext(scream, 0, 20, 100);\nfill(0, 0, 0, 50);\ntext(scream, 0, 40, 100);\nfill(0, 0, 0, 25);\ntext(scream, 0, 60, 100);\nstrokeWeight(2);\nellipseMode(CENTER);\nfill(255);\nellipse(15, 50, 15, 15);\nfill(0);\nellipse(11, 47, 1, 1);\nellipse(19, 47, 1, 1);\nellipse(15, 52, 5, 5);\nline(15, 60, 15, 70);\nline(15, 65, 5, 55);\nline(15, 65, 25, 55);\nline(15, 70, 10, 80);\nline(15, 70, 20, 80);\n
\nLoads an opentype font file (.otf, .ttf) from a file or a URL,\nand returns a p5.Font object. This function\nis asynchronous, meaning it may not finish before the next line in\nyour sketch is executed.
\nThe path to the font should be relative to the HTML file\nthat links in your sketch. Loading fonts from a URL or other\nremote location may be blocked due to your browser's built-in\nsecurity.
\n", "itemtype": "method", "name": "loadFont", "params": [ { "name": "path", "description": "name of the file or url to load
\n", "type": "String" }, { "name": "callback", "description": "function to be executed after\n loadFont() completes
\n", "type": "Function", "optional": true }, { "name": "onError", "description": "function to be executed if\n an error occurs
\n", "type": "Function", "optional": true } ], "return": { "description": "p5.Font object", "type": "p5.Font" }, "example": [ "\n\nCalling loadFont() inside preload() guarantees\nthat the load operation will have completed before setup()\nand draw() are called.\n\n\nlet myFont;\nfunction preload() {\n myFont = loadFont('assets/inconsolata.otf');\n}\n\nfunction setup() {\n fill('#ED225D');\n textFont(myFont);\n textSize(36);\n text('p5*js', 10, 50);\n}\n
\nfunction setup() {\n loadFont('assets/inconsolata.otf', drawText);\n}\n\nfunction drawText(font) {\n fill('#ED225D');\n textFont(font, 36);\n text('p5*js', 10, 50);\n}\n
\nfunction preload() {\n loadFont('assets/inconsolata.otf');\n}\n\nfunction setup() {\n let myDiv = createDiv('hello there');\n myDiv.style('font-family', 'Inconsolata');\n}\n
Draws text to the screen. Displays the information specified in the first\nparameter on the screen in the position specified by the additional\nparameters. A default font will be used unless a font is set with the\ntextFont() function and a default size will be\nused unless a font is set with textSize(). Change\nthe color of the text with the fill() function. Change\nthe outline of the text with the stroke() and\nstrokeWeight() functions.
\nThe text displays in relation to the textAlign()\nfunction, which gives the option to draw to the left, right, and center of the\ncoordinates.
\nThe x2 and y2 parameters define a rectangular area to display within and\nmay only be used with string data. When these parameters are specified,\nthey are interpreted based on the current rectMode()\nsetting. Text that does not fit completely within the rectangle specified will\nnot be drawn to the screen. If x2 and y2 are not specified, the baseline\nalignment is the default, which means that the text will be drawn upwards\nfrom x and y.
\nWEBGL: Only opentype/truetype fonts are supported. You must load a font\nusing the loadFont() method (see the example above).\nstroke() currently has no effect in webgl mode.\nLearn more about working with text in webgl mode on the\nwiki.
\n", "itemtype": "method", "name": "text", "params": [ { "name": "str", "description": "the alphanumeric\n symbols to be displayed
\n", "type": "String|Object|Array|Number|Boolean" }, { "name": "x", "description": "x-coordinate of text
\n", "type": "Number" }, { "name": "y", "description": "y-coordinate of text
\n", "type": "Number" }, { "name": "x2", "description": "by default, the width of the text box,\n see rectMode() for more info
\n", "type": "Number", "optional": true }, { "name": "y2", "description": "by default, the height of the text box,\n see rectMode() for more info
\n", "type": "Number", "optional": true } ], "chainable": 1, "example": [ "\n\ntextSize(32);\ntext('word', 10, 30);\nfill(0, 102, 153);\ntext('word', 10, 60);\nfill(0, 102, 153, 51);\ntext('word', 10, 90);\n
\n\nlet s = 'The quick brown fox jumped over the lazy dog.';\nfill(50);\ntext(s, 10, 10, 70, 80); // Text wraps within text box\n
\n\nlet inconsolata;\nfunction preload() {\n inconsolata = loadFont('assets/inconsolata.otf');\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n textFont(inconsolata);\n textSize(width / 3);\n textAlign(CENTER, CENTER);\n}\nfunction draw() {\n background(0);\n let time = millis();\n rotateX(time / 1000);\n rotateZ(time / 1234);\n text('p5.js', 0, 0);\n}\n
\nSets the current font that will be drawn with the text() function.\nIf textFont() is called without any argument, it will return the current font if one has\nbeen set already. If not, it will return the name of the default font as a string.\nIf textFont() is called with a font to use, it will return the p5 object.
\nWEBGL: Only fonts loaded via loadFont() are supported.
\n", "itemtype": "method", "name": "textFont", "return": { "description": "the current font / p5 Object", "type": "Object" }, "example": [ "\n\nfill(0);\ntextSize(12);\ntextFont('Georgia');\ntext('Georgia', 12, 30);\ntextFont('Helvetica');\ntext('Helvetica', 12, 60);\n
\n\nlet fontRegular, fontItalic, fontBold;\nfunction preload() {\n fontRegular = loadFont('assets/Regular.otf');\n fontItalic = loadFont('assets/Italic.ttf');\n fontBold = loadFont('assets/Bold.ttf');\n}\nfunction setup() {\n background(210);\n fill(0)\n .strokeWeight(0)\n .textSize(10);\n textFont(fontRegular);\n text('Font Style Normal', 10, 30);\n textFont(fontItalic);\n text('Font Style Italic', 10, 50);\n textFont(fontBold);\n text('Font Style Bold', 10, 70);\n}\n
\na font loaded via loadFont(),\nor a String representing a web safe font\n(a font that is generally available across all systems)
\n", "type": "Object|String" }, { "name": "size", "description": "the font size to use
\n", "type": "Number", "optional": true } ], "chainable": 1 } ] }, { "file": "src/typography/p5.Font.js", "line": 24, "description": "Underlying opentype font implementation
\n", "itemtype": "property", "name": "font", "class": "p5.Font", "module": "Typography", "submodule": "Loading & Displaying" }, { "file": "src/typography/p5.Font.js", "line": 31, "description": "Returns a tight bounding box for the given text string using this\nfont
\n", "itemtype": "method", "name": "textBounds", "params": [ { "name": "line", "description": "a line of text
\n", "type": "String" }, { "name": "x", "description": "x-position
\n", "type": "Number" }, { "name": "y", "description": "y-position
\n", "type": "Number" }, { "name": "fontSize", "description": "font size to use (optional) Default is 12.
\n", "type": "Number", "optional": true }, { "name": "options", "description": "opentype options (optional)\n opentype fonts contains alignment and baseline options.\n Default is 'LEFT' and 'alphabetic'
\n", "type": "Object", "optional": true } ], "return": { "description": "a rectangle object with properties: x, y, w, h", "type": "Object" }, "example": [ "\n\nlet font;\nlet textString = 'Lorem ipsum dolor sit amet.';\nfunction preload() {\n font = loadFont('./assets/Regular.otf');\n}\nfunction setup() {\n background(210);\n\n let bbox = font.textBounds(textString, 10, 30, 12);\n fill(255);\n stroke(0);\n rect(bbox.x, bbox.y, bbox.w, bbox.h);\n fill(0);\n noStroke();\n\n textFont(font);\n textSize(12);\n text(textString, 10, 30);\n\n describe(`Words “Lorem ipsum dol” go off canvas and\n contained by white bounding box`);\n}\n
\nComputes an array of points following the path for specified text
\n", "itemtype": "method", "name": "textToPoints", "params": [ { "name": "txt", "description": "a line of text
\n", "type": "String" }, { "name": "x", "description": "x-position
\n", "type": "Number" }, { "name": "y", "description": "y-position
\n", "type": "Number" }, { "name": "fontSize", "description": "font size to use (optional)
\n", "type": "Number" }, { "name": "options", "description": "an (optional) object that can contain:
\n
sampleFactor - the ratio of path-length to number of samples\n(default=.1); higher values yield more points and are therefore\nmore precise
simplifyThreshold - if set to a non-zero value, collinear points will be\nbe removed from the polygon; the value represents the threshold angle to use\nwhen determining whether two edges are collinear
\nlet font;\nfunction preload() {\n font = loadFont('assets/inconsolata.otf');\n}\n\nlet points;\nlet bounds;\nfunction setup() {\n createCanvas(100, 100);\n stroke(0);\n fill(255, 104, 204);\n\n points = font.textToPoints('p5', 0, 0, 10, {\n sampleFactor: 5,\n simplifyThreshold: 0\n });\n bounds = font.textBounds(' p5 ', 0, 0, 10);\n}\n\nfunction draw() {\n background(255);\n beginShape();\n translate(-bounds.x * width / bounds.w, -bounds.y * height / bounds.h);\n for (let i = 0; i < points.length; i++) {\n let p = points[i];\n vertex(\n p.x * width / bounds.w +\n sin(20 * p.y / bounds.h + millis() / 1000) * width / 30,\n p.y * height / bounds.h\n );\n }\n endShape(CLOSE);\n}\n
\nAdds a value to the end of an array. Extends the length of\nthe array by one. Maps to Array.push().
\n", "itemtype": "method", "name": "append", "deprecated": true, "deprecationMessage": "Use array.push(value) instead.", "params": [ { "name": "array", "description": "Array to append
\n", "type": "Array" }, { "name": "value", "description": "to be added to the Array
\n", "type": "Any" } ], "return": { "description": "the array that was appended to", "type": "Array" }, "example": [ "\n\nfunction setup() {\n let myArray = ['Mango', 'Apple', 'Papaya'];\n print(myArray); // ['Mango', 'Apple', 'Papaya']\n\n append(myArray, 'Peach');\n print(myArray); // ['Mango', 'Apple', 'Papaya', 'Peach']\n}\n
Copies an array (or part of an array) to another array. The src array is\ncopied to the dst array, beginning at the position specified by\nsrcPosition and into the position specified by dstPosition. The number of\nelements to copy is determined by length. Note that copying values\noverwrites existing values in the destination array. To append values\ninstead of overwriting them, use concat().
\nThe simplified version with only two arguments, arrayCopy(src, dst),\ncopies an entire array to another of the same size. It is equivalent to\narrayCopy(src, 0, dst, 0, src.length).
\nUsing this function is far more efficient for copying array data than\niterating through a for() loop and copying each element individually.
\n", "itemtype": "method", "name": "arrayCopy", "deprecated": true, "deprecationMessage": "Use arr1.copyWithin(arr2) instead.", "example": [ "\n\nlet src = ['A', 'B', 'C'];\nlet dst = [1, 2, 3];\nlet srcPosition = 1;\nlet dstPosition = 0;\nlet length = 2;\n\nprint(src); // ['A', 'B', 'C']\nprint(dst); // [ 1 , 2 , 3 ]\n\narrayCopy(src, srcPosition, dst, dstPosition, length);\nprint(dst); // ['B', 'C', 3]\n
the source Array
\n", "type": "Array" }, { "name": "srcPosition", "description": "starting position in the source Array
\n", "type": "Integer" }, { "name": "dst", "description": "the destination Array
\n", "type": "Array" }, { "name": "dstPosition", "description": "starting position in the destination Array
\n", "type": "Integer" }, { "name": "length", "description": "number of Array elements to be copied
\n", "type": "Integer" } ] }, { "line": 73, "params": [ { "name": "src", "description": "", "type": "Array" }, { "name": "dst", "description": "", "type": "Array" }, { "name": "length", "description": "", "type": "Integer", "optional": true } ] } ] }, { "file": "src/utilities/array_functions.js", "line": 112, "description": "Concatenates two arrays, maps to Array.concat(). Does not modify the\ninput arrays.
\n", "itemtype": "method", "name": "concat", "deprecated": true, "deprecationMessage": "Use arr1.concat(arr2) instead.", "params": [ { "name": "a", "description": "first Array to concatenate
\n", "type": "Array" }, { "name": "b", "description": "second Array to concatenate
\n", "type": "Array" } ], "return": { "description": "concatenated array", "type": "Array" }, "example": [ "\n\nfunction setup() {\n let arr1 = ['A', 'B', 'C'];\n let arr2 = [1, 2, 3];\n\n print(arr1); // ['A','B','C']\n print(arr2); // [1,2,3]\n\n let arr3 = concat(arr1, arr2);\n\n print(arr1); // ['A','B','C']\n print(arr2); // [1, 2, 3]\n print(arr3); // ['A','B','C', 1, 2, 3]\n}\n
Reverses the order of an array, maps to Array.reverse()
\n", "itemtype": "method", "name": "reverse", "deprecated": true, "deprecationMessage": "Use array.reverse() instead.", "params": [ { "name": "list", "description": "Array to reverse
\n", "type": "Array" } ], "return": { "description": "the reversed list", "type": "Array" }, "example": [ "\n\nfunction setup() {\n let myArray = ['A', 'B', 'C'];\n print(myArray); // ['A','B','C']\n\n reverse(myArray);\n print(myArray); // ['C','B','A']\n}\n
Decreases an array by one element and returns the shortened array,\nmaps to Array.pop().
\n", "itemtype": "method", "name": "shorten", "deprecated": true, "deprecationMessage": "Use array.pop() instead.", "params": [ { "name": "list", "description": "Array to shorten
\n", "type": "Array" } ], "return": { "description": "shortened Array", "type": "Array" }, "example": [ "\n\nfunction setup() {\n let myArray = ['A', 'B', 'C'];\n print(myArray); // ['A', 'B', 'C']\n let newArray = shorten(myArray);\n print(myArray); // ['A','B','C']\n print(newArray); // ['A','B']\n}\n
Randomizes the order of the elements of an array. Implements\n\nFisher-Yates Shuffle Algorithm.
\n", "itemtype": "method", "name": "shuffle", "params": [ { "name": "array", "description": "Array to shuffle
\n", "type": "Array" }, { "name": "bool", "description": "modify passed array
\n", "type": "Boolean", "optional": true } ], "return": { "description": "shuffled Array", "type": "Array" }, "example": [ "\n\nfunction setup() {\n let regularArr = ['ABC', 'def', createVector(), TAU, Math.E];\n print(regularArr);\n shuffle(regularArr, true); // force modifications to passed array\n print(regularArr);\n\n // By default shuffle() returns a shuffled cloned array:\n let newArr = shuffle(regularArr);\n print(regularArr);\n print(newArr);\n}\n
Sorts an array of numbers from smallest to largest, or puts an array of\nwords in alphabetical order. The original array is not modified; a\nre-ordered array is returned. The count parameter states the number of\nelements to sort. For example, if there are 12 elements in an array and\ncount is set to 5, only the first 5 elements in the array will be sorted.
\n", "itemtype": "method", "name": "sort", "deprecated": true, "deprecationMessage": "Use array.sort() instead.", "params": [ { "name": "list", "description": "Array to sort
\n", "type": "Array" }, { "name": "count", "description": "number of elements to sort, starting from 0
\n", "type": "Integer", "optional": true } ], "return": { "description": "the sorted list", "type": "Array" }, "example": [ "\n\nfunction setup() {\n let words = ['banana', 'apple', 'pear', 'lime'];\n print(words); // ['banana', 'apple', 'pear', 'lime']\n let count = 4; // length of array\n\n words = sort(words, count);\n print(words); // ['apple', 'banana', 'lime', 'pear']\n}\n
\nfunction setup() {\n let numbers = [2, 6, 1, 5, 14, 9, 8, 12];\n print(numbers); // [2, 6, 1, 5, 14, 9, 8, 12]\n let count = 5; // Less than the length of the array\n\n numbers = sort(numbers, count);\n print(numbers); // [1,2,5,6,14,9,8,12]\n}\n
Inserts a value or an array of values into an existing array. The first\nparameter specifies the initial array to be modified, and the second\nparameter defines the data to be inserted. The third parameter is an index\nvalue which specifies the array position from which to insert data.\n(Remember that array index numbering starts at zero, so the first position\nis 0, the second position is 1, and so on.)
\n", "itemtype": "method", "name": "splice", "deprecated": true, "deprecationMessage": "Use array.splice() instead.", "params": [ { "name": "list", "description": "Array to splice into
\n", "type": "Array" }, { "name": "value", "description": "value to be spliced in
\n", "type": "Any" }, { "name": "position", "description": "in the array from which to insert data
\n", "type": "Integer" } ], "return": { "description": "the list", "type": "Array" }, "example": [ "\n\nfunction setup() {\n let myArray = [0, 1, 2, 3, 4];\n let insArray = ['A', 'B', 'C'];\n print(myArray); // [0, 1, 2, 3, 4]\n print(insArray); // ['A','B','C']\n\n splice(myArray, insArray, 3);\n print(myArray); // [0,1,2,'A','B','C',3,4]\n}\n
Extracts an array of elements from an existing array. The list parameter\ndefines the array from which the elements will be copied, and the start\nand count parameters specify which elements to extract. If no count is\ngiven, elements will be extracted from the start to the end of the array.\nWhen specifying the start, remember that the first array element is 0.\nThis function does not change the source array.
\n", "itemtype": "method", "name": "subset", "deprecated": true, "deprecationMessage": "Use array.slice() instead.", "params": [ { "name": "list", "description": "Array to extract from
\n", "type": "Array" }, { "name": "start", "description": "position to begin
\n", "type": "Integer" }, { "name": "count", "description": "number of values to extract
\n", "type": "Integer", "optional": true } ], "return": { "description": "Array of extracted elements", "type": "Array" }, "example": [ "\n\nfunction setup() {\n let myArray = [1, 2, 3, 4, 5];\n print(myArray); // [1, 2, 3, 4, 5]\n\n let sub1 = subset(myArray, 0, 3);\n let sub2 = subset(myArray, 2, 2);\n print(sub1); // [1,2,3]\n print(sub2); // [3,4]\n}\n
Converts a string to its floating point representation. The contents of a\nstring must resemble a number, or NaN (not a number) will be returned.\nFor example, float(\"1234.56\") evaluates to 1234.56, but float(\"giraffe\")\nwill return NaN.
\nWhen an array of values is passed in, then an array of floats of the same\nlength is returned.
\n", "itemtype": "method", "name": "float", "params": [ { "name": "str", "description": "float string to parse
\n", "type": "String" } ], "return": { "description": "floating point representation of string", "type": "Number" }, "example": [ "\n\nlet str = '20';\nlet diameter = float(str);\nellipse(width / 2, height / 2, diameter, diameter);\n
\nprint(float('10.31')); // 10.31\nprint(float('Infinity')); // Infinity\nprint(float('-Infinity')); // -Infinity\n
Converts a boolean, string, or float to its integer representation.\nWhen an array of values is passed in, then an int array of the same length\nis returned.
\n", "itemtype": "method", "name": "int", "return": { "description": "integer representation of value", "type": "Number" }, "example": [ "\n\nprint(int('10')); // 10\nprint(int(10.31)); // 10\nprint(int(-10)); // -10\nprint(int(true)); // 1\nprint(int(false)); // 0\nprint(int([false, true, '10.3', 9.8])); // [0, 1, 10, 9]\nprint(int(Infinity)); // Infinity\nprint(int('-Infinity')); // -Infinity\n
value to parse
\n", "type": "String|Boolean|Number" }, { "name": "radix", "description": "the radix to convert to (default: 10)
\n", "type": "Integer", "optional": true } ], "return": { "description": "integer representation of value", "type": "Number" } }, { "line": 66, "params": [ { "name": "ns", "description": "values to parse
\n", "type": "Array" }, { "name": "radix", "description": "", "type": "Integer", "optional": true } ], "return": { "description": "integer representation of values", "type": "Number[]" } } ] }, { "file": "src/utilities/conversion.js", "line": 88, "description": "Converts a boolean, string or number to its string representation.\nWhen an array of values is passed in, then an array of strings of the same\nlength is returned.
\n", "itemtype": "method", "name": "str", "params": [ { "name": "n", "description": "value to parse
\n", "type": "String|Boolean|Number|Array" } ], "return": { "description": "string representation of value", "type": "String" }, "example": [ "\n\nprint(str('10')); // \"10\"\nprint(str(10.31)); // \"10.31\"\nprint(str(-10)); // \"-10\"\nprint(str(true)); // \"true\"\nprint(str(false)); // \"false\"\nprint(str([true, '10.3', 9.8])); // [ \"true\", \"10.3\", \"9.8\" ]\n
Converts a number or string to its boolean representation.\nFor a number, any non-zero value (positive or negative) evaluates to true,\nwhile zero evaluates to false. For a string, the value \"true\" evaluates to\ntrue, while any other value evaluates to false. When an array of number or\nstring values is passed in, then a array of booleans of the same length is\nreturned.
\n", "itemtype": "method", "name": "boolean", "params": [ { "name": "n", "description": "value to parse
\n", "type": "String|Boolean|Number|Array" } ], "return": { "description": "boolean representation of value", "type": "Boolean" }, "example": [ "\n\nprint(boolean(0)); // false\nprint(boolean(1)); // true\nprint(boolean('true')); // true\nprint(boolean('abcd')); // false\nprint(boolean([0, 12, 'true'])); // [false, true, true]\n
Converts a number, string representation of a number, or boolean to its byte\nrepresentation. A byte can be only a whole number between -128 and 127, so\nwhen a value outside of this range is converted, it wraps around to the\ncorresponding byte representation. When an array of number, string or boolean\nvalues is passed in, then an array of bytes the same length is returned.
\n", "itemtype": "method", "name": "byte", "return": { "description": "byte representation of value", "type": "Number" }, "example": [ "\n\nprint(byte(127)); // 127\nprint(byte(128)); // -128\nprint(byte(23.4)); // 23\nprint(byte('23.4')); // 23\nprint(byte('hello')); // NaN\nprint(byte(true)); // 1\nprint(byte([0, 255, '100'])); // [0, -1, 100]\n
value to parse
\n", "type": "String|Boolean|Number" } ], "return": { "description": "byte representation of value", "type": "Number" } }, { "line": 168, "params": [ { "name": "ns", "description": "values to parse
\n", "type": "Array" } ], "return": { "description": "array of byte representation of values", "type": "Number[]" } } ] }, { "file": "src/utilities/conversion.js", "line": 182, "description": "Converts a number or string to its corresponding single-character\nstring representation. If a string parameter is provided, it is first\nparsed as an integer and then translated into a single-character string.\nWhen an array of number or string values is passed in, then an array of\nsingle-character strings of the same length is returned.
\n", "itemtype": "method", "name": "char", "return": { "description": "string representation of value", "type": "String" }, "example": [ "\n\nprint(char(65)); // \"A\"\nprint(char('65')); // \"A\"\nprint(char([65, 66, 67])); // [ \"A\", \"B\", \"C\" ]\nprint(join(char([65, 66, 67]), '')); // \"ABC\"\n
value to parse
\n", "type": "String|Number" } ], "return": { "description": "string representation of value", "type": "String" } }, { "line": 201, "params": [ { "name": "ns", "description": "values to parse
\n", "type": "Array" } ], "return": { "description": "array of string representation of values", "type": "String[]" } } ] }, { "file": "src/utilities/conversion.js", "line": 216, "description": "Converts a single-character string to its corresponding integer\nrepresentation. When an array of single-character string values is passed\nin, then an array of integers of the same length is returned.
\n", "itemtype": "method", "name": "unchar", "return": { "description": "integer representation of value", "type": "Number" }, "example": [ "\n\nprint(unchar('A')); // 65\nprint(unchar(['A', 'B', 'C'])); // [ 65, 66, 67 ]\nprint(unchar(split('ABC', ''))); // [ 65, 66, 67 ]\n
value to parse
\n", "type": "String" } ], "return": { "description": "integer representation of value", "type": "Number" } }, { "line": 232, "params": [ { "name": "ns", "description": "values to parse
\n", "type": "Array" } ], "return": { "description": "integer representation of values", "type": "Number[]" } } ] }, { "file": "src/utilities/conversion.js", "line": 245, "description": "Converts a number to a string in its equivalent hexadecimal notation. If a\nsecond parameter is passed, it is used to set the number of characters to\ngenerate in the hexadecimal notation. When an array is passed in, an\narray of strings in hexadecimal notation of the same length is returned.
\n", "itemtype": "method", "name": "hex", "return": { "description": "hexadecimal string representation of value", "type": "String" }, "example": [ "\n\nprint(hex(255)); // \"000000FF\"\nprint(hex(255, 6)); // \"0000FF\"\nprint(hex([0, 127, 255], 6)); // [ \"000000\", \"00007F\", \"0000FF\" ]\nprint(Infinity); // \"FFFFFFFF\"\nprint(-Infinity); // \"00000000\"\n
value to parse
\n", "type": "Number" }, { "name": "digits", "description": "", "type": "Number", "optional": true } ], "return": { "description": "hexadecimal string representation of value", "type": "String" } }, { "line": 265, "params": [ { "name": "ns", "description": "array of values to parse
\n", "type": "Number[]" }, { "name": "digits", "description": "", "type": "Number", "optional": true } ], "return": { "description": "hexadecimal string representation of values", "type": "String[]" } } ] }, { "file": "src/utilities/conversion.js", "line": 295, "description": "Converts a string representation of a hexadecimal number to its equivalent\ninteger value. When an array of strings in hexadecimal notation is passed\nin, an array of integers of the same length is returned.
\n", "itemtype": "method", "name": "unhex", "return": { "description": "integer representation of hexadecimal value", "type": "Number" }, "example": [ "\n\nprint(unhex('A')); // 10\nprint(unhex('FF')); // 255\nprint(unhex(['FF', 'AA', '00'])); // [ 255, 170, 0 ]\n
value to parse
\n", "type": "String" } ], "return": { "description": "integer representation of hexadecimal value", "type": "Number" } }, { "line": 311, "params": [ { "name": "ns", "description": "values to parse
\n", "type": "Array" } ], "return": { "description": "integer representations of hexadecimal value", "type": "Number[]" } } ] }, { "file": "src/utilities/string_functions.js", "line": 15, "description": "Combines an array of Strings into one String, each separated by the\ncharacter(s) used for the separator parameter. To join arrays of ints or\nfloats, it's necessary to first convert them to Strings using nf() or\nnfs().
\n", "itemtype": "method", "name": "join", "params": [ { "name": "list", "description": "array of Strings to be joined
\n", "type": "Array" }, { "name": "separator", "description": "String to be placed between each item
\n", "type": "String" } ], "return": { "description": "joined String", "type": "String" }, "example": [ "\n\nlet array = ['Hello', 'world!'];\nlet separator = ' ';\nlet message = join(array, separator);\ntext(message, 5, 50);\n
\nThis function is used to apply a regular expression to a piece of text,\nand return matching groups (elements found inside parentheses) as a\nString array. If there are no matches, a null value will be returned.\nIf no groups are specified in the regular expression, but the sequence\nmatches, an array of length 1 (with the matched text as the first element\nof the array) will be returned.
\nTo use the function, first check to see if the result is null. If the\nresult is null, then the sequence did not match at all. If the sequence\ndid match, an array is returned.
\nIf there are groups (specified by sets of parentheses) in the regular\nexpression, then the contents of each will be returned in the array.\nElement [0] of a regular expression match returns the entire matching\nstring, and the match groups start at element [1] (the first group is [1],\nthe second [2], and so on).
\n", "itemtype": "method", "name": "match", "params": [ { "name": "str", "description": "the String to be searched
\n", "type": "String" }, { "name": "regexp", "description": "the regexp to be used for matching
\n", "type": "String" } ], "return": { "description": "Array of Strings found", "type": "String[]" }, "example": [ "\n\nlet string = 'Hello p5js*!';\nlet regexp = 'p5js\\\\*';\nlet m = match(string, regexp);\ntext(m, 5, 50);\n
\nThis function is used to apply a regular expression to a piece of text,\nand return a list of matching groups (elements found inside parentheses)\nas a two-dimensional String array. If there are no matches, a null value\nwill be returned. If no groups are specified in the regular expression,\nbut the sequence matches, a two dimensional array is still returned, but\nthe second dimension is only of length one.
\nTo use the function, first check to see if the result is null. If the\nresult is null, then the sequence did not match at all. If the sequence\ndid match, a 2D array is returned.
\nIf there are groups (specified by sets of parentheses) in the regular\nexpression, then the contents of each will be returned in the array.\nAssuming a loop with counter variable i, element [i][0] of a regular\nexpression match returns the entire matching string, and the match groups\nstart at element [i][1] (the first group is [i][1], the second [i][2],\nand so on).
\n", "itemtype": "method", "name": "matchAll", "params": [ { "name": "str", "description": "the String to be searched
\n", "type": "String" }, { "name": "regexp", "description": "the regexp to be used for matching
\n", "type": "String" } ], "return": { "description": "2d Array of Strings found", "type": "String[]" }, "example": [ "\n\nlet string = 'Hello p5js*! Hello world!';\nlet regexp = 'Hello';\nmatchAll(string, regexp);\n
\nUtility function for formatting numbers into strings. There are two\nversions: one for formatting floats, and one for formatting ints.
\nThe values for the digits, left, and right parameters should always\nbe positive integers.
\n(NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter\nif greater than the current length of the number.
\nFor example if number is 123.2 and left parameter passed is 4 which is greater than length of 123\n(integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than\nthe result will be 123.200.
\n", "itemtype": "method", "name": "nf", "return": { "description": "formatted String", "type": "String" }, "example": [ "\n\nfunction setup() {\n background(200);\n let num1 = 321;\n let num2 = -1321;\n\n noStroke();\n fill(0);\n textSize(16);\n\n text(nf(num1, 4, 2), 10, 30);\n text(nf(num2, 4, 2), 10, 80);\n // Draw dividing line\n stroke(120);\n line(0, 50, width, 50);\n}\n
\nthe Number to format
\n", "type": "Number|String" }, { "name": "left", "description": "number of digits to the left of the\n decimal point
\n", "type": "Integer|String", "optional": true }, { "name": "right", "description": "number of digits to the right of the\n decimal point
\n", "type": "Integer|String", "optional": true } ], "return": { "description": "formatted String", "type": "String" } }, { "line": 176, "params": [ { "name": "nums", "description": "the Numbers to format
\n", "type": "Array" }, { "name": "left", "description": "", "type": "Integer|String", "optional": true }, { "name": "right", "description": "", "type": "Integer|String", "optional": true } ], "return": { "description": "formatted Strings", "type": "String[]" } } ] }, { "file": "src/utilities/string_functions.js", "line": 237, "description": "Utility function for formatting numbers into strings and placing\nappropriate commas to mark units of 1000. There are two versions: one\nfor formatting ints, and one for formatting an array of ints. The value\nfor the right parameter should always be a positive integer.
\n", "itemtype": "method", "name": "nfc", "return": { "description": "formatted String", "type": "String" }, "example": [ "\n\nfunction setup() {\n background(200);\n let num = 11253106.115;\n let numArr = [1, 1, 2];\n\n noStroke();\n fill(0);\n textSize(12);\n\n // Draw formatted numbers\n text(nfc(num, 4), 10, 30);\n text(nfc(numArr, 2), 10, 80);\n\n // Draw dividing line\n stroke(120);\n line(0, 50, width, 50);\n}\n
\nthe Number to format
\n", "type": "Number|String" }, { "name": "right", "description": "number of digits to the right of the\n decimal point
\n", "type": "Integer|String", "optional": true } ], "return": { "description": "formatted String", "type": "String" } }, { "line": 275, "params": [ { "name": "nums", "description": "the Numbers to format
\n", "type": "Array" }, { "name": "right", "description": "", "type": "Integer|String", "optional": true } ], "return": { "description": "formatted Strings", "type": "String[]" } } ] }, { "file": "src/utilities/string_functions.js", "line": 311, "description": "Utility function for formatting numbers into strings. Similar to nf() but\nputs a \"+\" in front of positive numbers and a \"-\" in front of negative\nnumbers. There are two versions: one for formatting floats, and one for\nformatting ints. The values for left, and right parameters\nshould always be positive integers.
\n", "itemtype": "method", "name": "nfp", "return": { "description": "formatted String", "type": "String" }, "example": [ "\n\nfunction setup() {\n background(200);\n let num1 = 11253106.115;\n let num2 = -11253106.115;\n\n noStroke();\n fill(0);\n textSize(12);\n\n // Draw formatted numbers\n text(nfp(num1, 4, 2), 10, 30);\n text(nfp(num2, 4, 2), 10, 80);\n\n // Draw dividing line\n stroke(120);\n line(0, 50, width, 50);\n}\n
\nthe Number to format
\n", "type": "Number" }, { "name": "left", "description": "number of digits to the left of the decimal\n point
\n", "type": "Integer", "optional": true }, { "name": "right", "description": "number of digits to the right of the\n decimal point
\n", "type": "Integer", "optional": true } ], "return": { "description": "formatted String", "type": "String" } }, { "line": 352, "params": [ { "name": "nums", "description": "the Numbers to format
\n", "type": "Number[]" }, { "name": "left", "description": "", "type": "Integer", "optional": true }, { "name": "right", "description": "", "type": "Integer", "optional": true } ], "return": { "description": "formatted Strings", "type": "String[]" } } ] }, { "file": "src/utilities/string_functions.js", "line": 373, "description": "Utility function for formatting numbers into strings. Similar to nf() but\nputs an additional \"_\" (space) in front of positive numbers just in case to align it with negative\nnumbers which includes \"-\" (minus) sign.
\nThe main usecase of nfs() can be seen when one wants to align the digits (place values) of a non-negative\nnumber with some negative number (See the example to get a clear picture).\nThere are two versions: one for formatting float, and one for formatting int.
\nThe values for the digits, left, and right parameters should always be positive integers.
\n(IMP): The result on the canvas basically the expected alignment can vary based on the typeface you are using.
\n(NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter\nif greater than the current length of the number.
\nFor example if number is 123.2 and left parameter passed is 4 which is greater than length of 123\n(integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than\nthe result will be 123.200.
\n", "itemtype": "method", "name": "nfs", "return": { "description": "formatted String", "type": "String" }, "example": [ "\n\nfunction setup() {\n background(200);\n let num1 = 321;\n let num2 = -1321;\n\n noStroke();\n fill(0);\n textSize(16);\n\n // nfs() aligns num1 (positive number) with num2 (negative number) by\n // adding a blank space in front of the num1 (positive number)\n // [left = 4] in num1 add one 0 in front, to align the digits with num2\n // [right = 2] in num1 and num2 adds two 0's after both numbers\n // To see the differences check the example of nf() too.\n text(nfs(num1, 4, 2), 10, 30);\n text(nfs(num2, 4, 2), 10, 80);\n // Draw dividing line\n stroke(120);\n line(0, 50, width, 50);\n}\n
\nthe Number to format
\n", "type": "Number" }, { "name": "left", "description": "number of digits to the left of the decimal\n point
\n", "type": "Integer", "optional": true }, { "name": "right", "description": "number of digits to the right of the\n decimal point
\n", "type": "Integer", "optional": true } ], "return": { "description": "formatted String", "type": "String" } }, { "line": 430, "params": [ { "name": "nums", "description": "the Numbers to format
\n", "type": "Array" }, { "name": "left", "description": "", "type": "Integer", "optional": true }, { "name": "right", "description": "", "type": "Integer", "optional": true } ], "return": { "description": "formatted Strings", "type": "String[]" } } ] }, { "file": "src/utilities/string_functions.js", "line": 451, "description": "The split() function maps to String.split(), it breaks a String into\npieces using a character or string as the delimiter. The delim parameter\nspecifies the character or characters that mark the boundaries between\neach piece. A String[] array is returned that contains each of the pieces.
\nThe splitTokens() function works in a similar fashion, except that it\nsplits using a range of characters instead of a specific character or\nsequence.
\n", "itemtype": "method", "name": "split", "params": [ { "name": "value", "description": "the String to be split
\n", "type": "String" }, { "name": "delim", "description": "the String used to separate the data
\n", "type": "String" } ], "return": { "description": "Array of Strings", "type": "String[]" }, "example": [ "\n\nlet names = 'Pat,Xio,Alex';\nlet splitString = split(names, ',');\ntext(splitString[0], 5, 30);\ntext(splitString[1], 5, 50);\ntext(splitString[2], 5, 70);\n
\nThe splitTokens() function splits a String at one or many character\ndelimiters or \"tokens.\" The delim parameter specifies the character or\ncharacters to be used as a boundary.
\nIf no delim characters are specified, any whitespace character is used to\nsplit. Whitespace characters include tab (\\t), line feed (\\n), carriage\nreturn (\\r), form feed (\\f), and space.
\n", "itemtype": "method", "name": "splitTokens", "params": [ { "name": "value", "description": "the String to be split
\n", "type": "String" }, { "name": "delim", "description": "list of individual Strings that will be used as\n separators
\n", "type": "String", "optional": true } ], "return": { "description": "Array of Strings", "type": "String[]" }, "example": [ "\n\nfunction setup() {\n let myStr = 'Mango, Banana, Lime';\n let myStrArr = splitTokens(myStr, ',');\n\n print(myStrArr); // prints : [\"Mango\",\" Banana\",\" Lime\"]\n}\n
\nRemoves whitespace characters from the beginning and end of a String. In\naddition to standard whitespace characters such as space, carriage return,\nand tab, this function also removes the Unicode \"nbsp\" character.
\n", "itemtype": "method", "name": "trim", "return": { "description": "a trimmed String", "type": "String" }, "example": [ "\n\nlet string = trim(' No new lines\\n ');\ntext(string + ' here', 2, 50);\n
\na String to be trimmed
\n", "type": "String" } ], "return": { "description": "a trimmed String", "type": "String" } }, { "line": 557, "params": [ { "name": "strs", "description": "an Array of Strings to be trimmed
\n", "type": "Array" } ], "return": { "description": "an Array of trimmed Strings", "type": "String[]" } } ] }, { "file": "src/utilities/time_date.js", "line": 10, "description": "p5.js communicates with the clock on your computer. The day() function\nreturns the current day as a value from 1 - 31.
\n", "itemtype": "method", "name": "day", "return": { "description": "the current day", "type": "Integer" }, "example": [ "\n\nlet d = day();\ntext('Current day: \\n' + d, 5, 50);\n
\np5.js communicates with the clock on your computer. The hour() function\nreturns the current hour as a value from 0 - 23.
\n", "itemtype": "method", "name": "hour", "return": { "description": "the current hour", "type": "Integer" }, "example": [ "\n\nlet h = hour();\ntext('Current hour:\\n' + h, 5, 50);\n
\np5.js communicates with the clock on your computer. The minute() function\nreturns the current minute as a value from 0 - 59.
\n", "itemtype": "method", "name": "minute", "return": { "description": "the current minute", "type": "Integer" }, "example": [ "\n\nlet m = minute();\ntext('Current minute: \\n' + m, 5, 50);\n
\nReturns the number of milliseconds (thousandths of a second) since\nstarting the sketch (when setup()
is called). This information is often\nused for timing events and animation sequences.
\nlet millisecond = millis();\ntext('Milliseconds \\nrunning: \\n' + millisecond, 5, 40);\n
\np5.js communicates with the clock on your computer. The month() function\nreturns the current month as a value from 1 - 12.
\n", "itemtype": "method", "name": "month", "return": { "description": "the current month", "type": "Integer" }, "example": [ "\n\nlet m = month();\ntext('Current month: \\n' + m, 5, 50);\n
\np5.js communicates with the clock on your computer. The second() function\nreturns the current second as a value from 0 - 59.
\n", "itemtype": "method", "name": "second", "return": { "description": "the current second", "type": "Integer" }, "example": [ "\n\nlet s = second();\ntext('Current second: \\n' + s, 5, 50);\n
\np5.js communicates with the clock on your computer. The year() function\nreturns the current year as an integer (2014, 2015, 2016, etc).
\n", "itemtype": "method", "name": "year", "return": { "description": "the current year", "type": "Integer" }, "example": [ "\n\nlet y = year();\ntext('Current year: \\n' + y, 5, 50);\n
\nDraw a plane with given a width and height
\n", "itemtype": "method", "name": "plane", "params": [ { "name": "width", "description": "width of the plane
\n", "type": "Number", "optional": true }, { "name": "height", "description": "height of the plane
\n", "type": "Number", "optional": true }, { "name": "detailX", "description": "Optional number of triangle\n subdivisions in x-dimension
\n", "type": "Integer", "optional": true }, { "name": "detailY", "description": "Optional number of triangle\n subdivisions in y-dimension
\n", "type": "Integer", "optional": true } ], "chainable": 1, "example": [ "\n\n// draw a plane\n// with width 50 and height 50\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('a white plane with black wireframe lines');\n}\n\nfunction draw() {\n background(200);\n plane(50, 50);\n}\n
\nDraw a box with given width, height and depth
\n", "itemtype": "method", "name": "box", "params": [ { "name": "width", "description": "width of the box
\n", "type": "Number", "optional": true }, { "name": "height", "description": "height of the box
\n", "type": "Number", "optional": true }, { "name": "depth", "description": "depth of the box
\n", "type": "Number", "optional": true }, { "name": "detailX", "description": "Optional number of triangle\n subdivisions in x-dimension
\n", "type": "Integer", "optional": true }, { "name": "detailY", "description": "Optional number of triangle\n subdivisions in y-dimension
\n", "type": "Integer", "optional": true } ], "chainable": 1, "example": [ "\n\n// draw a spinning box\n// with width, height and depth of 50\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('a white box rotating in 3D space');\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(50);\n}\n
\nDraw a sphere with given radius.
\nDetailX and detailY determines the number of subdivisions in the x-dimension\nand the y-dimension of a sphere. More subdivisions make the sphere seem\nsmoother. The recommended maximum values are both 24. Using a value greater\nthan 24 may cause a warning or slow down the browser.
\n", "itemtype": "method", "name": "sphere", "params": [ { "name": "radius", "description": "radius of circle
\n", "type": "Number", "optional": true }, { "name": "detailX", "description": "optional number of subdivisions in x-dimension
\n", "type": "Integer", "optional": true }, { "name": "detailY", "description": "optional number of subdivisions in y-dimension
\n", "type": "Integer", "optional": true } ], "chainable": 1, "example": [ "\n\n// draw a sphere with radius 40\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('a white sphere with black wireframe lines');\n}\n\nfunction draw() {\n background(205, 102, 94);\n sphere(40);\n}\n
\n\nlet detailX;\n// slide to see how detailX works\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n detailX = createSlider(3, 24, 3);\n detailX.position(10, height + 5);\n detailX.style('width', '80px');\n describe(\n 'a white sphere with low detail on the x-axis, including a slider to adjust detailX'\n );\n}\n\nfunction draw() {\n background(205, 105, 94);\n rotateY(millis() / 1000);\n sphere(40, detailX.value(), 16);\n}\n
\n\nlet detailY;\n// slide to see how detailY works\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n detailY = createSlider(3, 16, 3);\n detailY.position(10, height + 5);\n detailY.style('width', '80px');\n describe(\n 'a white sphere with low detail on the y-axis, including a slider to adjust detailY'\n );\n}\n\nfunction draw() {\n background(205, 105, 94);\n rotateY(millis() / 1000);\n sphere(40, 16, detailY.value());\n}\n
\nDraw a cylinder with given radius and height
\nDetailX and detailY determines the number of subdivisions in the x-dimension\nand the y-dimension of a cylinder. More subdivisions make the cylinder seem smoother.\nThe recommended maximum value for detailX is 24. Using a value greater than 24\nmay cause a warning or slow down the browser.
\n", "itemtype": "method", "name": "cylinder", "params": [ { "name": "radius", "description": "radius of the surface
\n", "type": "Number", "optional": true }, { "name": "height", "description": "height of the cylinder
\n", "type": "Number", "optional": true }, { "name": "detailX", "description": "number of subdivisions in x-dimension;\n default is 24
\n", "type": "Integer", "optional": true }, { "name": "detailY", "description": "number of subdivisions in y-dimension;\n default is 1
\n", "type": "Integer", "optional": true }, { "name": "bottomCap", "description": "whether to draw the bottom of the cylinder
\n", "type": "Boolean", "optional": true }, { "name": "topCap", "description": "whether to draw the top of the cylinder
\n", "type": "Boolean", "optional": true } ], "chainable": 1, "example": [ "\n\n// draw a spinning cylinder\n// with radius 20 and height 50\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('a rotating white cylinder');\n}\n\nfunction draw() {\n background(205, 105, 94);\n rotateX(frameCount * 0.01);\n rotateZ(frameCount * 0.01);\n cylinder(20, 50);\n}\n
\n\n// slide to see how detailX works\nlet detailX;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n detailX = createSlider(3, 24, 3);\n detailX.position(10, height + 5);\n detailX.style('width', '80px');\n describe(\n 'a rotating white cylinder with limited X detail, with a slider that adjusts detailX'\n );\n}\n\nfunction draw() {\n background(205, 105, 94);\n rotateY(millis() / 1000);\n cylinder(20, 75, detailX.value(), 1);\n}\n
\n\n// slide to see how detailY works\nlet detailY;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n detailY = createSlider(1, 16, 1);\n detailY.position(10, height + 5);\n detailY.style('width', '80px');\n describe(\n 'a rotating white cylinder with limited Y detail, with a slider that adjusts detailY'\n );\n}\n\nfunction draw() {\n background(205, 105, 94);\n rotateY(millis() / 1000);\n cylinder(20, 75, 16, detailY.value());\n}\n
\nDraw a cone with given radius and height
\nDetailX and detailY determine the number of subdivisions in the x-dimension and\nthe y-dimension of a cone. More subdivisions make the cone seem smoother. The\nrecommended maximum value for detailX is 24. Using a value greater than 24\nmay cause a warning or slow down the browser.
\n", "itemtype": "method", "name": "cone", "params": [ { "name": "radius", "description": "radius of the bottom surface
\n", "type": "Number", "optional": true }, { "name": "height", "description": "height of the cone
\n", "type": "Number", "optional": true }, { "name": "detailX", "description": "number of segments,\n the more segments the smoother geometry\n default is 24
\n", "type": "Integer", "optional": true }, { "name": "detailY", "description": "number of segments,\n the more segments the smoother geometry\n default is 1
\n", "type": "Integer", "optional": true }, { "name": "cap", "description": "whether to draw the base of the cone
\n", "type": "Boolean", "optional": true } ], "chainable": 1, "example": [ "\n\n// draw a spinning cone\n// with radius 40 and height 70\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('a rotating white cone');\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateZ(frameCount * 0.01);\n cone(40, 70);\n}\n
\n\n// slide to see how detailx works\nlet detailX;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n detailX = createSlider(3, 16, 3);\n detailX.position(10, height + 5);\n detailX.style('width', '80px');\n describe(\n 'a rotating white cone with limited X detail, with a slider that adjusts detailX'\n );\n}\n\nfunction draw() {\n background(205, 102, 94);\n rotateY(millis() / 1000);\n cone(30, 65, detailX.value(), 16);\n}\n
\n\n// slide to see how detailY works\nlet detailY;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n detailY = createSlider(3, 16, 3);\n detailY.position(10, height + 5);\n detailY.style('width', '80px');\n describe(\n 'a rotating white cone with limited Y detail, with a slider that adjusts detailY'\n );\n}\n\nfunction draw() {\n background(205, 102, 94);\n rotateY(millis() / 1000);\n cone(30, 65, 16, detailY.value());\n}\n
\nDraw an ellipsoid with given radius
\nDetailX and detailY determine the number of subdivisions in the x-dimension and\nthe y-dimension of a cone. More subdivisions make the ellipsoid appear to be smoother.\nAvoid detail number above 150, it may crash the browser.
\n", "itemtype": "method", "name": "ellipsoid", "params": [ { "name": "radiusx", "description": "x-radius of ellipsoid
\n", "type": "Number", "optional": true }, { "name": "radiusy", "description": "y-radius of ellipsoid
\n", "type": "Number", "optional": true }, { "name": "radiusz", "description": "z-radius of ellipsoid
\n", "type": "Number", "optional": true }, { "name": "detailX", "description": "number of segments,\n the more segments the smoother geometry\n default is 24. Avoid detail number above\n 150, it may crash the browser.
\n", "type": "Integer", "optional": true }, { "name": "detailY", "description": "number of segments,\n the more segments the smoother geometry\n default is 16. Avoid detail number above\n 150, it may crash the browser.
\n", "type": "Integer", "optional": true } ], "chainable": 1, "example": [ "\n\n// draw an ellipsoid\n// with radius 30, 40 and 40.\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('a white 3d ellipsoid');\n}\n\nfunction draw() {\n background(205, 105, 94);\n ellipsoid(30, 40, 40);\n}\n
\n\n// slide to see how detailX works\nlet detailX;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n detailX = createSlider(2, 24, 12);\n detailX.position(10, height + 5);\n detailX.style('width', '80px');\n describe(\n 'a rotating white ellipsoid with limited X detail, with a slider that adjusts detailX'\n );\n}\n\nfunction draw() {\n background(205, 105, 94);\n rotateY(millis() / 1000);\n ellipsoid(30, 40, 40, detailX.value(), 8);\n}\n
\n\n// slide to see how detailY works\nlet detailY;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n detailY = createSlider(2, 24, 6);\n detailY.position(10, height + 5);\n detailY.style('width', '80px');\n describe(\n 'a rotating white ellipsoid with limited Y detail, with a slider that adjusts detailY'\n );\n}\n\nfunction draw() {\n background(205, 105, 9);\n rotateY(millis() / 1000);\n ellipsoid(30, 40, 40, 12, detailY.value());\n}\n
\nDraw a torus with given radius and tube radius
\nDetailX and detailY determine the number of subdivisions in the x-dimension and\nthe y-dimension of a torus. More subdivisions make the torus appear to be smoother.\nThe default and maximum values for detailX and detailY are 24 and 16, respectively.\nSetting them to relatively small values like 4 and 6 allows you to create new\nshapes other than a torus.
\n", "itemtype": "method", "name": "torus", "params": [ { "name": "radius", "description": "radius of the whole ring
\n", "type": "Number", "optional": true }, { "name": "tubeRadius", "description": "radius of the tube
\n", "type": "Number", "optional": true }, { "name": "detailX", "description": "number of segments in x-dimension,\n the more segments the smoother geometry\n default is 24
\n", "type": "Integer", "optional": true }, { "name": "detailY", "description": "number of segments in y-dimension,\n the more segments the smoother geometry\n default is 16
\n", "type": "Integer", "optional": true } ], "chainable": 1, "example": [ "\n\n// draw a spinning torus\n// with ring radius 30 and tube radius 15\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('a rotating white torus');\n}\n\nfunction draw() {\n background(205, 102, 94);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n torus(30, 15);\n}\n
\n\n// slide to see how detailX works\nlet detailX;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n detailX = createSlider(3, 24, 3);\n detailX.position(10, height + 5);\n detailX.style('width', '80px');\n describe(\n 'a rotating white torus with limited X detail, with a slider that adjusts detailX'\n );\n}\n\nfunction draw() {\n background(205, 102, 94);\n rotateY(millis() / 1000);\n torus(30, 15, detailX.value(), 12);\n}\n
\n\n// slide to see how detailY works\nlet detailY;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n detailY = createSlider(3, 16, 3);\n detailY.position(10, height + 5);\n detailY.style('width', '80px');\n describe(\n 'a rotating white torus with limited Y detail, with a slider that adjusts detailY'\n );\n}\n\nfunction draw() {\n background(205, 102, 94);\n rotateY(millis() / 1000);\n torus(30, 15, 16, detailY.value());\n}\n
\nAllows movement around a 3D sketch using a mouse or trackpad. Left-clicking\nand dragging will rotate the camera position about the center of the sketch,\nright-clicking and dragging will pan the camera position without rotation,\nand using the mouse wheel (scrolling) will move the camera closer or further\nfrom the center of the sketch. This function can be called with parameters\ndictating sensitivity to mouse movement along the X and Y axes. Calling\nthis function without parameters is equivalent to calling orbitControl(1,1).\nTo reverse direction of movement in either axis, enter a negative number\nfor sensitivity.
\n", "itemtype": "method", "name": "orbitControl", "params": [ { "name": "sensitivityX", "description": "sensitivity to mouse movement along X axis
\n", "type": "Number", "optional": true }, { "name": "sensitivityY", "description": "sensitivity to mouse movement along Y axis
\n", "type": "Number", "optional": true }, { "name": "sensitivityZ", "description": "sensitivity to scroll movement along Z axis
\n", "type": "Number", "optional": true } ], "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n describe(\n 'Camera orbits around a box when mouse is hold-clicked & then moved.'\n );\n}\nfunction draw() {\n background(200);\n orbitControl();\n rotateY(0.5);\n box(30, 50);\n}\n
\ndebugMode() helps visualize 3D space by adding a grid to indicate where the\n‘ground’ is in a sketch and an axes icon which indicates the +X, +Y, and +Z\ndirections. This function can be called without parameters to create a\ndefault grid and axes icon, or it can be called according to the examples\nabove to customize the size and position of the grid and/or axes icon. The\ngrid is drawn using the most recently set stroke color and weight. To\nspecify these parameters, add a call to stroke() and strokeWeight()\njust before the end of the draw() loop.
\nBy default, the grid will run through the origin (0,0,0) of the sketch\nalong the XZ plane\nand the axes icon will be offset from the origin. Both the grid and axes\nicon will be sized according to the current canvas size. Note that because the\ngrid runs parallel to the default camera view, it is often helpful to use\ndebugMode along with orbitControl to allow full view of the grid.
\n", "itemtype": "method", "name": "debugMode", "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n camera(0, -30, 100, 0, 0, 0, 0, 1, 0);\n normalMaterial();\n debugMode();\n describe(\n 'a 3D box is centered on a grid in a 3D sketch. an icon indicates the direction of each axis: a red line points +X, a green line +Y, and a blue line +Z. the grid and icon disappear when the spacebar is pressed.'\n );\n}\n\nfunction draw() {\n background(200);\n orbitControl();\n box(15, 30);\n // Press the spacebar to turn debugMode off!\n if (keyIsDown(32)) {\n noDebugMode();\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n camera(0, -30, 100, 0, 0, 0, 0, 1, 0);\n normalMaterial();\n debugMode(GRID);\n describe('a 3D box is centered on a grid in a 3D sketch.');\n}\n\nfunction draw() {\n background(200);\n orbitControl();\n box(15, 30);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n camera(0, -30, 100, 0, 0, 0, 0, 1, 0);\n normalMaterial();\n debugMode(AXES);\n describe(\n 'a 3D box is centered in a 3D sketch. an icon indicates the direction of each axis: a red line points +X, a green line +Y, and a blue line +Z.'\n );\n}\n\nfunction draw() {\n background(200);\n orbitControl();\n box(15, 30);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n camera(0, -30, 100, 0, 0, 0, 0, 1, 0);\n normalMaterial();\n debugMode(GRID, 100, 10, 0, 0, 0);\n describe('a 3D box is centered on a grid in a 3D sketch');\n}\n\nfunction draw() {\n background(200);\n orbitControl();\n box(15, 30);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n camera(0, -30, 100, 0, 0, 0, 0, 1, 0);\n normalMaterial();\n debugMode(100, 10, 0, 0, 0, 20, 0, -40, 0);\n describe(\n 'a 3D box is centered on a grid in a 3D sketch. an icon indicates the direction of each axis: a red line points +X, a green line +Y, and a blue line +Z.'\n );\n}\n\nfunction draw() {\n noStroke();\n background(200);\n orbitControl();\n box(15, 30);\n // set the stroke color and weight for the grid!\n stroke(255, 0, 150);\n strokeWeight(0.8);\n}\n
\neither GRID or AXES
\n", "type": "Constant" } ] }, { "line": 297, "params": [ { "name": "mode", "description": "", "type": "Constant" }, { "name": "gridSize", "description": "size of one side of the grid
\n", "type": "Number", "optional": true }, { "name": "gridDivisions", "description": "number of divisions in the grid
\n", "type": "Number", "optional": true }, { "name": "xOff", "description": "X axis offset from origin (0,0,0)
\n", "type": "Number", "optional": true }, { "name": "yOff", "description": "Y axis offset from origin (0,0,0)
\n", "type": "Number", "optional": true }, { "name": "zOff", "description": "Z axis offset from origin (0,0,0)
\n", "type": "Number", "optional": true } ] }, { "line": 307, "params": [ { "name": "mode", "description": "", "type": "Constant" }, { "name": "axesSize", "description": "size of axes icon
\n", "type": "Number", "optional": true }, { "name": "xOff", "description": "", "type": "Number", "optional": true }, { "name": "yOff", "description": "", "type": "Number", "optional": true }, { "name": "zOff", "description": "", "type": "Number", "optional": true } ] }, { "line": 316, "params": [ { "name": "gridSize", "description": "", "type": "Number", "optional": true }, { "name": "gridDivisions", "description": "", "type": "Number", "optional": true }, { "name": "gridXOff", "description": "", "type": "Number", "optional": true }, { "name": "gridYOff", "description": "", "type": "Number", "optional": true }, { "name": "gridZOff", "description": "", "type": "Number", "optional": true }, { "name": "axesSize", "description": "", "type": "Number", "optional": true }, { "name": "axesXOff", "description": "", "type": "Number", "optional": true }, { "name": "axesYOff", "description": "", "type": "Number", "optional": true }, { "name": "axesZOff", "description": "", "type": "Number", "optional": true } ] } ] }, { "file": "src/webgl/interaction.js", "line": 367, "description": "Turns off debugMode() in a 3D sketch.
\n", "itemtype": "method", "name": "noDebugMode", "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n camera(0, -30, 100, 0, 0, 0, 0, 1, 0);\n normalMaterial();\n debugMode();\n describe(\n 'a 3D box is centered on a grid in a 3D sketch. an icon indicates the direction of each axis: a red line points +X, a green line +Y, and a blue line +Z. the grid and icon disappear when the spacebar is pressed.'\n );\n}\n\nfunction draw() {\n background(200);\n orbitControl();\n box(15, 30);\n // Press the spacebar to turn debugMode off!\n if (keyIsDown(32)) {\n noDebugMode();\n }\n}\n
\nCreates an ambient light with the given color.
\nAmbient light does not come from a specific direction.\nObjects are evenly lit from all sides. Ambient lights are\nalmost always used in combination with other types of lights.
\nNote: lights need to be called (whether directly or indirectly)\nwithin draw() to remain persistent in a looping program.\nPlacing them in setup() will cause them to only have an effect\nthe first time through the loop.
\n", "itemtype": "method", "name": "ambientLight", "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noStroke();\n describe('sphere with coral color under black light');\n}\nfunction draw() {\n background(100);\n ambientLight(0); // black light (no light)\n ambientMaterial(255, 127, 80); // coral material\n sphere(40);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noStroke();\n describe('sphere with coral color under white light');\n}\nfunction draw() {\n background(100);\n ambientLight(255); // white light\n ambientMaterial(255, 127, 80); // coral material\n sphere(40);\n}\n
\nred or hue value relative to\n the current color range
\n", "type": "Number" }, { "name": "v2", "description": "green or saturation value\n relative to the current color range
\n", "type": "Number" }, { "name": "v3", "description": "blue or brightness value\n relative to the current color range
\n", "type": "Number" }, { "name": "alpha", "description": "alpha value relative to current\n color range (default is 0-255)
\n", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 73, "params": [ { "name": "gray", "description": "number specifying value between\n white and black
\n", "type": "Number" }, { "name": "alpha", "description": "", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 81, "params": [ { "name": "value", "description": "a color string
\n", "type": "String" } ], "chainable": 1 }, { "line": 87, "params": [ { "name": "values", "description": "an array containing the red,green,blue &\n and alpha components of the color
\n", "type": "Number[]" } ], "chainable": 1 }, { "line": 94, "params": [ { "name": "color", "description": "color as a p5.Color
\n", "type": "p5.Color" } ], "chainable": 1 } ] }, { "file": "src/webgl/light.js", "line": 115, "description": "Sets the color of the specular highlight of a non-ambient light\n(i.e. all lights except ambientLight()).
\nspecularColor() affects only the lights which are created after\nit in the code.
\nThis function is used in combination with\nspecularMaterial().\nIf a geometry does not use specularMaterial(), this function\nwill have no effect.
\nThe default color is white (255, 255, 255), which is used if\nspecularColor() is not explicitly called.
\nNote: specularColor is equivalent to the Processing function\nlightSpecular.
\n", "itemtype": "method", "name": "specularColor", "chainable": 1, "example": [ "\n\nlet setRedSpecularColor = true;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noStroke();\n describe(\n 'Sphere with specular highlight. Clicking the mouse toggles the specular highlight color between red and the default white.'\n );\n}\n\nfunction draw() {\n background(0);\n\n ambientLight(60);\n\n // add a point light to showcase specular color\n // -- use mouse location to position the light\n let lightPosX = mouseX - width / 2;\n let lightPosY = mouseY - height / 2;\n // -- set the light's specular color\n if (setRedSpecularColor) {\n specularColor(255, 0, 0); // red specular highlight\n }\n // -- create the light\n pointLight(200, 200, 200, lightPosX, lightPosY, 50); // white light\n\n // use specular material with high shininess\n specularMaterial(150);\n shininess(50);\n\n sphere(30, 64, 64);\n}\n\nfunction mouseClicked() {\n setRedSpecularColor = !setRedSpecularColor;\n}\n
\nred or hue value relative to\n the current color range
\n", "type": "Number" }, { "name": "v2", "description": "green or saturation value\n relative to the current color range
\n", "type": "Number" }, { "name": "v3", "description": "blue or brightness value\n relative to the current color range
\n", "type": "Number" } ], "chainable": 1 }, { "line": 188, "params": [ { "name": "gray", "description": "number specifying value between\n white and black
\n", "type": "Number" } ], "chainable": 1 }, { "line": 195, "params": [ { "name": "value", "description": "color as a CSS string
\n", "type": "String" } ], "chainable": 1 }, { "line": 201, "params": [ { "name": "values", "description": "color as an array containing the\n red, green, and blue components
\n", "type": "Number[]" } ], "chainable": 1 }, { "line": 208, "params": [ { "name": "color", "description": "color as a p5.Color
\n", "type": "p5.Color" } ], "chainable": 1 } ] }, { "file": "src/webgl/light.js", "line": 227, "description": "Creates a directional light with the given color and direction.
\nDirectional light comes from one direction.\nThe direction is specified as numbers inclusively between -1 and 1.\nFor example, setting the direction as (0, -1, 0) will cause the\ngeometry to be lit from below (since the light will be facing\ndirectly upwards). Similarly, setting the direction as (1, 0, 0)\nwill cause the geometry to be lit from the left (since the light\nwill be facing directly rightwards).
\nDirectional lights do not have a specific point of origin, and\ntherefore cannot be positioned closer or farther away from a geometry.
\nA maximum of 5 directional lights can be active at once.
\nNote: lights need to be called (whether directly or indirectly)\nwithin draw() to remain persistent in a looping program.\nPlacing them in setup() will cause them to only have an effect\nthe first time through the loop.
\n", "itemtype": "method", "name": "directionalLight", "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe(\n 'scene with sphere and directional light. The direction of the light is controlled with the mouse position.'\n );\n}\nfunction draw() {\n background(0);\n //move your mouse to change light direction\n let dirX = (mouseX / width - 0.5) * 2;\n let dirY = (mouseY / height - 0.5) * 2;\n directionalLight(250, 250, 250, -dirX, -dirY, -1);\n noStroke();\n sphere(40);\n}\n
\nred or hue value relative to the current\n color range
\n", "type": "Number" }, { "name": "v2", "description": "green or saturation value relative to the\n current color range
\n", "type": "Number" }, { "name": "v3", "description": "blue or brightness value relative to the\n current color range
\n", "type": "Number" }, { "name": "x", "description": "x component of direction (inclusive range of -1 to 1)
\n", "type": "Number" }, { "name": "y", "description": "y component of direction (inclusive range of -1 to 1)
\n", "type": "Number" }, { "name": "z", "description": "z component of direction (inclusive range of -1 to 1)
\n", "type": "Number" } ], "chainable": 1 }, { "line": 285, "params": [ { "name": "v1", "description": "", "type": "Number" }, { "name": "v2", "description": "", "type": "Number" }, { "name": "v3", "description": "", "type": "Number" }, { "name": "direction", "description": "direction of light as a\n p5.Vector
\n", "type": "p5.Vector" } ], "chainable": 1 }, { "line": 295, "params": [ { "name": "color", "description": "color as a p5.Color,\n as an array, or as a CSS string
\n", "type": "p5.Color|Number[]|String" }, { "name": "x", "description": "", "type": "Number" }, { "name": "y", "description": "", "type": "Number" }, { "name": "z", "description": "", "type": "Number" } ], "chainable": 1 }, { "line": 305, "params": [ { "name": "color", "description": "", "type": "p5.Color|Number[]|String" }, { "name": "direction", "description": "", "type": "p5.Vector" } ], "chainable": 1 } ] }, { "file": "src/webgl/light.js", "line": 354, "description": "Creates a point light with the given color and position.
\nA point light emits light from a single point in all directions.\nBecause the light is emitted from a specific point (position),\nit has a different effect when it is positioned farther vs. nearer\nan object.
\nA maximum of 5 point lights can be active at once.
\nNote: lights need to be called (whether directly or indirectly)\nwithin draw() to remain persistent in a looping program.\nPlacing them in setup() will cause them to only have an effect\nthe first time through the loop.
\n", "itemtype": "method", "name": "pointLight", "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe(\n 'scene with sphere and point light. The position of the light is controlled with the mouse position.'\n );\n}\nfunction draw() {\n background(0);\n // move your mouse to change light position\n let locX = mouseX - width / 2;\n let locY = mouseY - height / 2;\n // to set the light position,\n // think of the world's coordinate as:\n // -width/2,-height/2 ----------- width/2,-height/2\n // | |\n // | 0,0 |\n // | |\n // -width/2,height/2 ----------- width/2,height/2\n pointLight(250, 250, 250, locX, locY, 50);\n noStroke();\n sphere(40);\n}\n
\nred or hue value relative to the current\n color range
\n", "type": "Number" }, { "name": "v2", "description": "green or saturation value relative to the\n current color range
\n", "type": "Number" }, { "name": "v3", "description": "blue or brightness value relative to the\n current color range
\n", "type": "Number" }, { "name": "x", "description": "x component of position
\n", "type": "Number" }, { "name": "y", "description": "y component of position
\n", "type": "Number" }, { "name": "z", "description": "z component of position
\n", "type": "Number" } ], "chainable": 1 }, { "line": 413, "params": [ { "name": "v1", "description": "", "type": "Number" }, { "name": "v2", "description": "", "type": "Number" }, { "name": "v3", "description": "", "type": "Number" }, { "name": "position", "description": "of light as a p5.Vector
\n", "type": "p5.Vector" } ], "chainable": 1 }, { "line": 422, "params": [ { "name": "color", "description": "color as a p5.Color,\n as an array, or as a CSS string
\n", "type": "p5.Color|Number[]|String" }, { "name": "x", "description": "", "type": "Number" }, { "name": "y", "description": "", "type": "Number" }, { "name": "z", "description": "", "type": "Number" } ], "chainable": 1 }, { "line": 432, "params": [ { "name": "color", "description": "", "type": "p5.Color|Number[]|String" }, { "name": "position", "description": "", "type": "p5.Vector" } ], "chainable": 1 } ] }, { "file": "src/webgl/light.js", "line": 478, "description": "Places an ambient and directional light in the scene.\nThe lights are set to ambientLight(128, 128, 128) and\ndirectionalLight(128, 128, 128, 0, 0, -1).
\nNote: lights need to be called (whether directly or indirectly)\nwithin draw() to remain persistent in a looping program.\nPlacing them in setup() will cause them to only have an effect\nthe first time through the loop.
\n", "itemtype": "method", "name": "lights", "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('the light is partially ambient and partially directional');\n}\nfunction draw() {\n background(0);\n lights();\n rotateX(millis() / 1000);\n rotateY(millis() / 1000);\n rotateZ(millis() / 1000);\n box();\n}\n
\nSets the falloff rate for pointLight()\nand spotLight().
\nlightFalloff() affects only the lights which are created after it\nin the code.
\nThe constant
, linear
, an quadratic
parameters are used to calculate falloff as follows:
d = distance from light position to vertex position
\nfalloff = 1 / (CONSTANT + d * LINEAR + (d * d) * QUADRATIC)
\n", "itemtype": "method", "name": "lightFalloff", "params": [ { "name": "constant", "description": "CONSTANT value for determining falloff
\n", "type": "Number" }, { "name": "linear", "description": "LINEAR value for determining falloff
\n", "type": "Number" }, { "name": "quadratic", "description": "QUADRATIC value for determining falloff
\n", "type": "Number" } ], "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noStroke();\n describe(\n 'Two spheres with different falloff values show different intensity of light'\n );\n}\nfunction draw() {\n ortho();\n background(0);\n\n let locX = mouseX - width / 2;\n let locY = mouseY - height / 2;\n locX /= 2; // half scale\n\n lightFalloff(1, 0, 0);\n push();\n translate(-25, 0, 0);\n pointLight(250, 250, 250, locX - 25, locY, 50);\n sphere(20);\n pop();\n\n lightFalloff(0.97, 0.03, 0);\n push();\n translate(25, 0, 0);\n pointLight(250, 250, 250, locX + 25, locY, 50);\n sphere(20);\n pop();\n}\n
\nCreates a spot light with the given color, position,\nlight direction, angle, and concentration.
\nLike a pointLight(), a spotLight()\nemits light from a specific point (position). It has a different effect\nwhen it is positioned farther vs. nearer an object.
\nHowever, unlike a pointLight(), the light is emitted in one direction\nalong a conical shape. The shape of the cone can be controlled using\nthe angle
and concentration
parameters.
The angle
parameter is used to\ndetermine the radius of the cone. And the concentration
\nparameter is used to focus the light towards the center of\nthe cone. Both parameters are optional, however if you want\nto specify concentration
, you must also specify angle
.\nThe minimum concentration value is 1.
A maximum of 5 spot lights can be active at once.
\nNote: lights need to be called (whether directly or indirectly)\nwithin draw() to remain persistent in a looping program.\nPlacing them in setup() will cause them to only have an effect\nthe first time through the loop.
\n", "itemtype": "method", "name": "spotLight", "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe(\n 'scene with sphere and spot light. The position of the light is controlled with the mouse position.'\n );\n}\nfunction draw() {\n background(0);\n // move your mouse to change light position\n let locX = mouseX - width / 2;\n let locY = mouseY - height / 2;\n // to set the light position,\n // think of the world's coordinate as:\n // -width/2,-height/2 ----------- width/2,-height/2\n // | |\n // | 0,0 |\n // | |\n // -width/2,height/2 ----------- width/2,height/2\n ambientLight(50);\n spotLight(0, 250, 0, locX, locY, 100, 0, 0, -1, Math.PI / 16);\n noStroke();\n sphere(40);\n}\n
\nred or hue value relative to the current color range
\n", "type": "Number" }, { "name": "v2", "description": "green or saturation value relative to the current color range
\n", "type": "Number" }, { "name": "v3", "description": "blue or brightness value relative to the current color range
\n", "type": "Number" }, { "name": "x", "description": "x component of position
\n", "type": "Number" }, { "name": "y", "description": "y component of position
\n", "type": "Number" }, { "name": "z", "description": "z component of position
\n", "type": "Number" }, { "name": "rx", "description": "x component of light direction (inclusive range of -1 to 1)
\n", "type": "Number" }, { "name": "ry", "description": "y component of light direction (inclusive range of -1 to 1)
\n", "type": "Number" }, { "name": "rz", "description": "z component of light direction (inclusive range of -1 to 1)
\n", "type": "Number" }, { "name": "angle", "description": "angle of cone. Defaults to PI/3
\n", "type": "Number", "optional": true }, { "name": "concentration", "description": "concentration of cone. Defaults to 100
\n", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 700, "params": [ { "name": "color", "description": "color as a p5.Color,\n as an array, or as a CSS string
\n", "type": "p5.Color|Number[]|String" }, { "name": "position", "description": "position of light as a p5.Vector
\n", "type": "p5.Vector" }, { "name": "direction", "description": "direction of light as a p5.Vector
\n", "type": "p5.Vector" }, { "name": "angle", "description": "", "type": "Number", "optional": true }, { "name": "concentration", "description": "", "type": "Number", "optional": true } ] }, { "line": 709, "params": [ { "name": "v1", "description": "", "type": "Number" }, { "name": "v2", "description": "", "type": "Number" }, { "name": "v3", "description": "", "type": "Number" }, { "name": "position", "description": "", "type": "p5.Vector" }, { "name": "direction", "description": "", "type": "p5.Vector" }, { "name": "angle", "description": "", "type": "Number", "optional": true }, { "name": "concentration", "description": "", "type": "Number", "optional": true } ] }, { "line": 719, "params": [ { "name": "color", "description": "", "type": "p5.Color|Number[]|String" }, { "name": "x", "description": "", "type": "Number" }, { "name": "y", "description": "", "type": "Number" }, { "name": "z", "description": "", "type": "Number" }, { "name": "direction", "description": "", "type": "p5.Vector" }, { "name": "angle", "description": "", "type": "Number", "optional": true }, { "name": "concentration", "description": "", "type": "Number", "optional": true } ] }, { "line": 729, "params": [ { "name": "color", "description": "", "type": "p5.Color|Number[]|String" }, { "name": "position", "description": "", "type": "p5.Vector" }, { "name": "rx", "description": "", "type": "Number" }, { "name": "ry", "description": "", "type": "Number" }, { "name": "rz", "description": "", "type": "Number" }, { "name": "angle", "description": "", "type": "Number", "optional": true }, { "name": "concentration", "description": "", "type": "Number", "optional": true } ] }, { "line": 739, "params": [ { "name": "v1", "description": "", "type": "Number" }, { "name": "v2", "description": "", "type": "Number" }, { "name": "v3", "description": "", "type": "Number" }, { "name": "x", "description": "", "type": "Number" }, { "name": "y", "description": "", "type": "Number" }, { "name": "z", "description": "", "type": "Number" }, { "name": "direction", "description": "", "type": "p5.Vector" }, { "name": "angle", "description": "", "type": "Number", "optional": true }, { "name": "concentration", "description": "", "type": "Number", "optional": true } ] }, { "line": 751, "params": [ { "name": "v1", "description": "", "type": "Number" }, { "name": "v2", "description": "", "type": "Number" }, { "name": "v3", "description": "", "type": "Number" }, { "name": "position", "description": "", "type": "p5.Vector" }, { "name": "rx", "description": "", "type": "Number" }, { "name": "ry", "description": "", "type": "Number" }, { "name": "rz", "description": "", "type": "Number" }, { "name": "angle", "description": "", "type": "Number", "optional": true }, { "name": "concentration", "description": "", "type": "Number", "optional": true } ] }, { "line": 763, "params": [ { "name": "color", "description": "", "type": "p5.Color|Number[]|String" }, { "name": "x", "description": "", "type": "Number" }, { "name": "y", "description": "", "type": "Number" }, { "name": "z", "description": "", "type": "Number" }, { "name": "rx", "description": "", "type": "Number" }, { "name": "ry", "description": "", "type": "Number" }, { "name": "rz", "description": "", "type": "Number" }, { "name": "angle", "description": "", "type": "Number", "optional": true }, { "name": "concentration", "description": "", "type": "Number", "optional": true } ] } ] }, { "file": "src/webgl/light.js", "line": 988, "description": "Removes all lights present in a sketch.
\nAll subsequent geometry is rendered without lighting (until a new\nlight is created with a call to one of the lighting functions\n(lights(),\nambientLight(),\ndirectionalLight(),\npointLight(),\nspotLight()).
\n", "itemtype": "method", "name": "noLights", "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe(\n 'Three white spheres. Each appears as a different color due to lighting.'\n );\n}\nfunction draw() {\n background(200);\n noStroke();\n\n ambientLight(255, 0, 0);\n translate(-30, 0, 0);\n ambientMaterial(255);\n sphere(13);\n\n noLights();\n translate(30, 0, 0);\n ambientMaterial(255);\n sphere(13);\n\n ambientLight(0, 255, 0);\n translate(30, 0, 0);\n ambientMaterial(255);\n sphere(13);\n}\n
\nLoad a 3d model from an OBJ or STL file.
\nloadModel() should be placed inside of preload().\nThis allows the model to load fully before the rest of your code is run.
\nOne of the limitations of the OBJ and STL format is that it doesn't have a built-in\nsense of scale. This means that models exported from different programs might\nbe very different sizes. If your model isn't displaying, try calling\nloadModel() with the normalized parameter set to true. This will resize the\nmodel to a scale appropriate for p5. You can also make additional changes to\nthe final size of your model with the scale() function.
\nAlso, the support for colored STL files is not present. STL files with color will be\nrendered without color properties.
\n", "itemtype": "method", "name": "loadModel", "return": { "description": "the p5.Geometry object", "type": "p5.Geometry" }, "example": [ "\n\n//draw a spinning octahedron\nlet octahedron;\n\nfunction preload() {\n octahedron = loadModel('assets/octahedron.obj');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('Vertically rotating 3-d octahedron.');\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n model(octahedron);\n}\n
\n\n//draw a spinning teapot\nlet teapot;\n\nfunction preload() {\n // Load model with normalise parameter set to true\n teapot = loadModel('assets/teapot.obj', true);\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('Vertically rotating 3-d teapot with red, green and blue gradient.');\n}\n\nfunction draw() {\n background(200);\n scale(0.4); // Scaled to make model fit into canvas\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n normalMaterial(); // For effect\n model(teapot);\n}\n
\nPath of the model to be loaded
\n", "type": "String" }, { "name": "normalize", "description": "If true, scale the model to a\n standardized size when loading
\n", "type": "Boolean" }, { "name": "successCallback", "description": "Function to be called\n once the model is loaded. Will be passed\n the 3D model object.
\n", "type": "function(p5.Geometry)", "optional": true }, { "name": "failureCallback", "description": "called with event error if\n the model fails to load.
\n", "type": "Function(Event)", "optional": true }, { "name": "fileType", "description": "The file extension of the model\n (.stl
, .obj
).
Parse OBJ lines into model. For reference, this is what a simple model of a\nsquare might look like:
\nv -0.5 -0.5 0.5\nv -0.5 -0.5 -0.5\nv -0.5 0.5 -0.5\nv -0.5 0.5 0.5
\nf 4 3 2 1
\n", "class": "p5", "module": "Shape", "submodule": "3D Models" }, { "file": "src/webgl/loading.js", "line": 292, "description": "STL files can be of two types, ASCII and Binary,
\nWe need to convert the arrayBuffer to an array of strings,\nto parse it as an ASCII file.
\n", "class": "p5", "module": "Shape", "submodule": "3D Models" }, { "file": "src/webgl/loading.js", "line": 319, "description": "This function checks if the file is in ASCII format or in Binary format
\nIt is done by searching keyword solid
at the start of the file.
An ASCII STL data must begin with solid
as the first six bytes.\nHowever, ASCII STLs lacking the SPACE after the d
are known to be\nplentiful. So, check the first 5 bytes for solid
.
Several encodings, such as UTF-8, precede the text with up to 5 bytes:\nhttps://en.wikipedia.org/wiki/Byte_order_mark#Byte_order_marks_by_encoding\nSearch for solid
to start anywhere after those prefixes.
This function matches the query
at the provided offset
This function parses the Binary STL files.\nhttps://en.wikipedia.org/wiki/STL_%28file_format%29#Binary_STL
\nCurrently there is no support for the colors provided in STL files.
\n", "class": "p5", "module": "Shape", "submodule": "3D Models" }, { "file": "src/webgl/loading.js", "line": 446, "description": "ASCII STL file starts with solid 'nameOfFile'
\nThen contain the normal of the face, starting with facet normal
\nNext contain a keyword indicating the start of face vertex, outer loop
\nNext comes the three vertex, starting with vertex x y z
\nVertices ends with endloop
\nFace ends with endfacet
\nNext face starts with facet normal
\nThe end of the file is indicated by endsolid
Render a 3d model to the screen.
\n", "itemtype": "method", "name": "model", "params": [ { "name": "model", "description": "Loaded 3d model to be rendered
\n", "type": "p5.Geometry" } ], "example": [ "\n\n//draw a spinning octahedron\nlet octahedron;\n\nfunction preload() {\n octahedron = loadModel('assets/octahedron.obj');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('Vertically rotating 3-d octahedron.');\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n model(octahedron);\n}\n
\nCreates a new p5.Shader object\nfrom the provided vertex and fragment shader files.
\nThe shader files are loaded asynchronously in the\nbackground, so this method should be used in preload().
\nNote, shaders can only be used in WEBGL mode.
\n", "itemtype": "method", "name": "loadShader", "params": [ { "name": "vertFilename", "description": "path to file containing vertex shader\nsource code
\n", "type": "String" }, { "name": "fragFilename", "description": "path to file containing fragment shader\nsource code
\n", "type": "String" }, { "name": "callback", "description": "callback to be executed after loadShader\ncompletes. On success, the p5.Shader object is passed as the first argument.
\n", "type": "Function", "optional": true }, { "name": "errorCallback", "description": "callback to be executed when an error\noccurs inside loadShader. On error, the error is passed as the first\nargument.
\n", "type": "Function", "optional": true } ], "return": { "description": "a shader object created from the provided\nvertex and fragment shader files.", "type": "p5.Shader" }, "example": [ "\n\nlet mandel;\nfunction preload() {\n // load the shader definitions from files\n mandel = loadShader('assets/shader.vert', 'assets/shader.frag');\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n // use the shader\n shader(mandel);\n noStroke();\n mandel.setUniform('p', [-0.74364388703, 0.13182590421]);\n describe('zooming Mandelbrot set. a colorful, infinitely detailed fractal.');\n}\n\nfunction draw() {\n mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000))));\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n
\nCreates a new p5.Shader object\nfrom the provided vertex and fragment shader code.
\nNote, shaders can only be used in WEBGL mode.
\n", "itemtype": "method", "name": "createShader", "params": [ { "name": "vertSrc", "description": "source code for the vertex shader
\n", "type": "String" }, { "name": "fragSrc", "description": "source code for the fragment shader
\n", "type": "String" } ], "return": { "description": "a shader object created from the provided\nvertex and fragment shaders.", "type": "p5.Shader" }, "example": [ "\n\n// the 'varying's are shared between both vertex & fragment shaders\nlet varying = 'precision highp float; varying vec2 vPos;';\n\n// the vertex shader is called for each vertex\nlet vs =\n varying +\n 'attribute vec3 aPosition;' +\n 'void main() { vPos = (gl_Position = vec4(aPosition,1.0)).xy; }';\n\n// the fragment shader is called for each pixel\nlet fs =\n varying +\n 'uniform vec2 p;' +\n 'uniform float r;' +\n 'const int I = 500;' +\n 'void main() {' +\n ' vec2 c = p + vPos * r, z = c;' +\n ' float n = 0.0;' +\n ' for (int i = I; i > 0; i --) {' +\n ' if(z.x*z.x+z.y*z.y > 4.0) {' +\n ' n = float(i)/float(I);' +\n ' break;' +\n ' }' +\n ' z = vec2(z.x*z.x-z.y*z.y, 2.0*z.x*z.y) + c;' +\n ' }' +\n ' gl_FragColor = vec4(0.5-cos(n*17.0)/2.0,0.5-cos(n*13.0)/2.0,0.5-cos(n*23.0)/2.0,1.0);' +\n '}';\n\nlet mandel;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // create and initialize the shader\n mandel = createShader(vs, fs);\n shader(mandel);\n noStroke();\n\n // 'p' is the center point of the Mandelbrot image\n mandel.setUniform('p', [-0.74364388703, 0.13182590421]);\n describe('zooming Mandelbrot set. a colorful, infinitely detailed fractal.');\n}\n\nfunction draw() {\n // 'r' is the size of the image in Mandelbrot-space\n mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000))));\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n
\nSets the p5.Shader object to\nbe used to render subsequent shapes.
\nCustom shaders can be created using the\ncreateShader() and\nloadShader() functions.
\nUse resetShader() to\nrestore the default shaders.
\nNote, shaders can only be used in WEBGL mode.
\n", "itemtype": "method", "name": "shader", "chainable": 1, "params": [ { "name": "s", "description": "the p5.Shader object\nto use for rendering shapes.
\n", "type": "p5.Shader" } ], "example": [ "\n\n// Click within the image to toggle\n// the shader used by the quad shape\n// Note: for an alternative approach to the same example,\n// involving changing uniforms please refer to:\n// https://p5js.org/reference/#/p5.Shader/setUniform\n\nlet redGreen;\nlet orangeBlue;\nlet showRedGreen = false;\n\nfunction preload() {\n // note that we are using two instances\n // of the same vertex and fragment shaders\n redGreen = loadShader('assets/shader.vert', 'assets/shader-gradient.frag');\n orangeBlue = loadShader('assets/shader.vert', 'assets/shader-gradient.frag');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // initialize the colors for redGreen shader\n shader(redGreen);\n redGreen.setUniform('colorCenter', [1.0, 0.0, 0.0]);\n redGreen.setUniform('colorBackground', [0.0, 1.0, 0.0]);\n\n // initialize the colors for orangeBlue shader\n shader(orangeBlue);\n orangeBlue.setUniform('colorCenter', [1.0, 0.5, 0.0]);\n orangeBlue.setUniform('colorBackground', [0.226, 0.0, 0.615]);\n\n noStroke();\n\n describe(\n 'canvas toggles between a circular gradient of orange and blue vertically. and a circular gradient of red and green moving horizontally when mouse is clicked/pressed.'\n );\n}\n\nfunction draw() {\n // update the offset values for each shader,\n // moving orangeBlue in vertical and redGreen\n // in horizontal direction\n orangeBlue.setUniform('offset', [0, sin(millis() / 2000) + 1]);\n redGreen.setUniform('offset', [sin(millis() / 2000), 1]);\n\n if (showRedGreen === true) {\n shader(redGreen);\n } else {\n shader(orangeBlue);\n }\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n\nfunction mouseClicked() {\n showRedGreen = !showRedGreen;\n}\n
\nRestores the default shaders. Code that runs after resetShader()\nwill not be affected by the shader previously set by\nshader()
\n", "itemtype": "method", "name": "resetShader", "chainable": 1, "example": [ "\n\n// This variable will hold our shader object\nlet shaderProgram;\n\n// This variable will hold our vertex shader source code\nlet vertSrc = `\n attribute vec3 aPosition;\n attribute vec2 aTexCoord;\n uniform mat4 uProjectionMatrix;\n uniform mat4 uModelViewMatrix;\n varying vec2 vTexCoord;\n\n void main() {\n vTexCoord = aTexCoord;\n vec4 position = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * position;\n }\n`;\n\n// This variable will hold our fragment shader source code\nlet fragSrc = `\n precision mediump float;\n\n varying vec2 vTexCoord;\n\n void main() {\n vec2 uv = vTexCoord;\n vec3 color = vec3(uv.x, uv.y, min(uv.x + uv.y, 1.0));\n gl_FragColor = vec4(color, 1.0);\n }\n`;\n\nfunction setup() {\n // Shaders require WEBGL mode to work\n createCanvas(100, 100, WEBGL);\n\n // Create our shader\n shaderProgram = createShader(vertSrc, fragSrc);\n\n describe(\n 'Two rotating cubes. The left one is painted using a custom (user-defined) shader, while the right one is painted using the default fill shader.'\n );\n}\n\nfunction draw() {\n // Clear the scene\n background(200);\n\n // Draw a box using our shader\n // shader() sets the active shader with our shader\n shader(shaderProgram);\n push();\n translate(-width / 4, 0, 0);\n rotateX(millis() * 0.00025);\n rotateY(millis() * 0.0005);\n box(width / 4);\n pop();\n\n // Draw a box using the default fill shader\n // resetShader() restores the default fill shader\n resetShader();\n fill(255, 0, 0);\n push();\n translate(width / 4, 0, 0);\n rotateX(millis() * 0.00025);\n rotateY(millis() * 0.0005);\n box(width / 4);\n pop();\n}\n
\nSets the texture that will be used to render subsequent shapes.
\nA texture is like a \"skin\" that wraps around a 3D geometry. Currently\nsupported textures are images, video, and offscreen renders.
\nTo texture a geometry created with beginShape(),\nyou will need to specify uv coordinates in vertex().
\nNote, texture() can only be used in WEBGL mode.
\nYou can view more materials in this\nexample.
\n", "itemtype": "method", "name": "texture", "params": [ { "name": "tex", "description": "image to use as texture
\n", "type": "p5.Image|p5.MediaElement|p5.Graphics|p5.Texture" } ], "chainable": 1, "example": [ "\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('spinning cube with a texture from an image');\n}\n\nfunction draw() {\n background(0);\n rotateZ(frameCount * 0.01);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n //pass image as texture\n texture(img);\n box(width / 2);\n}\n
\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n pg = createGraphics(200, 200);\n pg.textSize(75);\n describe('plane with a texture from an image created by createGraphics()');\n}\n\nfunction draw() {\n background(0);\n pg.background(255);\n pg.text('hello!', 0, 100);\n //pass image as texture\n texture(pg);\n rotateX(0.5);\n noStroke();\n plane(50);\n}\n
\n\nlet vid;\nfunction preload() {\n vid = createVideo('assets/fingers.mov');\n vid.hide();\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('rectangle with video as texture');\n}\n\nfunction draw() {\n background(0);\n //pass video frame as texture\n texture(vid);\n rect(-40, -40, 80, 80);\n}\n\nfunction mousePressed() {\n vid.loop();\n}\n
\n\nlet img;\n\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('quad with a texture, mapped using normalized coordinates');\n}\n\nfunction draw() {\n background(0);\n texture(img);\n textureMode(NORMAL);\n beginShape();\n vertex(-40, -40, 0, 0);\n vertex(40, -40, 1, 0);\n vertex(40, 40, 1, 1);\n vertex(-40, 40, 0, 1);\n endShape();\n}\n
\nSets the coordinate space for texture mapping. The default mode is IMAGE\nwhich refers to the actual coordinates of the image.\nNORMAL refers to a normalized space of values ranging from 0 to 1.
\nWith IMAGE, if an image is 100×200 pixels, mapping the image onto the entire\nsize of a quad would require the points (0,0) (100, 0) (100,200) (0,200).\nThe same mapping in NORMAL is (0,0) (1,0) (1,1) (0,1).
\n", "itemtype": "method", "name": "textureMode", "params": [ { "name": "mode", "description": "either IMAGE or NORMAL
\n", "type": "Constant" } ], "example": [ "\n\nlet img;\n\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('quad with a texture, mapped using normalized coordinates');\n}\n\nfunction draw() {\n texture(img);\n textureMode(NORMAL);\n beginShape();\n vertex(-50, -50, 0, 0);\n vertex(50, -50, 1, 0);\n vertex(50, 50, 1, 1);\n vertex(-50, 50, 0, 1);\n endShape();\n}\n
\n\nlet img;\n\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('quad with a texture, mapped using image coordinates');\n}\n\nfunction draw() {\n texture(img);\n textureMode(IMAGE);\n beginShape();\n vertex(-50, -50, 0, 0);\n vertex(50, -50, img.width, 0);\n vertex(50, 50, img.width, img.height);\n vertex(-50, 50, 0, img.height);\n endShape();\n}\n
\nSets the global texture wrapping mode. This controls how textures behave\nwhen their uv's go outside of the 0 to 1 range. There are three options:\nCLAMP, REPEAT, and MIRROR.
\nCLAMP causes the pixels at the edge of the texture to extend to the bounds.\nREPEAT causes the texture to tile repeatedly until reaching the bounds.\nMIRROR works similarly to REPEAT but it flips the texture with every new tile.
\nREPEAT & MIRROR are only available if the texture\nis a power of two size (128, 256, 512, 1024, etc.).
\nThis method will affect all textures in your sketch until a subsequent\ntextureWrap() call is made.
\nIf only one argument is provided, it will be applied to both the\nhorizontal and vertical axes.
\n", "itemtype": "method", "name": "textureWrap", "params": [ { "name": "wrapX", "description": "either CLAMP, REPEAT, or MIRROR
\n", "type": "Constant" }, { "name": "wrapY", "description": "either CLAMP, REPEAT, or MIRROR
\n", "type": "Constant", "optional": true } ], "example": [ "\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies128.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n textureWrap(MIRROR);\n describe('an image of the rocky mountains repeated in mirrored tiles');\n}\n\nfunction draw() {\n background(0);\n\n let dX = mouseX;\n let dY = mouseY;\n\n let u = lerp(1.0, 2.0, dX);\n let v = lerp(1.0, 2.0, dY);\n\n scale(width / 2);\n\n texture(img);\n\n beginShape(TRIANGLES);\n vertex(-1, -1, 0, 0, 0);\n vertex(1, -1, 0, u, 0);\n vertex(1, 1, 0, u, v);\n\n vertex(1, 1, 0, u, v);\n vertex(-1, 1, 0, 0, v);\n vertex(-1, -1, 0, 0, 0);\n endShape();\n}\n
\nSets the current material as a normal material.
\nA normal material is not affected by light. It is often used as\na placeholder material when debugging.
\nSurfaces facing the X-axis become red, those facing the Y-axis\nbecome green, and those facing the Z-axis become blue.
\nYou can view more materials in this\nexample.
\n", "itemtype": "method", "name": "normalMaterial", "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('Sphere with normal material');\n}\n\nfunction draw() {\n background(200);\n normalMaterial();\n sphere(40);\n}\n
\nSets the ambient color of the material.
\nThe ambientMaterial() color is the color the object will reflect\nunder any lighting.
\nConsider an ambientMaterial() with the color yellow (255, 255, 0).\nIf the light emits the color white (255, 255, 255), then the object\nwill appear yellow as it will reflect the red and green components\nof the light. If the light emits the color red (255, 0, 0), then\nthe object will appear red as it will reflect the red component\nof the light. If the light emits the color blue (0, 0, 255),\nthen the object will appear black, as there is no component of\nthe light that it can reflect.
\nYou can view more materials in this\nexample.
\n", "itemtype": "method", "name": "ambientMaterial", "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('sphere reflecting red, blue, and green light');\n}\nfunction draw() {\n background(0);\n noStroke();\n ambientLight(255);\n ambientMaterial(70, 130, 230);\n sphere(40);\n}\n
\n\n// ambientLight is both red and blue (magenta),\n// so object only reflects it's red and blue components\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('box reflecting only red and blue light');\n}\nfunction draw() {\n background(70);\n ambientLight(255, 0, 255); // magenta light\n ambientMaterial(255); // white material\n box(30);\n}\n
\n\n// ambientLight is green. Since object does not contain\n// green, it does not reflect any light\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('box reflecting no light');\n}\nfunction draw() {\n background(70);\n ambientLight(0, 255, 0); // green light\n ambientMaterial(255, 0, 255); // magenta material\n box(30);\n}\n
\nred or hue value relative to the current\n color range
\n", "type": "Number" }, { "name": "v2", "description": "green or saturation value relative to the\n current color range
\n", "type": "Number" }, { "name": "v3", "description": "blue or brightness value relative to the\n current color range
\n", "type": "Number" } ], "chainable": 1 }, { "line": 806, "params": [ { "name": "gray", "description": "number specifying value between\n white and black
\n", "type": "Number" } ], "chainable": 1 }, { "line": 813, "params": [ { "name": "color", "description": "color as a p5.Color,\n as an array, or as a CSS string
\n", "type": "p5.Color|Number[]|String" } ], "chainable": 1 } ] }, { "file": "src/webgl/material.js", "line": 833, "description": "Sets the emissive color of the material.
\nAn emissive material will display the emissive color at\nfull strength regardless of lighting. This can give the\nappearance that the object is glowing.
\nNote, \"emissive\" is a misnomer in the sense that the material\ndoes not actually emit light that will affect surrounding objects.
\nYou can view more materials in this\nexample.
\n", "itemtype": "method", "name": "emissiveMaterial", "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('sphere with green emissive material');\n}\nfunction draw() {\n background(0);\n noStroke();\n ambientLight(0);\n emissiveMaterial(130, 230, 0);\n sphere(40);\n}\n
\nred or hue value relative to the current\n color range
\n", "type": "Number" }, { "name": "v2", "description": "green or saturation value relative to the\n current color range
\n", "type": "Number" }, { "name": "v3", "description": "blue or brightness value relative to the\n current color range
\n", "type": "Number" }, { "name": "alpha", "description": "alpha value relative to current color\n range (default is 0-255)
\n", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 877, "params": [ { "name": "gray", "description": "number specifying value between\n white and black
\n", "type": "Number" } ], "chainable": 1 }, { "line": 884, "params": [ { "name": "color", "description": "color as a p5.Color,\n as an array, or as a CSS string
\n", "type": "p5.Color|Number[]|String" } ], "chainable": 1 } ] }, { "file": "src/webgl/material.js", "line": 905, "description": "Sets the specular color of the material.
\nA specular material is reflective (shiny). The shininess can be\ncontrolled by the shininess() function.
\nLike ambientMaterial(),\nthe specularMaterial() color is the color the object will reflect\nunder ambientLight().\nHowever unlike ambientMaterial(), for all other types of lights\n(directionalLight(),\npointLight(),\nspotLight()),\na specular material will reflect the color of the light source.\nThis is what gives it its \"shiny\" appearance.
\nYou can view more materials in this\nexample.
\n", "itemtype": "method", "name": "specularMaterial", "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noStroke();\n describe('torus with specular material');\n}\n\nfunction draw() {\n background(0);\n\n ambientLight(60);\n\n // add point light to showcase specular material\n let locX = mouseX - width / 2;\n let locY = mouseY - height / 2;\n pointLight(255, 255, 255, locX, locY, 50);\n\n specularMaterial(250);\n shininess(50);\n torus(30, 10, 64, 64);\n}\n
\nnumber specifying value between white and black.
\n", "type": "Number" }, { "name": "alpha", "description": "alpha value relative to current color range\n (default is 0-255)
\n", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 959, "params": [ { "name": "v1", "description": "red or hue value relative to\n the current color range
\n", "type": "Number" }, { "name": "v2", "description": "green or saturation value\n relative to the current color range
\n", "type": "Number" }, { "name": "v3", "description": "blue or brightness value\n relative to the current color range
\n", "type": "Number" }, { "name": "alpha", "description": "", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 971, "params": [ { "name": "color", "description": "color as a p5.Color,\n as an array, or as a CSS string
\n", "type": "p5.Color|Number[]|String" } ], "chainable": 1 } ] }, { "file": "src/webgl/material.js", "line": 992, "description": "Sets the amount of gloss (\"shininess\") of a\nspecularMaterial().
\nThe default and minimum value is 1.
\n", "itemtype": "method", "name": "shininess", "params": [ { "name": "shine", "description": "degree of shininess
\n", "type": "Number" } ], "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('two spheres, one more shiny than the other');\n}\nfunction draw() {\n background(0);\n noStroke();\n let locX = mouseX - width / 2;\n let locY = mouseY - height / 2;\n ambientLight(60, 60, 60);\n pointLight(255, 255, 255, locX, locY, 50);\n specularMaterial(250);\n translate(-25, 0, 0);\n shininess(1);\n sphere(20);\n translate(50, 0, 0);\n shininess(20);\n sphere(20);\n}\n
\nSets the position of the current camera in a 3D sketch.\nParameters for this function define the camera's position,\nthe center of the sketch (where the camera is pointing),\nand an up direction (the orientation of the camera).
\nThis function simulates the movements of the camera, allowing objects to be\nviewed from various angles. Remember, it does not move the objects themselves\nbut the camera instead. For example when the centerX value is positive,\nand the camera is rotating to the right side of the sketch,\nthe object will seem like it's moving to the left.
\nSee this example\nto view the position of your camera.
\nIf no parameters are given, the following default is used:\ncamera(0, 0, (height/2) / tan(PI/6), 0, 0, 0, 0, 1, 0)
\n", "itemtype": "method", "name": "camera", "is_constructor": 1, "params": [ { "name": "x", "description": "camera position value on x axis
\n", "type": "Number", "optional": true }, { "name": "y", "description": "camera position value on y axis
\n", "type": "Number", "optional": true }, { "name": "z", "description": "camera position value on z axis
\n", "type": "Number", "optional": true }, { "name": "centerX", "description": "x coordinate representing center of the sketch
\n", "type": "Number", "optional": true }, { "name": "centerY", "description": "y coordinate representing center of the sketch
\n", "type": "Number", "optional": true }, { "name": "centerZ", "description": "z coordinate representing center of the sketch
\n", "type": "Number", "optional": true }, { "name": "upX", "description": "x component of direction 'up' from camera
\n", "type": "Number", "optional": true }, { "name": "upY", "description": "y component of direction 'up' from camera
\n", "type": "Number", "optional": true }, { "name": "upZ", "description": "z component of direction 'up' from camera
\n", "type": "Number", "optional": true } ], "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('a square moving closer and then away from the camera.');\n}\nfunction draw() {\n background(204);\n //move the camera away from the plane by a sin wave\n camera(0, 0, 20 + sin(frameCount * 0.01) * 10, 0, 0, 0, 0, 1, 0);\n plane(10, 10);\n}\n
\n\n//move slider to see changes!\n//sliders control the first 6 parameters of camera()\nlet sliderGroup = [];\nlet X;\nlet Y;\nlet Z;\nlet centerX;\nlet centerY;\nlet centerZ;\nlet h = 20;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n //create sliders\n for (var i = 0; i < 6; i++) {\n if (i === 2) {\n sliderGroup[i] = createSlider(10, 400, 200);\n } else {\n sliderGroup[i] = createSlider(-400, 400, 0);\n }\n h = map(i, 0, 6, 5, 85);\n sliderGroup[i].position(10, height + h);\n sliderGroup[i].style('width', '80px');\n }\n describe(\n 'White square repeatedly grows to fill canvas and then shrinks. An interactive example of a red cube with 3 sliders for moving it across x, y, z axis and 3 sliders for shifting its center.'\n );\n}\n\nfunction draw() {\n background(60);\n // assigning sliders' value to each parameters\n X = sliderGroup[0].value();\n Y = sliderGroup[1].value();\n Z = sliderGroup[2].value();\n centerX = sliderGroup[3].value();\n centerY = sliderGroup[4].value();\n centerZ = sliderGroup[5].value();\n camera(X, Y, Z, centerX, centerY, centerZ, 0, 1, 0);\n stroke(255);\n fill(255, 102, 94);\n box(85);\n}\n
\nSets a perspective projection for the current camera in a 3D sketch.\nThis projection represents depth through foreshortening: objects\nthat are close to the camera appear their actual size while those\nthat are further away from the camera appear smaller.
\nThe parameters to this function define the viewing frustum\n(the truncated pyramid within which objects are seen by the camera) through\nvertical field of view, aspect ratio (usually width/height), and near and far\nclipping planes.
\nIf no parameters are given, the following default is used:\nperspective(PI/3, width/height, eyeZ/10, eyeZ*10),\nwhere eyeZ is equal to ((height/2) / tan(PI/6)).
\n", "itemtype": "method", "name": "perspective", "params": [ { "name": "fovy", "description": "camera frustum vertical field of view,\n from bottom to top of view, in angleMode units
\n", "type": "Number", "optional": true }, { "name": "aspect", "description": "camera frustum aspect ratio
\n", "type": "Number", "optional": true }, { "name": "near", "description": "frustum near plane length
\n", "type": "Number", "optional": true }, { "name": "far", "description": "frustum far plane length
\n", "type": "Number", "optional": true } ], "chainable": 1, "example": [ "\n\n//drag the mouse to look around!\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n perspective(PI / 3.0, width / height, 0.1, 500);\n describe(\n 'two colored 3D boxes move back and forth, rotating as mouse is dragged.'\n );\n}\nfunction draw() {\n background(200);\n orbitControl();\n normalMaterial();\n\n rotateX(-0.3);\n rotateY(-0.2);\n translate(0, 0, -50);\n\n push();\n translate(-15, 0, sin(frameCount / 30) * 95);\n box(30);\n pop();\n push();\n translate(15, 0, sin(frameCount / 30 + PI) * 95);\n box(30);\n pop();\n}\n
\nSets an orthographic projection for the current camera in a 3D sketch\nand defines a box-shaped viewing frustum within which objects are seen.\nIn this projection, all objects with the same dimension appear the same\nsize, regardless of whether they are near or far from the camera.
\nThe parameters to this function specify the viewing frustum where\nleft and right are the minimum and maximum x values, top and bottom are\nthe minimum and maximum y values, and near and far are the minimum and\nmaximum z values.
\nIf no parameters are given, the following default is used:\northo(-width/2, width/2, -height/2, height/2).
\n", "itemtype": "method", "name": "ortho", "params": [ { "name": "left", "description": "camera frustum left plane
\n", "type": "Number", "optional": true }, { "name": "right", "description": "camera frustum right plane
\n", "type": "Number", "optional": true }, { "name": "bottom", "description": "camera frustum bottom plane
\n", "type": "Number", "optional": true }, { "name": "top", "description": "camera frustum top plane
\n", "type": "Number", "optional": true }, { "name": "near", "description": "camera frustum near plane
\n", "type": "Number", "optional": true }, { "name": "far", "description": "camera frustum far plane
\n", "type": "Number", "optional": true } ], "chainable": 1, "example": [ "\n\n//drag the mouse to look around!\n//there's no vanishing point\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n ortho(-width / 2, width / 2, height / 2, -height / 2, 0, 500);\n describe(\n 'two 3D boxes move back and forth along same plane, rotating as mouse is dragged.'\n );\n}\nfunction draw() {\n background(200);\n orbitControl();\n normalMaterial();\n\n rotateX(0.2);\n rotateY(-0.2);\n push();\n translate(-15, 0, sin(frameCount / 30) * 65);\n box(30);\n pop();\n push();\n translate(15, 0, sin(frameCount / 30 + PI) * 65);\n box(30);\n pop();\n}\n
\nSets the frustum of the current camera as defined by\nthe parameters.
\nA frustum is a geometric form: a pyramid with its top\ncut off. With the viewer's eye at the imaginary top of\nthe pyramid, the six planes of the frustum act as clipping\nplanes when rendering a 3D view. Thus, any form inside the\nclipping planes is visible; anything outside\nthose planes is not visible.
\nSetting the frustum changes the perspective of the scene being rendered.\nThis can be achieved more simply in many cases by using\nperspective().
\nIf no parameters are given, the following default is used:\nfrustum(-width/2, width/2, -height/2, height/2, 0, max(width, height)).
\n", "itemtype": "method", "name": "frustum", "params": [ { "name": "left", "description": "camera frustum left plane
\n", "type": "Number", "optional": true }, { "name": "right", "description": "camera frustum right plane
\n", "type": "Number", "optional": true }, { "name": "bottom", "description": "camera frustum bottom plane
\n", "type": "Number", "optional": true }, { "name": "top", "description": "camera frustum top plane
\n", "type": "Number", "optional": true }, { "name": "near", "description": "camera frustum near plane
\n", "type": "Number", "optional": true }, { "name": "far", "description": "camera frustum far plane
\n", "type": "Number", "optional": true } ], "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n setAttributes('antialias', true);\n frustum(-0.1, 0.1, -0.1, 0.1, 0.1, 200);\n describe(\n 'two 3D boxes move back and forth along same plane, rotating as mouse is dragged.'\n );\n}\nfunction draw() {\n background(200);\n orbitControl();\n normalMaterial();\n\n rotateY(-0.2);\n rotateX(-0.3);\n push();\n translate(-15, 0, sin(frameCount / 30) * 25);\n box(30);\n pop();\n push();\n translate(15, 0, sin(frameCount / 30 + PI) * 25);\n box(30);\n pop();\n}\n
\nCreates a new p5.Camera object and sets it\nas the current (active) camera.
\nThe new camera is initialized with a default position\n(see camera())\nand a default perspective projection\n(see perspective()).\nIts properties can be controlled with the p5.Camera\nmethods.
\nNote: Every 3D sketch starts with a default camera initialized.\nThis camera can be controlled with the global methods\ncamera(),\nperspective(), ortho(),\nand frustum() if it is the only camera\nin the scene.
\n", "itemtype": "method", "name": "createCamera", "return": { "description": "The newly created camera object.", "type": "p5.Camera" }, "example": [ "\n\n// Creates a camera object and animates it around a box.\nlet camera;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n background(0);\n camera = createCamera();\n describe('An example that creates a camera and moves it around the box.');\n}\n\nfunction draw() {\n camera.lookAt(0, 0, 0);\n camera.setPosition(sin(frameCount / 60) * 200, 0, 100);\n box(20);\n}\n
camera position value on x axis
\n", "itemtype": "property", "name": "eyeX", "type": "Number", "readonly": "", "example": [ "\n\n\nlet cam, div;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n background(0);\n cam = createCamera();\n div = createDiv();\n div.position(0, 0);\n describe('An example showing the use of camera object properties');\n}\n\nfunction draw() {\n orbitControl();\n box(10);\n div.html('eyeX = ' + cam.eyeX);\n}\n
camera position value on y axis
\n", "itemtype": "property", "name": "eyeY", "type": "Number", "readonly": "", "example": [ "\n\nlet cam, div;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n background(0);\n cam = createCamera();\n div = createDiv();\n div.position(0, 0);\n describe('An example showing the use of camera object properties');\n}\n\nfunction draw() {\n orbitControl();\n box(10);\n div.html('eyeY = ' + cam.eyeY);\n}\n
camera position value on z axis
\n", "itemtype": "property", "name": "eyeZ", "type": "Number", "readonly": "", "example": [ "\n\nlet cam, div;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n background(0);\n cam = createCamera();\n div = createDiv();\n div.position(0, 0);\n describe('An example showing the use of camera object properties');\n}\n\nfunction draw() {\n orbitControl();\n box(10);\n div.html('eyeZ = ' + cam.eyeZ);\n}\n
x coordinate representing center of the sketch
\n", "itemtype": "property", "name": "centerX", "type": "Number", "readonly": "", "example": [ "\n\nlet cam, div;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n background(255);\n cam = createCamera();\n cam.lookAt(1, 0, 0);\n div = createDiv('centerX = ' + cam.centerX);\n div.position(0, 0);\n div.style('color', 'white');\n describe('An example showing the use of camera object properties');\n}\n\nfunction draw() {\n orbitControl();\n box(10);\n}\n
y coordinate representing center of the sketch
\n", "itemtype": "property", "name": "centerY", "type": "Number", "readonly": "", "example": [ "\n\nlet cam, div;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n background(255);\n cam = createCamera();\n cam.lookAt(0, 1, 0);\n div = createDiv('centerY = ' + cam.centerY);\n div.position(0, 0);\n div.style('color', 'white');\n describe('An example showing the use of camera object properties');\n}\n\nfunction draw() {\n orbitControl();\n box(10);\n}\n
z coordinate representing center of the sketch
\n", "itemtype": "property", "name": "centerZ", "type": "Number", "readonly": "", "example": [ "\n\nlet cam, div;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n background(255);\n cam = createCamera();\n cam.lookAt(0, 0, 1);\n div = createDiv('centerZ = ' + cam.centerZ);\n div.position(0, 0);\n div.style('color', 'white');\n describe('An example showing the use of camera object properties');\n}\n\nfunction draw() {\n orbitControl();\n box(10);\n}\n
x component of direction 'up' from camera
\n", "itemtype": "property", "name": "upX", "type": "Number", "readonly": "", "example": [ "\n\nlet cam, div;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n background(255);\n cam = createCamera();\n div = createDiv('upX = ' + cam.upX);\n div.position(0, 0);\n div.style('color', 'blue');\n div.style('font-size', '18px');\n describe('An example showing the use of camera object properties');\n}\n
y component of direction 'up' from camera
\n", "itemtype": "property", "name": "upY", "type": "Number", "readonly": "", "example": [ "\n\nlet cam, div;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n background(255);\n cam = createCamera();\n div = createDiv('upY = ' + cam.upY);\n div.position(0, 0);\n div.style('color', 'blue');\n div.style('font-size', '18px');\n describe('An example showing the use of camera object properties');\n}\n
z component of direction 'up' from camera
\n", "itemtype": "property", "name": "upZ", "type": "Number", "readonly": "", "example": [ "\n\nlet cam, div;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n background(255);\n cam = createCamera();\n div = createDiv('upZ = ' + cam.upZ);\n div.position(0, 0);\n div.style('color', 'blue');\n div.style('font-size', '18px');\n describe('An example showing the use of camera object properties');\n}\n
Sets a perspective projection.\nAccepts the same parameters as the global\nperspective().\nMore information on this function can be found there.
\n", "itemtype": "method", "name": "perspective", "example": [ "\n\n// drag the mouse to look around!\n\nlet cam;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n // create a camera\n cam = createCamera();\n // give it a perspective projection\n cam.perspective(PI / 3.0, width / height, 0.1, 500);\n}\n\nfunction draw() {\n background(200);\n orbitControl();\n normalMaterial();\n\n rotateX(-0.3);\n rotateY(-0.2);\n translate(0, 0, -50);\n\n push();\n translate(-15, 0, sin(frameCount / 30) * 95);\n box(30);\n pop();\n push();\n translate(15, 0, sin(frameCount / 30 + PI) * 95);\n box(30);\n pop();\n}\n
\nSets an orthographic projection.\nAccepts the same parameters as the global\northo().\nMore information on this function can be found there.
\n", "itemtype": "method", "name": "ortho", "example": [ "\n\n// drag the mouse to look around!\n// there's no vanishing point\n\nlet cam;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n // create a camera\n cam = createCamera();\n // give it an orthographic projection\n cam.ortho(-width / 2, width / 2, height / 2, -height / 2, 0, 500);\n}\nfunction draw() {\n background(200);\n orbitControl();\n normalMaterial();\n\n rotateX(0.2);\n rotateY(-0.2);\n push();\n translate(-15, 0, sin(frameCount / 30) * 65);\n box(30);\n pop();\n push();\n translate(15, 0, sin(frameCount / 30 + PI) * 65);\n box(30);\n pop();\n}\n
\nSets the camera's frustum.\nAccepts the same parameters as the global\nfrustum().\nMore information on this function can be found there.
\n", "itemtype": "method", "name": "frustum", "example": [ "\n\nlet cam;\n\nfunction setup() {\n x = createCanvas(100, 100, WEBGL);\n setAttributes('antialias', true);\n // create a camera\n cam = createCamera();\n // set its frustum\n cam.frustum(-0.1, 0.1, -0.1, 0.1, 0.1, 200);\n}\n\nfunction draw() {\n background(200);\n orbitControl();\n normalMaterial();\n\n rotateY(-0.2);\n rotateX(-0.3);\n push();\n translate(-15, 0, sin(frameCount / 30) * 25);\n box(30);\n pop();\n push();\n translate(15, 0, sin(frameCount / 30 + PI) * 25);\n box(30);\n pop();\n}\n
\nPanning rotates the camera view to the left and right.
\n", "itemtype": "method", "name": "pan", "params": [ { "name": "angle", "description": "amount to rotate camera in current\nangleMode units.\nGreater than 0 values rotate counterclockwise (to the left).
\n", "type": "Number" } ], "example": [ "\n\nlet cam;\nlet delta = 0.01;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n // set initial pan angle\n cam.pan(-0.8);\n}\n\nfunction draw() {\n background(200);\n\n // pan camera according to angle 'delta'\n cam.pan(delta);\n\n // every 160 frames, switch direction\n if (frameCount % 160 === 0) {\n delta *= -1;\n }\n\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n
\nTilting rotates the camera view up and down.
\n", "itemtype": "method", "name": "tilt", "params": [ { "name": "angle", "description": "amount to rotate camera in current\nangleMode units.\nGreater than 0 values rotate counterclockwise (to the left).
\n", "type": "Number" } ], "example": [ "\n\nlet cam;\nlet delta = 0.01;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n // set initial tilt\n cam.tilt(-0.8);\n}\n\nfunction draw() {\n background(200);\n\n // pan camera according to angle 'delta'\n cam.tilt(delta);\n\n // every 160 frames, switch direction\n if (frameCount % 160 === 0) {\n delta *= -1;\n }\n\n rotateY(frameCount * 0.01);\n translate(0, -100, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n}\n
\nReorients the camera to look at a position in world space.
\n", "itemtype": "method", "name": "lookAt", "params": [ { "name": "x", "description": "x position of a point in world space
\n", "type": "Number" }, { "name": "y", "description": "y position of a point in world space
\n", "type": "Number" }, { "name": "z", "description": "z position of a point in world space
\n", "type": "Number" } ], "example": [ "\n\nlet cam;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n}\n\nfunction draw() {\n background(200);\n\n // look at a new random point every 60 frames\n if (frameCount % 60 === 0) {\n cam.lookAt(random(-100, 100), random(-50, 50), 0);\n }\n\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n
\nSets the camera's position and orientation.\nAccepts the same parameters as the global\ncamera().\nMore information on this function can be found there.
\n", "itemtype": "method", "name": "camera", "example": [ "\n\nlet cam;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n // Create a camera.\n // createCamera() sets the newly created camera as\n // the current (active) camera.\n cam = createCamera();\n}\n\nfunction draw() {\n background(204);\n // Move the camera away from the plane by a sin wave\n cam.camera(0, 0, 20 + sin(frameCount * 0.01) * 10, 0, 0, 0, 0, 1, 0);\n plane(10, 10);\n}\n
\n\n// move slider to see changes!\n// sliders control the first 6 parameters of camera()\n\nlet sliderGroup = [];\nlet X;\nlet Y;\nlet Z;\nlet centerX;\nlet centerY;\nlet centerZ;\nlet h = 20;\nlet cam;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n // create a camera\n cam = createCamera();\n // create sliders\n for (var i = 0; i < 6; i++) {\n if (i === 2) {\n sliderGroup[i] = createSlider(10, 400, 200);\n } else {\n sliderGroup[i] = createSlider(-400, 400, 0);\n }\n h = map(i, 0, 6, 5, 85);\n sliderGroup[i].position(10, height + h);\n sliderGroup[i].style('width', '80px');\n }\n}\n\nfunction draw() {\n background(60);\n // assigning sliders' value to each parameters\n X = sliderGroup[0].value();\n Y = sliderGroup[1].value();\n Z = sliderGroup[2].value();\n centerX = sliderGroup[3].value();\n centerY = sliderGroup[4].value();\n centerZ = sliderGroup[5].value();\n cam.camera(X, Y, Z, centerX, centerY, centerZ, 0, 1, 0);\n stroke(255);\n fill(255, 102, 94);\n box(85);\n}\n
\nMove camera along its local axes while maintaining current camera orientation.
\n", "itemtype": "method", "name": "move", "params": [ { "name": "x", "description": "amount to move along camera's left-right axis
\n", "type": "Number" }, { "name": "y", "description": "amount to move along camera's up-down axis
\n", "type": "Number" }, { "name": "z", "description": "amount to move along camera's forward-backward axis
\n", "type": "Number" } ], "example": [ "\n\n// see the camera move along its own axes while maintaining its orientation\nlet cam;\nlet delta = 0.5;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n}\n\nfunction draw() {\n background(200);\n\n // move the camera along its local axes\n cam.move(delta, delta, 0);\n\n // every 100 frames, switch direction\n if (frameCount % 150 === 0) {\n delta *= -1;\n }\n\n translate(-10, -10, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n}\n
\nSet camera position in world-space while maintaining current camera\norientation.
\n", "itemtype": "method", "name": "setPosition", "params": [ { "name": "x", "description": "x position of a point in world space
\n", "type": "Number" }, { "name": "y", "description": "y position of a point in world space
\n", "type": "Number" }, { "name": "z", "description": "z position of a point in world space
\n", "type": "Number" } ], "example": [ "\n\n// press '1' '2' or '3' keys to set camera position\n\nlet cam;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n}\n\nfunction draw() {\n background(200);\n\n // '1' key\n if (keyIsDown(49)) {\n cam.setPosition(30, 0, 80);\n }\n // '2' key\n if (keyIsDown(50)) {\n cam.setPosition(0, 0, 80);\n }\n // '3' key\n if (keyIsDown(51)) {\n cam.setPosition(-30, 0, 80);\n }\n\n box(20);\n}\n
\nSets the current (active) camera of a 3D sketch.\nAllows for switching between multiple cameras.
\n", "itemtype": "method", "name": "setCamera", "params": [ { "name": "cam", "description": "p5.Camera object
\n", "type": "p5.Camera" } ], "example": [ "\n\nlet cam1, cam2;\nlet currentCamera;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n\n cam1 = createCamera();\n cam2 = createCamera();\n cam2.setPosition(30, 0, 50);\n cam2.lookAt(0, 0, 0);\n cam2.ortho();\n\n // set variable for previously active camera:\n currentCamera = 1;\n\n describe(\n 'Canvas switches between two camera views, each showing a series of spinning 3D boxes.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // camera 1:\n cam1.lookAt(0, 0, 0);\n cam1.setPosition(sin(frameCount / 60) * 200, 0, 100);\n\n // every 100 frames, switch between the two cameras\n if (frameCount % 100 === 0) {\n if (currentCamera === 1) {\n setCamera(cam1);\n currentCamera = 0;\n } else {\n setCamera(cam2);\n currentCamera = 1;\n }\n }\n\n drawBoxes();\n}\n\nfunction drawBoxes() {\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n
\ncomputes faces for geometry objects based on the vertices.
\n", "itemtype": "method", "name": "computeFaces", "chainable": 1, "class": "p5.Geometry", "module": "Shape", "submodule": "3D Primitives" }, { "file": "src/webgl/p5.Geometry.js", "line": 114, "description": "computes smooth normals per vertex as an average of each\nface.
\n", "itemtype": "method", "name": "computeNormals", "chainable": 1, "class": "p5.Geometry", "module": "Shape", "submodule": "3D Primitives" }, { "file": "src/webgl/p5.Geometry.js", "line": 153, "description": "Averages the vertex normals. Used in curved\nsurfaces
\n", "itemtype": "method", "name": "averageNormals", "chainable": 1, "class": "p5.Geometry", "module": "Shape", "submodule": "3D Primitives" }, { "file": "src/webgl/p5.Geometry.js", "line": 174, "description": "Averages pole normals. Used in spherical primitives
\n", "itemtype": "method", "name": "averagePoleNormals", "chainable": 1, "class": "p5.Geometry", "module": "Shape", "submodule": "3D Primitives" }, { "file": "src/webgl/p5.Geometry.js", "line": 267, "description": "Modifies all vertices to be centered within the range -100 to 100.
\n", "itemtype": "method", "name": "normalize", "chainable": 1, "class": "p5.Geometry", "module": "Shape", "submodule": "3D Primitives" }, { "file": "src/webgl/p5.RendererGL.js", "line": 329, "description": "Set attributes for the WebGL Drawing context.\nThis is a way of adjusting how the WebGL\nrenderer works to fine-tune the display and performance.
\nNote that this will reinitialize the drawing context\nif called after the WebGL canvas is made.
\nIf an object is passed as the parameter, all attributes\nnot declared in the object will be set to defaults.
\nThe available attributes are:\n
\nalpha - indicates if the canvas contains an alpha buffer\ndefault is false
depth - indicates whether the drawing buffer has a depth buffer\nof at least 16 bits - default is true
\nstencil - indicates whether the drawing buffer has a stencil buffer\nof at least 8 bits
\nantialias - indicates whether or not to perform anti-aliasing\ndefault is false (true in Safari)
\npremultipliedAlpha - indicates that the page compositor will assume\nthe drawing buffer contains colors with pre-multiplied alpha\ndefault is false
\npreserveDrawingBuffer - if true the buffers will not be cleared and\nand will preserve their values until cleared or overwritten by author\n(note that p5 clears automatically on draw loop)\ndefault is true
\nperPixelLighting - if true, per-pixel lighting will be used in the\nlighting shader otherwise per-vertex lighting is used.\ndefault is true.
\n", "itemtype": "method", "name": "setAttributes", "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(255);\n push();\n rotateZ(frameCount * 0.02);\n rotateX(frameCount * 0.02);\n rotateY(frameCount * 0.02);\n fill(0, 0, 0);\n box(50);\n pop();\n}\n
\n\nfunction setup() {\n setAttributes('antialias', true);\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(255);\n push();\n rotateZ(frameCount * 0.02);\n rotateX(frameCount * 0.02);\n rotateY(frameCount * 0.02);\n fill(0, 0, 0);\n box(50);\n pop();\n}\n
\n\n// press the mouse button to disable perPixelLighting\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noStroke();\n fill(255);\n}\n\nlet lights = [\n { c: '#f00', t: 1.12, p: 1.91, r: 0.2 },\n { c: '#0f0', t: 1.21, p: 1.31, r: 0.2 },\n { c: '#00f', t: 1.37, p: 1.57, r: 0.2 },\n { c: '#ff0', t: 1.12, p: 1.91, r: 0.7 },\n { c: '#0ff', t: 1.21, p: 1.31, r: 0.7 },\n { c: '#f0f', t: 1.37, p: 1.57, r: 0.7 }\n];\n\nfunction draw() {\n let t = millis() / 1000 + 1000;\n background(0);\n directionalLight(color('#222'), 1, 1, 1);\n\n for (let i = 0; i < lights.length; i++) {\n let light = lights[i];\n pointLight(\n color(light.c),\n p5.Vector.fromAngles(t * light.t, t * light.p, width * light.r)\n );\n }\n\n specularMaterial(255);\n sphere(width * 0.1);\n\n rotateX(t * 0.77);\n rotateY(t * 0.83);\n rotateZ(t * 0.91);\n torus(width * 0.3, width * 0.07, 24, 10);\n}\n\nfunction mousePressed() {\n setAttributes('perPixelLighting', false);\n noStroke();\n fill(255);\n}\nfunction mouseReleased() {\n setAttributes('perPixelLighting', true);\n noStroke();\n fill(255);\n}\n
\nName of attribute
\n", "type": "String" }, { "name": "value", "description": "New value of named attribute
\n", "type": "Boolean" } ] }, { "line": 468, "params": [ { "name": "obj", "description": "object with key-value pairs
\n", "type": "Object" } ] } ] }, { "file": "src/webgl/p5.Shader.js", "line": 306, "description": "Used to set the uniforms of a\np5.Shader object.
\nUniforms are used as a way to provide shader programs\n(which run on the GPU) with values from a sketch\n(which runs on the CPU).
\n", "itemtype": "method", "name": "setUniform", "chainable": 1, "params": [ { "name": "uniformName", "description": "the name of the uniform.\nMust correspond to the name used in the vertex and fragment shaders
\n", "type": "String" }, { "name": "data", "description": "the data to associate with the uniform. The type can be\na boolean (true/false), a number, an array of numbers, or\nan image (p5.Image, p5.Graphics, p5.MediaElement, p5.Texture)
\n", "type": "Boolean|Number|Number[]|p5.Image|p5.Graphics|p5.MediaElement|p5.Texture" } ], "example": [ "\n\n// Click within the image to toggle the value of uniforms\n// Note: for an alternative approach to the same example,\n// involving toggling between shaders please refer to:\n// https://p5js.org/reference/#/p5/shader\n\nlet grad;\nlet showRedGreen = false;\n\nfunction preload() {\n // note that we are using two instances\n // of the same vertex and fragment shaders\n grad = loadShader('assets/shader.vert', 'assets/shader-gradient.frag');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n shader(grad);\n noStroke();\n\n describe(\n 'canvas toggles between a circular gradient of orange and blue vertically. and a circular gradient of red and green moving horizontally when mouse is clicked/pressed.'\n );\n}\n\nfunction draw() {\n // update the offset values for each scenario,\n // moving the \"grad\" shader in either vertical or\n // horizontal direction each with differing colors\n\n if (showRedGreen === true) {\n grad.setUniform('colorCenter', [1, 0, 0]);\n grad.setUniform('colorBackground', [0, 1, 0]);\n grad.setUniform('offset', [sin(millis() / 2000), 1]);\n } else {\n grad.setUniform('colorCenter', [1, 0.5, 0]);\n grad.setUniform('colorBackground', [0.226, 0, 0.615]);\n grad.setUniform('offset', [0, sin(millis() / 2000) + 1]);\n }\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n\nfunction mouseClicked() {\n showRedGreen = !showRedGreen;\n}\n
\np5.sound \nhttps://p5js.org/reference/#/libraries/p5.sound
\nFrom the Processing Foundation and contributors\nhttps://github.com/processing/p5.js-sound/graphs/contributors
\nMIT License (MIT)\nhttps://github.com/processing/p5.js-sound/blob/master/LICENSE
\nSome of the many audio libraries & resources that inspire p5.sound:
\nWeb Audio API: http://w3.org/TR/webaudio/
\n", "class": "p5.sound", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 159, "description": "Returns the Audio Context for this sketch. Useful for users\nwho would like to dig deeper into the Web Audio API\n.
\n\nSome browsers require users to startAudioContext\nwith a user gesture, such as touchStarted in the example below.
", "itemtype": "method", "name": "getAudioContext", "return": { "description": "AudioContext for this sketch", "type": "Object" }, "example": [ "\n\n function draw() {\n background(255);\n textAlign(CENTER);\n\n if (getAudioContext().state !== 'running') {\n text('click to start audio', width/2, height/2);\n } else {\n text('audio is enabled', width/2, height/2);\n }\n }\n\n function touchStarted() {\n if (getAudioContext().state !== 'running') {\n getAudioContext().resume();\n }\n var synth = new p5.MonoSynth();\n synth.play('A4', 0.5, 0, 0.2);\n }\n\n
It is not only a good practice to give users control over starting\naudio. This policy is enforced by many web browsers, including iOS and\nGoogle Chrome, which create the Web Audio API's\nAudio Context\nin a suspended state.
\n\nIn these browser-specific policies, sound will not play until a user\ninteraction event (i.e. mousePressed()
) explicitly resumes\nthe AudioContext, or starts an audio node. This can be accomplished by\ncalling start()
on a p5.Oscillator
,\n play()
on a p5.SoundFile
, or simply\nuserStartAudio()
.
userStartAudio()
starts the AudioContext on a user\ngesture. The default behavior will enable audio on any\nmouseUp or touchEnd event. It can also be placed in a specific\ninteraction function, such as mousePressed()
as in the\nexample below. This method utilizes\nStartAudioContext\n, a library by Yotam Mann (MIT Licence, 2016).
This argument can be an Element,\n Selector String, NodeList, p5.Element,\n jQuery Element, or an Array of any of those.
\n", "type": "Element|Array", "optional": true }, { "name": "callback", "description": "Callback to invoke when the AudioContext\n has started
\n", "type": "Function", "optional": true } ], "return": { "description": "Returns a Promise that resolves when\n the AudioContext state is 'running'", "type": "Promise" }, "itemtype": "method", "name": "userStartAudio", "example": [ "\n\nfunction setup() {\n // mimics the autoplay policy\n getAudioContext().suspend();\n\n let mySynth = new p5.MonoSynth();\n\n // This won't play until the context has resumed\n mySynth.play('A6');\n}\nfunction draw() {\n background(220);\n textAlign(CENTER, CENTER);\n text(getAudioContext().state, width/2, height/2);\n}\nfunction mousePressed() {\n userStartAudio();\n}\n
This module has shims
\n", "class": "p5", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 536, "description": "Determine which filetypes are supported (inspired by buzz.js)\nThe audio element (el) will only be used to test browser support for various audio formats
\n", "class": "p5", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 726, "description": "Returns a number representing the output volume for sound\nin this sketch.
\n", "itemtype": "method", "name": "getOutputVolume", "return": { "description": "Output volume for sound in this sketch.\n Should be between 0.0 (silence) and 1.0.", "type": "Number" }, "class": "p5", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 738, "description": "Scale the output of all sound in this sketch
\nScaled between 0.0 (silence) and 1.0 (full volume).\n1.0 is the maximum amplitude of a digital sound, so multiplying\nby greater than 1.0 may cause digital distortion. To\nfade, provide arampTime
parameter. For more\ncomplex fades, see the Envelope class.\n\nAlternately, you can pass in a signal source such as an\noscillator to modulate the amplitude with an audio signal.
\nHow This Works: When you load the p5.sound module, it\ncreates a single instance of p5sound. All sound objects in this\nmodule output to p5sound before reaching your computer's output.\nSo if you change the amplitude of p5sound, it impacts all of the\nsound in this module.
\n\nIf no value is provided, returns a Web Audio API Gain Node
", "itemtype": "method", "name": "outputVolume", "params": [ { "name": "volume", "description": "Volume (amplitude) between 0.0\n and 1.0 or modulating signal/oscillator
\n", "type": "Number|Object" }, { "name": "rampTime", "description": "Fade for t seconds
\n", "type": "Number", "optional": true }, { "name": "timeFromNow", "description": "Schedule this event to happen at\n t seconds in the future
\n", "type": "Number", "optional": true } ], "class": "p5", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 782, "description": "p5.soundOut
is the p5.sound final output bus. It sends output to\nthe destination of this window's web audio context. It contains\nWeb Audio API nodes including a dyanmicsCompressor (.limiter
),\nand Gain Nodes for .input
and .output
.
Returns a number representing the sample rate, in samples per second,\nof all sound objects in this audio context. It is determined by the\nsampling rate of your operating system's sound card, and it is not\ncurrently possile to change.\nIt is often 44100, or twice the range of human hearing.
\n", "itemtype": "method", "name": "sampleRate", "return": { "description": "samplerate samples per second", "type": "Number" }, "class": "p5", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 825, "description": "Returns the closest MIDI note value for\na given frequency.
\n", "itemtype": "method", "name": "freqToMidi", "params": [ { "name": "frequency", "description": "A freqeuncy, for example, the \"A\"\n above Middle C is 440Hz
\n", "type": "Number" } ], "return": { "description": "MIDI note value", "type": "Number" }, "class": "p5", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 841, "description": "Returns the frequency value of a MIDI note value.\nGeneral MIDI treats notes as integers where middle C\nis 60, C# is 61, D is 62 etc. Useful for generating\nmusical frequencies with oscillators.
\n", "itemtype": "method", "name": "midiToFreq", "params": [ { "name": "midiNote", "description": "The number of a MIDI note
\n", "type": "Number" } ], "return": { "description": "Frequency value of the given MIDI note", "type": "Number" }, "example": [ "\n\nlet midiNotes = [60, 64, 67, 72];\nlet noteIndex = 0;\nlet midiVal, freq;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(startSound);\n osc = new p5.TriOsc();\n env = new p5.Envelope();\n}\n\nfunction draw() {\n background(220);\n text('tap to play', 10, 20);\n if (midiVal) {\n text('MIDI: ' + midiVal, 10, 40);\n text('Freq: ' + freq, 10, 60);\n }\n}\n\nfunction startSound() {\n // see also: userStartAudio();\n osc.start();\n\n midiVal = midiNotes[noteIndex % midiNotes.length];\n freq = midiToFreq(midiVal);\n osc.freq(freq);\n env.ramp(osc, 0, 1.0, 0);\n\n noteIndex++;\n}\n
List the SoundFile formats that you will include. LoadSound\nwill search your directory for these extensions, and will pick\na format that is compatable with the client's web browser.\nHere is a free online file\nconverter.
\n", "itemtype": "method", "name": "soundFormats", "params": [ { "name": "formats", "description": "i.e. 'mp3', 'wav', 'ogg'
\n", "type": "String", "optional": true, "multiple": true } ], "example": [ "\n\nfunction preload() {\n // set the global sound formats\n soundFormats('mp3', 'ogg');\n\n // load either beatbox.mp3, or .ogg, depending on browser\n mySound = loadSound('assets/beatbox.mp3');\n}\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n background(220);\n text('sound loaded! tap to play', 10, 20, width - 20);\n cnv.mousePressed(function() {\n mySound.play();\n });\n }\n
Used by Osc and Envelope to chain signal math
\n", "class": "p5", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 1145, "description": "Save a p5.SoundFile as a .wav file. The browser will prompt the user\nto download the file to their device.\nFor uploading audio to a server, use\np5.SoundFile.saveBlob
.
p5.SoundFile that you wish to save
\n", "type": "p5.SoundFile" }, { "name": "fileName", "description": "name of the resulting .wav file.
\n", "type": "String" } ], "class": "p5", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 1662, "description": "Returns true if the sound file finished loading successfully.
\n", "itemtype": "method", "name": "isLoaded", "return": { "description": "", "type": "Boolean" }, "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 1679, "description": "Play the p5.SoundFile
\n", "itemtype": "method", "name": "play", "params": [ { "name": "startTime", "description": "(optional) schedule playback to start (in seconds from now).
\n", "type": "Number", "optional": true }, { "name": "rate", "description": "(optional) playback rate
\n", "type": "Number", "optional": true }, { "name": "amp", "description": "(optional) amplitude (volume)\n of playback
\n", "type": "Number", "optional": true }, { "name": "cueStart", "description": "(optional) cue start time in seconds
\n", "type": "Number", "optional": true }, { "name": "duration", "description": "(optional) duration of playback in seconds
\n", "type": "Number", "optional": true } ], "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 1787, "description": "p5.SoundFile has two play modes: restart
and\nsustain
. Play Mode determines what happens to a\np5.SoundFile if it is triggered while in the middle of playback.\nIn sustain mode, playback will continue simultaneous to the\nnew playback. In restart mode, play() will stop playback\nand start over. With untilDone, a sound will play only if it's\nnot already playing. Sustain is the default mode.
'restart' or 'sustain' or 'untilDone'
\n", "type": "String" } ], "example": [ "\n\nlet mySound;\nfunction preload(){\n mySound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(canvasPressed);\n noFill();\n rect(0, height/2, width - 1, height/2 - 1);\n rect(0, 0, width - 1, height/2);\n textAlign(CENTER, CENTER);\n fill(20);\n text('restart', width/2, 1 * height/4);\n text('sustain', width/2, 3 * height/4);\n}\nfunction canvasPressed() {\n if (mouseX < height/2) {\n mySound.playMode('restart');\n } else {\n mySound.playMode('sustain');\n }\n mySound.play();\n}\n\n
Pauses a file that is currently playing. If the file is not\nplaying, then nothing will happen.
\nAfter pausing, .play() will resume from the paused\nposition.\nIf p5.SoundFile had been set to loop before it was paused,\nit will continue to loop after it is unpaused with .play().
\n", "itemtype": "method", "name": "pause", "params": [ { "name": "startTime", "description": "(optional) schedule event to occur\n seconds from now
\n", "type": "Number", "optional": true } ], "example": [ "\n\nlet soundFile;\nfunction preload() {\n soundFormats('ogg', 'mp3');\n soundFile = loadSound('assets/Damscray_-_Dancing_Tiger_02.mp3');\n}\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(canvasPressed);\n background(220);\n text('tap to play, release to pause', 10, 20, width - 20);\n}\nfunction canvasPressed() {\n soundFile.loop();\n background(0, 200, 50);\n}\nfunction mouseReleased() {\n soundFile.pause();\n background(220);\n}\n
\nLoop the p5.SoundFile. Accepts optional parameters to set the\nplayback rate, playback volume, loopStart, loopEnd.
\n", "itemtype": "method", "name": "loop", "params": [ { "name": "startTime", "description": "(optional) schedule event to occur\n seconds from now
\n", "type": "Number", "optional": true }, { "name": "rate", "description": "(optional) playback rate
\n", "type": "Number", "optional": true }, { "name": "amp", "description": "(optional) playback volume
\n", "type": "Number", "optional": true }, { "name": "cueLoopStart", "description": "(optional) startTime in seconds
\n", "type": "Number", "optional": true }, { "name": "duration", "description": "(optional) loop duration in seconds
\n", "type": "Number", "optional": true } ], "example": [ "\n\n let soundFile;\n let loopStart = 0.5;\n let loopDuration = 0.2;\n function preload() {\n soundFormats('ogg', 'mp3');\n soundFile = loadSound('assets/Damscray_-_Dancing_Tiger_02.mp3');\n }\n function setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(canvasPressed);\n background(220);\n text('tap to play, release to pause', 10, 20, width - 20);\n }\n function canvasPressed() {\n soundFile.loop();\n background(0, 200, 50);\n }\n function mouseReleased() {\n soundFile.pause();\n background(220);\n }\n
\n Set a p5.SoundFile's looping flag to true or false. If the sound\nis currently playing, this change will take effect when it\nreaches the end of the current playback.
\n", "itemtype": "method", "name": "setLoop", "params": [ { "name": "Boolean", "description": "set looping to true or false
\n", "type": "Boolean" } ], "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 1976, "description": "Returns 'true' if a p5.SoundFile is currently looping and playing, 'false' if not.
\n", "itemtype": "method", "name": "isLooping", "return": { "description": "", "type": "Boolean" }, "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 1997, "description": "Returns true if a p5.SoundFile is playing, false if not (i.e.\npaused or stopped).
\n", "itemtype": "method", "name": "isPlaying", "return": { "description": "", "type": "Boolean" }, "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 2011, "description": "Returns true if a p5.SoundFile is paused, false if not (i.e.\nplaying or stopped).
\n", "itemtype": "method", "name": "isPaused", "return": { "description": "", "type": "Boolean" }, "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 2025, "description": "Stop soundfile playback.
\n", "itemtype": "method", "name": "stop", "params": [ { "name": "startTime", "description": "(optional) schedule event to occur\n in seconds from now
\n", "type": "Number", "optional": true } ], "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 2087, "description": "Set the stereo panning of a p5.sound object to\na floating point number between -1.0 (left) and 1.0 (right).\nDefault is 0.0 (center).
\n", "itemtype": "method", "name": "pan", "params": [ { "name": "panValue", "description": "Set the stereo panner
\n", "type": "Number", "optional": true }, { "name": "timeFromNow", "description": "schedule this event to happen\n seconds from now
\n", "type": "Number", "optional": true } ], "example": [ "\n\n let ballX = 0;\n let soundFile;\n\n function preload() {\n soundFormats('ogg', 'mp3');\n soundFile = loadSound('assets/beatbox.mp3');\n }\n\n function draw() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(canvasPressed);\n background(220);\n ballX = constrain(mouseX, 0, width);\n ellipse(ballX, height/2, 20, 20);\n }\n\n function canvasPressed(){\n // map the ball's x location to a panning degree\n // between -1.0 (left) and 1.0 (right)\n let panning = map(ballX, 0., width,-1.0, 1.0);\n soundFile.pan(panning);\n soundFile.play();\n }\n
Returns the current stereo pan position (-1.0 to 1.0)
\n", "itemtype": "method", "name": "getPan", "return": { "description": "Returns the stereo pan setting of the Oscillator\n as a number between -1.0 (left) and 1.0 (right).\n 0.0 is center and default.", "type": "Number" }, "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 2146, "description": "Set the playback rate of a sound file. Will change the speed and the pitch.\nValues less than zero will reverse the audio buffer.
\n", "itemtype": "method", "name": "rate", "params": [ { "name": "playbackRate", "description": "Set the playback rate. 1.0 is normal,\n .5 is half-speed, 2.0 is twice as fast.\n Values less than zero play backwards.
\n", "type": "Number", "optional": true } ], "example": [ "\n\nlet mySound;\n\nfunction preload() {\n mySound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(canvasPressed);\n}\nfunction canvasPressed() {\n mySound.loop();\n}\nfunction mouseReleased() {\n mySound.pause();\n}\nfunction draw() {\n background(220);\n\n // Set the rate to a range between 0.1 and 4\n // Changing the rate also alters the pitch\n let playbackRate = map(mouseY, 0.1, height, 2, 0);\n playbackRate = constrain(playbackRate, 0.01, 4);\n mySound.rate(playbackRate);\n\n line(0, mouseY, width, mouseY);\n text('rate: ' + round(playbackRate * 100) + '%', 10, 20);\n}\n\n
\n Multiply the output volume (amplitude) of a sound file\nbetween 0.0 (silence) and 1.0 (full volume).\n1.0 is the maximum amplitude of a digital sound, so multiplying\nby greater than 1.0 may cause digital distortion. To\nfade, provide a rampTime
parameter. For more\ncomplex fades, see the Envelope class.
Alternately, you can pass in a signal source such as an\noscillator to modulate the amplitude with an audio signal.
\n", "itemtype": "method", "name": "setVolume", "params": [ { "name": "volume", "description": "Volume (amplitude) between 0.0\n and 1.0 or modulating signal/oscillator
\n", "type": "Number|Object" }, { "name": "rampTime", "description": "Fade for t seconds
\n", "type": "Number", "optional": true }, { "name": "timeFromNow", "description": "Schedule this event to happen at\n t seconds in the future
\n", "type": "Number", "optional": true } ], "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 2276, "description": "Returns the duration of a sound file in seconds.
\n", "itemtype": "method", "name": "duration", "return": { "description": "The duration of the soundFile in seconds.", "type": "Number" }, "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 2293, "description": "Return the current position of the p5.SoundFile playhead, in seconds.\nTime is relative to the normal buffer direction, so if reverseBuffer
\nhas been called, currentTime will count backwards.
Move the playhead of a soundfile that is currently playing to a\nnew position and a new duration, in seconds.\nIf none are given, will reset the file to play entire duration\nfrom start to finish. To set the position of a soundfile that is\nnot currently playing, use the play
or loop
methods.
cueTime of the soundFile in seconds.
\n", "type": "Number" }, { "name": "duration", "description": "duration in seconds.
\n", "type": "Number" } ], "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 2340, "description": "Return the number of channels in a sound file.\nFor example, Mono = 1, Stereo = 2.
\n", "itemtype": "method", "name": "channels", "return": { "description": "[channels]", "type": "Number" }, "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 2354, "description": "Return the sample rate of the sound file.
\n", "itemtype": "method", "name": "sampleRate", "return": { "description": "[sampleRate]", "type": "Number" }, "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 2367, "description": "Return the number of samples in a sound file.\nEqual to sampleRate * duration.
\n", "itemtype": "method", "name": "frames", "return": { "description": "[sampleCount]", "type": "Number" }, "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 2381, "description": "Returns an array of amplitude peaks in a p5.SoundFile that can be\nused to draw a static waveform. Scans through the p5.SoundFile's\naudio buffer to find the greatest amplitudes. Accepts one\nparameter, 'length', which determines size of the array.\nLarger arrays result in more precise waveform visualizations.
\nInspired by Wavesurfer.js.
\n", "itemtype": "method", "name": "getPeaks", "params": [ { "name": "length", "description": "length is the size of the returned array.\n Larger length results in more precision.\n Defaults to 5*width of the browser window.
\n", "type": "Number", "optional": true } ], "return": { "description": "Array of peaks.", "type": "Float32Array" }, "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 2443, "description": "Reverses the p5.SoundFile's buffer source.\nPlayback must be handled separately (see example).
\n", "itemtype": "method", "name": "reverseBuffer", "example": [ "\n\nlet drum;\nfunction preload() {\n drum = loadSound('assets/drum.mp3');\n}\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(canvasPressed);\n background(220);\n text('tap to play', 20, 20);\n}\n\nfunction canvasPressed() {\n drum.stop();\n drum.reverseBuffer();\n drum.play();\n}\n
\n Schedule an event to be called when the soundfile\nreaches the end of a buffer. If the soundfile is\nplaying through once, this will be called when it\nends. If it is looping, it will be called when\nstop is called.
\n", "itemtype": "method", "name": "onended", "params": [ { "name": "callback", "description": "function to call when the\n soundfile has ended.
\n", "type": "Function" } ], "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 2565, "description": "Connects the output of a p5sound object to input of another\np5.sound object. For example, you may connect a p5.SoundFile to an\nFFT or an Effect. If no parameter is given, it will connect to\nthe main output. Most p5sound objects connect to the master\noutput when they are created.
\n", "itemtype": "method", "name": "connect", "params": [ { "name": "object", "description": "Audio object that accepts an input
\n", "type": "Object", "optional": true } ], "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 2590, "description": "Disconnects the output of this p5sound object.
\n", "itemtype": "method", "name": "disconnect", "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 2604, "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 2612, "description": "Reset the source for this SoundFile to a\nnew path (URL).
\n", "itemtype": "method", "name": "setPath", "params": [ { "name": "path", "description": "path to audio file
\n", "type": "String" }, { "name": "callback", "description": "Callback
\n", "type": "Function" } ], "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 2630, "description": "Replace the current Audio Buffer with a new Buffer.
\n", "itemtype": "method", "name": "setBuffer", "params": [ { "name": "buf", "description": "Array of Float32 Array(s). 2 Float32 Arrays\n will create a stereo source. 1 will create\n a mono source.
\n", "type": "Array" } ], "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 2719, "description": "Schedule events to trigger every time a MediaElement\n(audio/video) reaches a playback cue point.
\nAccepts a callback function, a time (in seconds) at which to trigger\nthe callback, and an optional parameter for the callback.
\nTime will be passed as the first parameter to the callback function,\nand param will be the second parameter.
\n", "itemtype": "method", "name": "addCue", "params": [ { "name": "time", "description": "Time in seconds, relative to this media\n element's playback. For example, to trigger\n an event every time playback reaches two\n seconds, pass in the number 2. This will be\n passed as the first parameter to\n the callback function.
\n", "type": "Number" }, { "name": "callback", "description": "Name of a function that will be\n called at the given time. The callback will\n receive time and (optionally) param as its\n two parameters.
\n", "type": "Function" }, { "name": "value", "description": "An object to be passed as the\n second parameter to the\n callback function.
\n", "type": "Object", "optional": true } ], "return": { "description": "id ID of this cue,\n useful for removeCue(id)", "type": "Number" }, "example": [ "\n\nlet mySound;\nfunction preload() {\n mySound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(canvasPressed);\n background(220);\n text('tap to play', 10, 20);\n\n // schedule calls to changeText\n mySound.addCue(0, changeText, \"hello\" );\n mySound.addCue(0.5, changeText, \"hello,\" );\n mySound.addCue(1, changeText, \"hello, p5!\");\n mySound.addCue(1.5, changeText, \"hello, p5!!\");\n mySound.addCue(2, changeText, \"hello, p5!!!!!\");\n}\n\nfunction changeText(val) {\n background(220);\n text(val, 10, 20);\n}\n\nfunction canvasPressed() {\n mySound.play();\n}\n
Remove a callback based on its ID. The ID is returned by the\naddCue method.
\n", "itemtype": "method", "name": "removeCue", "params": [ { "name": "id", "description": "ID of the cue, as returned by addCue
\n", "type": "Number" } ], "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 2817, "description": "Remove all of the callbacks that had originally been scheduled\nvia the addCue method.
\n", "itemtype": "method", "name": "clearCues", "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 2850, "description": "Save a p5.SoundFile as a .wav file. The browser will prompt the user\nto download the file to their device. To upload a file to a server, see\ngetBlob
\n", "itemtype": "method", "name": "save", "params": [ { "name": "fileName", "description": "name of the resulting .wav file.
\n", "type": "String", "optional": true } ], "example": [ "\n\n let mySound;\n function preload() {\n mySound = loadSound('assets/doorbell.mp3');\n }\n function setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(canvasPressed);\n background(220);\n text('tap to download', 10, 20);\n }\n\n function canvasPressed() {\n mySound.save('my cool filename');\n }\n
This method is useful for sending a SoundFile to a server. It returns the\n.wav-encoded audio data as a \"Blob\".\nA Blob is a file-like data object that can be uploaded to a server\nwith an http request. We'll\nuse the httpDo
options object to send a POST request with some\nspecific options: we encode the request as multipart/form-data
,\nand attach the blob as one of the form values using FormData
.
\n function preload() {\n mySound = loadSound('assets/doorbell.mp3');\n }\n\n function setup() {\n noCanvas();\n let soundBlob = mySound.getBlob();\n\n // Now we can send the blob to a server...\n let serverUrl = 'https://jsonplaceholder.typicode.com/posts';\n let httpRequestOptions = {\n method: 'POST',\n body: new FormData().append('soundBlob', soundBlob),\n headers: new Headers({\n 'Content-Type': 'multipart/form-data'\n })\n };\n httpDo(serverUrl, httpRequestOptions);\n\n // We can also create an `ObjectURL` pointing to the Blob\n let blobUrl = URL.createObjectURL(soundBlob);\n\n // The `
loadSound() returns a new p5.SoundFile from a specified\npath. If called during preload(), the p5.SoundFile will be ready\nto play in time for setup() and draw(). If called outside of\npreload, the p5.SoundFile will not be ready immediately, so\nloadSound accepts a callback as the second parameter. Using a\n\nlocal server is recommended when loading external files.
\n", "itemtype": "method", "name": "loadSound", "params": [ { "name": "path", "description": "Path to the sound file, or an array with\n paths to soundfiles in multiple formats\n i.e. ['sound.ogg', 'sound.mp3'].\n Alternately, accepts an object: either\n from the HTML5 File API, or a p5.File.
\n", "type": "String|Array" }, { "name": "successCallback", "description": "Name of a function to call once file loads
\n", "type": "Function", "optional": true }, { "name": "errorCallback", "description": "Name of a function to call if there is\n an error loading the file.
\n", "type": "Function", "optional": true }, { "name": "whileLoading", "description": "Name of a function to call while file is loading.\n This function will receive the percentage loaded\n so far, from 0.0 to 1.0.
\n", "type": "Function", "optional": true } ], "return": { "description": "Returns a p5.SoundFile", "type": "SoundFile" }, "example": [ "\n\nlet mySound;\nfunction preload() {\n soundFormats('mp3', 'ogg');\n mySound = loadSound('assets/doorbell');\n}\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(canvasPressed);\n background(220);\n text('tap here to play', 10, 20);\n}\n\nfunction canvasPressed() {\n // playing a sound file on a user gesture\n // is equivalent to `userStartAudio()`\n mySound.play();\n}\n
Connects to the p5sound instance (main output) by default.\nOptionally, you can pass in a specific source (i.e. a soundfile).
\n", "itemtype": "method", "name": "setInput", "params": [ { "name": "snd", "description": "set the sound source\n (optional, defaults to\n main output)
\n", "type": "SoundObject|undefined", "optional": true }, { "name": "smoothing", "description": "a range between 0.0 and 1.0\n to smooth amplitude readings
\n", "type": "Number|undefined", "optional": true } ], "example": [ "\n\nfunction preload(){\n sound1 = loadSound('assets/beat.mp3');\n sound2 = loadSound('assets/drum.mp3');\n}\nfunction setup(){\n cnv = createCanvas(100, 100);\n cnv.mouseClicked(toggleSound);\n\n amplitude = new p5.Amplitude();\n amplitude.setInput(sound2);\n}\n\nfunction draw() {\n background(220);\n text('tap to play', 20, 20);\n\n let level = amplitude.getLevel();\n let size = map(level, 0, 1, 0, 200);\n ellipse(width/2, height/2, size, size);\n}\n\nfunction toggleSound(){\n if (sound1.isPlaying() && sound2.isPlaying()) {\n sound1.stop();\n sound2.stop();\n } else {\n sound1.play();\n sound2.play();\n }\n}\n
Returns a single Amplitude reading at the moment it is called.\nFor continuous readings, run in the draw loop.
\n", "itemtype": "method", "name": "getLevel", "params": [ { "name": "channel", "description": "Optionally return only channel 0 (left) or 1 (right)
\n", "type": "Number", "optional": true } ], "return": { "description": "Amplitude as a number between 0.0 and 1.0", "type": "Number" }, "example": [ "\n\nfunction preload(){\n sound = loadSound('assets/beat.mp3');\n}\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mouseClicked(toggleSound);\n amplitude = new p5.Amplitude();\n}\n\nfunction draw() {\n background(220, 150);\n textAlign(CENTER);\n text('tap to play', width/2, 20);\n\n let level = amplitude.getLevel();\n let size = map(level, 0, 1, 0, 200);\n ellipse(width/2, height/2, size, size);\n}\n\nfunction toggleSound(){\n if (sound.isPlaying()) {\n sound.stop();\n } else {\n sound.play();\n }\n}\n
Determines whether the results of Amplitude.process() will be\nNormalized. To normalize, Amplitude finds the difference the\nloudest reading it has processed and the maximum amplitude of\n1.0. Amplitude adds this difference to all values to produce\nresults that will reliably map between 0.0 and 1.0. However,\nif a louder moment occurs, the amount that Normalize adds to\nall the values will change. Accepts an optional boolean parameter\n(true or false). Normalizing is off by default.
\n", "itemtype": "method", "name": "toggleNormalize", "params": [ { "name": "boolean", "description": "set normalize to true (1) or false (0)
\n", "type": "Boolean", "optional": true } ], "class": "p5.Amplitude", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 3293, "description": "Smooth Amplitude analysis by averaging with the last analysis\nframe. Off by default.
\n", "itemtype": "method", "name": "smooth", "params": [ { "name": "set", "description": "smoothing from 0.0 <= 1
\n", "type": "Number" } ], "class": "p5.Amplitude", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 3476, "description": "Set the input source for the FFT analysis. If no source is\nprovided, FFT will analyze all sound in the sketch.
\n", "itemtype": "method", "name": "setInput", "params": [ { "name": "source", "description": "p5.sound object (or web audio API source node)
\n", "type": "Object", "optional": true } ], "class": "p5.FFT", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 3501, "description": "Returns an array of amplitude values (between -1.0 and +1.0) that represent\na snapshot of amplitude readings in a single buffer. Length will be\nequal to bins (defaults to 1024). Can be used to draw the waveform\nof a sound.
\n", "itemtype": "method", "name": "waveform", "params": [ { "name": "bins", "description": "Must be a power of two between\n 16 and 1024. Defaults to 1024.
\n", "type": "Number", "optional": true }, { "name": "precision", "description": "If any value is provided, will return results\n in a Float32 Array which is more precise\n than a regular array.
\n", "type": "String", "optional": true } ], "return": { "description": "Array Array of amplitude values (-1 to 1)\n over time. Array length = bins.", "type": "Array" }, "class": "p5.FFT", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 3553, "description": "Returns an array of amplitude values (between 0 and 255)\nacross the frequency spectrum. Length is equal to FFT bins\n(1024 by default). The array indices correspond to frequencies\n(i.e. pitches), from the lowest to the highest that humans can\nhear. Each value represents amplitude at that slice of the\nfrequency spectrum. Must be called prior to using\ngetEnergy()
.
Must be a power of two between\n 16 and 1024. Defaults to 1024.
\n", "type": "Number", "optional": true }, { "name": "scale", "description": "If \"dB,\" returns decibel\n float measurements between\n -140 and 0 (max).\n Otherwise returns integers from 0-255.
\n", "type": "Number", "optional": true } ], "return": { "description": "spectrum Array of energy (amplitude/volume)\n values across the frequency spectrum.\n Lowest energy (silence) = 0, highest\n possible is 255.", "type": "Array" }, "example": [ "\n\nlet osc, fft;\n\nfunction setup(){\n let cnv = createCanvas(100,100);\n cnv.mousePressed(startSound);\n osc = new p5.Oscillator();\n osc.amp(0);\n fft = new p5.FFT();\n}\n\nfunction draw(){\n background(220);\n\n let freq = map(mouseX, 0, windowWidth, 20, 10000);\n freq = constrain(freq, 1, 20000);\n osc.freq(freq);\n\n let spectrum = fft.analyze();\n noStroke();\n fill(255, 0, 255);\n for (let i = 0; i< spectrum.length; i++){\n let x = map(i, 0, spectrum.length, 0, width);\n let h = -height + map(spectrum[i], 0, 255, height, 0);\n rect(x, height, width / spectrum.length, h );\n }\n\n stroke(255);\n if (!osc.started) {\n text('tap here and drag to change frequency', 10, 20, width - 20);\n } else {\n text(round(freq)+'Hz', 10, 20);\n }\n}\n\nfunction startSound() {\n osc.start();\n osc.amp(0.5, 0.2);\n}\n\nfunction mouseReleased() {\n osc.amp(0, 0.2);\n}\n
Returns the amount of energy (volume) at a specific\n\nfrequency, or the average amount of energy between two\nfrequencies. Accepts Number(s) corresponding\nto frequency (in Hz), or a \"string\" corresponding to predefined\nfrequency ranges (\"bass\", \"lowMid\", \"mid\", \"highMid\", \"treble\").\nReturns a range between 0 (no energy/volume at that frequency) and\n255 (maximum energy).\nNOTE: analyze() must be called prior to getEnergy(). analyze()\ntells the FFT to analyze frequency data, and getEnergy() uses\nthe results to determine the value at a specific frequency or\nrange of frequencies.
\n", "itemtype": "method", "name": "getEnergy", "params": [ { "name": "frequency1", "description": "Will return a value representing\n energy at this frequency. Alternately,\n the strings \"bass\", \"lowMid\" \"mid\",\n \"highMid\", and \"treble\" will return\n predefined frequency ranges.
\n", "type": "Number|String" }, { "name": "frequency2", "description": "If a second frequency is given,\n will return average amount of\n energy that exists between the\n two frequencies.
\n", "type": "Number", "optional": true } ], "return": { "description": "Energy Energy (volume/amplitude) from\n 0 and 255.", "type": "Number" }, "class": "p5.FFT", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 3739, "description": "Returns the\n\nspectral centroid of the input signal.\nNOTE: analyze() must be called prior to getCentroid(). Analyze()\ntells the FFT to analyze frequency data, and getCentroid() uses\nthe results determine the spectral centroid.
\n", "itemtype": "method", "name": "getCentroid", "return": { "description": "Spectral Centroid Frequency of the spectral centroid in Hz.", "type": "Number" }, "example": [ "\n\n function setup(){\ncnv = createCanvas(100,100);\ncnv.mousePressed(userStartAudio);\nsound = new p5.AudioIn();\nsound.start();\nfft = new p5.FFT();\nsound.connect(fft);\n}\n\nfunction draw() {\nif (getAudioContext().state !== 'running') {\n background(220);\n text('tap here and enable mic to begin', 10, 20, width - 20);\n return;\n}\nlet centroidplot = 0.0;\nlet spectralCentroid = 0;\n\nbackground(0);\nstroke(0,255,0);\nlet spectrum = fft.analyze();\nfill(0,255,0); // spectrum is green\n\n//draw the spectrum\nfor (let i = 0; i < spectrum.length; i++){\n let x = map(log(i), 0, log(spectrum.length), 0, width);\n let h = map(spectrum[i], 0, 255, 0, height);\n let rectangle_width = (log(i+1)-log(i))*(width/log(spectrum.length));\n rect(x, height, rectangle_width, -h )\n}\nlet nyquist = 22050;\n\n// get the centroid\nspectralCentroid = fft.getCentroid();\n\n// the mean_freq_index calculation is for the display.\nlet mean_freq_index = spectralCentroid/(nyquist/spectrum.length);\n\ncentroidplot = map(log(mean_freq_index), 0, log(spectrum.length), 0, width);\n\nstroke(255,0,0); // the line showing where the centroid is will be red\n\nrect(centroidplot, 0, width / spectrum.length, height)\nnoStroke();\nfill(255,255,255); // text is white\ntext('centroid: ', 10, 20);\ntext(round(spectralCentroid)+' Hz', 10, 40);\n}\n
Smooth FFT analysis by averaging with the last analysis frame.
\n", "itemtype": "method", "name": "smooth", "params": [ { "name": "smoothing", "description": "0.0 < smoothing < 1.0.\n Defaults to 0.8.
\n", "type": "Number" } ], "class": "p5.FFT", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 3854, "description": "Returns an array of average amplitude values for a given number\nof frequency bands split equally. N defaults to 16.\nNOTE: analyze() must be called prior to linAverages(). Analyze()\ntells the FFT to analyze frequency data, and linAverages() uses\nthe results to group them into a smaller set of averages.
\n", "itemtype": "method", "name": "linAverages", "params": [ { "name": "N", "description": "Number of returned frequency groups
\n", "type": "Number" } ], "return": { "description": "linearAverages Array of average amplitude values for each group", "type": "Array" }, "class": "p5.FFT", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 3889, "description": "Returns an array of average amplitude values of the spectrum, for a given\nset of \nOctave Bands\nNOTE: analyze() must be called prior to logAverages(). Analyze()\ntells the FFT to analyze frequency data, and logAverages() uses\nthe results to group them into a smaller set of averages.
\n", "itemtype": "method", "name": "logAverages", "params": [ { "name": "octaveBands", "description": "Array of Octave Bands objects for grouping
\n", "type": "Array" } ], "return": { "description": "logAverages Array of average amplitude values for each group", "type": "Array" }, "class": "p5.FFT", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 3925, "description": "Calculates and Returns the 1/N\nOctave Bands\nN defaults to 3 and minimum central frequency to 15.625Hz.\n(1/3 Octave Bands ~= 31 Frequency Bands)\nSetting fCtr0 to a central value of a higher octave will ignore the lower bands\nand produce less frequency groups.
\n", "itemtype": "method", "name": "getOctaveBands", "params": [ { "name": "N", "description": "Specifies the 1/N type of generated octave bands
\n", "type": "Number" }, { "name": "fCtr0", "description": "Minimum central frequency for the lowest band
\n", "type": "Number" } ], "return": { "description": "octaveBands Array of octave band objects with their bounds", "type": "Array" }, "class": "p5.FFT", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 4168, "description": "Start an oscillator.
\nStarting an oscillator on a user gesture will enable audio in browsers\nthat have a strict autoplay policy, including Chrome and most mobile\ndevices. See also: userStartAudio()
.
startTime in seconds from now.
\n", "type": "Number", "optional": true }, { "name": "frequency", "description": "frequency in Hz.
\n", "type": "Number", "optional": true } ], "class": "p5.Oscillator", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 4218, "description": "Stop an oscillator. Accepts an optional parameter\nto determine how long (in seconds from now) until the\noscillator stops.
\n", "itemtype": "method", "name": "stop", "params": [ { "name": "secondsFromNow", "description": "Time, in seconds from now.
\n", "type": "Number" } ], "class": "p5.Oscillator", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 4238, "description": "Set the amplitude between 0 and 1.0. Or, pass in an object\nsuch as an oscillator to modulate amplitude with an audio signal.
\n", "itemtype": "method", "name": "amp", "params": [ { "name": "vol", "description": "between 0 and 1.0\n or a modulating signal/oscillator
\n", "type": "Number|Object" }, { "name": "rampTime", "description": "create a fade that lasts rampTime
\n", "type": "Number", "optional": true }, { "name": "timeFromNow", "description": "schedule this event to happen\n seconds from now
\n", "type": "Number", "optional": true } ], "return": { "description": "gain If no value is provided,\n returns the Web Audio API\n AudioParam that controls\n this oscillator's\n gain/amplitude/volume)", "type": "AudioParam" }, "class": "p5.Oscillator", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 4271, "description": "Returns the value of output gain
\n", "itemtype": "method", "name": "getAmp", "return": { "description": "Amplitude value between 0.0 and 1.0", "type": "Number" }, "class": "p5.Oscillator", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 4285, "description": "Set frequency of an oscillator to a value. Or, pass in an object\nsuch as an oscillator to modulate the frequency with an audio signal.
\n", "itemtype": "method", "name": "freq", "params": [ { "name": "Frequency", "description": "Frequency in Hz\n or modulating signal/oscillator
\n", "type": "Number|Object" }, { "name": "rampTime", "description": "Ramp time (in seconds)
\n", "type": "Number", "optional": true }, { "name": "timeFromNow", "description": "Schedule this event to happen\n at x seconds from now
\n", "type": "Number", "optional": true } ], "return": { "description": "Frequency If no value is provided,\n returns the Web Audio API\n AudioParam that controls\n this oscillator's frequency", "type": "AudioParam" }, "example": [ "\n\nlet osc;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(playOscillator);\n osc = new p5.Oscillator(300);\n background(220);\n text('tap to play', 20, 20);\n}\n\nfunction playOscillator() {\n osc.start();\n osc.amp(0.5);\n // start at 700Hz\n osc.freq(700);\n // ramp to 60Hz over 0.7 seconds\n osc.freq(60, 0.7);\n osc.amp(0, 0.1, 0.7);\n}\n
Returns the value of frequency of oscillator
\n", "itemtype": "method", "name": "getFreq", "return": { "description": "Frequency of oscillator in Hertz", "type": "Number" }, "class": "p5.Oscillator", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 4373, "description": "Set type to 'sine', 'triangle', 'sawtooth' or 'square'.
\n", "itemtype": "method", "name": "setType", "params": [ { "name": "type", "description": "'sine', 'triangle', 'sawtooth' or 'square'.
\n", "type": "String" } ], "class": "p5.Oscillator", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 4386, "description": "Returns current type of oscillator eg. 'sine', 'triangle', 'sawtooth' or 'square'.
\n", "itemtype": "method", "name": "getType", "return": { "description": "type of oscillator eg . 'sine', 'triangle', 'sawtooth' or 'square'.", "type": "String" }, "class": "p5.Oscillator", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 4399, "description": "Connect to a p5.sound / Web Audio object.
\n", "itemtype": "method", "name": "connect", "params": [ { "name": "unit", "description": "A p5.sound or Web Audio object
\n", "type": "Object" } ], "class": "p5.Oscillator", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 4420, "description": "Disconnect all outputs
\n", "itemtype": "method", "name": "disconnect", "class": "p5.Oscillator", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 4444, "description": "Pan between Left (-1) and Right (1)
\n", "itemtype": "method", "name": "pan", "params": [ { "name": "panning", "description": "Number between -1 and 1
\n", "type": "Number" }, { "name": "timeFromNow", "description": "schedule this event to happen\n seconds from now
\n", "type": "Number" } ], "class": "p5.Oscillator", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 4460, "description": "Returns the current value of panPosition , between Left (-1) and Right (1)
\n", "itemtype": "method", "name": "getPan", "return": { "description": "panPosition of oscillator , between Left (-1) and Right (1)", "type": "Number" }, "class": "p5.Oscillator", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 4494, "description": "Set the phase of an oscillator between 0.0 and 1.0.\nIn this implementation, phase is a delay time\nbased on the oscillator's current frequency.
\n", "itemtype": "method", "name": "phase", "params": [ { "name": "phase", "description": "float between 0.0 and 1.0
\n", "type": "Number" } ], "class": "p5.Oscillator", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 4522, "description": "Add a value to the p5.Oscillator's output amplitude,\nand return the oscillator. Calling this method again\nwill override the initial add() with a new value.
\n", "itemtype": "method", "name": "add", "params": [ { "name": "number", "description": "Constant number to add
\n", "type": "Number" } ], "return": { "description": "Oscillator Returns this oscillator\n with scaled output", "type": "p5.Oscillator" }, "class": "p5.Oscillator", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 4543, "description": "Multiply the p5.Oscillator's output amplitude\nby a fixed value (i.e. turn it up!). Calling this method\nagain will override the initial mult() with a new value.
\n", "itemtype": "method", "name": "mult", "params": [ { "name": "number", "description": "Constant number to multiply
\n", "type": "Number" } ], "return": { "description": "Oscillator Returns this oscillator\n with multiplied output", "type": "p5.Oscillator" }, "class": "p5.Oscillator", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 4563, "description": "Scale this oscillator's amplitude values to a given\nrange, and return the oscillator. Calling this method\nagain will override the initial scale() with new values.
\n", "itemtype": "method", "name": "scale", "params": [ { "name": "inMin", "description": "input range minumum
\n", "type": "Number" }, { "name": "inMax", "description": "input range maximum
\n", "type": "Number" }, { "name": "outMin", "description": "input range minumum
\n", "type": "Number" }, { "name": "outMax", "description": "input range maximum
\n", "type": "Number" } ], "return": { "description": "Oscillator Returns this oscillator\n with scaled output", "type": "p5.Oscillator" }, "class": "p5.Oscillator", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 4767, "description": "Time until envelope reaches attackLevel
\n", "itemtype": "property", "name": "attackTime", "class": "p5.Envelope", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 4772, "description": "Level once attack is complete.
\n", "itemtype": "property", "name": "attackLevel", "class": "p5.Envelope", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 4778, "description": "Time until envelope reaches decayLevel.
\n", "itemtype": "property", "name": "decayTime", "class": "p5.Envelope", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 4784, "description": "Level after decay. The envelope will sustain here until it is released.
\n", "itemtype": "property", "name": "decayLevel", "class": "p5.Envelope", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 4790, "description": "Duration of the release portion of the envelope.
\n", "itemtype": "property", "name": "releaseTime", "class": "p5.Envelope", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 4796, "description": "Level at the end of the release.
\n", "itemtype": "property", "name": "releaseLevel", "class": "p5.Envelope", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 4833, "description": "Reset the envelope with a series of time/value pairs.
\n", "itemtype": "method", "name": "set", "params": [ { "name": "attackTime", "description": "Time (in seconds) before level\n reaches attackLevel
\n", "type": "Number" }, { "name": "attackLevel", "description": "Typically an amplitude between\n 0.0 and 1.0
\n", "type": "Number" }, { "name": "decayTime", "description": "Time
\n", "type": "Number" }, { "name": "decayLevel", "description": "Amplitude (In a standard ADSR envelope,\n decayLevel = sustainLevel)
\n", "type": "Number" }, { "name": "releaseTime", "description": "Release Time (in seconds)
\n", "type": "Number" }, { "name": "releaseLevel", "description": "Amplitude
\n", "type": "Number" } ], "example": [ "\n\nlet attackTime;\nlet l1 = 0.7; // attack level 0.0 to 1.0\nlet t2 = 0.3; // decay time in seconds\nlet l2 = 0.1; // decay level 0.0 to 1.0\nlet l3 = 0.2; // release time in seconds\n\nlet env, triOsc;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(playSound);\n\n env = new p5.Envelope();\n triOsc = new p5.Oscillator('triangle');\n}\n\nfunction draw() {\n background(220);\n text('tap here to play', 5, 20);\n\n attackTime = map(mouseX, 0, width, 0.0, 1.0);\n text('attack time: ' + attackTime, 5, height - 20);\n}\n\n// mouseClick triggers envelope if over canvas\nfunction playSound() {\n env.set(attackTime, l1, t2, l2, l3);\n\n triOsc.start();\n env.play(triOsc);\n}\n
Set values like a traditional\n\nADSR envelope\n.
\n", "itemtype": "method", "name": "setADSR", "params": [ { "name": "attackTime", "description": "Time (in seconds before envelope\n reaches Attack Level
\n", "type": "Number" }, { "name": "decayTime", "description": "Time (in seconds) before envelope\n reaches Decay/Sustain Level
\n", "type": "Number", "optional": true }, { "name": "susRatio", "description": "Ratio between attackLevel and releaseLevel, on a scale from 0 to 1,\n where 1.0 = attackLevel, 0.0 = releaseLevel.\n The susRatio determines the decayLevel and the level at which the\n sustain portion of the envelope will sustain.\n For example, if attackLevel is 0.4, releaseLevel is 0,\n and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is\n increased to 1.0 (using setRange
),\n then decayLevel would increase proportionally, to become 0.5.
Time in seconds from now (defaults to 0)
\n", "type": "Number", "optional": true } ], "example": [ "\n\nlet attackLevel = 1.0;\nlet releaseLevel = 0;\n\nlet attackTime = 0.001;\nlet decayTime = 0.2;\nlet susPercent = 0.2;\nlet releaseTime = 0.5;\n\nlet env, triOsc;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(playEnv);\n\n env = new p5.Envelope();\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.freq(220);\n}\n\nfunction draw() {\n background(220);\n text('tap here to play', 5, 20);\n attackTime = map(mouseX, 0, width, 0, 1.0);\n text('attack time: ' + attackTime, 5, height - 40);\n}\n\nfunction playEnv() {\n triOsc.start();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.play();\n}\n
Set max (attackLevel) and min (releaseLevel) of envelope.
\n", "itemtype": "method", "name": "setRange", "params": [ { "name": "aLevel", "description": "attack level (defaults to 1)
\n", "type": "Number" }, { "name": "rLevel", "description": "release level (defaults to 0)
\n", "type": "Number" } ], "example": [ "\n\nlet attackLevel = 1.0;\nlet releaseLevel = 0;\n\nlet attackTime = 0.001;\nlet decayTime = 0.2;\nlet susPercent = 0.2;\nlet releaseTime = 0.5;\n\nlet env, triOsc;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(playEnv);\n\n env = new p5.Envelope();\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.freq(220);\n}\n\nfunction draw() {\n background(220);\n text('tap here to play', 5, 20);\n attackLevel = map(mouseY, height, 0, 0, 1.0);\n text('attack level: ' + attackLevel, 5, height - 20);\n}\n\nfunction playEnv() {\n triOsc.start();\n env.setRange(attackLevel, releaseLevel);\n env.play();\n}\n
Assign a parameter to be controlled by this envelope.\nIf a p5.Sound object is given, then the p5.Envelope will control its\noutput gain. If multiple inputs are provided, the env will\ncontrol all of them.
\n", "itemtype": "method", "name": "setInput", "params": [ { "name": "inputs", "description": "A p5.sound object or\n Web Audio Param.
\n", "type": "Object", "optional": true, "multiple": true } ], "class": "p5.Envelope", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 5055, "description": "Set whether the envelope ramp is linear (default) or exponential.\nExponential ramps can be useful because we perceive amplitude\nand frequency logarithmically.
\n", "itemtype": "method", "name": "setExp", "params": [ { "name": "isExp", "description": "true is exponential, false is linear
\n", "type": "Boolean" } ], "class": "p5.Envelope", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 5078, "description": "Play tells the envelope to start acting on a given input.\nIf the input is a p5.sound object (i.e. AudioIn, Oscillator,\nSoundFile), then Envelope will control its output volume.\nEnvelopes can also be used to control any \nWeb Audio Audio Param.
", "itemtype": "method", "name": "play", "params": [ { "name": "unit", "description": "A p5.sound object or\n Web Audio Param.
\n", "type": "Object" }, { "name": "startTime", "description": "time from now (in seconds) at which to play
\n", "type": "Number", "optional": true }, { "name": "sustainTime", "description": "time to sustain before releasing the envelope
\n", "type": "Number", "optional": true } ], "example": [ "\n\nlet attackLevel = 1.0;\nlet releaseLevel = 0;\n\nlet attackTime = 0.001;\nlet decayTime = 0.2;\nlet susPercent = 0.2;\nlet releaseTime = 0.5;\n\nlet env, triOsc;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(playEnv);\n\n env = new p5.Envelope();\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.freq(220);\n triOsc.start();\n}\n\nfunction draw() {\n background(220);\n text('tap here to play', 5, 20);\n attackTime = map(mouseX, 0, width, 0, 1.0);\n attackLevel = map(mouseY, height, 0, 0, 1.0);\n text('attack time: ' + attackTime, 5, height - 40);\n text('attack level: ' + attackLevel, 5, height - 20);\n}\n\nfunction playEnv() {\n // ensure that audio is enabled\n userStartAudio();\n\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n env.play();\n}\n
Trigger the Attack, and Decay portion of the Envelope.\nSimilar to holding down a key on a piano, but it will\nhold the sustain level until you let go. Input can be\nany p5.sound object, or a \nWeb Audio Param.
\n", "itemtype": "method", "name": "triggerAttack", "params": [ { "name": "unit", "description": "p5.sound Object or Web Audio Param
\n", "type": "Object" }, { "name": "secondsFromNow", "description": "time from now (in seconds)
\n", "type": "Number" } ], "example": [ "\n\nlet attackTime = 0.001;\nlet decayTime = 0.2;\nlet susPercent = 0.3;\nlet releaseTime = 0.4;\nlet env, triOsc;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n background(220);\n textAlign(CENTER);\n textSize(10);\n text('tap to triggerAttack', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(1.0, 0.0);\n triOsc = new p5.Oscillator('triangle');\n triOsc.freq(220);\n\n cnv.mousePressed(envAttack);\n}\n\nfunction envAttack() {\n background(0, 255, 255);\n text('release to release', width/2, height/2);\n\n // ensures audio is enabled. See also: `userStartAudio`\n triOsc.start();\n\n env.triggerAttack(triOsc);\n}\n\nfunction mouseReleased() {\n background(220);\n text('tap to triggerAttack', width/2, height/2);\n\n env.triggerRelease(triOsc);\n}\n
Trigger the Release of the Envelope. This is similar to releasing\nthe key on a piano and letting the sound fade according to the\nrelease level and release time.
\n", "itemtype": "method", "name": "triggerRelease", "params": [ { "name": "unit", "description": "p5.sound Object or Web Audio Param
\n", "type": "Object" }, { "name": "secondsFromNow", "description": "time to trigger the release
\n", "type": "Number" } ], "example": [ "\n\nlet attackTime = 0.001;\nlet decayTime = 0.2;\nlet susPercent = 0.3;\nlet releaseTime = 0.4;\nlet env, triOsc;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n background(220);\n textAlign(CENTER);\n textSize(10);\n text('tap to triggerAttack', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(1.0, 0.0);\n triOsc = new p5.Oscillator('triangle');\n triOsc.freq(220);\n\n cnv.mousePressed(envAttack);\n}\n\nfunction envAttack() {\n background(0, 255, 255);\n text('release to release', width/2, height/2);\n\n // ensures audio is enabled. See also: `userStartAudio`\n triOsc.start();\n\n env.triggerAttack(triOsc);\n}\n\nfunction mouseReleased() {\n background(220);\n text('tap to triggerAttack', width/2, height/2);\n\n env.triggerRelease(triOsc);\n}\n
Exponentially ramp to a value using the first two\nvalues from setADSR(attackTime, decayTime)
\nas \ntime constants for simple exponential ramps.\nIf the value is higher than current value, it uses attackTime,\nwhile a decrease uses decayTime.
p5.sound Object or Web Audio Param
\n", "type": "Object" }, { "name": "secondsFromNow", "description": "When to trigger the ramp
\n", "type": "Number" }, { "name": "v", "description": "Target value
\n", "type": "Number" }, { "name": "v2", "description": "Second target value
\n", "type": "Number", "optional": true } ], "example": [ "\n\nlet env, osc, amp;\n\nlet attackTime = 0.001;\nlet decayTime = 0.2;\nlet attackLevel = 1;\nlet decayLevel = 0;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n fill(0,255,0);\n noStroke();\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime);\n osc = new p5.Oscillator();\n osc.amp(env);\n amp = new p5.Amplitude();\n\n cnv.mousePressed(triggerRamp);\n}\n\nfunction triggerRamp() {\n // ensures audio is enabled. See also: `userStartAudio`\n osc.start();\n\n env.ramp(osc, 0, attackLevel, decayLevel);\n}\n\nfunction draw() {\n background(20);\n text('tap to play', 10, 20);\n let h = map(amp.getLevel(), 0, 0.4, 0, height);;\n rect(0, height, width, -h);\n}\n
Add a value to the p5.Oscillator's output amplitude,\nand return the oscillator. Calling this method\nagain will override the initial add() with new values.
\n", "itemtype": "method", "name": "add", "params": [ { "name": "number", "description": "Constant number to add
\n", "type": "Number" } ], "return": { "description": "Envelope Returns this envelope\n with scaled output", "type": "p5.Envelope" }, "class": "p5.Envelope", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 5479, "description": "Multiply the p5.Envelope's output amplitude\nby a fixed value. Calling this method\nagain will override the initial mult() with new values.
\n", "itemtype": "method", "name": "mult", "params": [ { "name": "number", "description": "Constant number to multiply
\n", "type": "Number" } ], "return": { "description": "Envelope Returns this envelope\n with scaled output", "type": "p5.Envelope" }, "class": "p5.Envelope", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 5498, "description": "Scale this envelope's amplitude values to a given\nrange, and return the envelope. Calling this method\nagain will override the initial scale() with new values.
\n", "itemtype": "method", "name": "scale", "params": [ { "name": "inMin", "description": "input range minumum
\n", "type": "Number" }, { "name": "inMax", "description": "input range maximum
\n", "type": "Number" }, { "name": "outMin", "description": "input range minumum
\n", "type": "Number" }, { "name": "outMax", "description": "input range maximum
\n", "type": "Number" } ], "return": { "description": "Envelope Returns this envelope\n with scaled output", "type": "p5.Envelope" }, "class": "p5.Envelope", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 5657, "description": "Set type of noise to 'white', 'pink' or 'brown'.\nWhite is the default.
\n", "itemtype": "method", "name": "setType", "params": [ { "name": "type", "description": "'white', 'pink' or 'brown'
\n", "type": "String", "optional": true } ], "class": "p5.Noise", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 5871, "description": "Set the width of a Pulse object (an oscillator that implements\nPulse Width Modulation).
\n", "itemtype": "method", "name": "width", "params": [ { "name": "width", "description": "Width between the pulses (0 to 1.0,\n defaults to 0)
\n", "type": "Number", "optional": true } ], "class": "p5.Pulse", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6066, "itemtype": "property", "name": "input", "type": "GainNode", "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6070, "itemtype": "property", "name": "output", "type": "GainNode", "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6075, "itemtype": "property", "name": "stream", "type": "MediaStream|null", "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6080, "itemtype": "property", "name": "mediaStream", "type": "MediaStreamAudioSourceNode|null", "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6085, "itemtype": "property", "name": "currentSource", "type": "Number|null", "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6090, "description": "Client must allow browser to access their microphone / audioin source.\nDefault: false. Will become true when the client enables access.
\n", "itemtype": "property", "name": "enabled", "type": "Boolean", "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6098, "description": "Input amplitude, connect to it by default but not to master out
\n", "itemtype": "property", "name": "amplitude", "type": "p5.Amplitude", "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6114, "description": "Start processing audio input. This enables the use of other\nAudioIn methods like getLevel(). Note that by default, AudioIn\nis not connected to p5.sound's output. So you won't hear\nanything unless you use the connect() method.
Certain browsers limit access to the user's microphone. For example,\nChrome only allows access from localhost and over https. For this reason,\nyou may want to include an errorCallback—a function that is called in case\nthe browser won't provide mic access.
\n", "itemtype": "method", "name": "start", "params": [ { "name": "successCallback", "description": "Name of a function to call on\n success.
\n", "type": "Function", "optional": true }, { "name": "errorCallback", "description": "Name of a function to call if\n there was an error. For example,\n some browsers do not support\n getUserMedia.
\n", "type": "Function", "optional": true } ], "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6171, "description": "Turn the AudioIn off. If the AudioIn is stopped, it cannot getLevel().\nIf re-starting, the user may be prompted for permission access.
\n", "itemtype": "method", "name": "stop", "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6191, "description": "Connect to an audio unit. If no parameter is provided, will\nconnect to the main output (i.e. your speakers).
An object that accepts audio input,\n such as an FFT
\n", "type": "Object", "optional": true } ], "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6216, "description": "Disconnect the AudioIn from all audio units. For example, if\nconnect() had been called, disconnect() will stop sending\nsignal to your speakers.
Read the Amplitude (volume level) of an AudioIn. The AudioIn\nclass contains its own instance of the Amplitude class to help\nmake it easy to get a microphone's volume level. Accepts an\noptional smoothing value (0.0 < 1.0). NOTE: AudioIn must\n.start() before using .getLevel().
Smoothing is 0.0 by default.\n Smooths values based on previous values.
\n", "type": "Number", "optional": true } ], "return": { "description": "Volume level (between 0.0 and 1.0)", "type": "Number" }, "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6257, "description": "Set amplitude (volume) of a mic input between 0 and 1.0.
between 0 and 1.0
\n", "type": "Number" }, { "name": "time", "description": "ramp time (optional)
\n", "type": "Number", "optional": true } ], "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6280, "description": "Returns a list of available input sources. This is a wrapper\nfor \nMediaDevices.enumerateDevices() - Web APIs | MDN\nand it returns a Promise.
\n", "itemtype": "method", "name": "getSources", "params": [ { "name": "successCallback", "description": "This callback function handles the sources when they\n have been enumerated. The callback function\n receives the deviceList array as its only argument
\n", "type": "Function", "optional": true }, { "name": "errorCallback", "description": "This optional callback receives the error\n message as its argument.
\n", "type": "Function", "optional": true } ], "return": { "description": "Returns a Promise that can be used in place of the callbacks, similar\n to the enumerateDevices() method", "type": "Promise" }, "example": [ "\n\n let audioIn;\n\n function setup(){\n text('getting sources...', 0, 20);\n audioIn = new p5.AudioIn();\n audioIn.getSources(gotSources);\n }\n\n function gotSources(deviceList) {\n if (deviceList.length > 0) {\n //set the source to the first item in the deviceList array\n audioIn.setSource(0);\n let currentSource = deviceList[audioIn.currentSource];\n text('set source to: ' + currentSource.deviceId, 5, 20, width);\n }\n }\n
Set the input source. Accepts a number representing a\nposition in the array returned by getSources().\nThis is only available in browsers that support\n \n navigator.mediaDevices.enumerateDevices()
\n", "itemtype": "method", "name": "setSource", "params": [ { "name": "num", "description": "position of input source in the array
\n", "type": "Number" } ], "example": [ "\n\nlet audioIn;\n\nfunction setup(){\n text('getting sources...', 0, 20);\n audioIn = new p5.AudioIn();\n audioIn.getSources(gotSources);\n}\n\nfunction gotSources(deviceList) {\n if (deviceList.length > 0) {\n //set the source to the first item in the deviceList array\n audioIn.setSource(0);\n let currentSource = deviceList[audioIn.currentSource];\n text('set source to: ' + currentSource.deviceId, 5, 20, width);\n }\n}\n
In classes that extend\np5.Effect, connect effect nodes\nto the wet parameter
\n", "class": "p5.Effect", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6478, "description": "Set the output volume of the filter.
\n", "itemtype": "method", "name": "amp", "params": [ { "name": "vol", "description": "amplitude between 0 and 1.0
\n", "type": "Number", "optional": true }, { "name": "rampTime", "description": "create a fade that lasts until rampTime
\n", "type": "Number", "optional": true }, { "name": "tFromNow", "description": "schedule this event to happen in tFromNow seconds
\n", "type": "Number", "optional": true } ], "class": "p5.Effect", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6502, "description": "Link effects together in a chain\nExample usage: filter.chain(reverb, delay, panner);\nMay be used with an open-ended number of arguments
\n", "itemtype": "method", "name": "chain", "params": [ { "name": "arguments", "description": "Chain together multiple sound objects
\n", "type": "Object", "optional": true } ], "class": "p5.Effect", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6525, "description": "Adjust the dry/wet value.
\n", "itemtype": "method", "name": "drywet", "params": [ { "name": "fade", "description": "The desired drywet value (0 - 1.0)
\n", "type": "Number", "optional": true } ], "class": "p5.Effect", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6542, "description": "Send output to a p5.js-sound, Web Audio Node, or use signal to\ncontrol an AudioParam
\n", "itemtype": "method", "name": "connect", "params": [ { "name": "unit", "description": "", "type": "Object" } ], "class": "p5.Effect", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6557, "description": "Disconnect all output.
\n", "itemtype": "method", "name": "disconnect", "class": "p5.Effect", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6719, "description": "The p5.Filter is built with a\n\nWeb Audio BiquadFilter Node.
\n", "itemtype": "property", "name": "biquadFilter", "type": "DelayNode", "class": "p5.Filter", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6742, "description": "Filter an audio signal according to a set\nof filter parameters.
\n", "itemtype": "method", "name": "process", "params": [ { "name": "Signal", "description": "An object that outputs audio
\n", "type": "Object" }, { "name": "freq", "description": "Frequency in Hz, from 10 to 22050
\n", "type": "Number", "optional": true }, { "name": "res", "description": "Resonance/Width of the filter frequency\n from 0.001 to 1000
\n", "type": "Number", "optional": true } ], "class": "p5.Filter", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6760, "description": "Set the frequency and the resonance of the filter.
\n", "itemtype": "method", "name": "set", "params": [ { "name": "freq", "description": "Frequency in Hz, from 10 to 22050
\n", "type": "Number", "optional": true }, { "name": "res", "description": "Resonance (Q) from 0.001 to 1000
\n", "type": "Number", "optional": true }, { "name": "timeFromNow", "description": "schedule this event to happen\n seconds from now
\n", "type": "Number", "optional": true } ], "class": "p5.Filter", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6781, "description": "Set the filter frequency, in Hz, from 10 to 22050 (the range of\nhuman hearing, although in reality most people hear in a narrower\nrange).
\n", "itemtype": "method", "name": "freq", "params": [ { "name": "freq", "description": "Filter Frequency
\n", "type": "Number" }, { "name": "timeFromNow", "description": "schedule this event to happen\n seconds from now
\n", "type": "Number", "optional": true } ], "return": { "description": "value Returns the current frequency value", "type": "Number" }, "class": "p5.Filter", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6811, "description": "Controls either width of a bandpass frequency,\nor the resonance of a low/highpass cutoff frequency.
\n", "itemtype": "method", "name": "res", "params": [ { "name": "res", "description": "Resonance/Width of filter freq\n from 0.001 to 1000
\n", "type": "Number" }, { "name": "timeFromNow", "description": "schedule this event to happen\n seconds from now
\n", "type": "Number", "optional": true } ], "return": { "description": "value Returns the current res value", "type": "Number" }, "class": "p5.Filter", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6838, "description": "Controls the gain attribute of a Biquad Filter.\nThis is distinctly different from .amp() which is inherited from p5.Effect\n.amp() controls the volume via the output gain node\np5.Filter.gain() controls the gain parameter of a Biquad Filter node.
\n", "itemtype": "method", "name": "gain", "params": [ { "name": "gain", "description": "", "type": "Number" } ], "return": { "description": "Returns the current or updated gain value", "type": "Number" }, "class": "p5.Filter", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6864, "description": "Toggle function. Switches between the specified type and allpass
\n", "itemtype": "method", "name": "toggle", "return": { "description": "[Toggle value]", "type": "Boolean" }, "class": "p5.Filter", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 6884, "description": "Set the type of a p5.Filter. Possible types include:\n\"lowpass\" (default), \"highpass\", \"bandpass\",\n\"lowshelf\", \"highshelf\", \"peaking\", \"notch\",\n\"allpass\".
\n", "itemtype": "method", "name": "setType", "params": [ { "name": "t", "description": "", "type": "String" } ], "class": "p5.Filter", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 7198, "description": "The p5.EQ is built with abstracted p5.Filter objects.\nTo modify any bands, use methods of the \np5.Filter API, especially gain
and freq
.\nBands are stored in an array, with indices 0 - 3, or 0 - 7
Process an input by connecting it to the EQ
\n", "itemtype": "method", "name": "process", "params": [ { "name": "src", "description": "Audio source
\n", "type": "Object" } ], "class": "p5.EQ", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 7629, "description": "\nWeb Audio Spatial Panner Node
\nProperties include
\n Panning Model\n : \"equal power\" or \"HRTF\"
\n DistanceModel\n: \"linear\", \"inverse\", or \"exponential\"
Connect an audio sorce
\n", "itemtype": "method", "name": "process", "params": [ { "name": "src", "description": "Input source
\n", "type": "Object" } ], "class": "p5.Panner3D", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 7668, "description": "Set the X,Y,Z position of the Panner
\n", "itemtype": "method", "name": "set", "params": [ { "name": "xVal", "description": "", "type": "Number" }, { "name": "yVal", "description": "", "type": "Number" }, { "name": "zVal", "description": "", "type": "Number" }, { "name": "time", "description": "", "type": "Number" } ], "return": { "description": "Updated x, y, z values as an array", "type": "Array" }, "class": "p5.Panner3D", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 7687, "description": "Getter and setter methods for position coordinates
\n", "itemtype": "method", "name": "positionX", "return": { "description": "updated coordinate value", "type": "Number" }, "class": "p5.Panner3D", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 7694, "description": "Getter and setter methods for position coordinates
\n", "itemtype": "method", "name": "positionY", "return": { "description": "updated coordinate value", "type": "Number" }, "class": "p5.Panner3D", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 7701, "description": "Getter and setter methods for position coordinates
\n", "itemtype": "method", "name": "positionZ", "return": { "description": "updated coordinate value", "type": "Number" }, "class": "p5.Panner3D", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 7753, "description": "Set the X,Y,Z position of the Panner
\n", "itemtype": "method", "name": "orient", "params": [ { "name": "xVal", "description": "", "type": "Number" }, { "name": "yVal", "description": "", "type": "Number" }, { "name": "zVal", "description": "", "type": "Number" }, { "name": "time", "description": "", "type": "Number" } ], "return": { "description": "Updated x, y, z values as an array", "type": "Array" }, "class": "p5.Panner3D", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 7772, "description": "Getter and setter methods for orient coordinates
\n", "itemtype": "method", "name": "orientX", "return": { "description": "updated coordinate value", "type": "Number" }, "class": "p5.Panner3D", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 7779, "description": "Getter and setter methods for orient coordinates
\n", "itemtype": "method", "name": "orientY", "return": { "description": "updated coordinate value", "type": "Number" }, "class": "p5.Panner3D", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 7786, "description": "Getter and setter methods for orient coordinates
\n", "itemtype": "method", "name": "orientZ", "return": { "description": "updated coordinate value", "type": "Number" }, "class": "p5.Panner3D", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 7838, "description": "Set the rolloff factor and max distance
\n", "itemtype": "method", "name": "setFalloff", "params": [ { "name": "maxDistance", "description": "", "type": "Number", "optional": true }, { "name": "rolloffFactor", "description": "", "type": "Number", "optional": true } ], "class": "p5.Panner3D", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 7852, "description": "Maxium distance between the source and the listener
\n", "itemtype": "method", "name": "maxDist", "params": [ { "name": "maxDistance", "description": "", "type": "Number" } ], "return": { "description": "updated value", "type": "Number" }, "class": "p5.Panner3D", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 7869, "description": "How quickly the volume is reduced as the source moves away from the listener
\n", "itemtype": "method", "name": "rollof", "params": [ { "name": "rolloffFactor", "description": "", "type": "Number" } ], "return": { "description": "updated value", "type": "Number" }, "class": "p5.Panner3D", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 7989, "description": "The p5.Delay is built with two\n\nWeb Audio Delay Nodes, one for each stereo channel.
\n", "itemtype": "property", "name": "leftDelay", "type": "DelayNode", "class": "p5.Delay", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 7999, "description": "The p5.Delay is built with two\n\nWeb Audio Delay Nodes, one for each stereo channel.
\n", "itemtype": "property", "name": "rightDelay", "type": "DelayNode", "class": "p5.Delay", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 8049, "description": "Add delay to an audio signal according to a set\nof delay parameters.
\n", "itemtype": "method", "name": "process", "params": [ { "name": "Signal", "description": "An object that outputs audio
\n", "type": "Object" }, { "name": "delayTime", "description": "Time (in seconds) of the delay/echo.\n Some browsers limit delayTime to\n 1 second.
\n", "type": "Number", "optional": true }, { "name": "feedback", "description": "sends the delay back through itself\n in a loop that decreases in volume\n each time.
\n", "type": "Number", "optional": true }, { "name": "lowPass", "description": "Cutoff frequency. Only frequencies\n below the lowPass will be part of the\n delay.
\n", "type": "Number", "optional": true } ], "class": "p5.Delay", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 8094, "description": "Set the delay (echo) time, in seconds. Usually this value will be\na floating point number between 0.0 and 1.0.
\n", "itemtype": "method", "name": "delayTime", "params": [ { "name": "delayTime", "description": "Time (in seconds) of the delay
\n", "type": "Number" } ], "class": "p5.Delay", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 8116, "description": "Feedback occurs when Delay sends its signal back through its input\nin a loop. The feedback amount determines how much signal to send each\ntime through the loop. A feedback greater than 1.0 is not desirable because\nit will increase the overall output each time through the loop,\ncreating an infinite feedback loop. The default value is 0.5
\n", "itemtype": "method", "name": "feedback", "params": [ { "name": "feedback", "description": "0.0 to 1.0, or an object such as an\n Oscillator that can be used to\n modulate this param
\n", "type": "Number|Object" } ], "return": { "description": "Feedback value", "type": "Number" }, "class": "p5.Delay", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 8148, "description": "Set a lowpass filter frequency for the delay. A lowpass filter\nwill cut off any frequencies higher than the filter frequency.
\n", "itemtype": "method", "name": "filter", "params": [ { "name": "cutoffFreq", "description": "A lowpass filter will cut off any\n frequencies higher than the filter frequency.
\n", "type": "Number|Object" }, { "name": "res", "description": "Resonance of the filter frequency\n cutoff, or an object (i.e. a p5.Oscillator)\n that can be used to modulate this parameter.\n High numbers (i.e. 15) will produce a resonance,\n low numbers (i.e. .2) will produce a slope.
\n", "type": "Number|Object" } ], "class": "p5.Delay", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 8170, "description": "Choose a preset type of delay. 'pingPong' bounces the signal\nfrom the left to the right channel to produce a stereo effect.\nAny other parameter will revert to the default delay setting.
\n", "itemtype": "method", "name": "setType", "params": [ { "name": "type", "description": "'pingPong' (1) or 'default' (0)
\n", "type": "String|Number" } ], "class": "p5.Delay", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 8223, "description": "Set the output level of the delay effect.
\n", "itemtype": "method", "name": "amp", "params": [ { "name": "volume", "description": "amplitude between 0 and 1.0
\n", "type": "Number" }, { "name": "rampTime", "description": "create a fade that lasts rampTime
\n", "type": "Number", "optional": true }, { "name": "timeFromNow", "description": "schedule this event to happen\n seconds from now
\n", "type": "Number", "optional": true } ], "class": "p5.Delay", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 8234, "description": "Send output to a p5.sound or web audio object
\n", "itemtype": "method", "name": "connect", "params": [ { "name": "unit", "description": "", "type": "Object" } ], "class": "p5.Delay", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 8242, "description": "Disconnect all output.
\n", "itemtype": "method", "name": "disconnect", "class": "p5.Delay", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 8409, "description": "Connect a source to the reverb, and assign reverb parameters.
\n", "itemtype": "method", "name": "process", "params": [ { "name": "src", "description": "p5.sound / Web Audio object with a sound\n output.
\n", "type": "Object" }, { "name": "seconds", "description": "Duration of the reverb, in seconds.\n Min: 0, Max: 10. Defaults to 3.
\n", "type": "Number", "optional": true }, { "name": "decayRate", "description": "Percentage of decay with each echo.\n Min: 0, Max: 100. Defaults to 2.
\n", "type": "Number", "optional": true }, { "name": "reverse", "description": "Play the reverb backwards or forwards.
\n", "type": "Boolean", "optional": true } ], "class": "p5.Reverb", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 8446, "description": "Set the reverb settings. Similar to .process(), but without\nassigning a new input.
\n", "itemtype": "method", "name": "set", "params": [ { "name": "seconds", "description": "Duration of the reverb, in seconds.\n Min: 0, Max: 10. Defaults to 3.
\n", "type": "Number", "optional": true }, { "name": "decayRate", "description": "Percentage of decay with each echo.\n Min: 0, Max: 100. Defaults to 2.
\n", "type": "Number", "optional": true }, { "name": "reverse", "description": "Play the reverb backwards or forwards.
\n", "type": "Boolean", "optional": true } ], "class": "p5.Reverb", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 8482, "description": "Set the output level of the reverb effect.
\n", "itemtype": "method", "name": "amp", "params": [ { "name": "volume", "description": "amplitude between 0 and 1.0
\n", "type": "Number" }, { "name": "rampTime", "description": "create a fade that lasts rampTime
\n", "type": "Number", "optional": true }, { "name": "timeFromNow", "description": "schedule this event to happen\n seconds from now
\n", "type": "Number", "optional": true } ], "class": "p5.Reverb", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 8493, "description": "Send output to a p5.sound or web audio object
\n", "itemtype": "method", "name": "connect", "params": [ { "name": "unit", "description": "", "type": "Object" } ], "class": "p5.Reverb", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 8501, "description": "Disconnect all output.
\n", "itemtype": "method", "name": "disconnect", "class": "p5.Reverb", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 8621, "description": "Internally, the p5.Convolver uses the a\n\nWeb Audio Convolver Node.
\n", "itemtype": "property", "name": "convolverNode", "type": "ConvolverNode", "class": "p5.Convolver", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 8645, "description": "If you load multiple impulse files using the .addImpulse method,\nthey will be stored as Objects in this Array. Toggle between them\nwith the toggleImpulse(id)
method.
Connect a source to the convolver.
\n", "itemtype": "method", "name": "process", "params": [ { "name": "src", "description": "p5.sound / Web Audio object with a sound\n output.
\n", "type": "Object" } ], "example": [ "\n\nlet cVerb, sound;\nfunction preload() {\n // We have both MP3 and OGG versions of all sound assets\n soundFormats('ogg', 'mp3');\n\n // Try replacing 'bx-spring' with other soundfiles like\n // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox'\n cVerb = createConvolver('assets/bx-spring.mp3');\n\n // Try replacing 'Damscray_DancingTiger' with\n // 'beat', 'doorbell', lucky_dragons_-_power_melody'\n sound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(playSound);\n background(220);\n text('tap to play', 20, 20);\n\n // disconnect from main output...\n sound.disconnect();\n\n // ...and process with cVerb\n // so that we only hear the convolution\n cVerb.process(sound);\n}\n\nfunction playSound() {\n sound.play();\n}\n\n
Load and assign a new Impulse Response to the p5.Convolver.\nThe impulse is added to the .impulses
array. Previous\nimpulses can be accessed with the .toggleImpulse(id)
\nmethod.
path to a sound file
\n", "type": "String" }, { "name": "callback", "description": "function (optional)
\n", "type": "Function" }, { "name": "errorCallback", "description": "function (optional)
\n", "type": "Function" } ], "class": "p5.Convolver", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 8808, "description": "Similar to .addImpulse, except that the .impulses
\nArray is reset to save memory. A new .impulses
\narray is created with this impulse as the only item.
path to a sound file
\n", "type": "String" }, { "name": "callback", "description": "function (optional)
\n", "type": "Function" }, { "name": "errorCallback", "description": "function (optional)
\n", "type": "Function" } ], "class": "p5.Convolver", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 8831, "description": "If you have used .addImpulse()
to add multiple impulses\nto a p5.Convolver, then you can use this method to toggle between\nthe items in the .impulses
Array. Accepts a parameter\nto identify which impulse you wish to use, identified either by its\noriginal filename (String) or by its position in the .impulses\n
Array (Number).
\nYou can access the objects in the .impulses Array directly. Each\nObject has two attributes: an .audioBuffer
(type:\nWeb Audio \nAudioBuffer) and a .name
, a String that corresponds\nwith the original filename.
Identify the impulse by its original filename\n (String), or by its position in the\n .impulses
Array (Number).
Create a p5.Convolver. Accepts a path to a soundfile\nthat will be used to generate an impulse response.
\n", "itemtype": "method", "name": "createConvolver", "params": [ { "name": "path", "description": "path to a sound file
\n", "type": "String" }, { "name": "callback", "description": "function to call if loading is successful.\n The object will be passed in as the argument\n to the callback function.
\n", "type": "Function", "optional": true }, { "name": "errorCallback", "description": "function to call if loading is not successful.\n A custom error will be passed in as the argument\n to the callback function.
\n", "type": "Function", "optional": true } ], "return": { "description": "", "type": "p5.Convolver" }, "example": [ "\n\nlet cVerb, sound;\nfunction preload() {\n // We have both MP3 and OGG versions of all sound assets\n soundFormats('ogg', 'mp3');\n\n // Try replacing 'bx-spring' with other soundfiles like\n // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox'\n cVerb = createConvolver('assets/bx-spring.mp3');\n\n // Try replacing 'Damscray_DancingTiger' with\n // 'beat', 'doorbell', lucky_dragons_-_power_melody'\n sound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(playSound);\n background(220);\n text('tap to play', 20, 20);\n\n // disconnect from main output...\n sound.disconnect();\n\n // ...and process with cVerb\n // so that we only hear the convolution\n cVerb.process(sound);\n}\n\nfunction playSound() {\n sound.play();\n}\n
Set the global tempo, in beats per minute, for all\np5.Parts. This method will impact all active p5.Parts.
\n", "itemtype": "method", "name": "setBPM", "params": [ { "name": "BPM", "description": "Beats Per Minute
\n", "type": "Number" }, { "name": "rampTime", "description": "Seconds from now
\n", "type": "Number" } ], "class": "p5", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9173, "description": "Array of values to pass into the callback\nat each step of the phrase. Depending on the callback\nfunction's requirements, these values may be numbers,\nstrings, or an object with multiple parameters.\nZero (0) indicates a rest.
\n", "itemtype": "property", "name": "sequence", "type": "Array", "class": "p5.Phrase", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9263, "description": "Set the tempo of this part, in Beats Per Minute.
\n", "itemtype": "method", "name": "setBPM", "params": [ { "name": "BPM", "description": "Beats Per Minute
\n", "type": "Number" }, { "name": "rampTime", "description": "Seconds from now
\n", "type": "Number", "optional": true } ], "class": "p5.Part", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9278, "description": "Returns the tempo, in Beats Per Minute, of this part.
\n", "itemtype": "method", "name": "getBPM", "return": { "description": "", "type": "Number" }, "class": "p5.Part", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9291, "description": "Start playback of this part. It will play\nthrough all of its phrases at a speed\ndetermined by setBPM.
\n", "itemtype": "method", "name": "start", "params": [ { "name": "time", "description": "seconds from now
\n", "type": "Number", "optional": true } ], "class": "p5.Part", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9311, "description": "Loop playback of this part. It will begin\nlooping through all of its phrases at a speed\ndetermined by setBPM.
\n", "itemtype": "method", "name": "loop", "params": [ { "name": "time", "description": "seconds from now
\n", "type": "Number", "optional": true } ], "class": "p5.Part", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9333, "description": "Tell the part to stop looping.
\n", "itemtype": "method", "name": "noLoop", "class": "p5.Part", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9349, "description": "Stop the part and cue it to step 0. Playback will resume from the begining of the Part when it is played again.
\n", "itemtype": "method", "name": "stop", "params": [ { "name": "time", "description": "seconds from now
\n", "type": "Number", "optional": true } ], "class": "p5.Part", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9363, "description": "Pause the part. Playback will resume\nfrom the current step.
\n", "itemtype": "method", "name": "pause", "params": [ { "name": "time", "description": "seconds from now
\n", "type": "Number" } ], "class": "p5.Part", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9379, "description": "Add a p5.Phrase to this Part.
\n", "itemtype": "method", "name": "addPhrase", "params": [ { "name": "phrase", "description": "reference to a p5.Phrase
\n", "type": "p5.Phrase" } ], "class": "p5.Part", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9406, "description": "Remove a phrase from this part, based on the name it was\ngiven when it was created.
\n", "itemtype": "method", "name": "removePhrase", "params": [ { "name": "phraseName", "description": "", "type": "String" } ], "class": "p5.Part", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9424, "description": "Get a phrase from this part, based on the name it was\ngiven when it was created. Now you can modify its array.
\n", "itemtype": "method", "name": "getPhrase", "params": [ { "name": "phraseName", "description": "", "type": "String" } ], "class": "p5.Part", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9442, "description": "Find all sequences with the specified name, and replace their patterns with the specified array.
\n", "itemtype": "method", "name": "replaceSequence", "params": [ { "name": "phraseName", "description": "", "type": "String" }, { "name": "sequence", "description": "Array of values to pass into the callback\n at each step of the phrase.
\n", "type": "Array" } ], "class": "p5.Part", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9473, "description": "Set the function that will be called at every step. This will clear the previous function.
\n", "itemtype": "method", "name": "onStep", "params": [ { "name": "callback", "description": "The name of the callback\n you want to fire\n on every beat/tatum.
\n", "type": "Function" } ], "class": "p5.Part", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9542, "description": "Start playback of the score.
\n", "itemtype": "method", "name": "start", "class": "p5.Score", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9555, "description": "Stop playback of the score.
\n", "itemtype": "method", "name": "stop", "class": "p5.Score", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9569, "description": "Pause playback of the score.
\n", "itemtype": "method", "name": "pause", "class": "p5.Score", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9581, "description": "Loop playback of the score.
\n", "itemtype": "method", "name": "loop", "class": "p5.Score", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9594, "description": "Stop looping playback of the score. If it\nis currently playing, this will go into effect\nafter the current round of playback completes.
\n", "itemtype": "method", "name": "noLoop", "class": "p5.Score", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9628, "description": "Set the tempo for all parts in the score
\n", "itemtype": "method", "name": "setBPM", "params": [ { "name": "BPM", "description": "Beats Per Minute
\n", "type": "Number" }, { "name": "rampTime", "description": "Seconds from now
\n", "type": "Number" } ], "class": "p5.Score", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9729, "description": "Getters and Setters, setting any paramter will result in a change in the clock's\nfrequency, that will be reflected after the next callback\nbeats per minute (defaults to 60)
\n", "itemtype": "property", "name": "bpm", "type": "Number", "class": "p5.SoundLoop", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9750, "description": "number of quarter notes in a measure (defaults to 4)
\n", "itemtype": "property", "name": "timeSignature", "type": "Number", "class": "p5.SoundLoop", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9770, "description": "length of the loops interval
\n", "itemtype": "property", "name": "interval", "type": "Number|String", "class": "p5.SoundLoop", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9787, "description": "how many times the callback has been called so far
\n", "itemtype": "property", "name": "iterations", "type": "Number", "readonly": "", "class": "p5.SoundLoop", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9800, "description": "musicalTimeMode uses Tone.Time convention\ntrue if string, false if number
\n", "itemtype": "property", "name": "musicalTimeMode", "type": "Boolean", "class": "p5.SoundLoop", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9808, "description": "musicalTimeMode variables\nmodify these only when the interval is specified in musicalTime format as a string
\n", "class": "p5.SoundLoop", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9816, "description": "Set a limit to the number of loops to play. defaults to Infinity
\n", "itemtype": "property", "name": "maxIterations", "type": "Number", "class": "p5.SoundLoop", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9826, "description": "Do not initiate the callback if timeFromNow is < 0\nThis ususually occurs for a few milliseconds when the page\nis not fully loaded
\nThe callback should only be called until maxIterations is reached
\n", "class": "p5.SoundLoop", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9841, "description": "Start the loop
\n", "itemtype": "method", "name": "start", "params": [ { "name": "timeFromNow", "description": "schedule a starting time
\n", "type": "Number", "optional": true } ], "class": "p5.SoundLoop", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9860, "description": "Stop the loop
\n", "itemtype": "method", "name": "stop", "params": [ { "name": "timeFromNow", "description": "schedule a stopping time
\n", "type": "Number", "optional": true } ], "class": "p5.SoundLoop", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9878, "description": "Pause the loop
\n", "itemtype": "method", "name": "pause", "params": [ { "name": "timeFromNow", "description": "schedule a pausing time
\n", "type": "Number", "optional": true } ], "class": "p5.SoundLoop", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 9896, "description": "Synchronize loops. Use this method to start two or more loops in synchronization\nor to start a loop in synchronization with a loop that is already playing\nThis method will schedule the implicit loop in sync with the explicit master loop\ni.e. loopToStart.syncedStart(loopToSyncWith)
\n", "itemtype": "method", "name": "syncedStart", "params": [ { "name": "otherLoop", "description": "a p5.SoundLoop to sync with
\n", "type": "Object" }, { "name": "timeFromNow", "description": "Start the loops in sync after timeFromNow seconds
\n", "type": "Number", "optional": true } ], "class": "p5.SoundLoop", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 10068, "description": "The p5.Compressor is built with a Web Audio Dynamics Compressor Node\n
\n", "itemtype": "property", "name": "compressor", "type": "AudioNode", "class": "p5.Compressor", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 10084, "description": "Performs the same function as .connect, but also accepts\noptional parameters to set compressor's audioParams
\n", "itemtype": "method", "name": "process", "params": [ { "name": "src", "description": "Sound source to be connected
\n", "type": "Object" }, { "name": "attack", "description": "The amount of time (in seconds) to reduce the gain by 10dB,\n default = .003, range 0 - 1
\n", "type": "Number", "optional": true }, { "name": "knee", "description": "A decibel value representing the range above the\n threshold where the curve smoothly transitions to the \"ratio\" portion.\n default = 30, range 0 - 40
\n", "type": "Number", "optional": true }, { "name": "ratio", "description": "The amount of dB change in input for a 1 dB change in output\n default = 12, range 1 - 20
\n", "type": "Number", "optional": true }, { "name": "threshold", "description": "The decibel value above which the compression will start taking effect\n default = -24, range -100 - 0
\n", "type": "Number", "optional": true }, { "name": "release", "description": "The amount of time (in seconds) to increase the gain by 10dB\n default = .25, range 0 - 1
\n", "type": "Number", "optional": true } ], "class": "p5.Compressor", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 10112, "description": "Set the paramters of a compressor.
\n", "itemtype": "method", "name": "set", "params": [ { "name": "attack", "description": "The amount of time (in seconds) to reduce the gain by 10dB,\n default = .003, range 0 - 1
\n", "type": "Number" }, { "name": "knee", "description": "A decibel value representing the range above the\n threshold where the curve smoothly transitions to the \"ratio\" portion.\n default = 30, range 0 - 40
\n", "type": "Number" }, { "name": "ratio", "description": "The amount of dB change in input for a 1 dB change in output\n default = 12, range 1 - 20
\n", "type": "Number" }, { "name": "threshold", "description": "The decibel value above which the compression will start taking effect\n default = -24, range -100 - 0
\n", "type": "Number" }, { "name": "release", "description": "The amount of time (in seconds) to increase the gain by 10dB\n default = .25, range 0 - 1
\n", "type": "Number" } ], "class": "p5.Compressor", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 10152, "description": "Get current attack or set value w/ time ramp
\n", "itemtype": "method", "name": "attack", "params": [ { "name": "attack", "description": "Attack is the amount of time (in seconds) to reduce the gain by 10dB,\n default = .003, range 0 - 1
\n", "type": "Number", "optional": true }, { "name": "time", "description": "Assign time value to schedule the change in value
\n", "type": "Number", "optional": true } ], "class": "p5.Compressor", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 10178, "description": "Get current knee or set value w/ time ramp
\n", "itemtype": "method", "name": "knee", "params": [ { "name": "knee", "description": "A decibel value representing the range above the\n threshold where the curve smoothly transitions to the \"ratio\" portion.\n default = 30, range 0 - 40
\n", "type": "Number", "optional": true }, { "name": "time", "description": "Assign time value to schedule the change in value
\n", "type": "Number", "optional": true } ], "class": "p5.Compressor", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 10204, "description": "Get current ratio or set value w/ time ramp
\n", "itemtype": "method", "name": "ratio", "params": [ { "name": "ratio", "description": "The amount of dB change in input for a 1 dB change in output\n default = 12, range 1 - 20
\n", "type": "Number", "optional": true }, { "name": "time", "description": "Assign time value to schedule the change in value
\n", "type": "Number", "optional": true } ], "class": "p5.Compressor", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 10228, "description": "Get current threshold or set value w/ time ramp
\n", "itemtype": "method", "name": "threshold", "params": [ { "name": "threshold", "description": "The decibel value above which the compression will start taking effect\n default = -24, range -100 - 0
\n", "type": "Number" }, { "name": "time", "description": "Assign time value to schedule the change in value
\n", "type": "Number", "optional": true } ], "class": "p5.Compressor", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 10252, "description": "Get current release or set value w/ time ramp
\n", "itemtype": "method", "name": "release", "params": [ { "name": "release", "description": "The amount of time (in seconds) to increase the gain by 10dB\n default = .25, range 0 - 1
\n", "type": "Number" }, { "name": "time", "description": "Assign time value to schedule the change in value
\n", "type": "Number", "optional": true } ], "class": "p5.Compressor", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 10277, "description": "Return the current reduction value
\n", "itemtype": "method", "name": "reduction", "return": { "description": "Value of the amount of gain reduction that is applied to the signal", "type": "Number" }, "class": "p5.Compressor", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 10419, "description": "isDetected is set to true when a peak is detected.
\n", "itemtype": "attribute", "name": "isDetected", "type": "Boolean", "default": "false", "class": "p5.PeakDetect", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 10432, "description": "The update method is run in the draw loop.
\nAccepts an FFT object. You must call .analyze()\non the FFT object prior to updating the peakDetect\nbecause it relies on a completed FFT analysis.
\n", "itemtype": "method", "name": "update", "params": [ { "name": "fftObject", "description": "A p5.FFT object
\n", "type": "p5.FFT" } ], "class": "p5.PeakDetect", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 10470, "description": "onPeak accepts two arguments: a function to call when\na peak is detected. The value of the peak,\nbetween 0.0 and 1.0, is passed to the callback.
\n", "itemtype": "method", "name": "onPeak", "params": [ { "name": "callback", "description": "Name of a function that will\n be called when a peak is\n detected.
\n", "type": "Function" }, { "name": "val", "description": "Optional value to pass\n into the function when\n a peak is detected.
\n", "type": "Object", "optional": true } ], "example": [ "\n\nvar cnv, soundFile, fft, peakDetect;\nvar ellipseWidth = 0;\n\nfunction preload() {\n soundFile = loadSound('assets/beat.mp3');\n}\n\nfunction setup() {\n cnv = createCanvas(100,100);\n textAlign(CENTER);\n\n fft = new p5.FFT();\n peakDetect = new p5.PeakDetect();\n\n setupSound();\n\n // when a beat is detected, call triggerBeat()\n peakDetect.onPeak(triggerBeat);\n}\n\nfunction draw() {\n background(0);\n fill(255);\n text('click to play', width/2, height/2);\n\n fft.analyze();\n peakDetect.update(fft);\n\n ellipseWidth *= 0.95;\n ellipse(width/2, height/2, ellipseWidth, ellipseWidth);\n}\n\n// this function is called by peakDetect.onPeak\nfunction triggerBeat() {\n ellipseWidth = 50;\n}\n\n// mouseclick starts/stops sound\nfunction setupSound() {\n cnv.mouseClicked( function() {\n if (soundFile.isPlaying() ) {\n soundFile.stop();\n } else {\n soundFile.play();\n }\n });\n}\n
Connect a specific device to the p5.SoundRecorder.\nIf no parameter is given, p5.SoundRecorer will record\nall audible p5.sound from your sketch.
\n", "itemtype": "method", "name": "setInput", "params": [ { "name": "unit", "description": "p5.sound object or a web audio unit\n that outputs sound
\n", "type": "Object", "optional": true } ], "class": "p5.SoundRecorder", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 10703, "description": "Start recording. To access the recording, provide\na p5.SoundFile as the first parameter. The p5.SoundRecorder\nwill send its recording to that p5.SoundFile for playback once\nrecording is complete. Optional parameters include duration\n(in seconds) of the recording, and a callback function that\nwill be called once the complete recording has been\ntransfered to the p5.SoundFile.
\n", "itemtype": "method", "name": "record", "params": [ { "name": "soundFile", "description": "p5.SoundFile
\n", "type": "p5.SoundFile" }, { "name": "duration", "description": "Time (in seconds)
\n", "type": "Number", "optional": true }, { "name": "callback", "description": "The name of a function that will be\n called once the recording completes
\n", "type": "Function", "optional": true } ], "class": "p5.SoundRecorder", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 10739, "description": "Stop the recording. Once the recording is stopped,\nthe results will be sent to the p5.SoundFile that\nwas given on .record(), and if a callback function\nwas provided on record, that function will be called.
\n", "itemtype": "method", "name": "stop", "class": "p5.SoundRecorder", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 10864, "description": "The p5.Distortion is built with a\n\nWeb Audio WaveShaper Node.
\n", "itemtype": "property", "name": "WaveShaperNode", "type": "AudioNode", "class": "p5.Distortion", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 10883, "description": "Process a sound source, optionally specify amount and oversample values.
\n", "itemtype": "method", "name": "process", "params": [ { "name": "amount", "description": "Unbounded distortion amount.\n Normal values range from 0-1.
\n", "type": "Number", "optional": true, "optdefault": "0.25" }, { "name": "oversample", "description": "'none', '2x', or '4x'.
\n", "type": "String", "optional": true, "optdefault": "'none'" } ], "class": "p5.Distortion", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 10900, "description": "Set the amount and oversample of the waveshaper distortion.
\n", "itemtype": "method", "name": "set", "params": [ { "name": "amount", "description": "Unbounded distortion amount.\n Normal values range from 0-1.
\n", "type": "Number", "optional": true, "optdefault": "0.25" }, { "name": "oversample", "description": "'none', '2x', or '4x'.
\n", "type": "String", "optional": true, "optdefault": "'none'" } ], "class": "p5.Distortion", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 10923, "description": "Return the distortion amount, typically between 0-1.
\n", "itemtype": "method", "name": "getAmount", "return": { "description": "Unbounded distortion amount.\n Normal values range from 0-1.", "type": "Number" }, "class": "p5.Distortion", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 10937, "description": "Return the oversampling.
\n", "itemtype": "method", "name": "getOversample", "return": { "description": "Oversample can either be 'none', '2x', or '4x'.", "type": "String" }, "class": "p5.Distortion", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 11055, "description": "Connect a source to the gain node.
\n", "itemtype": "method", "name": "setInput", "params": [ { "name": "src", "description": "p5.sound / Web Audio object with a sound\n output.
\n", "type": "Object" } ], "class": "p5.Gain", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 11070, "description": "Send output to a p5.sound or web audio object
\n", "itemtype": "method", "name": "connect", "params": [ { "name": "unit", "description": "", "type": "Object" } ], "class": "p5.Gain", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 11084, "description": "Disconnect all output.
\n", "itemtype": "method", "name": "disconnect", "class": "p5.Gain", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 11098, "description": "Set the output level of the gain node.
\n", "itemtype": "method", "name": "amp", "params": [ { "name": "volume", "description": "amplitude between 0 and 1.0
\n", "type": "Number" }, { "name": "rampTime", "description": "create a fade that lasts rampTime
\n", "type": "Number", "optional": true }, { "name": "timeFromNow", "description": "schedule this event to happen\n seconds from now
\n", "type": "Number", "optional": true } ], "class": "p5.Gain", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 11181, "description": "Connect to p5 objects or Web Audio Nodes
\n", "itemtype": "method", "name": "connect", "params": [ { "name": "unit", "description": "", "type": "Object" } ], "class": "p5.AudioVoice", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 11194, "description": "Disconnect from soundOut
\n", "itemtype": "method", "name": "disconnect", "class": "p5.AudioVoice", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 11322, "description": "Getters and Setters
\n", "itemtype": "property", "name": "attack", "type": "Number", "class": "p5.MonoSynth", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 11328, "itemtype": "property", "name": "decay", "type": "Number", "class": "p5.MonoSynth", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 11333, "itemtype": "property", "name": "sustain", "type": "Number", "class": "p5.MonoSynth", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 11338, "itemtype": "property", "name": "release", "type": "Number", "class": "p5.MonoSynth", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 11379, "description": "Play tells the MonoSynth to start playing a note. This method schedules\nthe calling of .triggerAttack and .triggerRelease.
\n", "itemtype": "method", "name": "play", "params": [ { "name": "note", "description": "the note you want to play, specified as a\n frequency in Hertz (Number) or as a midi\n value in Note/Octave format (\"C4\", \"Eb3\"...etc\")\n See \n Tone. Defaults to 440 hz.
\n", "type": "String | Number" }, { "name": "velocity", "description": "velocity of the note to play (ranging from 0 to 1)
\n", "type": "Number", "optional": true }, { "name": "secondsFromNow", "description": "time from now (in seconds) at which to play
\n", "type": "Number", "optional": true }, { "name": "sustainTime", "description": "time to sustain before releasing the envelope. Defaults to 0.15 seconds.
\n", "type": "Number", "optional": true } ], "example": [ "\n\nlet monoSynth;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(playSynth);\n background(220);\n textAlign(CENTER);\n text('tap to play', width/2, height/2);\n\n monoSynth = new p5.MonoSynth();\n}\n\nfunction playSynth() {\n userStartAudio();\n\n let note = random(['Fb4', 'G4']);\n // note velocity (volume, from 0 to 1)\n let velocity = random();\n // time from now (in seconds)\n let time = 0;\n // note duration (in seconds)\n let dur = 1/6;\n\n monoSynth.play(note, velocity, time, dur);\n}\n
Trigger the Attack, and Decay portion of the Envelope.\nSimilar to holding down a key on a piano, but it will\nhold the sustain level until you let go.
\n", "params": [ { "name": "note", "description": "the note you want to play, specified as a\n frequency in Hertz (Number) or as a midi\n value in Note/Octave format (\"C4\", \"Eb3\"...etc\")\n See \n Tone. Defaults to 440 hz
\n", "type": "String | Number" }, { "name": "velocity", "description": "velocity of the note to play (ranging from 0 to 1)
\n", "type": "Number", "optional": true }, { "name": "secondsFromNow", "description": "time from now (in seconds) at which to play
\n", "type": "Number", "optional": true } ], "itemtype": "method", "name": "triggerAttack", "example": [ "\n\nlet monoSynth;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(triggerAttack);\n background(220);\n text('tap here for attack, let go to release', 5, 20, width - 20);\n monoSynth = new p5.MonoSynth();\n}\n\nfunction triggerAttack() {\n userStartAudio();\n\n monoSynth.triggerAttack(\"E3\");\n}\n\nfunction mouseReleased() {\n monoSynth.triggerRelease();\n}\n
Trigger the release of the Envelope. This is similar to releasing\nthe key on a piano and letting the sound fade according to the\nrelease level and release time.
\n", "params": [ { "name": "secondsFromNow", "description": "time to trigger the release
\n", "type": "Number" } ], "itemtype": "method", "name": "triggerRelease", "example": [ "\n\nlet monoSynth;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(triggerAttack);\n background(220);\n text('tap here for attack, let go to release', 5, 20, width - 20);\n monoSynth = new p5.MonoSynth();\n}\n\nfunction triggerAttack() {\n userStartAudio();\n\n monoSynth.triggerAttack(\"E3\");\n}\n\nfunction mouseReleased() {\n monoSynth.triggerRelease();\n}\n
Set values like a traditional\n\nADSR envelope\n.
\n", "itemtype": "method", "name": "setADSR", "params": [ { "name": "attackTime", "description": "Time (in seconds before envelope\n reaches Attack Level
\n", "type": "Number" }, { "name": "decayTime", "description": "Time (in seconds) before envelope\n reaches Decay/Sustain Level
\n", "type": "Number", "optional": true }, { "name": "susRatio", "description": "Ratio between attackLevel and releaseLevel, on a scale from 0 to 1,\n where 1.0 = attackLevel, 0.0 = releaseLevel.\n The susRatio determines the decayLevel and the level at which the\n sustain portion of the envelope will sustain.\n For example, if attackLevel is 0.4, releaseLevel is 0,\n and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is\n increased to 1.0 (using setRange
),\n then decayLevel would increase proportionally, to become 0.5.
Time in seconds from now (defaults to 0)
\n", "type": "Number", "optional": true } ], "class": "p5.MonoSynth", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 11544, "description": "MonoSynth amp
\n", "itemtype": "method", "name": "amp", "params": [ { "name": "vol", "description": "desired volume
\n", "type": "Number" }, { "name": "rampTime", "description": "Time to reach new volume
\n", "type": "Number", "optional": true } ], "return": { "description": "new volume value", "type": "Number" }, "class": "p5.MonoSynth", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 11564, "description": "Connect to a p5.sound / Web Audio object.
\n", "itemtype": "method", "name": "connect", "params": [ { "name": "unit", "description": "A p5.sound or Web Audio object
\n", "type": "Object" } ], "class": "p5.MonoSynth", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 11578, "description": "Disconnect all outputs
\n", "itemtype": "method", "name": "disconnect", "class": "p5.MonoSynth", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 11592, "description": "Get rid of the MonoSynth and free up its resources / memory.
\n", "itemtype": "method", "name": "dispose", "class": "p5.MonoSynth", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 11742, "description": "An object that holds information about which notes have been played and\nwhich notes are currently being played. New notes are added as keys\non the fly. While a note has been attacked, but not released, the value of the\nkey is the audiovoice which is generating that note. When notes are released,\nthe value of the key becomes undefined.
\n", "itemtype": "property", "name": "notes", "class": "p5.PolySynth", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 11755, "description": "A PolySynth must have at least 1 voice, defaults to 8
\n", "itemtype": "property", "name": "polyvalue", "class": "p5.PolySynth", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 11761, "description": "Monosynth that generates the sound for each note that is triggered. The\np5.PolySynth defaults to using the p5.MonoSynth as its voice.
\n", "itemtype": "property", "name": "AudioVoice", "class": "p5.PolySynth", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 11800, "description": "Play a note by triggering noteAttack and noteRelease with sustain time
\n", "itemtype": "method", "name": "play", "params": [ { "name": "note", "description": "midi note to play (ranging from 0 to 127 - 60 being a middle C)
\n", "type": "Number", "optional": true }, { "name": "velocity", "description": "velocity of the note to play (ranging from 0 to 1)
\n", "type": "Number", "optional": true }, { "name": "secondsFromNow", "description": "time from now (in seconds) at which to play
\n", "type": "Number", "optional": true }, { "name": "sustainTime", "description": "time to sustain before releasing the envelope
\n", "type": "Number", "optional": true } ], "example": [ "\n\nlet polySynth;\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(playSynth);\n background(220);\n text('click to play', 20, 20);\n\n polySynth = new p5.PolySynth();\n}\n\nfunction playSynth() {\n userStartAudio();\n\n // note duration (in seconds)\n let dur = 1.5;\n\n // time from now (in seconds)\n let time = 0;\n\n // velocity (volume, from 0 to 1)\n let vel = 0.1;\n\n // notes can overlap with each other\n polySynth.play('G2', vel, 0, dur);\n polySynth.play('C3', vel, time += 1/3, dur);\n polySynth.play('G3', vel, time += 1/3, dur);\n}\n
noteADSR sets the envelope for a specific note that has just been triggered.\nUsing this method modifies the envelope of whichever audiovoice is being used\nto play the desired note. The envelope should be reset before noteRelease is called\nin order to prevent the modified envelope from being used on other notes.
\n", "itemtype": "method", "name": "noteADSR", "params": [ { "name": "note", "description": "Midi note on which ADSR should be set.
\n", "type": "Number", "optional": true }, { "name": "attackTime", "description": "Time (in seconds before envelope\n reaches Attack Level
\n", "type": "Number", "optional": true }, { "name": "decayTime", "description": "Time (in seconds) before envelope\n reaches Decay/Sustain Level
\n", "type": "Number", "optional": true }, { "name": "susRatio", "description": "Ratio between attackLevel and releaseLevel, on a scale from 0 to 1,\n where 1.0 = attackLevel, 0.0 = releaseLevel.\n The susRatio determines the decayLevel and the level at which the\n sustain portion of the envelope will sustain.\n For example, if attackLevel is 0.4, releaseLevel is 0,\n and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is\n increased to 1.0 (using setRange
),\n then decayLevel would increase proportionally, to become 0.5.
Time in seconds from now (defaults to 0)
\n", "type": "Number", "optional": true } ], "class": "p5.PolySynth", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 11881, "description": "Set the PolySynths global envelope. This method modifies the envelopes of each\nmonosynth so that all notes are played with this envelope.
\n", "itemtype": "method", "name": "setADSR", "params": [ { "name": "attackTime", "description": "Time (in seconds before envelope\n reaches Attack Level
\n", "type": "Number", "optional": true }, { "name": "decayTime", "description": "Time (in seconds) before envelope\n reaches Decay/Sustain Level
\n", "type": "Number", "optional": true }, { "name": "susRatio", "description": "Ratio between attackLevel and releaseLevel, on a scale from 0 to 1,\n where 1.0 = attackLevel, 0.0 = releaseLevel.\n The susRatio determines the decayLevel and the level at which the\n sustain portion of the envelope will sustain.\n For example, if attackLevel is 0.4, releaseLevel is 0,\n and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is\n increased to 1.0 (using setRange
),\n then decayLevel would increase proportionally, to become 0.5.
Time in seconds from now (defaults to 0)
\n", "type": "Number", "optional": true } ], "class": "p5.PolySynth", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 11909, "description": "Trigger the Attack, and Decay portion of a MonoSynth.\nSimilar to holding down a key on a piano, but it will\nhold the sustain level until you let go.
\n", "itemtype": "method", "name": "noteAttack", "params": [ { "name": "note", "description": "midi note on which attack should be triggered.
\n", "type": "Number", "optional": true }, { "name": "velocity", "description": "velocity of the note to play (ranging from 0 to 1)/
\n", "type": "Number", "optional": true }, { "name": "secondsFromNow", "description": "time from now (in seconds)
\n", "type": "Number", "optional": true } ], "example": [ "\n\nlet polySynth = new p5.PolySynth();\nlet pitches = ['G', 'D', 'G', 'C'];\nlet octaves = [2, 3, 4];\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(playChord);\n background(220);\n text('tap to play', 20, 20);\n}\n\nfunction playChord() {\n userStartAudio();\n\n // play a chord: multiple notes at the same time\n for (let i = 0; i < 4; i++) {\n let note = random(pitches) + random(octaves);\n polySynth.noteAttack(note, 0.1);\n }\n}\n\nfunction mouseReleased() {\n // release all voices\n polySynth.noteRelease();\n}\n
Trigger the Release of an AudioVoice note. This is similar to releasing\nthe key on a piano and letting the sound fade according to the\nrelease level and release time.
\n", "itemtype": "method", "name": "noteRelease", "params": [ { "name": "note", "description": "midi note on which attack should be triggered.\n If no value is provided, all notes will be released.
\n", "type": "Number", "optional": true }, { "name": "secondsFromNow", "description": "time to trigger the release
\n", "type": "Number", "optional": true } ], "example": [ "\n\nlet polySynth = new p5.PolySynth();\nlet pitches = ['G', 'D', 'G', 'C'];\nlet octaves = [2, 3, 4];\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n cnv.mousePressed(playChord);\n background(220);\n text('tap to play', 20, 20);\n}\n\nfunction playChord() {\n userStartAudio();\n\n // play a chord: multiple notes at the same time\n for (let i = 0; i < 4; i++) {\n let note = random(pitches) + random(octaves);\n polySynth.noteAttack(note, 0.1);\n }\n}\n\nfunction mouseReleased() {\n // release all voices\n polySynth.noteRelease();\n}\n
Connect to a p5.sound / Web Audio object.
\n", "itemtype": "method", "name": "connect", "params": [ { "name": "unit", "description": "A p5.sound or Web Audio object
\n", "type": "Object" } ], "class": "p5.PolySynth", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 12119, "description": "Disconnect all outputs
\n", "itemtype": "method", "name": "disconnect", "class": "p5.PolySynth", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", "line": 12133, "description": "Get rid of the MonoSynth and free up its resources / memory.
\n", "itemtype": "method", "name": "dispose", "class": "p5.PolySynth", "module": "p5.sound", "submodule": "p5.sound" } ], "warnings": [ { "message": "replacing incorrect tag: returns with return", "line": " src/core/friendly_errors/fes_core.js:123" }, { "message": "replacing incorrect tag: returns with return", "line": " src/core/friendly_errors/fes_core.js:219" }, { "message": "replacing incorrect tag: returns with return", "line": " src/core/friendly_errors/fes_core.js:319" }, { "message": "replacing incorrect tag: returns with return", "line": " src/core/friendly_errors/fes_core.js:460" }, { "message": "replacing incorrect tag: returns with return", "line": " src/core/friendly_errors/fes_core.js:1004" }, { "message": "replacing incorrect tag: returns with return", "line": " src/core/friendly_errors/sketch_reader.js:243" }, { "message": "replacing incorrect tag: returns with return", "line": " src/core/friendly_errors/sketch_reader.js:268" }, { "message": "replacing incorrect tag: returns with return", "line": " src/core/friendly_errors/validate_params.js:336" }, { "message": "unknown tag: alt", "line": " src/core/shape/attributes.js:12" }, { "message": "unknown tag: alt", "line": " src/core/shape/attributes.js:81" }, { "message": "unknown tag: alt", "line": " src/core/shape/attributes.js:116" }, { "message": "unknown tag: alt", "line": " src/core/shape/attributes.js:185" }, { "message": "unknown tag: alt", "line": " src/core/shape/attributes.js:220" }, { "message": "unknown tag: alt", "line": " src/core/shape/attributes.js:260" }, { "message": "unknown tag: alt", "line": " src/core/shape/attributes.js:332" }, { "message": "unknown tag: alt", "line": " src/core/shape/curves.js:13" }, { "message": "unknown tag: alt", "line": " src/core/shape/curves.js:92" }, { "message": "unknown tag: alt", "line": " src/core/shape/curves.js:131" }, { "message": "unknown tag: alt", "line": " src/core/shape/curves.js:186" }, { "message": "unknown tag: alt", "line": " src/core/shape/curves.js:265" }, { "message": "unknown tag: alt", "line": " src/core/shape/curves.js:359" }, { "message": "unknown tag: alt", "line": " src/core/shape/curves.js:399" }, { "message": "unknown tag: alt", "line": " src/core/shape/curves.js:494" }, { "message": "unknown tag: alt", "line": " src/core/shape/vertex.js:20" }, { "message": "unknown tag: alt", "line": " src/core/shape/vertex.js:67" }, { "message": "unknown tag: alt", "line": " src/core/shape/vertex.js:293" }, { "message": "unknown tag: alt", "line": " src/core/shape/vertex.js:415" }, { "message": "unknown tag: alt", "line": " src/core/shape/vertex.js:460" }, { "message": "unknown tag: alt", "line": " src/core/shape/vertex.js:524" }, { "message": "unknown tag: alt", "line": " src/core/shape/vertex.js:583" }, { "message": "unknown tag: alt", "line": " src/core/shape/vertex.js:668" }, { "message": "unknown tag: alt", "line": " src/core/shape/vertex.js:733" }, { "message": "unknown tag: alt", "line": " src/core/shape/vertex.js:826" }, { "message": "unknown tag: alt", "line": " src/core/constants.js:66" }, { "message": "unknown tag: alt", "line": " src/core/constants.js:84" }, { "message": "unknown tag: alt", "line": " src/core/constants.js:102" }, { "message": "unknown tag: alt", "line": " src/core/constants.js:120" }, { "message": "unknown tag: alt", "line": " src/core/constants.js:138" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:20" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:52" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:79" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:129" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:160" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:228" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:331" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:354" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:372" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:390" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:405" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:421" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:500" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:550" }, { "message": "replacing incorrect tag: returns with return", "line": " src/core/environment.js:586" }, { "message": "replacing incorrect tag: returns with return", "line": " src/core/environment.js:605" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:605" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:660" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:691" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:713" }, { "message": "replacing incorrect tag: function with method", "line": " src/core/internationalization.js:105" }, { "message": "replacing incorrect tag: returns with return", "line": " src/core/internationalization.js:105" }, { "message": "unknown tag: alt", "line": " src/core/main.js:42" }, { "message": "unknown tag: alt", "line": " src/core/main.js:83" }, { "message": "unknown tag: alt", "line": " src/core/main.js:114" }, { "message": "unknown tag: alt", "line": " src/core/main.js:420" }, { "message": "unknown tag: alt", "line": " src/core/p5.Element.js:47" }, { "message": "unknown tag: alt", "line": " src/core/p5.Element.js:114" }, { "message": "unknown tag: alt", "line": " src/core/p5.Element.js:154" }, { "message": "unknown tag: alt", "line": " src/core/p5.Element.js:189" }, { "message": "unknown tag: alt", "line": " src/core/p5.Element.js:246" }, { "message": "unknown tag: alt", "line": " src/core/p5.Element.js:292" }, { "message": "unknown tag: alt", "line": " src/core/p5.Element.js:354" }, { "message": "unknown tag: alt", "line": " src/core/p5.Element.js:403" }, { "message": "unknown tag: alt", "line": " src/core/p5.Element.js:454" }, { "message": "unknown tag: alt", "line": " src/core/p5.Element.js:510" }, { "message": "unknown tag: alt", "line": " src/core/p5.Element.js:551" }, { "message": "unknown tag: alt", "line": " src/core/p5.Element.js:592" }, { "message": "unknown tag: alt", "line": " src/core/p5.Element.js:639" }, { "message": "unknown tag: alt", "line": " src/core/p5.Element.js:678" }, { "message": "unknown tag: alt", "line": " src/core/p5.Element.js:725" }, { "message": "unknown tag: alt", "line": " src/core/p5.Element.js:763" }, { "message": "unknown tag: alt", "line": " src/core/p5.Graphics.js:70" }, { "message": "unknown tag: alt", "line": " src/core/p5.Graphics.js:122" }, { "message": "unknown tag: alt", "line": " src/core/reference.js:7" }, { "message": "unknown tag: alt", "line": " src/core/reference.js:34" }, { "message": "unknown tag: alt", "line": " src/core/reference.js:87" }, { "message": "unknown tag: alt", "line": " src/core/reference.js:115" }, { "message": "unknown tag: alt", "line": " src/core/reference.js:137" }, { "message": "unknown tag: alt", "line": " src/core/reference.js:158" }, { "message": "unknown tag: alt", "line": " src/core/reference.js:179" }, { "message": "unknown tag: alt", "line": " src/core/reference.js:200" }, { "message": "unknown tag: alt", "line": " src/core/reference.js:231" }, { "message": "unknown tag: alt", "line": " src/core/reference.js:267" }, { "message": "unknown tag: alt", "line": " src/core/reference.js:288" }, { "message": "unknown tag: alt", "line": " src/core/reference.js:309" }, { "message": "unknown tag: alt", "line": " src/core/reference.js:331" }, { "message": "unknown tag: alt", "line": " src/core/reference.js:351" }, { "message": "unknown tag: alt", "line": " src/core/reference.js:379" }, { "message": "unknown tag: alt", "line": " src/core/reference.js:408" }, { "message": "unknown tag: alt", "line": " src/core/reference.js:448" }, { "message": "unknown tag: alt", "line": " src/core/reference.js:490" }, { "message": "unknown tag: alt", "line": " src/core/reference.js:512" }, { "message": "unknown tag: alt", "line": " src/core/rendering.js:15" }, { "message": "unknown tag: alt", "line": " src/core/rendering.js:125" }, { "message": "unknown tag: alt", "line": " src/core/rendering.js:183" }, { "message": "unknown tag: alt", "line": " src/core/rendering.js:204" }, { "message": "unknown tag: alt", "line": " src/core/rendering.js:243" }, { "message": "unknown tag: alt", "line": " src/core/rendering.js:327" }, { "message": "unknown tag: alt", "line": " src/core/structure.js:10" }, { "message": "unknown tag: alt", "line": " src/core/structure.js:83" }, { "message": "replacing incorrect tag: returns with return", "line": " src/core/structure.js:134" }, { "message": "unknown tag: alt", "line": " src/core/structure.js:134" }, { "message": "unknown tag: alt", "line": " src/core/structure.js:193" }, { "message": "unknown tag: alt", "line": " src/core/structure.js:291" }, { "message": "unknown tag: alt", "line": " src/core/structure.js:392" }, { "message": "unknown tag: alt", "line": " src/core/structure.js:498" }, { "message": "unknown tag: alt", "line": " src/core/transform.js:11" }, { "message": "unknown tag: alt", "line": " src/core/transform.js:197" }, { "message": "unknown tag: alt", "line": " src/core/transform.js:222" }, { "message": "unknown tag: alt", "line": " src/core/transform.js:261" }, { "message": "unknown tag: alt", "line": " src/core/transform.js:297" }, { "message": "unknown tag: alt", "line": " src/core/transform.js:333" }, { "message": "unknown tag: alt", "line": " src/core/transform.js:371" }, { "message": "unknown tag: alt", "line": " src/core/transform.js:445" }, { "message": "unknown tag: alt", "line": " src/core/transform.js:484" }, { "message": "unknown tag: alt", "line": " src/core/transform.js:523" }, { "message": "unknown tag: alt", "line": " src/dom/dom.js:204" }, { "message": "unknown tag: alt", "line": " src/dom/dom.js:271" }, { "message": "replacing incorrect tag: returns with return", "line": " src/dom/dom.js:1574" }, { "message": "replacing incorrect tag: returns with return", "line": " src/dom/dom.js:1636" }, { "message": "replacing incorrect tag: returns with return", "line": " src/dom/dom.js:1740" }, { "message": "replacing incorrect tag: returns with return", "line": " src/dom/dom.js:1779" }, { "message": "replacing incorrect tag: returns with return", "line": " src/dom/dom.js:1899" }, { "message": "unknown tag: alt", "line": " src/dom/dom.js:2282" }, { "message": "unknown tag: alt", "line": " src/dom/dom.js:2792" }, { "message": "unknown tag: alt", "line": " src/image/image.js:15" }, { "message": "unknown tag: alt", "line": " src/image/image.js:94" }, { "message": "unknown tag: alt", "line": " src/image/image.js:416" }, { "message": "unknown tag: alt", "line": " src/image/loading_displaying.js:18" }, { "message": "unknown tag: alt", "line": " src/image/loading_displaying.js:162" }, { "message": "replacing incorrect tag: returns with return", "line": " src/image/loading_displaying.js:669" }, { "message": "replacing incorrect tag: returns with return", "line": " src/image/loading_displaying.js:701" }, { "message": "replacing incorrect tag: returns with return", "line": " src/image/loading_displaying.js:736" }, { "message": "replacing incorrect tag: returns with return", "line": " src/image/loading_displaying.js:779" }, { "message": "unknown tag: alt", "line": " src/image/loading_displaying.js:796" }, { "message": "unknown tag: alt", "line": " src/image/loading_displaying.js:1036" }, { "message": "unknown tag: alt", "line": " src/image/loading_displaying.js:1134" }, { "message": "unknown tag: alt", "line": " src/image/loading_displaying.js:1173" }, { "message": "unknown tag: alt", "line": " src/image/p5.Image.js:88" }, { "message": "unknown tag: alt", "line": " src/image/p5.Image.js:115" }, { "message": "unknown tag: alt", "line": " src/image/p5.Image.js:152" }, { "message": "unknown tag: alt", "line": " src/image/p5.Image.js:261" }, { "message": "unknown tag: alt", "line": " src/image/p5.Image.js:296" }, { "message": "unknown tag: alt", "line": " src/image/p5.Image.js:346" }, { "message": "unknown tag: alt", "line": " src/image/p5.Image.js:400" }, { "message": "unknown tag: alt", "line": " src/image/p5.Image.js:437" }, { "message": "unknown tag: alt", "line": " src/image/p5.Image.js:545" }, { "message": "unknown tag: alt", "line": " src/image/p5.Image.js:600" }, { "message": "unknown tag: alt", "line": " src/image/p5.Image.js:680" }, { "message": "unknown tag: alt", "line": " src/image/p5.Image.js:753" }, { "message": "unknown tag: alt", "line": " src/image/p5.Image.js:874" }, { "message": "unknown tag: alt", "line": " src/image/p5.Image.js:915" }, { "message": "unknown tag: alt", "line": " src/image/p5.Image.js:956" }, { "message": "unknown tag: alt", "line": " src/image/p5.Image.js:987" }, { "message": "unknown tag: alt", "line": " src/image/p5.Image.js:1032" }, { "message": "unknown tag: alt", "line": " src/image/p5.Image.js:1067" }, { "message": "unknown tag: alt", "line": " src/image/p5.Image.js:1104" }, { "message": "unknown tag: alt", "line": " src/image/p5.Image.js:1140" }, { "message": "unknown tag: alt", "line": " src/image/pixels.js:12" }, { "message": "unknown tag: alt", "line": " src/image/pixels.js:80" }, { "message": "unknown tag: alt", "line": " src/image/pixels.js:173" }, { "message": "unknown tag: alt", "line": " src/image/pixels.js:307" }, { "message": "unknown tag: alt", "line": " src/image/pixels.js:481" }, { "message": "unknown tag: alt", "line": " src/image/pixels.js:566" }, { "message": "unknown tag: alt", "line": " src/image/pixels.js:602" }, { "message": "unknown tag: alt", "line": " src/image/pixels.js:674" }, { "message": "replacing incorrect tag: returns with return", "line": " src/io/files.js:686" }, { "message": "replacing incorrect tag: returns with return", "line": " src/math/calculation.js:827" }, { "message": "replacing incorrect tag: returns with return", "line": " src/math/trigonometry.js:322" }, { "message": "replacing incorrect tag: returns with return", "line": " src/math/trigonometry.js:337" }, { "message": "replacing incorrect tag: returns with return", "line": " src/math/trigonometry.js:352" }, { "message": "unknown tag: alt", "line": " src/typography/loading_displaying.js:16" }, { "message": "unknown tag: alt", "line": " src/typography/loading_displaying.js:140" }, { "message": "unknown tag: alt", "line": " src/typography/loading_displaying.js:231" }, { "message": "unknown tag: alt", "line": " src/utilities/conversion.js:10" }, { "message": "unknown tag: alt", "line": " src/utilities/string_functions.js:15" }, { "message": "unknown tag: alt", "line": " src/utilities/string_functions.js:43" }, { "message": "unknown tag: alt", "line": " src/utilities/string_functions.js:130" }, { "message": "unknown tag: alt", "line": " src/utilities/string_functions.js:237" }, { "message": "unknown tag: alt", "line": " src/utilities/string_functions.js:311" }, { "message": "unknown tag: alt", "line": " src/utilities/string_functions.js:373" }, { "message": "unknown tag: alt", "line": " src/utilities/string_functions.js:451" }, { "message": "unknown tag: alt", "line": " src/utilities/string_functions.js:537" }, { "message": "unknown tag: alt", "line": " src/utilities/time_date.js:10" }, { "message": "unknown tag: alt", "line": " src/utilities/time_date.js:31" }, { "message": "unknown tag: alt", "line": " src/utilities/time_date.js:52" }, { "message": "unknown tag: alt", "line": " src/utilities/time_date.js:73" }, { "message": "unknown tag: alt", "line": " src/utilities/time_date.js:100" }, { "message": "unknown tag: alt", "line": " src/utilities/time_date.js:122" }, { "message": "unknown tag: alt", "line": " src/utilities/time_date.js:143" }, { "message": "unknown tag: alt", "line": " src/webgl/3d_primitives.js:13" }, { "message": "unknown tag: alt", "line": " src/webgl/interaction.js:11" }, { "message": "unknown tag: alt", "line": " src/webgl/interaction.js:148" }, { "message": "unknown tag: alt", "line": " src/webgl/interaction.js:148" }, { "message": "unknown tag: alt", "line": " src/webgl/interaction.js:148" }, { "message": "unknown tag: alt", "line": " src/webgl/interaction.js:148" }, { "message": "unknown tag: alt", "line": " src/webgl/interaction.js:148" }, { "message": "unknown tag: alt", "line": " src/webgl/interaction.js:367" }, { "message": "unknown tag: alt", "line": " src/webgl/light.js:11" }, { "message": "unknown tag: alt", "line": " src/webgl/light.js:11" }, { "message": "unknown tag: alt", "line": " src/webgl/light.js:115" }, { "message": "unknown tag: alt", "line": " src/webgl/light.js:227" }, { "message": "unknown tag: alt", "line": " src/webgl/light.js:354" }, { "message": "unknown tag: alt", "line": " src/webgl/light.js:478" }, { "message": "unknown tag: alt", "line": " src/webgl/light.js:525" }, { "message": "unknown tag: alt", "line": " src/webgl/light.js:627" }, { "message": "unknown tag: alt", "line": " src/webgl/light.js:988" }, { "message": "unknown tag: alt", "line": " src/webgl/loading.js:12" }, { "message": "unknown tag: alt", "line": " src/webgl/loading.js:12" }, { "message": "unknown tag: alt", "line": " src/webgl/loading.js:590" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:12" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/material.js:112" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:112" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:186" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:288" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:377" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:377" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:377" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:377" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:524" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:524" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:602" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:675" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:720" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:720" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:720" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:833" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:905" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:992" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:13" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:119" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:183" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:246" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:316" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:371" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:461" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:490" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:518" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:546" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:575" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:604" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:633" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:657" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:681" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:709" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:828" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:925" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:1070" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:1128" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:1186" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:1253" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:1253" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:1417" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:1489" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:1754" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/p5.RendererGL.Immediate.js:237" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/p5.RendererGL.Retained.js:8" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.RendererGL.js:329" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.RendererGL.js:598" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.RendererGL.js:639" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.RendererGL.js:744" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Shader.js:306" }, { "message": "replacing incorrect tag: function with method", "line": " src/webgl/text.js:115" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/text.js:158" }, { "message": "replacing incorrect tag: function with method", "line": " src/webgl/text.js:191" }, { "message": "replacing incorrect tag: function with method", "line": " src/webgl/text.js:203" }, { "message": "replacing incorrect tag: function with method", "line": " src/webgl/text.js:236" }, { "message": "replacing incorrect tag: function with method", "line": " src/webgl/text.js:250" }, { "message": "replacing incorrect tag: function with method", "line": " src/webgl/text.js:388" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/text.js:388" }, { "message": "replacing incorrect tag: function with method", "line": " src/webgl/text.js:456" }, { "message": "replacing incorrect tag: function with method", "line": " src/webgl/text.js:471" }, { "message": "replacing incorrect tag: function with method", "line": " src/webgl/text.js:556" }, { "message": "replacing incorrect tag: params with param", "line": " lib/addons/p5.sound.js:2381" }, { "message": "replacing incorrect tag: returns with return", "line": " lib/addons/p5.sound.js:2381" }, { "message": "replacing incorrect tag: returns with return", "line": " lib/addons/p5.sound.js:2882" }, { "message": "replacing incorrect tag: returns with return", "line": " lib/addons/p5.sound.js:4271" }, { "message": "replacing incorrect tag: returns with return", "line": " lib/addons/p5.sound.js:4360" }, { "message": "replacing incorrect tag: returns with return", "line": " lib/addons/p5.sound.js:4386" }, { "message": "replacing incorrect tag: returns with return", "line": " lib/addons/p5.sound.js:4460" }, { "message": "replacing incorrect tag: returns with return", "line": " lib/addons/p5.sound.js:6280" }, { "message": "replacing incorrect tag: returns with return", "line": " lib/addons/p5.sound.js:8116" }, { "message": "Missing item type\nConversions adapted from