{ "project": { "name": "p5", "description": "[![npm version](https://badge.fury.io/js/p5.svg)](https://www.npmjs.com/package/p5)", "version": "1.9.2", "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": {}, "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/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": { "Events": 1, "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/GeometryBuilder.js": { "name": "src/webgl/GeometryBuilder.js", "modules": {}, "classes": {}, "fors": {}, "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.DataArray.js": { "name": "src/webgl/p5.DataArray.js", "modules": {}, "classes": {}, "fors": {}, "namespaces": {} }, "src/webgl/p5.Framebuffer.js": { "name": "src/webgl/p5.Framebuffer.js", "modules": { "Rendering": 1 }, "classes": { "p5.FramebufferCamera": 1, "p5.FramebufferTexture": 1, "p5.Framebuffer": 1 }, "fors": { "p5.Framebuffer": 1 }, "namespaces": {} }, "src/webgl/p5.Geometry.js": { "name": "src/webgl/p5.Geometry.js", "modules": {}, "classes": { "p5.Geometry": 1 }, "fors": { "p5": 1, "p5.Geometry": 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": 318 }, "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": 318, "requires": [ "core", "constants" ], "description": "
A class to describe a color.
\nEach p5.Color
object stores the color mode\nand level maxes that were active during its construction. These values are\nused to interpret the arguments passed to the object's constructor. They\nalso determine output formatting such as when\nsaturation() is called.
Color is stored internally as an array of ideal RGBA values in floating\npoint form, normalized from 0 to 1. These values are used to calculate the\nclosest screen colors, which are RGBA levels from 0 to 255. Screen colors\nare sent to the renderer.
\nWhen different color representations are calculated, the results are cached\nfor performance. These values are normalized, floating-point numbers.
\nNote: color() is the recommended way to create an\ninstance of this class.
\n" }, "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, "p5.Geometry": 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": 5456, "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": {}, "elements": {}, "classes": { "p5.Graphics": 1, "p5.Renderer": 1, "p5.FramebufferCamera": 1, "p5.FramebufferTexture": 1, "p5.Framebuffer": 1, "p5.RendererGL": 1 }, "fors": { "p5": 1, "p5.Framebuffer": 1 }, "namespaces": {}, "module": "Rendering", "file": "src/webgl/p5.RendererGL.js", "line": 945, "tag": "module", "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", "requires": [ "constants" ] }, "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": 415 }, "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": 415, "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": {}, "file": "src/events/acceleration.js", "line": 1, "requires": [ "core" ], "tag": "main", "itemtype": "main" }, "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" ], "tag": "main", "itemtype": "main" }, "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": "A class to describe an image.
\nImages are rectangular grids of pixels that can be displayed and modified.
\nExisting images can be loaded by calling\nloadImage(). Blank images can be created by\ncalling createImage(). p5.Image
objects\nhave methods for common tasks such as applying filters and modifying\npixel values.
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": 1186, "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": 11 }, "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": 11, "requires": [ "core" ], "description": "A class to describe a two or three-dimensional vector.
\nA vector can be thought of in different ways. In one view, a vector is like\nan arrow pointing in space. Vectors have both magnitude (length) and\ndirection.
\np5.Vector
objects are often used to program motion because they simplify\nthe math. For example, a moving ball has a position and a velocity.\nPosition describes where the ball is in space. The ball's position vector\nextends from the origin to the ball's center. Velocity describes the ball's\nspeed and the direction it's moving. If the ball is moving straight up, its\nvelocity vector points straight up. Adding the ball's velocity vector to\nits position vector moves it, as in pos.add(vel)
. Vector math relies on\nmethods inside the p5.Vector
class.
Note: createVector() is the recommended way\nto make an instance of this 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, "p5.Geometry": 1 }, "is_submodule": 1, "namespaces": {}, "module": "Shape", "namespace": "", "file": "src/webgl/p5.Geometry.js", "line": 13, "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": 277 }, "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": 511, "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 properties\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": 12, "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(p5)" }, { "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": 318, "description": "A class to describe a color.
\nEach p5.Color
object stores the color mode\nand level maxes that were active during its construction. These values are\nused to interpret the arguments passed to the object's constructor. They\nalso determine output formatting such as when\nsaturation() is called.
Color is stored internally as an array of ideal RGBA values in floating\npoint form, normalized from 0 to 1. These values are used to calculate the\nclosest screen colors, which are RGBA levels from 0 to 255. Screen colors\nare sent to the renderer.
\nWhen different color representations are calculated, the results are cached\nfor performance. These values are normalized, floating-point numbers.
\nNote: color() is the recommended way to create an\ninstance of this class.
\n", "is_constructor": 1, "params": [ { "name": "pInst", "description": "pointer to p5 instance.
\n", "type": "P5", "optional": true }, { "name": "vals", "description": "an array containing the color values\n for red, green, blue and alpha channel\n or CSS color.
\n", "type": "Number[]|String" } ] }, "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": "A class to describe an\nHTML element.
\nSketches can use many elements. Common elements include the drawing canvas,\nbuttons, sliders, webcam feeds, and so on.
\nAll elements share the methods of the p5.Element
class. They're created\nwith functions such as createCanvas() and\ncreateButton().
wrapped DOM element.
\n", "type": "HTMLElement" }, { "name": "pInst", "description": "pointer to p5 instance.
\n", "type": "P5", "optional": true } ], "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a button element and\n // place it beneath the canvas.\n let btn = createButton('change');\n btn.position(0, 100);\n\n // Call randomColor() when\n // the button is pressed.\n btn.mousePressed(randomColor);\n\n describe('A gray square with a button that says \"change\" beneath it. The square changes color when the user presses the button.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nThin 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 }, { "name": "canvas", "description": "existing html canvas element
\n", "type": "HTMLCanvasElement", "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": "HTMLElement" }, { "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": 397, "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": 415, "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": 4073, "description": "A class to handle audio and video.
\np5.MediaElement
extends p5.Element with\nmethods to handle audio and video. p5.MediaElement
objects are created by\ncalling createVideo,\ncreateAudio, and\ncreateCapture.
DOM node that is wrapped
\n", "type": "String" } ], "extends": "p5.Element", "example": [ "\n\nlet capture;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createCapture().\n capture = createCapture(VIDEO);\n capture.hide();\n\n describe('A webcam feed with inverted colors.');\n}\n\nfunction draw() {\n // Display the video stream and invert the colors.\n image(capture, 0, 0, width, width * capture.height / capture.width);\n filter(INVERT);\n}\n
\nA class to describe a file.
\np5.File
objects are used by\nmyElement.drop() and\ncreated by\ncreateFileInput.
wrapped file.
\n", "type": "File" } ], "example": [ "\n\n// Use the file input to load a\n// file and display its info.\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a file input and place it beneath the canvas.\n // Call displayInfo() when the file loads.\n let input = createFileInput(displayInfo);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user loads a file, its info is written in black.');\n}\n\n// Display the p5.File's info once it loads.\nfunction displayInfo(file) {\n background(200);\n\n // Display the p5.File's name.\n text(file.name, 10, 10, 80, 40);\n\n // Display the p5.File's type and subtype.\n text(`${file.type}/${file.subtype}`, 10, 70);\n\n // Display the p5.File's size in bytes.\n text(file.size, 10, 90);\n}\n
\n\n// Use the file input to select an image to\n// load and display.\nlet img;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a file input and place it beneath the canvas.\n // Call handleImage() when the file image loads.\n let input = createFileInput(handleImage);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user selects an image file to load, it is displayed on the square.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw the image if it's ready.\n if (img) {\n image(img, 0, 0, width, height);\n }\n}\n\n// Use the p5.File's data once it loads.\nfunction handleImage(file) {\n // Check the p5.File's type.\n if (file.type === 'image') {\n // Create an image using using the p5.File's data.\n img = createImg(file.data, '');\n\n // Hide the image element so it doesn't appear twice.\n img.hide();\n } else {\n img = null;\n }\n}\n
\nA class to describe an image.
\nImages are rectangular grids of pixels that can be displayed and modified.
\nExisting images can be loaded by calling\nloadImage(). Blank images can be created by\ncalling createImage(). p5.Image
objects\nhave methods for common tasks such as applying filters and modifying\npixel values.
\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('An image of a brick wall.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Apply the GRAY filter.\n img.filter(GRAY);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('A grayscale image of a brick wall.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the image's pixels.\n img.loadPixels();\n\n // Set the pixels to black.\n for (let x = 0; x < img.width; x += 1) {\n for (let y = 0; y < img.height; y += 1) {\n img.set(x, y, 0);\n }\n }\n\n // Update the image.\n img.updatePixels();\n\n // Display the image.\n image(img, 17, 17);\n\n describe('A black square drawn in the middle of a gray square.');\n}\n
\nTable 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.
\nA vector can be thought of in different ways. In one view, a vector is like\nan arrow pointing in space. Vectors have both magnitude (length) and\ndirection.
\np5.Vector
objects are often used to program motion because they simplify\nthe math. For example, a moving ball has a position and a velocity.\nPosition describes where the ball is in space. The ball's position vector\nextends from the origin to the ball's center. Velocity describes the ball's\nspeed and the direction it's moving. If the ball is moving straight up, its\nvelocity vector points straight up. Adding the ball's velocity vector to\nits position vector moves it, as in pos.add(vel)
. Vector math relies on\nmethods inside the p5.Vector
class.
Note: createVector() is the recommended way\nto make an instance of this 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\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create p5.Vector objects.\n let p1 = createVector(25, 25);\n let p2 = createVector(75, 75);\n\n // Style the points.\n strokeWeight(5);\n\n // Draw the first point using a p5.Vector.\n point(p1);\n\n // Draw the second point using a p5.Vector's components.\n point(p2.x, p2.y);\n\n describe('Two black dots on a gray square, one at the top left and the other at the bottom right.');\n}\n
\n\nlet pos;\nlet vel;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create p5.Vector objects.\n pos = createVector(50, 100);\n vel = createVector(0, -1);\n\n describe('A black dot moves from bottom to top on a gray square. The dot reappears at the bottom when it reaches the top.');\n}\n\nfunction draw() {\n background(200);\n\n // Add velocity to position.\n pos.add(vel);\n\n // If the dot reaches the top of the canvas,\n // restart from the bottom.\n if (pos.y < 0) {\n pos.y = 100;\n }\n\n // Draw the dot.\n strokeWeight(5);\n point(pos);\n}\n
\nA class to describe fonts.
\n", "is_constructor": 1, "params": [ { "name": "pInst", "description": "pointer to p5 instance.
\n", "type": "P5", "optional": true } ], "example": [ "\n\nlet font;\n\nfunction preload() {\n // Creates a p5.Font object.\n font = loadFont('assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Style the text.\n fill('deeppink');\n textFont(font);\n textSize(36);\n\n // Display the text.\n text('p5*js', 10, 50);\n\n describe('The text \"p5*js\" written in pink on a gray background.');\n}\n
\nThis 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 properties\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 cam.camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n cam.perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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
\nAn object that one can draw to and then read as a texture. While similar\nto a p5.Graphics, using a p5.Framebuffer as a texture will generally run\nmuch faster, as it lives within the same WebGL context as the canvas it\nis created on. It only works in WebGL mode.
\n", "is_constructor": 1, "params": [ { "name": "target", "description": "A p5 global instance or p5.Graphics
\n", "type": "p5.Graphics|p5" }, { "name": "settings", "description": "A settings object
\n", "type": "Object", "optional": true } ] }, "p5.Geometry": { "name": "p5.Geometry", "shortname": "p5.Geometry", "classitems": [], "plugins": [], "extensions": [], "plugin_for": [], "extension_for": [], "module": "Shape", "submodule": "3D Primitives", "namespace": "", "file": "src/webgl/p5.Geometry.js", "line": 13, "description": "p5 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 of the canvas.
\nThe first parameter, text
, is the description of the canvas.
The second parameter, display
, is optional. It determines how the\ndescription is displayed. If LABEL
is passed, as in\ndescribe('A description.', LABEL)
, the description will be visible in\na div element next to the canvas. If FALLBACK
is passed, as in\ndescribe('A description.', FALLBACK)
, the description will only be\nvisible to screen readers. This is the default mode.
Read\nWriting accessible canvas descriptions\nto learn more about making sketches accessible.
\n", "itemtype": "method", "name": "describe", "params": [ { "name": "text", "description": "description of the canvas.
\n", "type": "String" }, { "name": "display", "description": "either LABEL or FALLBACK.
\n", "type": "Constant", "optional": true } ], "example": [ "\n\nfunction setup() {\n background('pink');\n\n // Draw a heart.\n fill('red');\n noStroke();\n circle(67, 67, 20);\n circle(83, 67, 20);\n triangle(91, 73, 75, 95, 59, 73);\n\n // Add a general description of the canvas.\n describe('A pink square with a red heart in the bottom-right corner.');\n}\n
\n\nfunction setup() {\n background('pink');\n\n // Draw a heart.\n fill('red');\n noStroke();\n circle(67, 67, 20);\n circle(83, 67, 20);\n triangle(91, 73, 75, 95, 59, 73);\n\n // Add a general description of the canvas\n // and display it for debugging.\n describe('A pink square with a red heart in the bottom-right corner.', LABEL);\n}\n
\n\nfunction draw() {\n background(200);\n\n // The expression\n // frameCount % 100\n // causes x to increase from 0\n // to 99, then restart from 0.\n let x = frameCount % 100;\n\n // Draw the circle.\n fill(0, 255, 0);\n circle(x, 50, 40);\n\n // Add a general description of the canvas.\n describe(`A green circle at (${x}, 50) moves from left to right on a gray square.`);\n}\n
\n\nfunction draw() {\n background(200);\n\n // The expression\n // frameCount % 100\n // causes x to increase from 0\n // to 99, then restart from 0.\n let x = frameCount % 100;\n\n // Draw the circle.\n fill(0, 255, 0);\n circle(x, 50, 40);\n\n // Add a general description of the canvas\n // and display it for debugging.\n describe(`A green circle at (${x}, 50) moves from left to right on a gray square.`, LABEL);\n}\n
\nCreates a screen reader-accessible description of elements in the canvas.
\nElements are shapes or groups of shapes that create meaning together. For\nexample, a few overlapping circles could make an \"eye\" element.
\nThe first parameter, name
, is the name of the element.
The second parameter, text
, is the description of the element.
The third parameter, display
, is optional. It determines how the\ndescription is displayed. If LABEL
is passed, as in\ndescribe('A description.', LABEL)
, the description will be visible in\na div element next to the canvas. Using LABEL
creates unhelpful\nduplicates for screen readers. Only use LABEL
during development. If\nFALLBACK
is passed, as in describe('A description.', FALLBACK)
, the\ndescription will only be visible to screen readers. This is the default\nmode.
Read\nWriting accessible canvas descriptions\nto learn more about making sketches accessible.
\n", "itemtype": "method", "name": "describeElement", "params": [ { "name": "name", "description": "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\nfunction setup() {\n background('pink');\n\n // Describe the first element\n // and draw it.\n describeElement('Circle', 'A yellow circle in the top-left corner.');\n noStroke();\n fill('yellow');\n circle(25, 25, 40);\n\n // Describe the second element\n // and draw it.\n describeElement('Heart', 'A red heart in the bottom-right corner.');\n fill('red');\n circle(66.6, 66.6, 20);\n circle(83.2, 66.6, 20);\n triangle(91.2, 72.6, 75, 95, 58.6, 72.6);\n\n // Add a general description of the canvas.\n describe('A red heart and yellow circle over a pink background.');\n}\n
\n\nfunction setup() {\n background('pink');\n\n // Describe the first element\n // and draw it. Display the\n // description for debugging.\n describeElement('Circle', 'A yellow circle in the top-left corner.', LABEL);\n noStroke();\n fill('yellow');\n circle(25, 25, 40);\n\n // Describe the second element\n // and draw it. Display the\n // description for debugging.\n describeElement('Heart', 'A red heart in the bottom-right corner.', LABEL);\n fill('red');\n circle(66.6, 66.6, 20);\n circle(83.2, 66.6, 20);\n triangle(91.2, 72.6, 75, 95, 58.6, 72.6);\n\n // Add a general description of the canvas.\n describe('A red heart and yellow circle over a pink background.');\n}\n
\nCreates a screen reader-accessible description of shapes on the canvas.
\ntextOutput()
adds a general description, list of shapes, and\ntable of shapes to the web page. The general description includes the\ncanvas size, canvas color, and number of shapes. For example,\nYour output is a, 100 by 100 pixels, gray canvas containing the following 2 shapes:
.
A list of shapes follows the general description. The list describes the\ncolor, location, and area of each shape. For example,\na red circle at middle covering 3% of the canvas
. Each shape can be\nselected to get more details.
textOutput()
uses its table of shapes as a list. The table describes the\nshape, color, location, coordinates and area. For example,\nred circle location = middle area = 3%
. This is different from\ngridOutput(), which uses its table as a grid.
The display
parameter is optional. It determines how the description is\ndisplayed. If LABEL
is passed, as in textOutput(LABEL)
, the description\nwill be visible in a div element next to the canvas. Using LABEL
creates\nunhelpful duplicates for screen readers. Only use LABEL
during\ndevelopment. If FALLBACK
is passed, as in textOutput(FALLBACK)
, the\ndescription will only be visible to screen readers. This is the default\nmode.
Read\nWriting accessible canvas descriptions\nto learn more about making sketches accessible.
\n", "itemtype": "method", "name": "textOutput", "params": [ { "name": "display", "description": "either FALLBACK or LABEL.
\n", "type": "Constant", "optional": true } ], "example": [ "\n\nfunction setup() {\n // Add the text description.\n textOutput();\n\n // Draw a couple of shapes.\n background(200);\n fill(255, 0, 0);\n circle(20, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle and a blue square on a gray background.');\n}\n
\n\nfunction setup() {\n // Add the text description and\n // display it for debugging.\n textOutput(LABEL);\n\n // Draw a couple of shapes.\n background(200);\n fill(255, 0, 0);\n circle(20, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle and a blue square on a gray background.');\n}\n
\n\nfunction draw() {\n // Add the text description.\n textOutput();\n\n // Draw a moving circle.\n background(200);\n let x = frameCount * 0.1;\n fill(255, 0, 0);\n circle(x, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle moves from left to right above a blue square.');\n}\n
\n\nfunction draw() {\n // Add the text description and\n // display it for debugging.\n textOutput(LABEL);\n\n // Draw a moving circle.\n background(200);\n let x = frameCount * 0.1;\n fill(255, 0, 0);\n circle(x, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle moves from left to right above a blue square.');\n}\n
\nCreates a screen reader-accessible description of shapes on the canvas.
\ngridOutput()
adds a general description, table of shapes, and list of\nshapes to the web page. The general description includes the canvas size,\ncanvas color, and number of shapes. For example,\ngray canvas, 100 by 100 pixels, contains 2 shapes: 1 circle 1 square
.
gridOutput()
uses its table of shapes as a grid. Each shape in the grid\nis placed in a cell whose row and column correspond to the shape's location\non the canvas. The grid cells describe the color and type of shape at that\nlocation. For example, red circle
. These descriptions can be selected\nindividually to get more details. This is different from\ntextOutput(), which uses its table as a list.
A list of shapes follows the table. The list describes the color, type,\nlocation, and area of each shape. For example,\nred circle, location = middle, area = 3 %
.
The display
parameter is optional. It determines how the description is\ndisplayed. If LABEL
is passed, as in gridOutput(LABEL)
, the description\nwill be visible in a div element next to the canvas. Using LABEL
creates\nunhelpful duplicates for screen readers. Only use LABEL
during\ndevelopment. If FALLBACK
is passed, as in gridOutput(FALLBACK)
, the\ndescription will only be visible to screen readers. This is the default\nmode.
Read\nWriting accessible canvas descriptions\nto learn more about making sketches accessible.
\n", "itemtype": "method", "name": "gridOutput", "params": [ { "name": "display", "description": "either FALLBACK or LABEL.
\n", "type": "Constant", "optional": true } ], "example": [ "\n\nfunction setup() {\n // Add the grid description.\n gridOutput();\n\n // Draw a couple of shapes.\n background(200);\n fill(255, 0, 0);\n circle(20, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle and a blue square on a gray background.');\n}\n
\n\nfunction setup() {\n // Add the grid description and\n // display it for debugging.\n gridOutput(LABEL);\n\n // Draw a couple of shapes.\n background(200);\n fill(255, 0, 0);\n circle(20, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle and a blue square on a gray background.');\n}\n
\n\nfunction draw() {\n // Add the grid description.\n gridOutput();\n\n // Draw a moving circle.\n background(200);\n let x = frameCount * 0.1;\n fill(255, 0, 0);\n circle(x, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle moves from left to right above a blue square.');\n}\n
\n\nfunction draw() {\n // Add the grid description and\n // display it for debugging.\n gridOutput(LABEL);\n\n // Draw a moving circle.\n background(200);\n let x = frameCount * 0.1;\n fill(255, 0, 0);\n circle(x, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle moves from left to right above a blue square.');\n}\n
\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": 18, "description": "Convert an HSBA array to HSLA.
\n", "class": "p5", "module": "Color", "submodule": "Color Conversion" }, { "file": "src/color/color_conversion.js", "line": 44, "description": "Convert an HSBA array to RGBA.
\n", "class": "p5", "module": "Color", "submodule": "Color Conversion" }, { "file": "src/color/color_conversion.js", "line": 99, "description": "Convert an HSLA array to HSBA.
\n", "class": "p5", "module": "Color", "submodule": "Color Conversion" }, { "file": "src/color/color_conversion.js", "line": 122, "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": 186, "description": "Convert an RGBA array to HSBA.
\n", "class": "p5", "module": "Color", "submodule": "Color Conversion" }, { "file": "src/color/color_conversion.js", "line": 225, "description": "Convert an RGBA array to HSLA.
\n", "class": "p5", "module": "Color", "submodule": "Color Conversion" }, { "file": "src/color/creating_reading.js", "line": 16, "description": "Gets the alpha (transparency) value of a color.
\nalpha()
extracts the alpha value from a\np5.Color object, an array of color components, or\na CSS color string.
p5.Color object, array of\n color components, or CSS color string.
\n", "type": "p5.Color|Number[]|String" } ], "return": { "description": "the alpha value.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let c = color(0, 126, 255, 102);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'alphaValue' to 102.\n let alphaValue = alpha(c);\n\n // Draw the right rectangle.\n fill(alphaValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light blue and the right one is charcoal gray.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a color array.\n let c = [0, 126, 255, 102];\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'alphaValue' to 102.\n let alphaValue = alpha(c);\n\n // Draw the left rectangle.\n fill(alphaValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light blue and the right one is charcoal gray.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a CSS color string.\n let c = 'rgba(0, 126, 255, 0.4)';\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'alphaValue' to 102.\n let alphaValue = alpha(c);\n\n // Draw the right rectangle.\n fill(alphaValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light blue and the right one is charcoal gray.');\n}\n
\nGets the blue value of a color.
\nblue()
extracts the blue value from a\np5.Color object, an array of color components, or\na CSS color string.
By default, blue()
returns a color's blue value in the range 0\nto 255. If the colorMode() is set to RGB, it\nreturns the blue value in the given range.
p5.Color object, array of\n color components, or CSS color string.
\n", "type": "p5.Color|Number[]|String" } ], "return": { "description": "the blue value.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object using RGB values.\n let c = color(175, 100, 220);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'blueValue' to 220.\n let blueValue = blue(c);\n\n // Draw the right rectangle.\n fill(0, 0, blueValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is royal blue.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a color array.\n let c = [175, 100, 220];\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'blueValue' to 220.\n let blueValue = blue(c);\n\n // Draw the right rectangle.\n fill(0, 0, blueValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is royal blue.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a CSS color string.\n let c = 'rgb(175, 100, 220)';\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'blueValue' to 220.\n let blueValue = blue(c);\n\n // Draw the right rectangle.\n fill(0, 0, blueValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is royal blue.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use RGB color with values in the range 0-100.\n colorMode(RGB, 100);\n\n // Create a p5.Color object using RGB values.\n let c = color(69, 39, 86);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'blueValue' to 86.\n let blueValue = blue(c);\n\n // Draw the right rectangle.\n fill(0, 0, blueValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is royal blue.');\n}\n
\nGets the brightness value of a color.
\nbrightness()
extracts the HSB brightness value from a\np5.Color object, an array of color components, or\na CSS color string.
By default, brightness()
returns a color's HSB brightness in the range 0\nto 100. If the colorMode() is set to HSB, it\nreturns the brightness value in the given range.
p5.Color object, array of\n color components, or CSS color string.
\n", "type": "p5.Color|Number[]|String" } ], "return": { "description": "the brightness value.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use HSB color.\n colorMode(HSB);\n\n // Create a p5.Color object.\n let c = color(0, 50, 100);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'brightValue' to 100.\n let brightValue = brightness(c);\n\n // Draw the right rectangle.\n fill(brightValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is white.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use HSB color.\n colorMode(HSB);\n\n // Create a color array.\n let c = [0, 50, 100];\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'brightValue' to 100.\n let brightValue = brightness(c);\n\n // Draw the right rectangle.\n fill(brightValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is white.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use HSB color.\n colorMode(HSB);\n\n // Create a CSS color string.\n let c = 'rgb(255, 128, 128)';\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'brightValue' to 100.\n let brightValue = brightness(c);\n\n // Draw the right rectangle.\n fill(brightValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is white.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use HSB color with values in the range 0-255.\n colorMode(HSB, 255);\n\n // Create a p5.Color object.\n let c = color(0, 127, 255);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'brightValue' to 255.\n let brightValue = brightness(c);\n\n // Draw the right rectangle.\n fill(brightValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is white.');\n}\n
\nCreates a p5.Color object.
\nBy default, the parameters are interpreted as RGB values. Calling\ncolor(255, 204, 0)
will return a bright yellow color. The way these\nparameters are interpreted may be changed with the\ncolorMode() function.
The version of color()
with one parameter interprets the value one of two\nways. If the parameter is a number, it's interpreted as a grayscale value.\nIf the parameter is a string, it's interpreted as a CSS color string.
The version of color()
with two parameters interprets the first one as a\ngrayscale value. The second parameter sets the alpha (transparency) value.
The version of color()
with three parameters interprets them as RGB, HSB,\nor HSL colors, depending on the current colorMode()
.
The version of color()
with four parameters interprets them as RGBA, HSBA,\nor HSLA colors, depending on the current colorMode()
. The last parameter\nsets the alpha (transparency) value.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object using RGB values.\n let c = color(255, 204, 0);\n\n // Draw the square.\n fill(c);\n noStroke();\n square(30, 20, 55);\n\n describe('A yellow square on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object using RGB values.\n let c1 = color(255, 204, 0);\n\n // Draw the left circle.\n fill(c1);\n noStroke();\n circle(25, 25, 80);\n\n // Create a p5.Color object using a grayscale value.\n let c2 = color(65);\n\n // Draw the right circle.\n fill(c2);\n circle(75, 75, 80);\n\n describe(\n 'Two circles on a gray canvas. The circle in the top-left corner is yellow and the one at the bottom-right is gray.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object using a named color.\n let c = color('magenta');\n\n // Draw the square.\n fill(c);\n noStroke();\n square(20, 20, 60);\n\n describe('A magenta square on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object using a hex color code.\n let c1 = color('#0f0');\n\n // Draw the left rectangle.\n fill(c1);\n noStroke();\n rect(0, 10, 45, 80);\n\n // Create a p5.Color object using a hex color code.\n let c2 = color('#00ff00');\n\n // Draw the right rectangle.\n fill(c2);\n rect(55, 10, 45, 80);\n\n describe('Two bright green rectangles on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object using a RGB color string.\n let c1 = color('rgb(0, 0, 255)');\n\n // Draw the top-left square.\n fill(c1);\n square(10, 10, 35);\n\n // Create a p5.Color object using a RGB color string.\n let c2 = color('rgb(0%, 0%, 100%)');\n\n // Draw the top-right square.\n fill(c2);\n square(55, 10, 35);\n\n // Create a p5.Color object using a RGBA color string.\n let c3 = color('rgba(0, 0, 255, 1)');\n\n // Draw the bottom-left square.\n fill(c3);\n square(10, 55, 35);\n\n // Create a p5.Color object using a RGBA color string.\n let c4 = color('rgba(0%, 0%, 100%, 1)');\n\n // Draw the bottom-right square.\n fill(c4);\n square(55, 55, 35);\n\n describe('Four blue squares in the corners of a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object using a HSL color string.\n let c1 = color('hsl(160, 100%, 50%)');\n\n // Draw the left rectangle.\n noStroke();\n fill(c1);\n rect(0, 10, 45, 80);\n\n // Create a p5.Color object using a HSLA color string.\n let c2 = color('hsla(160, 100%, 50%, 0.5)');\n\n // Draw the right rectangle.\n fill(c2);\n rect(55, 10, 45, 80);\n\n describe('Two sea green rectangles. A darker rectangle on the left and a brighter one on the right.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object using a HSB color string.\n let c1 = color('hsb(160, 100%, 50%)');\n\n // Draw the left rectangle.\n noStroke();\n fill(c1);\n rect(0, 10, 45, 80);\n\n // Create a p5.Color object using a HSBA color string.\n let c2 = color('hsba(160, 100%, 50%, 0.5)');\n\n // Draw the right rectangle.\n fill(c2);\n rect(55, 10, 45, 80);\n\n describe('Two green rectangles. A darker rectangle on the left and a brighter one on the right.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object using RGB values.\n let c1 = color(50, 55, 100);\n\n // Draw the left rectangle.\n fill(c1);\n rect(0, 10, 45, 80);\n\n // Switch the color mode to HSB.\n colorMode(HSB, 100);\n\n // Create a p5.Color object using HSB values.\n let c2 = color(50, 55, 100);\n\n // Draw the right rectangle.\n fill(c2);\n rect(55, 10, 45, 80);\n\n describe('Two blue rectangles. A darker rectangle on the left and a brighter one on the right.');\n}\n
\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": 652, "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": 664, "params": [ { "name": "value", "description": "a color string.
\n", "type": "String" } ], "return": { "description": "", "type": "p5.Color" } }, { "line": 670, "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": 677, "params": [ { "name": "color", "description": "", "type": "p5.Color" } ], "return": { "description": "", "type": "p5.Color" } } ] }, { "file": "src/color/creating_reading.js", "line": 692, "description": "Gets the green value of a color.
\ngreen()
extracts the green value from a\np5.Color object, an array of color components, or\na CSS color string.
By default, green()
returns a color's green value in the range 0\nto 255. If the colorMode() is set to RGB, it\nreturns the green value in the given range.
p5.Color object, array of\n color components, or CSS color string.
\n", "type": "p5.Color|Number[]|String" } ], "return": { "description": "the green value.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let c = color(175, 100, 220);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'greenValue' to 100.\n let greenValue = green(c);\n\n // Draw the right rectangle.\n fill(0, greenValue, 0);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is dark green.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a color array.\n let c = [175, 100, 220];\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'greenValue' to 100.\n let greenValue = green(c);\n\n // Draw the right rectangle.\n fill(0, greenValue, 0);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is dark green.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a CSS color string.\n let c = 'rgb(175, 100, 220)';\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'greenValue' to 100.\n let greenValue = green(c);\n\n // Draw the right rectangle.\n fill(0, greenValue, 0);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is dark green.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use RGB color with values in the range 0-100.\n colorMode(RGB, 100);\n\n // Create a p5.Color object using RGB values.\n let c = color(69, 39, 86);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'greenValue' to 39.\n let greenValue = green(c);\n\n // Draw the right rectangle.\n fill(0, greenValue, 0);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is dark green.');\n}\n
\nGets the hue value of a color.
\nhue()
extracts the hue value from a\np5.Color object, an array of color components, or\na CSS color string.
Hue describes a color's position on the color wheel. By default, hue()
\nreturns a color's HSL hue in the range 0 to 360. If the\ncolorMode() is set to HSB or HSL, it returns the hue\nvalue in the given mode.
p5.Color object, array of\n color components, or CSS color string.
\n", "type": "p5.Color|Number[]|String" } ], "return": { "description": "the hue value.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use HSL color.\n colorMode(HSL);\n\n // Create a p5.Color object.\n let c = color(0, 50, 100);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 20, 35, 60);\n\n // Set 'hueValue' to 0.\n let hueValue = hue(c);\n\n // Draw the right rectangle.\n fill(hueValue);\n rect(50, 20, 35, 60);\n\n describe(\n 'Two rectangles. The rectangle on the left is salmon pink and the one on the right is black.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use HSL color.\n colorMode(HSL);\n\n // Create a color array.\n let c = [0, 50, 100];\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 20, 35, 60);\n\n // Set 'hueValue' to 0.\n let hueValue = hue(c);\n\n // Draw the right rectangle.\n fill(hueValue);\n rect(50, 20, 35, 60);\n\n describe(\n 'Two rectangles. The rectangle on the left is salmon pink and the one on the right is black.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use HSL color.\n colorMode(HSL);\n\n // Create a CSS color string.\n let c = 'rgb(255, 128, 128)';\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 20, 35, 60);\n\n // Set 'hueValue' to 0.\n let hueValue = hue(c);\n\n // Draw the right rectangle.\n fill(hueValue);\n rect(50, 20, 35, 60);\n\n describe(\n 'Two rectangles. The rectangle on the left is salmon pink and the one on the right is black.'\n );\n}\n
\nBlends two colors to find a third color between them.
\nThe amt
parameter specifies the amount to interpolate between the two\nvalues. 0 is equal to the first color, 0.1 is very near the first color,\n0.5 is halfway between the two colors, and so on. Negative numbers are set\nto 0. Numbers greater than 1 are set to 1. This differs from the behavior of\nlerp. It's necessary because numbers outside of the\ninterval [0, 1] will produce strange and unexpected colors.
The way that colors are interpolated depends on the current\ncolorMode().
\n", "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\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create p5.Color objects to interpolate between.\n let from = color(218, 165, 32);\n let to = color(72, 61, 139);\n\n // Create intermediate colors.\n let interA = lerpColor(from, to, 0.33);\n let interB = lerpColor(from, to, 0.66);\n\n // Draw the left rectangle.\n noStroke();\n fill(from);\n rect(10, 20, 20, 60);\n\n // Draw the left-center rectangle.\n fill(interA);\n rect(30, 20, 20, 60);\n\n // Draw the right-center rectangle.\n fill(interB);\n rect(50, 20, 20, 60);\n\n // Draw the right rectangle.\n fill(to);\n rect(70, 20, 20, 60);\n\n describe(\n 'Four rectangles. From left to right, the rectangles are tan, brown, brownish purple, and purple.'\n );\n}\n
\nGets the lightness value of a color.
\nlightness()
extracts the HSL lightness value from a\np5.Color object, an array of color components, or\na CSS color string.
By default, lightness()
returns a color's HSL lightness in the range 0\nto 100. If the colorMode() is set to HSL, it\nreturns the lightness value in the given range.
p5.Color object, array of\n color components, or CSS color string.
\n", "type": "p5.Color|Number[]|String" } ], "return": { "description": "the lightness value.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Use HSL color.\n colorMode(HSL);\n\n // Create a p5.Color object using HSL values.\n let c = color(0, 100, 75);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'lightValue' to 75.\n let lightValue = lightness(c);\n\n // Draw the right rectangle.\n fill(lightValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is gray.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Use HSL color.\n colorMode(HSL);\n\n // Create a color array.\n let c = [0, 100, 75];\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'lightValue' to 75.\n let lightValue = lightness(c);\n\n // Draw the right rectangle.\n fill(lightValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is gray.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Use HSL color.\n colorMode(HSL);\n\n // Create a CSS color string.\n let c = 'rgb(255, 128, 128)';\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'lightValue' to 75.\n let lightValue = lightness(c);\n\n // Draw the right rectangle.\n fill(lightValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is gray.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Use HSL color with values in the range 0-255.\n colorMode(HSL, 255);\n\n // Create a p5.Color object using HSL values.\n let c = color(0, 255, 191.5);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'lightValue' to 191.5.\n let lightValue = lightness(c);\n\n // Draw the right rectangle.\n fill(lightValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is gray.');\n}\n
\nGets the red value of a color.
\nred()
extracts the red value from a\np5.Color object, an array of color components, or\na CSS color string.
By default, red()
returns a color's red value in the range 0\nto 255. If the colorMode() is set to RGB, it\nreturns the red value in the given range.
p5.Color object, array of\n color components, or CSS color string.
\n", "type": "p5.Color|Number[]|String" } ], "return": { "description": "the red value.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let c = color(175, 100, 220);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'redValue' to 175.\n let redValue = red(c);\n\n // Draw the right rectangle.\n fill(redValue, 0, 0);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is red.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a color array.\n let c = [175, 100, 220];\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'redValue' to 175.\n let redValue = red(c);\n\n // Draw the right rectangle.\n fill(redValue, 0, 0);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is red.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a CSS color string.\n let c = 'rgb(175, 100, 220)';\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'redValue' to 175.\n let redValue = red(c);\n\n // Draw the right rectangle.\n fill(redValue, 0, 0);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is red.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use RGB color with values in the range 0-100.\n colorMode(RGB, 100);\n\n // Create a p5.Color object.\n let c = color(69, 39, 86);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'redValue' to 69.\n let redValue = red(c);\n\n // Draw the right rectangle.\n fill(redValue, 0, 0);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is light purple and the right one is red.');\n}\n
\nGets the saturation value of a color.
\nsaturation()
extracts the saturation value from a\np5.Color object, an array of color components, or\na CSS color string.
Saturation is scaled differently in HSB and HSL. By default, saturation()
\nreturns a color's HSL saturation in the range 0 to 100. If the\ncolorMode() is set to HSB or HSL, it returns the\nsaturation value in the given mode.
p5.Color object, array of\n color components, or CSS color string.
\n", "type": "p5.Color|Number[]|String" } ], "return": { "description": "the saturation value", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Use HSB color.\n colorMode(HSB);\n\n // Create a p5.Color object.\n let c = color(0, 50, 100);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'satValue' to 50.\n let satValue = saturation(c);\n\n // Draw the right rectangle.\n fill(satValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is dark gray.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Use HSB color.\n colorMode(HSB);\n\n // Create a color array.\n let c = [0, 50, 100];\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'satValue' to 100.\n let satValue = saturation(c);\n\n // Draw the right rectangle.\n fill(satValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is gray.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Use HSB color.\n colorMode(HSB);\n\n // Create a CSS color string.\n let c = 'rgb(255, 128, 128)';\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'satValue' to 100.\n let satValue = saturation(c);\n\n // Draw the right rectangle.\n fill(satValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is gray.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Use HSL color.\n colorMode(HSL);\n\n // Create a p5.Color object.\n let c = color(0, 100, 75);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'satValue' to 100.\n let satValue = saturation(c);\n\n // Draw the right rectangle.\n fill(satValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is white.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Use HSL color with values in the range 0-255.\n colorMode(HSL, 255);\n\n // Create a p5.Color object.\n let c = color(0, 255, 191.5);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 15, 35, 70);\n\n // Set 'satValue' to 255.\n let satValue = saturation(c);\n\n // Draw the right rectangle.\n fill(satValue);\n rect(50, 15, 35, 70);\n\n describe('Two rectangles. The left one is salmon pink and the right one is white.');\n}\n
\nCSS named colors.
\n", "class": "p5", "module": "Color", "submodule": "Creating & Reading" }, { "file": "src/color/p5.Color.js", "line": 168, "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", "module": "Color", "submodule": "Creating & Reading" }, { "file": "src/color/p5.Color.js", "line": 181, "description": "Full color string patterns. The capture groups are necessary.
\n", "class": "p5", "module": "Color", "submodule": "Creating & Reading" }, { "file": "src/color/p5.Color.js", "line": 362, "description": "Returns the color formatted as a String
.
Calling myColor.toString()
can be useful for debugging, as in\nprint(myColor.toString())
. It's also helpful for using p5.js with other\nlibraries.
The parameter, format
, is optional. If a format string is passed, as in\nmyColor.toString('#rrggbb')
, it will determine how the color string is\nformatted. By default, color strings are formatted as 'rgba(r, g, b, a)'
.
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.\n\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let myColor = color('darkorchid');\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the text.\n text(myColor.toString('#rrggbb'), 50, 50);\n\n describe('The text \"#9932cc\" written in purple on a gray background.');\n}\n
\nSets the red component of a color.
\nThe range depends on the colorMode(). In the\ndefault 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\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let c = color(255, 128, 128);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 20, 35, 60);\n\n // Change the red value.\n c.setRed(64);\n\n // Draw the right rectangle.\n fill(c);\n rect(50, 20, 35, 60);\n\n describe('Two rectangles. The left one is salmon pink and the right one is teal.');\n}\n
\nSets the green component of a color.
\nThe range depends on the colorMode(). In the\ndefault RGB mode it's between 0 and 255.
\n", "itemtype": "method", "name": "setGreen", "params": [ { "name": "green", "description": "the new green value.
\n", "type": "Number" } ], "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let c = color(255, 128, 128);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 20, 35, 60);\n\n // Change the green value.\n c.setGreen(255);\n\n // Draw the right rectangle.\n fill(c);\n rect(50, 20, 35, 60);\n\n describe('Two rectangles. The left one is salmon pink and the right one is yellow.');\n}\n
\nSets the blue component of a color.
\nThe range depends on the colorMode(). In the\ndefault 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\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let c = color(255, 128, 128);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 20, 35, 60);\n\n // Change the blue value.\n c.setBlue(255);\n\n // Draw the right rectangle.\n fill(c);\n rect(50, 20, 35, 60);\n\n describe('Two rectangles. The left one is salmon pink and the right one is pale fuchsia.');\n}\n
\nSets the alpha (transparency) value of a color.
\nThe range depends on the\ncolorMode(). In the default RGB mode it's\nbetween 0 and 255.
\n", "itemtype": "method", "name": "setAlpha", "params": [ { "name": "alpha", "description": "the new alpha value.
\n", "type": "Number" } ], "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let c = color(255, 128, 128);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 20, 35, 60);\n\n // Change the alpha value.\n c.setAlpha(128);\n\n // Draw the right rectangle.\n fill(c);\n rect(50, 20, 35, 60);\n\n describe('Two rectangles. The left one is salmon pink and the right one is faded pink.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let c = color(255, 128, 128);\n\n // Draw the left rectangle.\n noStroke();\n fill(c);\n rect(15, 20, 35, 60);\n\n // Change the alpha value.\n c.setAlpha(128);\n\n // Draw the right rectangle.\n fill(c);\n rect(50, 20, 35, 60);\n\n describe('Two rectangles. The left one is salmon pink and the right one is faded pink.');\n}\n
\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": 820, "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": 1048, "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": "Starts defining a shape that will mask any shapes drawn afterward.
\nAny shapes drawn between beginClip()
and\nendClip() will add to the mask shape. The mask\nwill apply to anything drawn after endClip().
The parameter, options
, is optional. If an object with an invert
\nproperty is passed, as in beginClip({ invert: true })
, it will be used to\nset the masking mode. { invert: true }
inverts the mask, creating holes\nin shapes that are masked. invert
is false
by default.
Masks can be contained between the\npush() and pop() functions.\nDoing so allows unmasked shapes to be drawn after masked shapes.
\nMasks can also be defined in a callback function that's passed to\nclip().
\n", "itemtype": "method", "name": "beginClip", "params": [ { "name": "options", "description": "an object containing clip settings.
\n", "type": "Object", "optional": true } ], "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a mask.\n beginClip();\n triangle(15, 37, 30, 13, 43, 37);\n circle(45, 45, 7);\n endClip();\n\n // Draw a backing shape.\n square(5, 5, 45);\n\n describe('A white triangle and circle on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an inverted mask.\n beginClip({ invert: true });\n triangle(15, 37, 30, 13, 43, 37);\n circle(45, 45, 7);\n endClip();\n\n // Draw a backing shape.\n square(5, 5, 45);\n\n describe('A white square at the top-left corner of a gray square. The white square has a triangle and a circle cut out of it.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n noStroke();\n\n // Draw a masked shape.\n push();\n // Create a mask.\n beginClip();\n triangle(15, 37, 30, 13, 43, 37);\n circle(45, 45, 7);\n endClip();\n\n // Draw a backing shape.\n square(5, 5, 45);\n pop();\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Draw an inverted masked shape.\n push();\n // Create an inverted mask.\n beginClip({ invert: true });\n triangle(15, 37, 30, 13, 43, 37);\n circle(45, 45, 7);\n endClip();\n\n // Draw a backing shape.\n square(5, 5, 45);\n pop();\n\n describe('In the top left, a white triangle and circle. In the bottom right, a white square with a triangle and circle cut out of it.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A silhouette of a rotating torus colored fuchsia.');\n}\n\nfunction draw() {\n background(200);\n\n // Create a mask.\n beginClip();\n push();\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n scale(0.5);\n torus(30, 15);\n pop();\n endClip();\n\n // Draw a backing shape.\n noStroke();\n fill('fuchsia');\n plane(100);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A silhouette of a rotating torus colored with a gradient from cyan to purple.');\n}\n\nfunction draw() {\n background(200);\n\n // Create a mask.\n beginClip();\n push();\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n scale(0.5);\n torus(30, 15);\n pop();\n endClip();\n\n // Draw a backing shape.\n noStroke();\n beginShape(QUAD_STRIP);\n fill(0, 255, 255);\n vertex(-width / 2, -height / 2);\n vertex(width / 2, -height / 2);\n fill(100, 0, 100);\n vertex(-width / 2, height / 2);\n vertex(width / 2, height / 2);\n endShape();\n}\n
\nEnds defining a mask that was started with\nbeginClip().
\n", "itemtype": "method", "name": "endClip", "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a mask.\n beginClip();\n triangle(15, 37, 30, 13, 43, 37);\n circle(45, 45, 7);\n endClip();\n\n // Draw a backing shape.\n square(5, 5, 45);\n\n describe('A white triangle and circle on a gray background.');\n}\n
\nDefines a shape that will mask any shapes drawn afterward.
\nThe first parameter, callback
, is a function that defines the mask.\nAny shapes drawn in callback
will add to the mask shape. The mask\nwill apply to anything drawn after clip()
is called.
The second parameter, options
, is optional. If an object with an invert
\nproperty is passed, as in beginClip({ invert: true })
, it will be used to\nset the masking mode. { invert: true }
inverts the mask, creating holes\nin shapes that are masked. invert
is false
by default.
Masks can be contained between the\npush() and pop() functions.\nDoing so allows unmasked shapes to be drawn after masked shapes.
\nMasks can also be defined with beginClip()\nand endClip().
\n", "itemtype": "method", "name": "clip", "params": [ { "name": "callback", "description": "a function that draws the mask shape.
\n", "type": "Function" }, { "name": "options", "description": "an object containing clip settings.
\n", "type": "Object", "optional": true } ], "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a mask.\n clip(mask);\n\n // Draw a backing shape.\n square(5, 5, 45);\n\n describe('A white triangle and circle on a gray background.');\n}\n\n// Declare a function that defines the mask.\nfunction mask() {\n triangle(15, 37, 30, 13, 43, 37);\n circle(45, 45, 7);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an inverted mask.\n clip(mask, { invert: true });\n\n // Draw a backing shape.\n square(5, 5, 45);\n\n describe('A white square at the top-left corner of a gray square. The white square has a triangle and a circle cut out of it.');\n}\n\n// Declare a function that defines the mask.\nfunction mask() {\n triangle(15, 37, 30, 13, 43, 37);\n circle(45, 45, 7);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n noStroke();\n\n // Draw a masked shape.\n push();\n // Create a mask.\n clip(mask);\n\n // Draw a backing shape.\n square(5, 5, 45);\n pop();\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Draw an inverted masked shape.\n push();\n // Create an inverted mask.\n clip(mask, { invert: true });\n\n // Draw a backing shape.\n square(5, 5, 45);\n pop();\n\n describe('In the top left, a white triangle and circle. In the bottom right, a white square with a triangle and circle cut out of it.');\n}\n\n// Declare a function that defines the mask.\nfunction mask() {\n triangle(15, 37, 30, 13, 43, 37);\n circle(45, 45, 7);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A silhouette of a rotating torus colored fuchsia.');\n}\n\nfunction draw() {\n background(200);\n\n // Create a mask.\n clip(mask);\n\n // Draw a backing shape.\n noStroke();\n fill('fuchsia');\n plane(100);\n}\n\n// Declare a function that defines the mask.\nfunction mask() {\n push();\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n scale(0.5);\n torus(30, 15);\n pop();\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A silhouette of a rotating torus colored with a gradient from cyan to purple.');\n}\n\nfunction draw() {\n background(200);\n\n // Create a mask.\n clip(mask);\n\n // Draw a backing shape.\n noStroke();\n beginShape(QUAD_STRIP);\n fill(0, 255, 255);\n vertex(-width / 2, -height / 2);\n vertex(width / 2, -height / 2);\n fill(100, 0, 100);\n vertex(-width / 2, height / 2);\n vertex(width / 2, height / 2);\n endShape();\n}\n\n// Declare a function that defines the mask.\nfunction mask() {\n push();\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n scale(0.5);\n torus(30, 15);\n pop();\n}\n
\nSets the color used for the background of the canvas.
\nBy default, the background is transparent. background()
is typically used\nwithin draw() to clear the display window at the\nbeginning of each frame. It can also be used inside\nsetup() to set the background on the first frame\nof animation.
The version of background()
with one parameter interprets the value one\nof four ways. If the parameter is a Number
, it's interpreted as a grayscale\nvalue. If the parameter is a String
, it's interpreted as a CSS color string.\nRGB, RGBA, HSL, HSLA, hex, and named color strings are supported. If the\nparameter is a p5.Color object, it will be used as\nthe background color. If the parameter is a\np5.Image object, it will be used as the background\nimage.
The version of background()
with two parameters interprets the first one\nas a grayscale value. The second parameter sets the alpha (transparency)\nvalue.
The version of background()
with three parameters interprets them as RGB,\nHSB, or HSL colors, depending on the current\ncolorMode(). By default, colors are specified\nin RGB values. Calling background(255, 204, 0)
sets the background a bright\nyellow color.
\nfunction setup() {\n createCanvas(100, 100);\n\n // A grayscale value.\n background(51);\n\n describe('A canvas with a dark charcoal gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // A grayscale value and an alpha value.\n background(51, 0.4);\n describe('A canvas with a transparent gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // R, G & B values.\n background(255, 204, 0);\n\n describe('A canvas with a yellow background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use HSB color.\n colorMode(HSB);\n\n // H, S & B values.\n background(255, 204, 100);\n\n describe('A canvas with a royal blue background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // A CSS named color.\n background('red');\n\n describe('A canvas with a red background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Three-digit hex RGB notation.\n background('#fae');\n\n describe('A canvas with a pink background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Six-digit hex RGB notation.\n background('#222222');\n\n describe('A canvas with a black background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Integer RGB notation.\n background('rgb(0, 255, 0)');\n\n describe('A canvas with a bright green background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Integer RGBA notation.\n background('rgba(0, 255, 0, 0.25)');\n\n describe('A canvas with a transparent green background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Percentage RGB notation.\n background('rgb(100%, 0%, 10%)');\n\n describe('A canvas with a red background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Percentage RGBA notation.\n background('rgba(100%, 0%, 100%, 0.5)');\n\n describe('A canvas with a transparent purple background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // A p5.Color object.\n let c = color(0, 0, 255);\n background(c);\n\n describe('A canvas with a blue background.');\n}\n
\nany value created by the color() function
\n", "type": "p5.Color" } ], "chainable": 1 }, { "line": 608, "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": 618, "params": [ { "name": "gray", "description": "specifies a value between white and black.
\n", "type": "Number" }, { "name": "a", "description": "", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 625, "params": [ { "name": "v1", "description": "red value if color mode is RGB, or hue value if color mode is HSB.
\n", "type": "Number" }, { "name": "v2", "description": "green value if color mode is RGB, or saturation value if color mode is HSB.
\n", "type": "Number" }, { "name": "v3", "description": "blue value if color mode is RGB, or brightness value if color mode is HSB.
\n", "type": "Number" }, { "name": "a", "description": "", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 634, "params": [ { "name": "values", "description": "an array containing the red, green, blue\n and alpha components of the color.
\n", "type": "Number[]" } ], "chainable": 1 }, { "line": 641, "params": [ { "name": "image", "description": "image created with loadImage()\n 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": 655, "description": "Clears the pixels on the canvas.
\nclear()
makes every pixel 100% transparent. Calling clear()
doesn't\nclear objects created by createX()
functions such as\ncreateGraphics(),\ncreateVideo(), and\ncreateImg(). These objects will remain\nunchanged after calling clear()
and can be redrawn.
In WebGL mode, this function can clear the screen to a specific color. It\ninterprets four numeric parameters as normalized RGBA color values. It also\nclears the depth buffer. If you are not using the WebGL renderer, these\nparameters will have no effect.
\n", "itemtype": "method", "name": "clear", "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A gray square. White circles are drawn as the user moves the mouse. The circles disappear when the user presses the mouse.');\n}\n\nfunction draw() {\n circle(mouseX, mouseY, 20);\n}\n\nfunction mousePressed() {\n clear();\n background(200);\n}\n
\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n\n pg = createGraphics(60, 60);\n pg.background(200);\n pg.noStroke();\n pg.circle(pg.width / 2, pg.height / 2, 15);\n image(pg, 20, 20);\n\n describe('A white circle drawn on a gray square. The square gets smaller when the mouse is pressed.');\n}\n\nfunction mousePressed() {\n clear();\n image(pg, 20, 20);\n}\n
\nnormalized red value.
\n", "type": "Number", "optional": true }, { "name": "g", "description": "normalized green value.
\n", "type": "Number", "optional": true }, { "name": "b", "description": "normalized blue value.
\n", "type": "Number", "optional": true }, { "name": "a", "description": "normalized alpha value.
\n", "type": "Number", "optional": true } ], "class": "p5", "module": "Color", "submodule": "Setting" }, { "file": "src/color/setting.js", "line": 733, "description": "Changes the way color values are interpreted.
\nBy default, the Number
parameters for fill(),\nstroke(),\nbackground(), and\ncolor() are defined by values between 0 and 255\nusing the RGB color model. This is equivalent to calling\ncolorMode(RGB, 255)
. Pure red is color(255, 0, 0)
in this model.
Calling colorMode(RGB, 100)
sets colors to use RGB color values\nbetween 0 and 100. Pure red is color(100, 0, 0)
in this model.
Calling colorMode(HSB)
or colorMode(HSL)
changes to HSB or HSL system\ninstead of RGB. Pure red is color(0, 100, 100)
in HSB and\ncolor(0, 100, 50)
in HSL.
p5.Color objects remember the mode that they were\ncreated in. Changing modes doesn't affect their appearance.
\n", "itemtype": "method", "name": "colorMode", "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Fill with pure red.\n fill(255, 0, 0);\n\n circle(50, 50, 25);\n\n describe('A gray square with a red circle at its center.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use RGB color with values in the range 0-100.\n colorMode(RGB, 100);\n\n // Fill with pure red.\n fill(100, 0, 0);\n\n circle(50, 50, 25);\n\n describe('A gray square with a red circle at its center.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use HSB color.\n colorMode(HSB);\n\n // Fill with pure red.\n fill(0, 100, 100);\n\n circle(50, 50, 25);\n\n describe('A gray square with a red circle at its center.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use HSL color.\n colorMode(HSL);\n\n // Fill with pure red.\n fill(0, 100, 50);\n\n circle(50, 50, 25);\n\n describe('A gray square with a red circle at its center.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use RGB color with values in the range 0-100.\n colorMode(RGB, 100);\n\n for (let x = 0; x < 100; x += 1) {\n for (let y = 0; y < 100; y += 1) {\n stroke(x, y, 0);\n point(x, y);\n }\n }\n\n describe(\n 'A diagonal green to red gradient from bottom-left to top-right with shading transitioning to black at top-left corner.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use HSB color with values in the range 0-100.\n colorMode(HSB, 100);\n\n for (let x = 0; x < 100; x += 1) {\n for (let y = 0; y < 100; y += 1) {\n stroke(x, y, 100);\n point(x, y);\n }\n }\n\n describe('A rainbow gradient from left-to-right. Brightness transitions to white at the top.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Color object.\n let myColor = color(180, 175, 230);\n background(myColor);\n\n // Use RGB color with values in the range 0-1.\n colorMode(RGB, 1);\n\n // Get the red, green, and blue color components.\n let redValue = red(myColor);\n let greenValue = green(myColor);\n let blueValue = blue(myColor);\n\n // Round the color components for display.\n redValue = round(redValue, 2);\n greenValue = round(greenValue, 2);\n blueValue = round(blueValue, 2);\n\n // Display the color components.\n text(`Red: ${redValue}`, 10, 10, 80, 80);\n text(`Green: ${greenValue}`, 10, 40, 80, 80);\n text(`Blue: ${blueValue}`, 10, 70, 80, 80);\n\n describe('A purple canvas with the red, green, and blue decimal values of the color written on it.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(255);\n\n // Use RGB color with alpha values in the range 0-1.\n colorMode(RGB, 255, 255, 255, 1);\n\n noFill();\n strokeWeight(4);\n stroke(255, 0, 10, 0.3);\n circle(40, 40, 50);\n circle(50, 60, 50);\n\n describe('Two overlapping translucent pink circle outlines.');\n}\n
\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": 938, "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": 982, "description": "Sets the color used to fill shapes.
\nCalling fill(255, 165, 0)
or fill('orange')
means all shapes drawn\nafter the fill command will be filled with the color orange.
The version of fill()
with one parameter interprets the value one of\nthree ways. If the parameter is a Number
, it's interpreted as a grayscale\nvalue. If the parameter is a String
, it's interpreted as a CSS color\nstring. A p5.Color object can also be provided to\nset the fill color.
The version of fill()
with three parameters interprets them as RGB, HSB,\nor HSL colors, depending on the current\ncolorMode(). The default color space is RGB,\nwith each value in the range from 0 to 255.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // A grayscale value.\n fill(51);\n square(20, 20, 60);\n\n describe('A dark charcoal gray square with a black outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // R, G & B values.\n fill(255, 204, 0);\n square(20, 20, 60);\n\n describe('A yellow square with a black outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(100);\n\n // Use HSB color.\n colorMode(HSB);\n\n // H, S & B values.\n fill(255, 204, 100);\n square(20, 20, 60);\n\n describe('A royal blue square with a black outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // A CSS named color.\n fill('red');\n square(20, 20, 60);\n\n describe('A red square with a black outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Three-digit hex RGB notation.\n fill('#fae');\n square(20, 20, 60);\n\n describe('A pink square with a black outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Six-digit hex RGB notation.\n fill('#A251FA');\n square(20, 20, 60);\n\n describe('A purple square with a black outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Integer RGB notation.\n fill('rgb(0, 255, 0)');\n square(20, 20, 60);\n\n describe('A bright green square with a black outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Integer RGBA notation.\n fill('rgba(0, 255, 0, 0.25)');\n square(20, 20, 60);\n\n describe('A soft green rectange with a black outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Percentage RGB notation.\n fill('rgb(100%, 0%, 10%)');\n square(20, 20, 60);\n\n describe('A red square with a black outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Percentage RGBA notation.\n fill('rgba(100%, 0%, 100%, 0.5)');\n square(20, 20, 60);\n\n describe('A dark fuchsia square with a black outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // A p5.Color object.\n let c = color(0, 0, 255);\n fill(c);\n square(20, 20, 60);\n\n describe('A blue square with a black outline.');\n}\n
\nred value if color mode is RGB or hue value if color mode is HSB.
\n", "type": "Number" }, { "name": "v2", "description": "green value if color mode is RGB or saturation value if color mode is HSB.
\n", "type": "Number" }, { "name": "v3", "description": "blue value if color mode is RGB or brightness value if color mode is HSB.
\n", "type": "Number" }, { "name": "alpha", "description": "", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 1187, "params": [ { "name": "value", "description": "a color string.
\n", "type": "String" } ], "chainable": 1 }, { "line": 1193, "params": [ { "name": "gray", "description": "a grayscale value.
\n", "type": "Number" }, { "name": "alpha", "description": "", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 1200, "params": [ { "name": "values", "description": "an array containing the red, green, blue &\n and alpha components of the color.
\n", "type": "Number[]" } ], "chainable": 1 }, { "line": 1207, "params": [ { "name": "color", "description": "the fill color.
\n", "type": "p5.Color" } ], "chainable": 1 } ] }, { "file": "src/color/setting.js", "line": 1219, "description": "Disables setting the fill color for shapes.
\nCalling noFill()
is the same as making the fill completely transparent,\nas in fill(0, 0)
. If both noStroke() and\nnoFill()
are called, nothing will be drawn to the screen.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw the top square.\n square(32, 10, 35);\n\n // Draw the bottom square.\n noFill();\n square(32, 55, 35);\n\n describe('A white square on above an empty square. Both squares have black outlines.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A purple cube wireframe spinning on a black canvas.');\n}\n\nfunction draw() {\n background(0);\n\n // Style the box.\n noFill();\n stroke(100, 100, 240);\n\n // Rotate the coordinates.\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n\n // Draw the box.\n box(45);\n}\n
\nDisables drawing points, lines, and the outlines of shapes.
\nCalling noStroke()
is the same as making the stroke completely transparent,\nas in stroke(0, 0)
. If both noStroke()
and\nnoFill() are called, nothing will be drawn to the\nscreen.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n noStroke();\n square(20, 20, 60);\n\n describe('A white square with no outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A pink cube with no edge outlines spinning on a black canvas.');\n}\n\nfunction draw() {\n background(0);\n\n // Style the box.\n noStroke();\n fill(240, 150, 150);\n\n // Rotate the coordinates.\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n\n // Draw the box.\n box(45);\n}\n
\nSets the color used to draw points, lines, and the outlines of shapes.
\nCalling stroke(255, 165, 0)
or stroke('orange')
means all shapes drawn\nafter calling stroke()
will be filled with the color orange. The way\nthese parameters are interpreted may be changed with the\ncolorMode() function.
The version of stroke()
with one parameter interprets the value one of\nthree ways. If the parameter is a Number
, it's interpreted as a grayscale\nvalue. If the parameter is a String
, it's interpreted as a CSS color\nstring. A p5.Color object can also be provided to\nset the stroke color.
The version of stroke()
with two parameters interprets the first one as a\ngrayscale value. The second parameter sets the alpha (transparency) value.
The version of stroke()
with three parameters interprets them as RGB, HSB,\nor HSL colors, depending on the current colorMode()
.
The version of stroke()
with four parameters interprets them as RGBA, HSBA,\nor HSLA colors, depending on the current colorMode()
. The last parameter\nsets the alpha (transparency) value.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // A grayscale value.\n strokeWeight(4);\n stroke(51);\n square(20, 20, 60);\n\n describe('A white square with a dark charcoal gray outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // R, G & B values.\n stroke(255, 204, 0);\n strokeWeight(4);\n square(20, 20, 60);\n\n describe('A white square with a yellow outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use HSB color.\n colorMode(HSB);\n\n // H, S & B values.\n strokeWeight(4);\n stroke(255, 204, 100);\n square(20, 20, 60);\n\n describe('A white square with a royal blue outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // A CSS named color.\n stroke('red');\n strokeWeight(4);\n square(20, 20, 60);\n\n describe('A white square with a red outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Three-digit hex RGB notation.\n stroke('#fae');\n strokeWeight(4);\n square(20, 20, 60);\n\n describe('A white square with a pink outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Six-digit hex RGB notation.\n stroke('#222222');\n strokeWeight(4);\n square(20, 20, 60);\n\n describe('A white square with a black outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Integer RGB notation.\n stroke('rgb(0, 255, 0)');\n strokeWeight(4);\n square(20, 20, 60);\n\n describe('A whiite square with a bright green outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Integer RGBA notation.\n stroke('rgba(0, 255, 0, 0.25)');\n strokeWeight(4);\n square(20, 20, 60);\n\n describe('A white square with a soft green outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Percentage RGB notation.\n stroke('rgb(100%, 0%, 10%)');\n strokeWeight(4);\n square(20, 20, 60);\n\n describe('A white square with a red outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Percentage RGBA notation.\n stroke('rgba(100%, 0%, 100%, 0.5)');\n strokeWeight(4);\n square(20, 20, 60);\n\n describe('A white square with a dark fuchsia outline.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // A p5.Color object.\n stroke(color(0, 0, 255));\n strokeWeight(4);\n square(20, 20, 60);\n\n describe('A white square with a blue outline.');\n}\n
\nred value if color mode is RGB or hue value if color mode is HSB.
\n", "type": "Number" }, { "name": "v2", "description": "green value if color mode is RGB or saturation value if color mode is HSB.
\n", "type": "Number" }, { "name": "v3", "description": "blue value if color mode is RGB or brightness value if color mode is HSB.
\n", "type": "Number" }, { "name": "alpha", "description": "", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 1558, "params": [ { "name": "value", "description": "a color string.
\n", "type": "String" } ], "chainable": 1 }, { "line": 1564, "params": [ { "name": "gray", "description": "a grayscale value.
\n", "type": "Number" }, { "name": "alpha", "description": "", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 1571, "params": [ { "name": "values", "description": "an array containing the red, green, blue,\n and alpha components of the color.
\n", "type": "Number[]" } ], "chainable": 1 }, { "line": 1578, "params": [ { "name": "color", "description": "the stroke color.
\n", "type": "p5.Color" } ], "chainable": 1 } ] }, { "file": "src/color/setting.js", "line": 1591, "description": "Starts using shapes to erase parts of the canvas.
\nAll drawing that follows erase()
will subtract from the canvas, revealing\nthe web page underneath. The erased areas will become transparent, allowing\nthe content behind the canvas to show through. The\nfill(), stroke(), and\nblendMode() have no effect once erase()
is\ncalled.
The erase()
function has two optional parameters. The first parameter\nsets the strength of erasing by the shape's interior. A value of 0 means\nthat no erasing will occur. A value of 255 means that the shape's interior\nwill fully erase the content underneath. The default value is 255\n(full strength).
The second parameter sets the strength of erasing by the shape's edge. A\nvalue of 0 means that no erasing will occur. A value of 255 means that the\nshape's edge will fully erase the content underneath. The default value is\n255 (full strength).
\nTo cancel the erasing effect, use the noErase()\nfunction.
\nerase()
has no effect on drawing done with the\nimage() and\nbackground() functions.
a number (0-255) for the strength of erasing under a shape's interior.\n Defaults to 255, which is full strength.
\n", "type": "Number", "optional": true }, { "name": "strengthStroke", "description": "a number (0-255) for the strength of erasing under a shape's edge.\n Defaults to 255, which is full strength.
\n", "type": "Number", "optional": true } ], "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(100, 100, 250);\n\n // Draw a pink square.\n fill(250, 100, 100);\n square(20, 20, 60);\n\n // Erase a circular area.\n erase();\n circle(25, 30, 30);\n noErase();\n\n describe('A purple canvas with a pink square in the middle. A circle is erased from the top-left, leaving a hole.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(100, 100, 250);\n\n // Draw a pink square.\n fill(250, 100, 100);\n square(20, 20, 60);\n\n // Erase a circular area.\n strokeWeight(5);\n erase(150, 255);\n circle(25, 30, 30);\n noErase();\n\n describe('A purple canvas with a pink square in the middle. A circle at the top-left partially erases its interior and a fully erases its outline.');\n}\n
\nEnds erasing that was started with erase().
\nThe fill(), stroke(), and\nblendMode() settings will return to what they\nwere prior to calling erase().
\n", "itemtype": "method", "name": "noErase", "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(235, 145, 15);\n\n // Draw the left rectangle.\n noStroke();\n fill(30, 45, 220);\n rect(30, 10, 10, 80);\n\n // Erase a circle.\n erase();\n circle(50, 50, 60);\n noErase();\n\n // Draw the right rectangle.\n rect(70, 10, 10, 80);\n\n describe('An orange canvas with two tall blue rectangles. A circular hole in the center erases the rectangle on the left but not the one on the right.');\n}\n
\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).
\nDraws an arc.
\nAn arc is a section of an ellipse defined by the x
, y
, w
, and\nh
parameters. x
and y
set the location of the arc's center. w
and\nh
set the arc's width and height. See\nellipse() and\nellipseMode() for more details.
The fifth and sixth parameters, start
and stop
, set the angles\nbetween which to draw the arc. Arcs are always drawn clockwise from\nstart
to stop
. Angles are always given in radians.
The seventh parameter, mode
, is optional. It determines the arc's fill\nstyle. The fill modes are a semi-circle (OPEN
), a closed semi-circle\n(CHORD
), or a closed pie segment (PIE
).
The eighth parameter, detail
, is also optional. It determines how many\nvertices are used to draw the arc in WebGL mode. The default value is 25.
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\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n arc(50, 50, 80, 80, 0, PI + HALF_PI);\n\n describe('A white circle on a gray canvas. The top-right quarter of the circle is missing.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n arc(50, 50, 80, 40, 0, PI + HALF_PI);\n\n describe('A white ellipse on a gray canvas. The top-right quarter of the ellipse is missing.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Bottom-right.\n arc(50, 55, 50, 50, 0, HALF_PI);\n\n noFill();\n\n // Bottom-left.\n arc(50, 55, 60, 60, HALF_PI, PI);\n\n // Top-left.\n arc(50, 55, 70, 70, PI, PI + QUARTER_PI);\n\n // Top-right.\n arc(50, 55, 80, 80, PI + QUARTER_PI, TWO_PI);\n\n describe(\n 'A shattered outline of an circle with a quarter of a white circle at the bottom-right.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Default fill mode.\n arc(50, 50, 80, 80, 0, PI + QUARTER_PI);\n\n describe('A white circle with the top-right third missing. The bottom is outlined in black.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // OPEN fill mode.\n arc(50, 50, 80, 80, 0, PI + QUARTER_PI, OPEN);\n\n describe(\n 'A white circle missing a section from the top-right. The bottom is outlined in black.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // CHORD fill mode.\n arc(50, 50, 80, 80, 0, PI + QUARTER_PI, CHORD);\n\n describe('A white circle with a black outline missing a section from the top-right.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // PIE fill mode.\n arc(50, 50, 80, 80, 0, PI + QUARTER_PI, PIE);\n\n describe('A white circle with a black outline. The top-right third is missing.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n // PIE fill mode.\n arc(0, 0, 80, 80, 0, PI + QUARTER_PI, PIE);\n\n describe('A white circle with a black outline. The top-right third is missing.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n // PIE fill mode with 5 vertices.\n arc(0, 0, 80, 80, 0, PI + QUARTER_PI, PIE, 5);\n\n describe('A white circle with a black outline. The top-right third is missing.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A yellow circle on a black background. The circle opens and closes its mouth.');\n}\n\nfunction draw() {\n background(0);\n\n // Style the arc.\n noStroke();\n fill(255, 255, 0);\n\n // Update start and stop angles.\n let biteSize = PI / 16;\n let startAngle = biteSize * sin(frameCount * 0.1) + biteSize;\n let endAngle = TWO_PI - startAngle;\n\n // Draw the arc.\n arc(50, 50, 80, 80, startAngle, endAngle, PIE);\n}\n
\nDraws an ellipse (oval).
\nAn ellipse is a round shape defined by the x
, y
, w
, and\nh
parameters. x
and y
set the location of its center. w
and\nh
set its width and height. See\nellipseMode() for other ways to set\nits position.
If no height is set, the value of width is used for both the width and\nheight. If a negative height or width is specified, the absolute value is\ntaken.
\nThe fifth parameter, detail
, is also optional. It determines how many\nvertices are used to draw the ellipse in WebGL mode. The default value is\n25.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n ellipse(50, 50, 80, 80);\n\n describe('A white circle on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n ellipse(50, 50, 80);\n\n describe('A white circle on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n ellipse(50, 50, 80, 40);\n\n describe('A white ellipse on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n ellipse(0, 0, 80, 40);\n\n describe('A white ellipse on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n // Use 6 vertices.\n ellipse(0, 0, 80, 40, 6);\n\n describe('A white hexagon on a gray canvas.');\n}\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": 474, "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": 490, "description": "Draws a circle.
\nA circle is a round shape defined by the x
, y
, and d
\nparameters. x
and y
set the location of its center. d
sets its\nwidth and height (diameter). Every point on the circle's edge is the\nsame distance, d
, from its center. See\nellipseMode() for other ways to set\nits position.
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\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n circle(50, 50, 25);\n\n describe('A white circle with black outline in the middle of a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n circle(0, 0, 25);\n\n describe('A white circle with black outline in the middle of a gray canvas.');\n}\n
\nDraws a straight line between two points.
\nA line's default width is one pixel. The version of line()
with four\nparameters draws the line in 2D. To color a line, use the\nstroke() function. To change its width, use the\nstrokeWeight() function. A line\ncan't be filled, so the fill() function won't\naffect the line's color.
The version of line()
with six parameters allows the line to be drawn in\n3D space. Doing so requires adding the WEBGL
argument to\ncreateCanvas().
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n line(30, 20, 85, 75);\n\n describe(\n 'A black line on a gray canvas running from top-center to bottom-right.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the line.\n stroke('magenta');\n strokeWeight(5);\n\n line(30, 20, 85, 75);\n\n describe(\n 'A thick, magenta line on a gray canvas running from top-center to bottom-right.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Top.\n line(30, 20, 85, 20);\n\n // Right.\n stroke(126);\n line(85, 20, 85, 75);\n\n // Bottom.\n stroke(255);\n line(85, 75, 30, 75);\n\n describe(\n 'Three lines drawn in grayscale on a gray canvas. They form the top, right, and bottom sides of a square.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n line(-20, -30, 35, 25);\n\n describe(\n 'A black line on a gray canvas running from top-center to bottom-right.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A black line connecting two spheres. The scene spins slowly.');\n}\n\nfunction draw() {\n background(200);\n\n // Rotate around the y-axis.\n rotateY(frameCount * 0.01);\n\n // Draw a line.\n line(0, 0, 0, 30, 20, -10);\n\n // Draw the center sphere.\n sphere(10);\n\n // Translate to the second point.\n translate(30, 20, -10);\n\n // Draw the bottom-right sphere.\n sphere(10);\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": 706, "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": 731, "description": "Draws a single point in space.
\nA point's default width is one pixel. To color a point, use the\nstroke() function. To change its width, use the\nstrokeWeight() function. A point\ncan't be filled, so the fill() function won't\naffect the point's color.
\nThe version of point()
with one parameter allows the point's location to\nbe set with its x- and y-coordinates, as in point(10, 20)
.
The version of point()
with three parameters allows the point to be drawn\nin 3D space with x-, y-, and z-coordinates, as in point(10, 20, 30)
.\nDoing so requires adding the WEBGL
argument to\ncreateCanvas().
The version of point()
with one parameter allows the point's location to\nbe set with a p5.Vector object.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Top-left.\n point(30, 20);\n\n // Top-right.\n point(85, 20);\n\n // Bottom-right.\n point(85, 75);\n\n // Bottom-left.\n point(30, 75);\n\n describe(\n 'Four small, black points drawn on a gray canvas. The points form the corners of a square.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Top-left.\n point(30, 20);\n\n // Top-right.\n point(70, 20);\n\n // Style the next points.\n stroke('purple');\n strokeWeight(10);\n\n // Bottom-right.\n point(70, 80);\n\n // Bottom-left.\n point(30, 80);\n\n describe(\n 'Four points drawn on a gray canvas. Two are black and two are purple. The points form the corners of a square.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Top-left.\n let a = createVector(30, 20);\n point(a);\n\n // Top-right.\n let b = createVector(70, 20);\n point(b);\n\n // Bottom-right.\n let c = createVector(70, 80);\n point(c);\n\n // Bottom-left.\n let d = createVector(30, 80);\n point(d);\n\n describe(\n 'Four small, black points drawn on a gray canvas. The points form the corners of a square.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('Two purple points drawn on a gray canvas.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the points.\n stroke('purple');\n strokeWeight(10);\n\n // Top-left.\n point(-20, -30);\n\n // Bottom-right.\n point(20, 30);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('Two purple points drawn on a gray canvas. The scene spins slowly.');\n}\n\nfunction draw() {\n background(200);\n\n // Rotate around the y-axis.\n rotateY(frameCount * 0.01);\n\n // Style the points.\n stroke('purple');\n strokeWeight(10);\n\n // Top-left.\n point(-20, -30, 0);\n\n // Bottom-right.\n point(20, 30, -50);\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": 895, "params": [ { "name": "coordinateVector", "description": "the coordinate vector.
\n", "type": "p5.Vector" } ], "chainable": 1 } ] }, { "file": "src/core/shape/2d_primitives.js", "line": 923, "description": "Draws a quadrilateral (four-sided shape).
\nQuadrilaterals include rectangles, squares, rhombuses, and trapezoids. The\nfirst pair of parameters (x1, y1)
sets the quad's first point. The next\nthree pairs of parameters set the coordinates for its next three points\n(x2, y2)
, (x3, y3)
, and (x4, y4)
. Points should be added in either\nclockwise or counter-clockwise order.
The version of quad()
with twelve parameters allows the quad to be drawn\nin 3D space. Doing so requires adding the WEBGL
argument to\ncreateCanvas().
The thirteenth and fourteenth parameters are optional. In WebGL mode, they\nset the number of segments used to draw the quadrilateral in the x- and\ny-directions. They're both 25 by default.
\n", "itemtype": "method", "name": "quad", "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n quad(20, 20, 80, 20, 80, 80, 20, 80);\n\n describe('A white square with a black outline drawn on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n quad(20, 30, 80, 30, 80, 70, 20, 70);\n\n describe('A white rectangle with a black outline drawn on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n quad(50, 62, 86, 50, 50, 38, 14, 50);\n\n describe('A white rhombus with a black outline drawn on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n quad(20, 50, 80, 30, 80, 70, 20, 70);\n\n describe('A white trapezoid with a black outline drawn on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n quad(-30, -30, 30, -30, 30, 30, -30, 30);\n\n describe('A white square with a black outline drawn on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A wavy white surface spins around on gray canvas.');\n}\n\nfunction draw() {\n background(200);\n\n // Rotate around the y-axis.\n rotateY(frameCount * 0.01);\n\n // Draw the quad.\n quad(-30, -30, 0, 30, -30, 0, 30, 30, 20, -30, 30, -20);\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" }, { "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": 1043, "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": 1086, "description": "Draws a rectangle.
\nA rectangle is a four-sided shape defined by the x
, y
, w
, and h
\nparameters. x
and y
set the location of its top-left corner. w
sets\nits width and h
sets its height. Every angle in the rectangle measures\n90˚. See rectMode() for other ways to define\nrectangles.
The version of rect()
with five parameters creates a rounded rectangle. The\nfifth parameter sets the radius for all four corners.
The version of rect()
with eight parameters also creates a rounded\nrectangle. Each of the last four parameters set the radius of a corner. The\nradii start with the top-left corner and move clockwise around the\nrectangle. If any of these parameters are omitted, they are set to the\nvalue of the last radius that was set.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n rect(30, 20, 55, 55);\n\n describe('A white square with a black outline on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n rect(30, 20, 55, 40);\n\n describe('A white rectangle with a black outline on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Give all corners a radius of 20.\n rect(30, 20, 55, 50, 20);\n\n describe('A white rectangle with a black outline and round edges on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Give each corner a unique radius.\n rect(30, 20, 55, 50, 20, 15, 10, 5);\n\n describe('A white rectangle with a black outline and round edges of different radii.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n rect(-20, -30, 55, 55);\n\n describe('A white square with a black outline on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white square spins around on gray canvas.');\n}\n\nfunction draw() {\n background(200);\n\n // Rotate around the y-axis.\n rotateY(frameCount * 0.01);\n\n // Draw the rectangle.\n rect(-20, -30, 55, 55);\n}\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": 1209, "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": 1224, "description": "Draws a square.
\nA square is a four-sided shape defined by the x
, y
, and s
\nparameters. x
and y
set the location of its top-left corner. s
sets\nits width and height. Every angle in the square measures 90˚ and all its\nsides are the same length. See rectMode() for\nother ways to define squares.
The version of square()
with four parameters creates a rounded square.\nThe fourth parameter sets the radius for all four corners.
The version of square()
with seven parameters also creates a rounded\nsquare. Each of the last four parameters set the radius of a corner. The\nradii start with the top-left corner and move clockwise around the\nsquare. If any of these parameters are omitted, they are set to the\nvalue of the last radius that was set.
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\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n square(30, 20, 55);\n\n describe('A white square with a black outline in on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Give all corners a radius of 20.\n square(30, 20, 55, 20);\n\n describe(\n 'A white square with a black outline and round edges on a gray canvas.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Give each corner a unique radius.\n square(30, 20, 55, 20, 15, 10, 5);\n\n describe('A white square with a black outline and round edges of different radii.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n square(-20, -30, 55);\n\n describe('A white square with a black outline in on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white square spins around on gray canvas.');\n}\n\nfunction draw() {\n background(200);\n\n // Rotate around the y-axis.\n rotateY(frameCount * 0.01);\n\n // Draw the square.\n square(-20, -30, 55);\n}\n
\nDraws a triangle.
\nA triangle is a three-sided shape defined by three points. The\nfirst two parameters specify the triangle's first point (x1, y1)
. The\nmiddle two parameters specify its second point (x2, y2)
. And the last two\nparameters specify its third point (x3, y3)
.
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\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n triangle(30, 75, 58, 20, 86, 75);\n\n describe('A white triangle with a black outline on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n triangle(-20, 25, 8, -30, 36, 25);\n\n describe('A white triangle with a black outline on a gray canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white triangle spins around on a gray canvas.');\n}\n\nfunction draw() {\n background(200);\n\n // Rotate around the y-axis.\n rotateY(frameCount * 0.01);\n\n // Draw the triangle.\n triangle(-20, 25, 8, -30, 36, 25);\n}\n
\nChanges where ellipses, circles, and arcs are drawn.
\nBy default, the first two parameters of\nellipse(), circle(),\nand arc()\nare the x- and y-coordinates of the shape's center. The next parameters set\nthe shape's width and height. This is the same as calling\nellipseMode(CENTER)
.
ellipseMode(RADIUS)
also uses the first two parameters to set the x- and\ny-coordinates of the shape's center. The next parameters are half of the\nshapes's width and height. Calling ellipse(0, 0, 10, 15)
draws a shape\nwith a width of 20 and height of 30.
ellipseMode(CORNER)
uses the first two parameters as the upper-left\ncorner of the shape. The next parameters are its width and height.
ellipseMode(CORNERS)
uses the first two parameters as the location of one\ncorner of the ellipse's bounding box. The next parameters are the location\nof the opposite corner.
The argument passed to ellipseMode()
must be written in ALL CAPS because\nthe constants CENTER
, RADIUS
, CORNER
, and CORNERS
are defined this\nway. JavaScript is a case-sensitive language.
either CENTER, RADIUS, CORNER, or CORNERS
\n", "type": "Constant" } ], "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // White ellipse.\n ellipseMode(RADIUS);\n fill(255);\n ellipse(50, 50, 30, 30);\n\n // Gray ellipse.\n ellipseMode(CENTER);\n fill(100);\n ellipse(50, 50, 30, 30);\n\n describe('A white circle with a gray circle at its center. Both circles have black outlines.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // White ellipse.\n ellipseMode(CORNER);\n fill(255);\n ellipse(25, 25, 50, 50);\n\n // Gray ellipse.\n ellipseMode(CORNERS);\n fill(100);\n ellipse(25, 25, 50, 50);\n\n describe('A white circle with a gray circle at its top-left corner. Both circles have black outlines.');\n}\n
\nDraws certain features with jagged (aliased) edges.
\nsmooth() is active by default. In 2D mode,\nnoSmooth()
is helpful for scaling up images without blurring. The\nfunctions don't affect shapes or fonts.
In WebGL mode, noSmooth()
causes all shapes to be drawn with jagged\n(aliased) edges. The functions don't affect images or fonts.
\nlet heart;\n\n// Load a pixelated heart image from an image data string.\nfunction preload() {\n heart = loadImage('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAAXNSR0IArs4c6QAAAEZJREFUGFd9jcsNACAIQ9tB2MeR3YdBMBBq8CIXPi2vBICIiOwkOedatllqWO6Y8yOWoyuNf1GZwgmf+RRG2YXr+xVFmA8HZ9Mx/KGPMtcAAAAASUVORK5CYII=');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Antialiased hearts.\n image(heart, 10, 10);\n image(heart, 20, 10, 16, 16);\n image(heart, 40, 10, 32, 32);\n\n // Aliased hearts.\n noSmooth();\n image(heart, 10, 60);\n image(heart, 20, 60, 16, 16);\n image(heart, 40, 60, 32, 32);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n circle(0, 0, 80);\n\n describe('A white circle on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Disable smoothing.\n noSmooth();\n\n background(200);\n\n circle(0, 0, 80);\n\n describe('A pixelated white circle on a gray background.');\n}\n
\nChanges where rectangles and squares are drawn.
\nBy default, the first two parameters of\nrect() and square(),\nare the x- and y-coordinates of the shape's center. The next parameters set\nthe shape's width and height. This is the same as calling\nrectMode(CORNER)
.
rectMode(CORNERS)
also uses the first two parameters as the location of\none of the corners. The next parameters are the location of the opposite\ncorner. This mode only works for rect().
rectMode(CENTER)
uses the first two parameters as the x- and\ny-coordinates of the shape's center. The next parameters are its width and\nheight.
rectMode(RADIUS)
also uses the first two parameters as the x- and\ny-coordinates of the shape's center. The next parameters are\nhalf of the shape's width and height.
The argument passed to rectMode()
must be written in ALL CAPS because the\nconstants CENTER
, RADIUS
, CORNER
, and CORNERS
are defined this way.\nJavaScript is a case-sensitive language.
either CORNER, CORNERS, CENTER, or RADIUS
\n", "type": "Constant" } ], "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n rectMode(CORNER);\n fill(255);\n rect(25, 25, 50, 50);\n\n rectMode(CORNERS);\n fill(100);\n rect(25, 25, 50, 50);\n\n describe('A small gray square drawn at the top-left corner of a white square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n rectMode(RADIUS);\n fill(255);\n rect(50, 50, 30, 30);\n\n rectMode(CENTER);\n fill(100);\n rect(50, 50, 30, 30);\n\n describe('A small gray square drawn at the center of a white square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n rectMode(CORNER);\n fill(255);\n square(25, 25, 50);\n\n describe('A white square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n rectMode(RADIUS);\n fill(255);\n square(50, 50, 30);\n\n rectMode(CENTER);\n fill(100);\n square(50, 50, 30);\n\n describe('A small gray square drawn at the center of a white square.');\n}\n
\nDraws certain features with smooth (antialiased) edges.
\nsmooth()
is active by default. In 2D mode,\nnoSmooth() is helpful for scaling up images\nwithout blurring. The functions don't affect shapes or fonts.
In WebGL mode, noSmooth() causes all shapes to\nbe drawn with jagged (aliased) edges. The functions don't affect images or\nfonts.
\n", "itemtype": "method", "name": "smooth", "chainable": 1, "example": [ "\n\nlet heart;\n\n// Load a pixelated heart image from an image data string.\nfunction preload() {\n heart = loadImage('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAAXNSR0IArs4c6QAAAEZJREFUGFd9jcsNACAIQ9tB2MeR3YdBMBBq8CIXPi2vBICIiOwkOedatllqWO6Y8yOWoyuNf1GZwgmf+RRG2YXr+xVFmA8HZ9Mx/KGPMtcAAAAASUVORK5CYII=');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Antialiased hearts.\n image(heart, 10, 10);\n image(heart, 20, 10, 16, 16);\n image(heart, 40, 10, 32, 32);\n\n // Aliased hearts.\n noSmooth();\n image(heart, 10, 60);\n image(heart, 20, 60, 16, 16);\n image(heart, 40, 60, 32, 32);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n circle(0, 0, 80);\n\n describe('A white circle on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Disable smoothing.\n noSmooth();\n\n background(200);\n\n circle(0, 0, 80);\n\n describe('A pixelated white circle on a gray background.');\n}\n
\nSets the style for rendering the ends of lines.
\nThe caps for line endings are either rounded (ROUND
), squared\n(SQUARE
), or extended (PROJECT
). The default cap is ROUND
.
The argument passed to strokeCap()
must be written in ALL CAPS because\nthe constants ROUND
, SQUARE
, and PROJECT
are defined this way.\nJavaScript is a case-sensitive language.
either ROUND, SQUARE, or PROJECT
\n", "type": "Constant" } ], "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n strokeWeight(12);\n\n // Top.\n strokeCap(ROUND);\n line(20, 30, 80, 30);\n\n // Middle.\n strokeCap(SQUARE);\n line(20, 50, 80, 50);\n\n // Bottom.\n strokeCap(PROJECT);\n line(20, 70, 80, 70);\n\n describe(\n 'Three horizontal lines. The top line has rounded ends, the middle line has squared ends, and the bottom line has longer, squared ends.'\n );\n}\n
\nSets the style of the joints that connect line segments.
\nJoints are either mitered (MITER
), beveled (BEVEL
), or rounded\n(ROUND
). The default joint is MITER
in 2D mode and ROUND
in WebGL\nmode.
The argument passed to strokeJoin()
must be written in ALL CAPS because\nthe constants MITER
, BEVEL
, and ROUND
are defined this way.\nJavaScript is a case-sensitive language.
either MITER, BEVEL, or ROUND
\n", "type": "Constant" } ], "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the line.\n noFill();\n strokeWeight(10);\n strokeJoin(MITER);\n\n // Draw the line.\n beginShape();\n vertex(35, 20);\n vertex(65, 50);\n vertex(35, 80);\n endShape();\n\n describe('A right-facing arrowhead shape with a pointed tip in center of canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the line.\n noFill();\n strokeWeight(10);\n strokeJoin(BEVEL);\n\n // Draw the line.\n beginShape();\n vertex(35, 20);\n vertex(65, 50);\n vertex(35, 80);\n endShape();\n\n describe('A right-facing arrowhead shape with a flat tip in center of canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the line.\n noFill();\n strokeWeight(10);\n strokeJoin(ROUND);\n\n // Draw the line.\n beginShape();\n vertex(35, 20);\n vertex(65, 50);\n vertex(35, 80);\n endShape();\n\n describe('A right-facing arrowhead shape with a rounded tip in center of canvas.');\n}\n
\nSets the width of the stroke used for points, lines, and the outlines of\nshapes.
\nNote: strokeWeight()
is affected by transformations, especially calls to\nscale().
the weight of the stroke (in pixels).
\n", "type": "Number" } ], "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Top.\n line(20, 20, 80, 20);\n\n // Middle.\n strokeWeight(4);\n line(20, 40, 80, 40);\n\n // Bottom.\n strokeWeight(10);\n line(20, 70, 80, 70);\n\n describe('Three horizontal black lines. The top line is thin, the middle is medium, and the bottom is thick.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Top.\n line(20, 20, 80, 20);\n\n // Scale by a factor of 5.\n scale(5);\n\n // Bottom. Coordinates are adjusted for scaling.\n line(4, 8, 16, 8);\n\n describe('Two horizontal black lines. The top line is thin and the bottom is five times thicker than the top.');\n}\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": 379, "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": 419, "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": 464, "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": 528, "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 is the value for the mode
parameter to close\nthe shape (to connect the beginning and the end).\nWhen using instancing with endShape() the instancing will not apply to the strokes.\nWhen the count parameter is used with a value greater than 1, it enables instancing for shapes built when in WEBGL mode. Instancing\nis a feature that allows the GPU to efficiently draw multiples of the same shape. It's often used for particle effects or other\ntimes when you need a lot of repetition. In order to take advantage of instancing, you will also need to write your own custom\nshader using the gl_InstanceID keyword. You can read more about instancing\nhere or by working from the example on this\npage.
use CLOSE to close the shape
\n", "type": "Constant", "optional": true }, { "name": "count", "description": "number of times you want to draw/instance the shape (for WebGL mode).
\n", "type": "Integer", "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
\n\nlet fx;\nlet vs = `#version 300 es\n\nprecision mediump float;\n\nin vec3 aPosition;\nflat out int instanceID;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nvoid main() {\n\n // copy the instance ID to the fragment shader\n instanceID = gl_InstanceID;\n vec4 positionVec4 = vec4(aPosition, 1.0);\n\n // gl_InstanceID represents a numeric value for each instance\n // using gl_InstanceID allows us to move each instance separately\n // here we move each instance horizontally by id * 23\n float xOffset = float(gl_InstanceID) * 23.0;\n\n // apply the offset to the final position\n gl_Position = uProjectionMatrix * uModelViewMatrix * (positionVec4 -\n vec4(xOffset, 0.0, 0.0, 0.0));\n}\n`;\nlet fs = `#version 300 es\n\nprecision mediump float;\n\nout vec4 outColor;\nflat in int instanceID;\nuniform float numInstances;\n\nvoid main() {\n vec4 red = vec4(1.0, 0.0, 0.0, 1.0);\n vec4 blue = vec4(0.0, 0.0, 1.0, 1.0);\n\n // Normalize the instance id\n float normId = float(instanceID) / numInstances;\n\n // Mix between two colors using the normalized instance id\n outColor = mix(red, blue, normId);\n}\n`;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n fx = createShader(vs, fs);\n}\n\nfunction draw() {\n background(220);\n\n // strokes aren't instanced, and are rather used for debug purposes\n shader(fx);\n fx.setUniform('numInstances', 4);\n\n // this doesn't have to do with instancing, this is just for centering the squares\n translate(25, -10);\n\n // here we draw the squares we want to instance\n beginShape();\n vertex(0, 0);\n vertex(0, 20);\n vertex(20, 20);\n vertex(20, 0);\n vertex(0, 0);\n endShape(CLOSE, 4);\n\n resetShader();\n}\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": 837, "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": 930, "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": 1061, "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": 1069, "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": 1107, "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": 1144, "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, used for computationally intensive tasks like 3D rendering and shaders.
\nWEBGL
differs from the default P2D
renderer in the following ways:
WEBGL
mode, the origin point (0,0,0) is located at the center of the screen, not the top-left corner. See the learn page about coordinates and transformations.WEBGL
mode can be used to draw 3-dimensional shapes like box(), sphere(), cone(), and more. See the learn page about custom geometry to make more complex objects.WEBGL
mode, you can specify how smooth curves should be drawn by using a detail
parameter. See the wiki section about shapes for a more information and an example.WEBGL
offers different types of lights like ambientLight() to place around a scene. Materials like specularMaterial() reflect the lighting to convey shape and depth. See the learn page for styling and appearance to experiment with different combinations.WEBGL
sketch can be adjusted by changing camera attributes. See the learn page section about cameras for an explanation of camera controls.WEBGL
requires opentype/truetype font files to be preloaded using loadFont(). See the wiki section about text for details, along with a workaround.WEBGL
mode uses the graphics card instead of the CPU, so it may help boost the performance of your sketch (example: drawing more shapes on the screen at once).To learn more about WEBGL mode, check out all the interactive WEBGL tutorials in the \"Learn\" section of this website, or read the wiki article \"Getting started with WebGL in p5\".
\n", "itemtype": "property", "name": "WEBGL", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 45, "description": "One of the two possible values of a WebGL canvas (either WEBGL or WEBGL2),\nwhich can be used to determine what capabilities the rendering environment\nhas.
\n", "itemtype": "property", "name": "WEBGL2", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 55, "itemtype": "property", "name": "ARROW", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 60, "itemtype": "property", "name": "CROSS", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 65, "itemtype": "property", "name": "HAND", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 70, "itemtype": "property", "name": "MOVE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 75, "itemtype": "property", "name": "TEXT", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 80, "itemtype": "property", "name": "WAIT", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 88, "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": 378, "itemtype": "property", "name": "HSL", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 385, "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": 395, "itemtype": "property", "name": "ALT", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 401, "itemtype": "property", "name": "BACKSPACE", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 406, "itemtype": "property", "name": "CONTROL", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 411, "itemtype": "property", "name": "DELETE", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 416, "itemtype": "property", "name": "DOWN_ARROW", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 421, "itemtype": "property", "name": "ENTER", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 426, "itemtype": "property", "name": "ESCAPE", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 431, "itemtype": "property", "name": "LEFT_ARROW", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 436, "itemtype": "property", "name": "OPTION", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 441, "itemtype": "property", "name": "RETURN", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 446, "itemtype": "property", "name": "RIGHT_ARROW", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 451, "itemtype": "property", "name": "SHIFT", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 456, "itemtype": "property", "name": "TAB", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 461, "itemtype": "property", "name": "UP_ARROW", "type": "Number", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 468, "itemtype": "property", "name": "BLEND", "type": "String", "final": 1, "default": "source-over", "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 474, "itemtype": "property", "name": "REMOVE", "type": "String", "final": 1, "default": "destination-out", "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 480, "itemtype": "property", "name": "ADD", "type": "String", "final": 1, "default": "lighter", "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 488, "itemtype": "property", "name": "DARKEST", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 493, "itemtype": "property", "name": "LIGHTEST", "type": "String", "final": 1, "default": "lighten", "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 499, "itemtype": "property", "name": "DIFFERENCE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 504, "itemtype": "property", "name": "SUBTRACT", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 509, "itemtype": "property", "name": "EXCLUSION", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 514, "itemtype": "property", "name": "MULTIPLY", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 519, "itemtype": "property", "name": "SCREEN", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 524, "itemtype": "property", "name": "REPLACE", "type": "String", "final": 1, "default": "copy", "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 530, "itemtype": "property", "name": "OVERLAY", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 535, "itemtype": "property", "name": "HARD_LIGHT", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 540, "itemtype": "property", "name": "SOFT_LIGHT", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 545, "itemtype": "property", "name": "DODGE", "type": "String", "final": 1, "default": "color-dodge", "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 551, "itemtype": "property", "name": "BURN", "type": "String", "final": 1, "default": "color-burn", "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 559, "itemtype": "property", "name": "THRESHOLD", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 564, "itemtype": "property", "name": "GRAY", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 569, "itemtype": "property", "name": "OPAQUE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 574, "itemtype": "property", "name": "INVERT", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 579, "itemtype": "property", "name": "POSTERIZE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 584, "itemtype": "property", "name": "DILATE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 589, "itemtype": "property", "name": "ERODE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 594, "itemtype": "property", "name": "BLUR", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 601, "itemtype": "property", "name": "NORMAL", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 606, "itemtype": "property", "name": "ITALIC", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 611, "itemtype": "property", "name": "BOLD", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 616, "itemtype": "property", "name": "BOLDITALIC", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 621, "itemtype": "property", "name": "CHAR", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 626, "itemtype": "property", "name": "WORD", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 638, "itemtype": "property", "name": "LINEAR", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 643, "itemtype": "property", "name": "QUADRATIC", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 648, "itemtype": "property", "name": "BEZIER", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 653, "itemtype": "property", "name": "CURVE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 660, "itemtype": "property", "name": "STROKE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 665, "itemtype": "property", "name": "FILL", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 670, "itemtype": "property", "name": "TEXTURE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 675, "itemtype": "property", "name": "IMMEDIATE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 683, "itemtype": "property", "name": "IMAGE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 691, "itemtype": "property", "name": "NEAREST", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 696, "itemtype": "property", "name": "REPEAT", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 701, "itemtype": "property", "name": "CLAMP", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 706, "itemtype": "property", "name": "MIRROR", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 713, "itemtype": "property", "name": "FLAT", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 718, "itemtype": "property", "name": "SMOOTH", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 725, "itemtype": "property", "name": "LANDSCAPE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 730, "itemtype": "property", "name": "PORTRAIT", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 740, "itemtype": "property", "name": "GRID", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 746, "itemtype": "property", "name": "AXES", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 752, "itemtype": "property", "name": "LABEL", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 757, "itemtype": "property", "name": "FALLBACK", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 763, "itemtype": "property", "name": "CONTAIN", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 769, "itemtype": "property", "name": "COVER", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 775, "itemtype": "property", "name": "UNSIGNED_BYTE", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 781, "itemtype": "property", "name": "UNSIGNED_INT", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 787, "itemtype": "property", "name": "FLOAT", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 793, "itemtype": "property", "name": "HALF_FLOAT", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/constants.js", "line": 799, "itemtype": "property", "name": "RGBA", "type": "String", "final": 1, "class": "p5", "module": "Constants", "submodule": "Constants" }, { "file": "src/core/environment.js", "line": 21, "description": "Displays text in the web browser's console.
\nprint()
is helpful for printing values while debugging. Each call to\nprint()
creates a new line of text.
Note: Call print('\\n')
to print a blank line. Calling print()
without\nan argument opens the browser's dialog for printing documents.
content to print to the console.
\n", "type": "Any" } ], "example": [ "\n\nfunction setup() {\n // Prints \"hello, world\" to the console.\n print('hello, world');\n}\n
\n\nfunction setup() {\n let name = 'ada';\n // Prints \"hello, ada\" to the console.\n print(`hello, ${name}`);\n}\n
\nA Number
variable that tracks the number of frames drawn since the sketch\nstarted.
frameCount
's value is 0 inside setup(). It\nincrements by 1 each time the code in draw()\nfinishes executing.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Display the value of\n // frameCount.\n textSize(30);\n textAlign(CENTER, CENTER);\n text(frameCount, 50, 50);\n\n describe('The number 0 written in black in the middle of a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Set the frameRate to 30.\n frameRate(30);\n\n textSize(30);\n textAlign(CENTER, CENTER);\n\n describe('A number written in black in the middle of a gray square. Its value increases rapidly.');\n}\n\nfunction draw() {\n background(200);\n\n // Display the value of\n // frameCount.\n text(frameCount, 50, 50);\n}\n
\nA Number
variable that tracks the number of milliseconds it took to draw\nthe last frame.
deltaTime
contains the amount of time it took\ndraw() to execute during the previous frame. It's\nuseful for simulating physics.
\nlet x = 0;\nlet speed = 0.05;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Set the frameRate to 30.\n frameRate(30);\n\n describe('A white circle moves from left to right on a gray background. It reappears on the left side when it reaches the right side.');\n}\n\nfunction draw() {\n background(200);\n\n // Use deltaTime to calculate\n // a change in position.\n let deltaX = speed * deltaTime;\n\n // Update the x variable.\n x += deltaX;\n\n // Reset x to 0 if it's\n // greater than 100.\n if (x > 100) {\n x = 0;\n }\n\n // Use x to set the circle's\n // position.\n circle(x, 50, 20);\n}\n
\nA Boolean
variable that's true
if the browser is focused and false
if\nnot.
Note: The browser window can only receive input if it's focused.
\n", "itemtype": "property", "name": "focused", "type": "Boolean", "readonly": "", "example": [ "\n\n// Open this example in two separate browser\n// windows placed side-by-side to demonstrate.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A square changes color from green to red when the browser window is out of focus.');\n}\n\nfunction draw() {\n // Change the background color\n // when the browser window\n // goes in/out of focus.\n if (focused === true) {\n background(0, 255, 0);\n } else {\n background(255, 0, 0);\n }\n}\n
\nChanges the cursor's appearance.
\nThe first parameter, type
, sets the type of cursor to display. The\nbuilt-in options are ARROW
, CROSS
, HAND
, MOVE
, TEXT
, and WAIT
.\ncursor()
also recognizes standard CSS cursor properties passed as\nstrings: 'help'
, 'wait'
, 'crosshair'
, 'not-allowed'
, 'zoom-in'
,\nand 'grab'
. If the path to an image is passed, as in\ncursor('assets/target.png')
, then the image will be used as the cursor.\nImages must be in .cur, .gif, .jpg, .jpeg, or .png format and should be at most 32 by 32 pixels large.
The parameters x
and y
are optional. If an image is used for the\ncursor, x
and y
set the location pointed to within the image. They are\nboth 0 by default, so the cursor points to the image's top-left corner. x
\nand y
must be less than the image's width and height, respectively.
Built-in: either ARROW, CROSS, HAND, MOVE, TEXT, or WAIT.\n Native CSS properties: 'grab', 'progress', and so on.\n Path to cursor image.
\n", "type": "String|Constant" }, { "name": "x", "description": "horizontal active spot of the cursor.
\n", "type": "Number", "optional": true }, { "name": "y", "description": "vertical active spot of the cursor.
\n", "type": "Number", "optional": true } ], "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A gray square. The cursor appears as crosshairs.');\n}\n\nfunction draw() {\n background(200);\n\n // Set the cursor to crosshairs: +\n cursor(CROSS);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A gray square divided into quadrants. The cursor image changes when the mouse moves to each quadrant.');\n}\n\nfunction draw() {\n background(200);\n\n // Divide the canvas into quadrants.\n line(50, 0, 50, 100);\n line(0, 50, 100, 50);\n\n // Change cursor based on mouse position.\n if (mouseX < 50 && mouseY < 50) {\n cursor(CROSS);\n } else if (mouseX > 50 && mouseY < 50) {\n cursor('progress');\n } else if (mouseX > 50 && mouseY > 50) {\n cursor('https://avatars0.githubusercontent.com/u/1617169?s=16');\n } else {\n cursor('grab');\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('An image of three purple curves follows the mouse. The image shifts when the mouse is pressed.');\n}\n\nfunction draw() {\n background(200);\n\n // Change the cursor's active spot\n // when the mouse is pressed.\n if (mouseIsPressed === true) {\n cursor('https://avatars0.githubusercontent.com/u/1617169?s=16', 8, 8);\n } else {\n cursor('https://avatars0.githubusercontent.com/u/1617169?s=16');\n }\n}\n
\nSets the number of frames to draw per second.
\nCalling frameRate()
with one numeric argument, as in frameRate(30)
,\nattempts to draw 30 frames per second (FPS). The target frame rate may not\nbe achieved depending on the sketch's processing needs. Most computers\ndefault to a frame rate of 60 FPS. Frame rates of 24 FPS and above are\nfast enough for smooth animations.
Calling frameRate()
without an argument returns the current frame rate.\nThe value returned is an approximation.
\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle on a gray background. The circle moves from left to right in a loop. It slows down when the mouse is pressed.');\n}\n\nfunction draw() {\n background(200);\n\n // Set the x variable based\n // on the current frameCount.\n let x = frameCount % 100;\n\n // If the mouse is pressed,\n // decrease the frame rate.\n if (mouseIsPressed === true) {\n frameRate(10);\n } else {\n frameRate(60);\n }\n\n // Use x to set the circle's\n // position.\n circle(x, 50, 20);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A number written in black on a gray background. The number decreases when the mouse is pressed.');\n}\n\nfunction draw() {\n background(200);\n\n // If the mouse is pressed, do lots\n // of math to slow down drawing.\n if (mouseIsPressed === true) {\n for (let i = 0; i < 1000000; i += 1) {\n random();\n }\n }\n\n // Get the current frame rate\n // and display it.\n let fps = frameRate();\n text(fps, 50, 50);\n}\n
\nnumber of frames to draw per second.
\n", "type": "Number" } ], "chainable": 1 }, { "line": 404, "params": [], "return": { "description": "current frame rate.", "type": "Number" } } ] }, { "file": "src/core/environment.js", "line": 447, "description": "Returns the target frame rate.
\nThe value is either the system frame rate or the last value passed to\nframeRate().
\n", "itemtype": "method", "name": "getTargetFrameRate", "return": { "description": "_targetFrameRate", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('The number 20 written in black on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Set the frame rate to 20.\n frameRate(20);\n\n // Get the target frame rate and\n // display it.\n let fps = getTargetFrameRate();\n text(fps, 43, 54);\n}\n
\nHides the cursor from view.
\n", "itemtype": "method", "name": "noCursor", "example": [ "\n\nfunction setup() {\n // Hide the cursor.\n noCursor();\n}\n\nfunction draw() {\n background(200);\n\n circle(mouseX, mouseY, 10);\n\n describe('A white circle on a gray background. The circle follows the mouse as it moves. The cursor is hidden.');\n}\n
\nA String
variable with the WebGL version in use.
webglVersion
's value equals one of the following string constants:
WEBGL2
whose value is 'webgl2'
,WEBGL
whose value is 'webgl'
, orP2D
whose value is 'p2d'
. This is the default for 2D sketches.See setAttributes() for ways to set the\nWebGL version.
\n", "itemtype": "property", "name": "webglVersion", "type": "String", "readonly": "", "example": [ "\n\nfunction setup() {\n background(200);\n\n // Display the current WebGL version.\n text(webglVersion, 42, 54);\n\n describe('The text \"p2d\" written in black on a gray background.');\n}\n
\n\nlet font;\n\nfunction preload() {\n // Load a font to use.\n font = loadFont('assets/inconsolata.otf');\n}\n\nfunction setup() {\n // Create a canvas using WEBGL mode.\n createCanvas(100, 50, WEBGL);\n background(200);\n\n // Display the current WebGL version.\n fill(0);\n textFont(font);\n text(webglVersion, -15, 5);\n\n describe('The text \"webgl2\" written in black on a gray background.');\n}\n
\n\nlet font;\n\nfunction preload() {\n // Load a font to use.\n font = loadFont('assets/inconsolata.otf');\n}\n\nfunction setup() {\n // Create a canvas using WEBGL mode.\n createCanvas(100, 50, WEBGL);\n\n // Set WebGL to version 1.\n setAttributes({ version: 1 });\n\n background(200);\n\n // Display the current WebGL version.\n fill(0);\n textFont(font);\n text(webglVersion, -14, 5);\n\n describe('The text \"webgl\" written in black on a gray background.');\n}\n
\nA Number
variable that stores the width of the screen display.
displayWidth
is useful for running full-screen programs. Its value\ndepends on the current pixelDensity().
Note: The actual screen width can be computed as\ndisplayWidth * pixelDensity()
.
\nfunction setup() {\n // Set the canvas' width and height\n // using the display's dimensions.\n createCanvas(displayWidth, displayHeight);\n\n background(200);\n\n describe('A gray canvas that is the same size as the display.');\n}\n
\nA Number
variable that stores the height of the screen display.
displayHeight
is useful for running full-screen programs. Its value\ndepends on the current pixelDensity().
Note: The actual screen height can be computed as\ndisplayHeight * pixelDensity()
.
\nfunction setup() {\n // Set the canvas' width and height\n // using the display's dimensions.\n createCanvas(displayWidth, displayHeight);\n\n background(200);\n\n describe('A gray canvas that is the same size as the display.');\n}\n
\nA Number
variable that stores the width of the browser's viewport.
The layout viewport\nis the area within the browser that's available for drawing.
\n", "itemtype": "property", "name": "windowWidth", "type": "Number", "readonly": "", "example": [ "\n\nfunction setup() {\n // Set the canvas' width and height\n // using the browser's dimensions.\n createCanvas(windowWidth, windowHeight);\n\n background(200);\n\n describe('A gray canvas that takes up the entire browser window.');\n}\n
\nA Number
variable that stores the height of the browser's viewport.
The layout viewport\nis the area within the browser that's available for drawing.
\n", "itemtype": "property", "name": "windowHeight", "type": "Number", "readonly": "", "example": [ "\n\nfunction setup() {\n // Set the canvas' width and height\n // using the browser's dimensions.\n createCanvas(windowWidth, windowHeight);\n\n background(200);\n\n describe('A gray canvas that takes up the entire browser window.');\n}\n
\nA function that's called when the browser window is resized.
\nCode placed in the body of windowResized()
will run when the\nbrowser window's size changes. It's a good place to call\nresizeCanvas() or make other\nadjustments to accommodate the new window size.
The event
parameter is optional. If added to the function declaration, it\ncan be used for debugging or other purposes.
optional resize Event.
\n", "type": "UIEvent", "optional": true } ], "example": [ "\n\nfunction setup() {\n createCanvas(windowWidth, windowHeight);\n\n describe('A gray canvas with a white circle at its center. The canvas takes up the entire browser window. It changes size to match the browser window.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw a circle at the center.\n circle(width / 2, height / 2, 50);\n}\n\n// Resize the canvas when the\n// browser's size changes.\nfunction windowResized() {\n resizeCanvas(windowWidth, windowHeight);\n}\n
\nA Number
variable that stores the width of the canvas in pixels.
width
's default value is 100. Calling\ncreateCanvas() or\nresizeCanvas() changes the value of\nwidth
. Calling noCanvas() sets its value to\n0.
\nfunction setup() {\n background(200);\n\n // Display the canvas' width.\n text(width, 42, 54);\n\n describe('The number 100 written in black on a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(50, 100);\n\n background(200);\n\n // Display the canvas' width.\n text(width, 21, 54);\n\n describe('The number 50 written in black on a gray rectangle.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Display the canvas' width.\n text(width, 42, 54);\n\n describe('The number 100 written in black on a gray square. When the mouse is pressed, the square becomes a rectangle and the number becomes 50.');\n}\n\n// If the mouse is pressed, reisze\n// the canvas and display its new\n// width.\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n resizeCanvas(50, 100);\n background(200);\n text(width, 21, 54);\n }\n}\n
\nA Number
variable that stores the height of the canvas in pixels.
height
's default value is 100. Calling\ncreateCanvas() or\nresizeCanvas() changes the value of\nheight
. Calling noCanvas() sets its value to\n0.
\nfunction setup() {\n background(200);\n\n // Display the canvas' height.\n text(height, 42, 54);\n\n describe('The number 100 written in black on a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 50);\n\n background(200);\n\n // Display the canvas' height.\n text(height, 42, 27);\n\n describe('The number 50 written in black on a gray rectangle.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Display the canvas' height.\n text(height, 42, 54);\n\n describe('The number 100 written in black on a gray square. When the mouse is pressed, the square becomes a rectangle and the number becomes 50.');\n}\n\n// If the mouse is pressed, reisze\n// the canvas and display its new\n// height.\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n resizeCanvas(100, 50);\n background(200);\n text(height, 42, 27);\n }\n}\n
\nToggles full-screen mode or returns the current mode.
\nCalling fullscreen(true)
makes the sketch full-screen. Calling\nfullscreen(false)
makes the sketch its original size.
Calling fullscreen()
without an argument returns true
if the sketch\nis in full-screen mode and false
if not.
Note: Due to browser restrictions, fullscreen()
can only be called with\nuser input such as a mouse press.
whether the sketch should be in fullscreen mode.
\n", "type": "Boolean", "optional": true } ], "return": { "description": "current fullscreen state.", "type": "Boolean" }, "example": [ "\n\nfunction setup() {\n background(200);\n\n describe('A gray canvas that switches between default and full-screen display when clicked.');\n}\n\n// If the mouse is pressed,\n// toggle full-screen mode.\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n let fs = fullscreen();\n fullscreen(!fs);\n }\n}\n
\nSets the pixel density or returns the current density.
\nComputer displays are grids of little lights called pixels. A\ndisplay's pixel density describes how many pixels it packs into an\narea. Displays with smaller pixels have a higher pixel density and create\nsharper images.
\npixelDensity()
sets the pixel scaling for high pixel density displays.\nBy default, the pixel density is set to match the display's density.\nCalling pixelDensity(1)
turn this off.
Calling pixelDensity()
without an argument returns the current pixel\ndensity.
\nfunction setup() {\n // Set the pixel density to 1.\n pixelDensity(1);\n\n // Create a canvas and draw\n // a circle.\n createCanvas(100, 100);\n background(200);\n circle(50, 50, 70);\n\n describe('A fuzzy white circle on a gray canvas.');\n}\n
\n\nfunction setup() {\n // Set the pixel density to 3.\n pixelDensity(3);\n\n // Create a canvas, paint the\n // background, and draw a\n // circle.\n createCanvas(100, 100);\n background(200);\n circle(50, 50, 70);\n\n describe('A sharp white circle on a gray canvas.');\n}\n
\ndesired pixel density.
\n", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 1050, "params": [], "return": { "description": "current pixel density of the sketch.", "type": "Number" } } ] }, { "file": "src/core/environment.js", "line": 1069, "description": "Returns the display's current pixel density.
\n", "itemtype": "method", "name": "displayDensity", "return": { "description": "current pixel density of the display.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n // Set the pixel density to 1.\n pixelDensity(1);\n\n // Create a canvas and draw\n // a circle.\n createCanvas(100, 100);\n background(200);\n circle(50, 50, 70);\n\n describe('A fuzzy white circle drawn on a gray background. The circle becomes sharper when the mouse is pressed.');\n}\n\nfunction mousePressed() {\n // Get the current display density.\n let d = displayDensity();\n\n // Use the display density to set\n // the sketch's pixel density.\n pixelDensity(d);\n\n // Paint the background and\n // draw a circle.\n background(200);\n circle(50, 50, 70);\n}\n
\nReturns the sketch's current\nURL\nas a String
.
\nfunction setup() {\n background(200);\n\n // Get the sketch's URL\n // and display it.\n let url = getURL();\n textWrap(CHAR);\n text(url, 0, 40, 100);\n\n describe('The URL \"https://p5js.org/reference/#/p5/getURL\" written in black on a gray background.');\n}\n
\nReturns the current\nURL\npath as an Array
of String
s.
For example, consider a sketch hosted at the URL\nhttps://example.com/sketchbook
. Calling getURLPath()
returns\n['sketchbook']
. For a sketch hosted at the URL\nhttps://example.com/sketchbook/monday
, getURLPath()
returns\n['sketchbook', 'monday']
.
\nfunction setup() {\n background(200);\n\n // Get the sketch's URL path\n // and display the first\n // part.\n let path = getURLPath();\n text(path[0], 25, 54);\n\n describe('The word \"reference\" written in black on a gray background.');\n}\n
\nReturns the current\nURL parameters\nin an Object
.
For example, calling getURLParams()
in a sketch hosted at the URL\nhttp://p5js.org?year=2014&month=May&day=15
returns\n{ year: 2014, month: 'May', day: 15 }
.
\n// Imagine this sketch is hosted at the following URL:\n// https://p5js.org?year=2014&month=May&day=15\n\nfunction setup() {\n background(200);\n\n // Get the sketch's URL\n // parameters and display\n // them.\n let params = getURLParams();\n text(params.day, 10, 20);\n text(params.month, 10, 40);\n text(params.year, 10, 60);\n\n describe('The text \"15\", \"May\", and \"2014\" written in black on separate lines.');\n}\n
\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": 41, "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
The element's underlying HTMLElement
object.
The\nHTMLElement\nobject's properties and methods can be used directly.
\n", "example": [ "\n\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Set the border style for the\n // canvas.\n cnv.elt.style.border = '5px dashed deeppink';\n\n describe('A gray square with a pink border drawn with dashed lines.');\n}\n
\nA Number
property that stores the element's width.
A Number
property that stores the element's height.
Attaches the element to a parent element.
\nFor example, a <div></div>
element may be used as a box to\nhold two pieces of text, a header and a paragraph. The\n<div></div>
is the parent element of both the header and\nparagraph.
The parameter parent
can have one of three types. parent
can be a\nstring with the parent element's ID, as in\nmyElement.parent('container')
. It can also be another\np5.Element object, as in\nmyElement.parent(myDiv)
. Finally, parent
can be an HTMLElement
\nobject, as in myElement.parent(anotherElement)
.
Calling myElement.parent()
without an argument returns the element's\nparent.
\nfunction setup() {\n background(200);\n\n // Create a div element.\n let div = createDiv();\n\n // Place the div in the top-left corner.\n div.position(10, 20);\n\n // Set its width and height.\n div.size(80, 60);\n\n // Set its background color to white\n div.style('background-color', 'white');\n\n // Align any text to the center.\n div.style('text-align', 'center');\n\n // Set its ID to \"container\".\n div.id('container');\n\n // Create a paragraph element.\n let p = createP('p5*js');\n\n // Make the div its parent\n // using its ID \"container\".\n p.parent('container');\n\n describe('The text \"p5*js\" written in black at the center of a white rectangle. The rectangle is inside a gray square.');\n}\n
\n\nfunction setup() {\n background(200);\n\n // Create rectangular div element.\n let div = createDiv();\n\n // Place the div in the top-left corner.\n div.position(10, 20);\n\n // Set its width and height.\n div.size(80, 60);\n\n // Set its background color and align\n // any text to the center.\n div.style('background-color', 'white');\n div.style('text-align', 'center');\n\n // Create a paragraph element.\n let p = createP('p5*js');\n\n // Make the div its parent.\n p.parent(div);\n\n describe('The text \"p5*js\" written in black at the center of a white rectangle. The rectangle is inside a gray square.');\n}\n
\n\nfunction setup() {\n background(200);\n\n // Create rectangular div element.\n let div = createDiv();\n\n // Place the div in the top-left corner.\n div.position(10, 20);\n\n // Set its width and height.\n div.size(80, 60);\n\n // Set its background color and align\n // any text to the center.\n div.style('background-color', 'white');\n div.style('text-align', 'center');\n\n // Create a paragraph element.\n let p = createP('p5*js');\n\n // Make the div its parent\n // using the underlying\n // HTMLElement.\n p.parent(div.elt);\n\n describe('The text \"p5*js\" written in black at the center of a white rectangle. The rectangle is inside a gray square.');\n}\n
\nID, p5.Element,\n or HTMLElement of desired parent element.
\n", "type": "String|p5.Element|Object" } ], "chainable": 1 }, { "line": 233, "params": [], "return": { "description": "", "type": "p5.Element" } } ] }, { "file": "src/core/p5.Element.js", "line": 254, "description": "Sets the element's ID using a given string.
\nCalling myElement.id()
without an argument returns its ID as a string.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Set the canvas' ID\n // to \"mycanvas\".\n cnv.id('mycanvas');\n\n // Get the canvas' ID.\n let id = cnv.id();\n text(id, 24, 54);\n\n describe('The text \"mycanvas\" written in black on a gray background.');\n}\n
\nID of the element.
\n", "type": "String" } ], "chainable": 1 }, { "line": 286, "params": [], "return": { "description": "ID of the element.", "type": "String" } } ] }, { "file": "src/core/p5.Element.js", "line": 301, "description": "Adds a\nclass attribute\nto the element using a given string.
\nCalling myElement.class()
without an argument returns a string with its current classes.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Add the class \"small\" to the\n // canvas element.\n cnv.class('small');\n\n // Get the canvas element's class\n // and display it.\n let c = cnv.class();\n text(c, 35, 54);\n\n describe('The word \"small\" written in black on a gray canvas.');\n\n}\n
\nclass to add.
\n", "type": "String" } ], "chainable": 1 }, { "line": 337, "params": [], "return": { "description": "element's classes, if any.", "type": "String" } } ] }, { "file": "src/core/p5.Element.js", "line": 350, "description": "Calls a function when the mouse is pressed over the element.
\nCalling myElement.mousePressed(false)
disables the function.
Note: Some mobile browsers may also trigger this event when the element\nreceives a quick tap.
\n", "itemtype": "method", "name": "mousePressed", "params": [ { "name": "fxn", "description": "function to call when the mouse is\n pressed over the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the canvas\n // is pressed.\n cnv.mousePressed(randomColor);\n\n describe('A gray square changes color when the mouse is pressed.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the mouse is pressed twice over the element.
\nCalling myElement.doubleClicked(false)
disables the function.
function to call when the mouse is\n double clicked over the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // canvas is double-clicked.\n cnv.doubleClicked(randomColor);\n\n describe('A gray square changes color when the user double-clicks the canvas.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the mouse wheel scrolls over the element.
\nThe callback function, fxn
, is passed an event
object. event
has\ntwo numeric properties, deltaY
and deltaX
. event.deltaY
is\nnegative if the mouse wheel rotates away from the user. It's positive if\nthe mouse wheel rotates toward the user. event.deltaX
is positive if\nthe mouse wheel moves to the right. It's negative if the mouse wheel moves\nto the left.
Calling myElement.mouseWheel(false)
disables the function.
function to call when the mouse wheel is\n scrolled over the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // mouse wheel moves.\n cnv.mouseWheel(randomColor);\n\n describe('A gray square changes color when the user scrolls the mouse wheel over the canvas.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\n\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call changeBackground() when the\n // mouse wheel moves.\n cnv.mouseWheel(changeBackground);\n\n describe('A gray square. When the mouse wheel scrolls over the square, it changes color and displays shapes.');\n}\n\nfunction changeBackground(event) {\n // Change the background color\n // based on deltaY.\n if (event.deltaY > 0) {\n background('deeppink');\n } else if (event.deltaY < 0) {\n background('cornflowerblue');\n } else {\n background(200);\n }\n\n // Draw a shape based on deltaX.\n if (event.deltaX > 0) {\n circle(50, 50, 20);\n } else if (event.deltaX < 0) {\n square(40, 40, 20);\n }\n}\n
\nCalls a function when the mouse is released over the element.
\nCalling myElement.mouseReleased(false)
disables the function.
Note: Some mobile browsers may also trigger this event when the element\nreceives a quick tap.
\n", "itemtype": "method", "name": "mouseReleased", "params": [ { "name": "fxn", "description": "function to call when the mouse is\n pressed over the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when a\n // mouse press ends.\n cnv.mouseReleased(randomColor);\n\n describe('A gray square changes color when the user releases a mouse press.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the mouse is pressed and released over the element.
\nCalling myElement.mouseReleased(false)
disables the function.
Note: Some mobile browsers may also trigger this event when the element\nreceives a quick tap.
\n", "itemtype": "method", "name": "mouseClicked", "params": [ { "name": "fxn", "description": "function to call when the mouse is\n pressed and released over the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when a\n // mouse press ends.\n cnv.mouseClicked(randomColor);\n\n describe('A gray square changes color when the user releases a mouse press.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the mouse moves over the element.
\nCalling myElement.mouseMoved(false)
disables the function.
function to call when the mouse\n moves over the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // mouse moves.\n cnv.mouseMoved(randomColor);\n\n describe('A gray square changes color when the mouse moves over the canvas.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the mouse moves onto the element.
\nCalling myElement.mouseOver(false)
disables the function.
function to call when the mouse\n moves onto the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // mouse moves onto the canvas.\n cnv.mouseOver(randomColor);\n\n describe('A gray square changes color when the mouse moves onto the canvas.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the mouse moves off the element.
\nCalling myElement.mouseOut(false)
disables the function.
function to call when the mouse\n moves off the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // mouse moves off the canvas.\n cnv.mouseOut(randomColor);\n\n describe('A gray square changes color when the mouse moves off the canvas.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the element is touched.
\nCalling myElement.touchStarted(false)
disables the function.
Note: Touch functions only work on mobile devices.
\n", "itemtype": "method", "name": "touchStarted", "params": [ { "name": "fxn", "description": "function to call when the touch\n starts.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // user touches the canvas.\n cnv.touchStarted(randomColor);\n\n describe('A gray square changes color when the user touches the canvas.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the user touches the element and moves.
\nCalling myElement.touchMoved(false)
disables the function.
Note: Touch functions only work on mobile devices.
\n", "itemtype": "method", "name": "touchMoved", "params": [ { "name": "fxn", "description": "function to call when the touch\n moves over the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // user touches the canvas\n // and moves.\n cnv.touchMoved(randomColor);\n\n describe('A gray square changes color when the user touches the canvas and moves.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the user stops touching the element.
\nCalling myElement.touchMoved(false)
disables the function.
Note: Touch functions only work on mobile devices.
\n", "itemtype": "method", "name": "touchEnded", "params": [ { "name": "fxn", "description": "function to call when the touch\n ends.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // user touches the canvas,\n // then lifts their finger.\n cnv.touchEnded(randomColor);\n\n describe('A gray square changes color when the user touches the canvas, then lifts their finger.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when a file is dragged over the element.
\nCalling myElement.dragOver(false)
disables the function.
function to call when the file is\n dragged over the element.\n false
disables the function.
\n// Drag a file over the canvas to test.\n\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call helloFile() when a\n // file is dragged over\n // the canvas.\n cnv.dragOver(helloFile);\n\n describe('A gray square. The text \"hello, file\" appears when a file is dragged over the square.');\n}\n\nfunction helloFile() {\n text('hello, file', 50, 50);\n}\n
\nCalls a function when a file is dragged off the element.
\nCalling myElement.dragLeave(false)
disables the function.
function to call when the file is\n dragged off the element.\n false
disables the function.
\n// Drag a file over, then off\n// the canvas to test.\n\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call byeFile() when a\n // file is dragged over,\n // then off the canvas.\n cnv.dragLeave(byeFile);\n\n describe('A gray square. The text \"bye, file\" appears when a file is dragged over, then off the square.');\n}\n\nfunction byeFile() {\n text('bye, file', 50, 50);\n}\n
\nHelper fxn for sharing pixel methods
\n", "class": "p5.Element", "module": "DOM", "submodule": "DOM" }, { "file": "src/core/p5.Graphics.js", "line": 83, "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
Creates and returns a new p5.Framebuffer\ninside a p5.Graphics WebGL context.
\nThis takes the same parameters as the global\ncreateFramebuffer function.
\n", "itemtype": "method", "name": "createFramebuffer", "return": { "description": "", "type": "p5.Framebuffer" }, "class": "p5.Graphics", "module": "Rendering", "submodule": "Rendering" }, { "file": "src/core/p5.Renderer.js", "line": 120, "description": "Resize our canvas element.
\n", "class": "p5.Renderer", "module": "Rendering", "submodule": "Rendering" }, { "file": "src/core/p5.Renderer.js", "line": 468, "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": 520, "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": 535, "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.
A WebGL canvas will use a WebGL2 context if it is supported by the browser.\nCheck the webglVersion property to check what\nversion is being used, or call setAttributes({ version: 1 })\nto create a WebGL1 context.
\nThe 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.
\nOptionally, an existing canvas can be passed using a selector, ie. document.getElementById('')
.\nIf specified, avoid using setAttributes()
afterwards, as this will remove and recreate the existing canvas.
For more ways to position the canvas, see the\n\npositioning the canvas wiki page.
\n", "itemtype": "method", "name": "createCanvas", "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
\nwidth 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 }, { "name": "canvas", "description": "existing html canvas element
\n", "type": "HTMLCanvasElement", "optional": true } ], "return": { "description": "pointer to p5.Renderer holding canvas", "type": "p5.Renderer" } }, { "line": 64, "params": [ { "name": "w", "description": "", "type": "Number" }, { "name": "h", "description": "", "type": "Number" }, { "name": "canvas", "description": "", "type": "HTMLCanvasElement", "optional": true } ], "return": { "description": "pointer to p5.Renderer holding canvas", "type": "p5.Renderer" } } ] }, { "file": "src/core/rendering.js", "line": 166, "description": "Resizes 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.Graphics 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.
\nA WebGL p5.Graphics will use a WebGL2 context if it is supported by the browser.\nCheck the pg.webglVersion property of the renderer\nto check what version is being used, or call pg.setAttributes({ version: 1 })\nto create a WebGL1 context.
\nOptionally, an existing canvas can be passed using a selector, ie. document.getElementById('').\nBy default this canvas will be hidden (offscreen buffer), to make visible, set element's style to display:block;
\n", "itemtype": "method", "name": "createGraphics", "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
\nwidth 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 }, { "name": "canvas", "description": "existing html canvas element
\n", "type": "HTMLCanvasElement", "optional": true } ], "return": { "description": "offscreen graphics buffer", "type": "p5.Graphics" } }, { "line": 296, "params": [ { "name": "w", "description": "", "type": "Number" }, { "name": "h", "description": "", "type": "Number" }, { "name": "canvas", "description": "", "type": "HTMLCanvasElement", "optional": true } ], "return": { "description": "offscreen graphics buffer", "type": "p5.Graphics" } } ] }, { "file": "src/core/rendering.js", "line": 304, "description": "args[0] is expected to be renderer\nargs[1] is expected to be canvas
\n", "class": "p5", "module": "Rendering", "submodule": "Rendering" }, { "file": "src/core/rendering.js", "line": 316, "description": "Creates and returns a new p5.Framebuffer, a\nhigh-performance WebGL object that you can draw to and then use as a texture.
\nOptions can include:
\nformat
: The data format of the texture, either UNSIGNED_BYTE
, FLOAT
, or HALF_FLOAT
. The default is UNSIGNED_BYTE
.channels
: What color channels to store, either RGB
or RGBA
. The default is to match the channels in the main canvas (with alpha unless disabled with setAttributes
.)depth
: A boolean, whether or not to include a depth buffer. Defaults to true.depthFormat
: The data format for depth information, either UNSIGNED_INT
or FLOAT
. The default is FLOAT
if available, or UNSIGNED_INT
otherwise.stencil
: A boolean, whether or not to include a stencil buffer, which can be used for masking. This may only be used if also using a depth buffer. Defaults to the value of depth
, which is true if not provided.antialias
: Boolean or Number, whether or not to render with antialiased edges, and if so, optionally the number of samples to use. Defaults to whether or not the main canvas is antialiased, using a default of 2 samples if so. Antialiasing is only supported when WebGL 2 is available.width
: The width of the texture. Defaults to matching the main canvas.height
: The height of the texture. Defaults to matching the main canvas.density
: The pixel density of the texture. Defaults to the pixel density of the main canvas.textureFiltering
: Either LINEAR
(nearby pixels will be interpolated when reading values from the color texture) or NEAREST
(no interpolation.) Generally, use LINEAR
when using the texture as an image, and use NEAREST
if reading the texture as data. Defaults to LINEAR
.If width
, height
, or density
are specified, then the framebuffer will\nkeep that size until manually changed. Otherwise, it will be autosized, and\nit will update to match the main canvas's size and density when the main\ncanvas changes.
An optional object with configuration
\n", "type": "Object", "optional": true } ], "return": { "description": "", "type": "p5.Framebuffer" }, "example": [ "\n\nlet prev, next;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n prev = createFramebuffer({ format: FLOAT });\n next = createFramebuffer({ format: FLOAT });\n noStroke();\n}\n\nfunction draw() {\n // Swap prev and next so that we can use the previous\n // frame as a texture when drawing the current frame\n [prev, next] = [next, prev];\n\n // Draw to the framebuffer\n next.begin();\n background(255);\n\n push();\n tint(255, 253);\n image(prev, -width/2, -height/2);\n // Make sure the image plane doesn't block you from seeing any part\n // of the scene\n clearDepth();\n pop();\n\n push();\n normalMaterial();\n translate(25*sin(frameCount * 0.014), 25*sin(frameCount * 0.02), 0);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(12);\n pop();\n next.end();\n\n image(next, -width/2, -height/2);\n}\n
\nThis makes the canvas forget how far from the camera everything that has\nbeen drawn was. Use this if you want to make sure the next thing you draw\nwill not draw behind anything that is already on the canvas.
\nThis is useful for things like feedback effects, where you want the previous\nframe to act like a background for the next frame, and not like a plane in\n3D space in the scene.
\nThis method is only available in WebGL mode. Since 2D mode does not have\n3D depth, anything you draw will always go on top of the previous content on\nthe canvas anyway.
\n", "itemtype": "method", "name": "clearDepth", "params": [ { "name": "depth", "description": "The value, between 0 and 1, to reset the depth to, where\n0 corresponds to a value as close as possible to the camera before getting\nclipped, and 1 corresponds to a value as far away from the camera as possible.\nThe default value is 1.
\n", "type": "Number", "optional": true } ], "example": [ "\n\nlet prev, next;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n prev = createFramebuffer({ format: FLOAT });\n next = createFramebuffer({ format: FLOAT });\n noStroke();\n}\n\nfunction draw() {\n // Swap prev and next so that we can use the previous\n // frame as a texture when drawing the current frame\n [prev, next] = [next, prev];\n\n // Draw to the framebuffer\n next.begin();\n background(255);\n\n push();\n tint(255, 253);\n image(prev, -width/2, -height/2);\n // Make sure the image plane doesn't block you from seeing any part\n // of the scene\n clearDepth();\n pop();\n\n push();\n normalMaterial();\n translate(25*sin(frameCount * 0.014), 25*sin(frameCount * 0.02), 0);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(12);\n pop();\n next.end();\n\n image(next, -width/2, -height/2);\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
\nStops 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\n", "itemtype": "method", "name": "applyMatrix", "chainable": 1, "example": [ "\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 (2×3 or 4×4 matrix values)
\n", "type": "Array" } ], "chainable": 1 }, { "line": 157, "params": [ { "name": "a", "description": "numbers which define the 2×3 or 4×4 matrix to be multiplied
\n", "type": "Number" }, { "name": "b", "description": "numbers which define the 2×3 or 4×4 matrix to be multiplied
\n", "type": "Number" }, { "name": "c", "description": "numbers which define the 2×3 or 4×4 matrix to be multiplied
\n", "type": "Number" }, { "name": "d", "description": "numbers which define the 2×3 or 4×4 matrix to be multiplied
\n", "type": "Number" }, { "name": "e", "description": "numbers which define the 2×3 or 4×4 matrix to be multiplied
\n", "type": "Number" }, { "name": "f", "description": "numbers which define the 2×3 or 4×4 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 4×4 matrix to be multiplied
\n", "type": "Number" }, { "name": "h", "description": "numbers which define the 4×4 matrix to be multiplied
\n", "type": "Number" }, { "name": "i", "description": "numbers which define the 4×4 matrix to be multiplied
\n", "type": "Number" }, { "name": "j", "description": "numbers which define the 4×4 matrix to be multiplied
\n", "type": "Number" }, { "name": "k", "description": "numbers which define the 4×4 matrix to be multiplied
\n", "type": "Number" }, { "name": "l", "description": "numbers which define the 4×4 matrix to be multiplied
\n", "type": "Number" }, { "name": "m", "description": "numbers which define the 4×4 matrix to be multiplied
\n", "type": "Number" }, { "name": "n", "description": "numbers which define the 4×4 matrix to be multiplied
\n", "type": "Number" }, { "name": "o", "description": "numbers which define the 4×4 matrix to be multiplied
\n", "type": "Number" }, { "name": "p", "description": "numbers which define the 4×4 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 camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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 camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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 camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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": 421, "params": [ { "name": "scales", "description": "per-axis percents to scale the object
\n", "type": "p5.Vector|Number[]" } ], "chainable": 1 } ] }, { "file": "src/core/transform.js", "line": 451, "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": 582, "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": 102, "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": 209, "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": 245, "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": 430, "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": 439, "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": 567, "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": 629, "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\nCSS selector string.
\nThe selector string can be an ID, class, tag name, or a combination.\nselect()
returns a p5.Element object if it\nfinds a match and null
if not.
The second parameter, container
, is optional. It specifies a container to\nsearch within. container
can be CSS selector string, a\np5.Element object, or an\nHTMLElement object.
CSS selector string of element to search for.
\n", "type": "String" }, { "name": "container", "description": "CSS selector string, p5.Element, or\n HTMLElement to search within.
\n", "type": "String|p5.Element|HTMLElement", "optional": true } ], "return": { "description": "p5.Element containing the element.", "type": "p5.Element|null" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n\n // Select the canvas by its tag.\n let cnv = select('canvas');\n cnv.style('border', '5px deeppink dashed');\n\n describe('A gray square with a dashed pink border.');\n}\n
\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n // Add a class attribute to the canvas.\n cnv.class('pinkborder');\n\n background(200);\n\n // Select the canvas by its class.\n cnv = select('.pinkborder');\n\n // Style its border.\n cnv.style('border', '5px deeppink dashed');\n\n describe('A gray square with a dashed pink border.');\n}\n
\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n // Set the canvas' ID.\n cnv.id('mycanvas');\n\n background(200);\n\n // Select the canvas by its ID.\n cnv = select('#mycanvas');\n\n // Style its border.\n cnv.style('border', '5px deeppink dashed');\n\n describe('A gray square with a dashed pink border.');\n}\n
\nSearches the page for all elements that matches the given\nCSS selector string.
\nThe selector string can be an ID, class, tag name, or a combination.\nselectAll()
returns an array of p5.Element\nobjects if it finds any matches and an empty array if none are found.
The second parameter, container
, is optional. It specifies a container to\nsearch within. container
can be CSS selector string, a\np5.Element object, or an\nHTMLElement object.
CSS selector string of element to search for.
\n", "type": "String" }, { "name": "container", "description": "CSS selector string, p5.Element, or\n HTMLElement to search within.
\n", "type": "String|p5.Element|HTMLElement", "optional": true } ], "return": { "description": "array of p5.Elements containing any elements found.", "type": "p5.Element[]" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create three buttons.\n createButton('1');\n createButton('2');\n createButton('3');\n\n // Select the buttons by their tag.\n let buttons = selectAll('button');\n\n // Position the buttons.\n for (let i = 0; i < 3; i += 1) {\n buttons[i].position(0, i * 30);\n }\n\n describe('Three buttons stacked vertically. The buttons are labeled, \"1\", \"2\", and \"3\".');\n}\n
\n\nfunction setup() {\n // Create three buttons and position them.\n let b1 = createButton('1');\n b1.position(0, 0);\n let b2 = createButton('2');\n b2.position(0, 30);\n let b3 = createButton('3');\n b3.position(0, 60);\n\n // Add a class attribute to each button.\n b1.class('btn');\n b2.class('btn btn-pink');\n b3.class('btn');\n\n // Select the buttons by their class.\n let buttons = selectAll('.btn');\n let pinkButtons = selectAll('.btn-pink');\n\n // Style the selected buttons.\n buttons.forEach(setFont);\n pinkButtons.forEach(setColor);\n\n describe('Three buttons stacked vertically. The buttons are labeled, \"1\", \"2\", and \"3\". Buttons \"1\" and \"3\" are gray. Button \"2\" is pink.');\n}\n\n// Set a button's font to Comic Sans MS.\nfunction setFont(btn) {\n btn.style('font-family', 'Comic Sans MS');\n}\n\n// Set a button's background and font color.\nfunction setColor(btn) {\n btn.style('background', 'deeppink');\n btn.style('color', 'white');\n}\n
\nHelper function for select and selectAll
\n", "class": "p5", "module": "DOM", "submodule": "DOM" }, { "file": "src/dom/dom.js", "line": 221, "description": "Helper function for getElement and getElements.
\n", "class": "p5", "module": "DOM", "submodule": "DOM" }, { "file": "src/dom/dom.js", "line": 255, "description": "Removes all elements created by p5.js, including any event handlers.
\nThere are two exceptions:\ncanvas elements created by createCanvas()\nand p5.Render objects created by\ncreateGraphics().
\n", "itemtype": "method", "name": "removeElements", "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element and place\n // it in the middle of the canvas.\n let p = createP('p5*js');\n p.position(25, 25);\n\n describe('A gray square with the text \"p5*js\" written in its center. The text disappears when the mouse is pressed.');\n}\n\n// Remove all elements when the mouse is pressed.\nfunction mousePressed() {\n removeElements();\n}\n
\n\nlet slider;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a paragraph element and place\n // it at the top of the canvas.\n let p = createP('p5*js');\n p.position(25, 25);\n\n // Create a slider element and place it\n // beneath the canvas.\n slider = createSlider(0, 255, 200);\n slider.position(0, 100);\n\n describe('A gray square with the text \"p5*js\" written in its center and a range slider beneath it. The square changes color when the slider is moved. The text and slider disappear when the square is double-clicked.');\n}\n\nfunction draw() {\n // Use the slider value to change the background color.\n let g = slider.value();\n background(g);\n}\n\n// Remove all elements when the mouse is double-clicked.\nfunction doubleClicked() {\n removeElements();\n}\n
\nCalls a function when the element changes.
\nCalling myElement.changed(false)
disables the function.
function to call when the element changes.\n false
disables the function.
\nlet dropdown;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a dropdown menu and add a few color options.\n dropdown = createSelect();\n dropdown.position(0, 0);\n dropdown.option('red');\n dropdown.option('green');\n dropdown.option('blue');\n\n // Call paintBackground() when the color option changes.\n dropdown.changed(paintBackground);\n\n describe('A gray square with a dropdown menu at the top. The square changes color when an option is selected.');\n}\n\n// Paint the background with the selected color.\nfunction paintBackground() {\n let c = dropdown.value();\n background(c);\n}\n
\n\nlet checkbox;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a checkbox and place it beneath the canvas.\n checkbox = createCheckbox(' circle');\n checkbox.position(0, 100);\n\n // Call repaint() when the checkbox changes.\n checkbox.changed(repaint);\n\n describe('A gray square with a checkbox underneath it that says \"circle\". A white circle appears when the box is checked and disappears otherwise.');\n}\n\n// Paint the background gray and determine whether to draw a circle.\nfunction repaint() {\n background(200);\n if (checkbox.checked() === true) {\n circle(50, 50, 30);\n }\n}\n
\nCalls a function when the element receives input.
\nmyElement.input()
is often used to with text inputs and sliders. Calling\nmyElement.input(false)
disables the function.
function to call when input is detected within\n the element.\n false
disables the function.
\nlet slider;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a slider and place it beneath the canvas.\n slider = createSlider(0, 255, 200);\n slider.position(0, 100);\n\n // Call repaint() when the slider changes.\n slider.input(repaint);\n\n describe('A gray square with a range slider underneath it. The background changes shades of gray when the slider is moved.');\n}\n\n// Paint the background using slider's value.\nfunction repaint() {\n let g = slider.value();\n background(g);\n}\n
\n\nlet input;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an input and place it beneath the canvas.\n input = createInput('');\n input.position(0, 100);\n\n // Call repaint() when input is detected.\n input.input(repaint);\n\n describe('A gray square with a text input bar beneath it. Any text written in the input appears in the middle of the square.');\n}\n\n// Paint the background gray and display the input's value.\nfunction repaint() {\n background(200);\n let msg = input.value();\n text(msg, 5, 50);\n}\n
\nHelpers for create methods.
\n", "class": "p5", "module": "DOM", "submodule": "DOM" }, { "file": "src/dom/dom.js", "line": 490, "description": "Creates a <div></div>
element.
<div></div>
elements are commonly used as containers for\nother elements.
The parameter html
is optional. It accepts a string that sets the\ninner HTML of the new <div></div>
.
inner HTML for the new <div></div>
element.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a div element and set its position.\n let div = createDiv('p5*js');\n div.position(25, 35);\n\n describe('A gray square with the text \"p5*js\" written in its center.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an h3 element within the div.\n let div = createDiv('p5*js
');\n div.position(20, 5);\n\n describe('A gray square with the text \"p5*js\" written in its center.');\n}\n
\nCreates a <p></p>
element.
<p></p>
elements are commonly used for paragraph-length text.
The parameter html
is optional. It accepts a string that sets the\ninner HTML of the new <p></p>
.
inner HTML for the new <p></p>
element.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element and set its position.\n let p = createP('Tell me a story.');\n p.position(5, 0);\n\n describe('A gray square displaying the text \"Tell me a story.\" written in black.');\n}\n
\nCreates a <span></span>
element.
<span></span>
elements are commonly used as containers\nfor inline elements. For example, a <span></span>
\ncan hold part of a sentence that's a\ndifferent style.
The parameter html
is optional. It accepts a string that sets the\ninner HTML of the new <span></span>
.
inner HTML for the new <span></span>
element.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a span element and set its position.\n let span = createSpan('p5*js');\n span.position(25, 35);\n\n describe('A gray square with the text \"p5*js\" written in its center.');\n}\n
\n\nfunction setup() {\n background(200);\n\n // Create a div element as a container.\n let div = createDiv();\n\n // Place the div at the center.\n div.position(25, 35);\n\n // Create a span element.\n let s1 = createSpan('p5');\n\n // Create a second span element.\n let s2 = createSpan('*');\n\n // Set the second span's font color.\n s2.style('color', 'deeppink');\n\n // Create a third span element.\n let s3 = createSpan('js');\n\n // Add all the spans to the container div.\n s1.parent(div);\n s2.parent(div);\n s3.parent(div);\n\n describe('A gray square with the text \"p5*js\" written in black at its center. The asterisk is pink.');\n}\n
\nCreates an <img>
element that can appear outside of the canvas.
The first parameter, src
, is a string with the path to the image file.\nsrc
should be a relative path, as in 'assets/image.png'
, or a URL, as\nin 'https://example.com/image.png'
.
The second parameter, alt
, is a string with the\nalternate text\nfor the image. An empty string ''
can be used for images that aren't displayed.
The third parameter, crossOrigin
, is optional. It's a string that sets the\ncrossOrigin property\nof the image. Use 'anonymous'
or 'use-credentials'
to fetch the image\nwith cross-origin access.
The fourth parameter, callback
, is also optional. It sets a function to\ncall after the image loads. The new image is passed to the callback\nfunction as a p5.Element object.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n let img = createImg(\n 'https://p5js.org/assets/img/asterisk-01.png',\n 'The p5.js magenta asterisk.'\n );\n img.position(0, -10);\n\n describe('A gray square with a magenta asterisk in its center.');\n}\n
\nrelative path or URL for the image.
\n", "type": "String" }, { "name": "alt", "description": "alternate text for the image.
\n", "type": "String" } ], "return": { "description": "new p5.Element object.", "type": "p5.Element" } }, { "line": 692, "params": [ { "name": "src", "description": "", "type": "String" }, { "name": "alt", "description": "", "type": "String" }, { "name": "crossOrigin", "description": "crossOrigin property to use when fetching the image.
\n", "type": "String", "optional": true }, { "name": "successCallback", "description": "function to call once the image loads. The new image will be passed\n to the function as a p5.Element object.
\n", "type": "Function", "optional": true } ], "return": { "description": "new p5.Element object.", "type": "p5.Element" } } ] }, { "file": "src/dom/dom.js", "line": 723, "description": "Creates an <a></a>
element that links to another web page.
The first parmeter, href
, is a string that sets the URL of the linked\npage.
The second parameter, html
, is a string that sets the inner HTML of the\nlink. It's common to use text, images, or buttons as links.
The third parameter, target
, is optional. It's a string that tells the\nweb browser where to open the link. By default, links open in the current\nbrowser tab. Passing '_blank'
will cause the link to open in a new\nbrowser tab. MDN describes a few\nother options.
URL of linked page.
\n", "type": "String" }, { "name": "html", "description": "inner HTML of link element to display.
\n", "type": "String" }, { "name": "target", "description": "target where the new link should open,\n either '_blank'
, '_self'
, '_parent'
, or '_top'
.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an anchor element that links to p5js.org.\n let a = createA('http://p5js.org/', 'p5*js');\n a.position(25, 35);\n\n describe('The text \"p5*js\" written at the center of a gray square.');\n}\n
\n\nfunction setup() {\n background(200);\n\n // Create an anchor tag that links to p5js.org.\n // Open the link in a new tab.\n let a = createA('http://p5js.org/', 'p5*js', '_blank');\n a.position(25, 35);\n\n describe('The text \"p5*js\" written at the center of a gray square.');\n}\n
\nCreates a slider <input></input>
element.
Range sliders are useful for quickly selecting numbers from a given range.
\nThe first two parameters, min
and max
, are numbers that set the\nslider's minimum and maximum.
The third parameter, value
, is optional. It's a number that sets the\nslider's default value.
The fourth parameter, step
, is also optional. It's a number that sets the\nspacing between each value in the slider's range. Setting step
to 0\nallows the slider to move smoothly from min
to max
.
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": "size for each step in the slider's range.
\n", "type": "Number", "optional": true } ], "return": { "description": "new p5.Element object.", "type": "p5.Element" }, "example": [ "\n\nlet slider;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a slider and place it at the top of the canvas.\n slider = createSlider(0, 255);\n slider.position(10, 10);\n slider.size(80);\n\n describe('A dark gray square with a range slider at the top. The square changes color when the slider is moved.');\n}\n\nfunction draw() {\n // Use the slider as a grayscale value.\n let g = slider.value();\n background(g);\n}\n
\n\nlet slider;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a slider and place it at the top of the canvas.\n // Set its default value to 0.\n slider = createSlider(0, 255, 0);\n slider.position(10, 10);\n slider.size(80);\n\n describe('A black square with a range slider at the top. The square changes color when the slider is moved.');\n}\n\nfunction draw() {\n // Use the slider as a grayscale value.\n let g = slider.value();\n background(g);\n}\n
\n\nlet slider;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a slider and place it at the top of the canvas.\n // Set its default value to 0.\n // Set its step size to 50.\n slider = createSlider(0, 255, 0, 50);\n slider.position(10, 10);\n slider.size(80);\n\n describe('A black square with a range slider at the top. The square changes color when the slider is moved.');\n}\n\nfunction draw() {\n // Use the slider as a grayscale value.\n let g = slider.value();\n background(g);\n}\n
\n\nlet slider;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a slider and place it at the top of the canvas.\n // Set its default value to 0.\n // Set its step size to 0 so that it moves smoothly.\n slider = createSlider(0, 255, 0, 0);\n slider.position(10, 10);\n slider.size(80);\n\n describe('A black square with a range slider at the top. The square changes color when the slider is moved.');\n}\n\nfunction draw() {\n // Use the slider as a grayscale value.\n let g = slider.value();\n background(g);\n}\n
\nCreates a <button></button>
element.
The first parameter, label
, is a string that sets the label displayed on\nthe button.
The second parameter, value
, is optional. It's a string that sets the\nbutton's value. See\nMDN\nfor more details.
label displayed on the button.
\n", "type": "String" }, { "name": "value", "description": "value of the button.
\n", "type": "String", "optional": true } ], "return": { "description": "new p5.Element object.", "type": "p5.Element" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a button and place it beneath the canvas.\n let button = createButton('click me');\n button.position(0, 100);\n\n // Call repaint() when the button is pressed.\n button.mousePressed(repaint);\n\n describe('A gray square with a button that says \"click me\" beneath it. The square changes color when the button is clicked.');\n}\n\n// Change the background color.\nfunction repaint() {\n let g = random(255);\n background(g);\n}\n
\n\nlet button;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a button and set its value to 0.\n // Place the button beneath the canvas.\n button = createButton('click me', 'red');\n button.position(0, 100);\n\n // Call randomColor() when the button is pressed.\n button.mousePressed(randomColor);\n\n describe('A red square with a button that says \"click me\" beneath it. The square changes color when the button is clicked.');\n}\n\nfunction draw() {\n // Use the button's value to set the background color.\n let c = button.value();\n background(c);\n}\n\n// Set the button's value to a random color.\nfunction randomColor() {\n let c = random(['red', 'green', 'blue', 'yellow']);\n button.value(c);\n}\n
\nCreates a checkbox <input></input>
element.
Checkboxes extend the p5.Element class with a\nchecked()
method. Calling myBox.checked()
returns true
if it the box\nis checked and false
if not.
The first parameter, label
, is optional. It's a string that sets the label\nto display next to the checkbox.
The second parameter, value
, is also optional. It's a boolean that sets the\ncheckbox's value.
label displayed after the checkbox.
\n", "type": "String", "optional": true }, { "name": "value", "description": "value of the checkbox. Checked is true
and unchecked is false
.
\nlet checkbox;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a checkbox and place it beneath the canvas.\n checkbox = createCheckbox();\n checkbox.position(0, 100);\n\n describe('A black square with a checkbox beneath it. The square turns white when the box is checked.');\n}\n\nfunction draw() {\n // Use the checkbox to set the background color.\n if (checkbox.checked()) {\n background(255);\n } else {\n background(0);\n }\n}\n
\n\nlet checkbox;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a checkbox and place it beneath the canvas.\n // Label the checkbox \"white\".\n checkbox = createCheckbox(' white');\n checkbox.position(0, 100);\n\n describe('A black square with a checkbox labeled \"white\" beneath it. The square turns white when the box is checked.');\n}\n\nfunction draw() {\n // Use the checkbox to set the background color.\n if (checkbox.checked()) {\n background(255);\n } else {\n background(0);\n }\n}\n
\n\nlet checkbox;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a checkbox and place it beneath the canvas.\n // Label the checkbox \"white\" and set its value to true.\n checkbox = createCheckbox(' white', true);\n checkbox.position(0, 100);\n\n describe('A white square with a checkbox labeled \"white\" beneath it. The square turns black when the box is unchecked.');\n}\n\nfunction draw() {\n // Use the checkbox to set the background color.\n if (checkbox.checked()) {\n background(255);\n } else {\n background(0);\n }\n}\n
\nCreates a dropdown menu <select></select>
element.
The parameter is optional. If true
is passed, as in\nlet mySelect = createSelect(true)
, then the dropdown will support\nmultiple selections. If an existing <select></select>
element\nis passed, as in let mySelect = createSelect(otherSelect)
, the existing\nelement will be wrapped in a new p5.Element\nobject.
Dropdowns extend the p5.Element class with a few\nhelpful methods for managing options:
\nmySelect.option(name, [value])
adds an option to the menu. The first paremeter, name
, is a string that sets the option's name and value. The second parameter, value
, is optional. If provided, it sets the value that corresponds to the key name
. If an option with name
already exists, its value is changed to value
.mySelect.value()
returns the currently-selected option's value.mySelect.selected()
returns the currently-selected option.mySelect.selected(option)
selects the given option by default.mySelect.disable()
marks the whole dropdown element as disabled.mySelect.disable(option)
marks a given option as disabled.mySelect.enable()
marks the whole dropdown element as enabled.mySelect.enable(option)
marks a given option as enabled.\nlet mySelect;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a dropdown and place it beneath the canvas.\n mySelect = createSelect();\n mySelect.position(0, 100);\n\n // Add color options.\n mySelect.option('red');\n mySelect.option('green');\n mySelect.option('blue');\n mySelect.option('yellow');\n\n // Set the selected option to \"red\".\n mySelect.selected('red');\n\n describe('A red square with a dropdown menu beneath it. The square changes color when a new color is selected.');\n}\n\nfunction draw() {\n // Use the selected value to paint the background.\n let c = mySelect.selected();\n background(c);\n}\n
\n\nlet mySelect;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a dropdown and place it beneath the canvas.\n mySelect = createSelect();\n mySelect.position(0, 100);\n\n // Add color options.\n mySelect.option('red');\n mySelect.option('green');\n mySelect.option('blue');\n mySelect.option('yellow');\n\n // Set the selected option to \"red\".\n mySelect.selected('red');\n\n // Disable the \"yellow\" option.\n mySelect.disable('yellow');\n\n describe('A red square with a dropdown menu beneath it. The square changes color when a new color is selected.');\n}\n\nfunction draw() {\n // Use the selected value to paint the background.\n let c = mySelect.selected();\n background(c);\n}\n
\n\nlet mySelect;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a dropdown and place it beneath the canvas.\n mySelect = createSelect();\n mySelect.position(0, 100);\n\n // Add color options with names and values.\n mySelect.option('one', 'red');\n mySelect.option('two', 'green');\n mySelect.option('three', 'blue');\n mySelect.option('four', 'yellow');\n\n // Set the selected option to \"one\".\n mySelect.selected('one');\n\n describe('A red square with a dropdown menu beneath it. The square changes color when a new color is selected.');\n}\n\nfunction draw() {\n // Use the selected value to paint the background.\n let c = mySelect.selected();\n background(c);\n}\n
\n\n// Hold CTRL to select multiple options on Windows and Linux.\n// Hold CMD to select multiple options on macOS.\nlet mySelect;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a dropdown and allow multiple selections.\n // Place it beneath the canvas.\n mySelect = createSelect(true);\n mySelect.position(0, 100);\n\n // Add color options.\n mySelect.option('red');\n mySelect.option('green');\n mySelect.option('blue');\n mySelect.option('yellow');\n\n describe('A gray square with a dropdown menu beneath it. Colorful circles appear when their color is selected.');\n}\n\nfunction draw() {\n background(200);\n\n // Use the selected value(s) to draw circles.\n let colors = mySelect.selected();\n for (let i = 0; i < colors.length; i += 1) {\n // Calculate the x-coordinate.\n let x = 10 + i * 20;\n\n // Access the color.\n let c = colors[i];\n\n // Draw the circle.\n fill(c);\n circle(x, 50, 20);\n }\n}\n
\nsupport multiple selections.
\n", "type": "Boolean", "optional": true } ], "return": { "description": "new p5.Element object.", "type": "p5.Element" } }, { "line": 1323, "params": [ { "name": "existing", "description": "select element to wrap, either as a p5.Element or\n a HTMLSelectElement.
\n", "type": "Object" } ], "return": { "description": "", "type": "p5.Element" } } ] }, { "file": "src/dom/dom.js", "line": 1439, "description": "Creates a radio button element.
\nThe parameter is optional. If a string is passed, as in\nlet myRadio = createSelect('food')
, then each radio option will\nhave \"food\"
as its name
parameter: <input name=\"food\"></input>
.\nIf an existing <div></div>
or <span></span>
\nelement is passed, as in let myRadio = createSelect(container)
, it will\nbecome the radio button's parent element.
Radio buttons extend the p5.Element class with a few\nhelpful methods for managing options:
\nmyRadio.option(value, [label])
adds an option to the menu. The first paremeter, value
, is a string that sets the option's value and label. The second parameter, label
, is optional. If provided, it sets the label displayed for the value
. If an option with value
already exists, its label is changed and its value is returned.myRadio.value()
returns the currently-selected option's value.myRadio.selected()
returns the currently-selected option.myRadio.selected(value)
selects the given option and returns it as an HTMLInputElement
.myRadio.disable(shouldDisable)
enables the entire radio button if true
is passed and disables it if false
is passed.\nlet myRadio;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a radio button element and place it\n // in the top-left corner.\n myRadio = createRadio();\n myRadio.position(0, 0);\n myRadio.size(60);\n\n // Add a few color options.\n myRadio.option('red');\n myRadio.option('yellow');\n myRadio.option('blue');\n\n // Choose a default option.\n myRadio.selected('yellow');\n\n describe('A yellow square with three color options listed, \"red\", \"yellow\", and \"blue\". The square changes color when the user selects a new option.');\n}\n\nfunction draw() {\n // Set the background color using the radio button.\n let g = myRadio.value();\n background(g);\n}\n
\n\nlet myRadio;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a radio button element and place it\n // in the top-left corner.\n myRadio = createRadio();\n myRadio.position(0, 0);\n myRadio.size(50);\n\n // Add a few color options.\n // Color values are labeled with\n // emotions they evoke.\n myRadio.option('red', 'love');\n myRadio.option('yellow', 'joy');\n myRadio.option('blue', 'trust');\n\n // Choose a default option.\n myRadio.selected('yellow');\n\n describe('A yellow square with three options listed, \"love\", \"joy\", and \"trust\". The square changes color when the user selects a new option.');\n}\n\nfunction draw() {\n // Set the background color using the radio button.\n let c = myRadio.value();\n background(c);\n}\n
\n\nlet myRadio;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a radio button element and place it\n // in the top-left corner.\n myRadio = createRadio();\n myRadio.position(0, 0);\n myRadio.size(50);\n\n // Add a few color options.\n myRadio.option('red');\n myRadio.option('yellow');\n myRadio.option('blue');\n\n // Choose a default option.\n myRadio.selected('yellow');\n\n // Create a button and place it beneath the canvas.\n let btn = createButton('disable');\n btn.position(0, 100);\n\n // Call disableRadio() when btn is pressed.\n btn.mousePressed(disableRadio);\n\n describe('A yellow square with three options listed, \"red\", \"yellow\", and \"blue\". The square changes color when the user selects a new option. A \"disable\" button beneath the canvas disables the color options when pressed.');\n}\n\nfunction draw() {\n // Set the background color using the radio button.\n let c = myRadio.value();\n background(c);\n}\n\n// Disable myRadio.\nfunction disableRadio() {\n myRadio.disable(true);\n}\n
\ncontainer HTML Element, either a <div></div>
\nor <span></span>
.
name parameter assigned to each option's <input></input>
element.
Creates a color picker element.
\nThe parameter, value
, is optional. If a color string or\np5.Color object is passed, it will set the default\ncolor.
Color pickers extend the p5.Element class with a\ncouple of helpful methods for managing colors:
\nmyPicker.value()
returns the current color as a hex string in the format '#rrggbb'
.myPicker.color()
returns the current color as a p5.Color object.default color as a CSS color string.
\n", "type": "String|p5.Color", "optional": true } ], "return": { "description": "new p5.Element object.", "type": "p5.Element" }, "example": [ "\n\nlet myPicker;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a color picker and set its position.\n myPicker = createColorPicker('deeppink');\n myPicker.position(0, 100);\n\n describe('A pink square with a color picker beneath it. The square changes color when the user picks a new color.');\n}\n\nfunction draw() {\n // Use the color picker to paint the background.\n let c = myPicker.color();\n background(c);\n}\n
\n\nlet myPicker;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a color picker and set its position.\n myPicker = createColorPicker('deeppink');\n myPicker.position(0, 100);\n\n describe('A number with the format \"#rrggbb\" is displayed on a pink canvas. The background color and number change when the user picks a new color.');\n}\n\nfunction draw() {\n // Use the color picker to paint the background.\n let c = myPicker.value();\n background(c);\n\n // Display the current color as a hex string.\n text(c, 25, 55);\n}\n
\nCreates a text <input></input>
element.
Call myInput.size()
to set the length of the text box.
The first parameter, value
, is optional. It's a string that sets the\ninput's default value. The input is blank by default.
The second parameter, type
, is also optional. It's a string that\nspecifies the type of text being input. See MDN for a full\nlist of options.\nThe default is 'text'
.
\nlet myInput;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create an input element and place it\n // beneath the canvas.\n myInput = createInput();\n myInput.position(0, 100);\n\n describe('A gray square with a text box beneath it. The text in the square changes when the user types something new in the input bar.');\n}\n\nfunction draw() {\n background(200);\n\n // Use the input to display a message.\n let msg = myInput.value();\n text(msg, 25, 55);\n}\n
\n\nlet myInput;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create an input element and place it\n // beneath the canvas. Set its default\n // text to \"hello!\".\n myInput = createInput('hello!');\n myInput.position(0, 100);\n\n describe('The text \"hello!\" written at the center of a gray square. A text box beneath the square also says \"hello!\". The text in the square changes when the user types something new in the input bar.');\n}\n\nfunction draw() {\n background(200);\n\n // Use the input to display a message.\n let msg = myInput.value();\n text(msg, 25, 55);\n}\n
\ndefault value of the input box. Defaults to an empty string ''
.
type of input. Defaults to 'text'
.
Creates an <input></input>
element of type 'file'
.
createFileInput()
allows users to select local files for use in a sketch.\nIt returns a p5.File object.
The first parameter, callback
, is a function that's called when the file\nloads. The callback function should have one parameter, file
, that's a\np5.File object.
The second parameter, multiple
, is optional. It's a boolean value that\nallows loading multiple files if set to true
. If true
, callback
\nwill be called once per file.
function to call once the file loads.
\n", "type": "Function" }, { "name": "multiple", "description": "allow multiple files to be selected.
\n", "type": "Boolean", "optional": true } ], "return": { "description": "new p5.File object.", "type": "p5.File" }, "example": [ "\n\n// Use the file input to select an image to\n// load and display.\nlet input;\nlet img;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a file input and place it beneath\n // the canvas.\n input = createFileInput(handleImage);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user selects an image file to load, it is displayed on the square.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw the image if loaded.\n if (img) {\n image(img, 0, 0, width, height);\n }\n}\n\n// Create an image if the file is an image.\nfunction handleImage(file) {\n if (file.type === 'image') {\n img = createImg(file.data, '');\n img.hide();\n } else {\n img = null;\n }\n}\n
\n\n// Use the file input to select multiple images\n// to load and display.\nlet input;\nlet images = [];\n\nfunction setup() {\n // Create a file input and place it beneath\n // the canvas. Allow it to load multiple files.\n input = createFileInput(handleImage, true);\n input.position(0, 100);\n}\n\nfunction draw() {\n background(200);\n\n // Draw the images if loaded. Each image\n // is drawn 20 pixels lower than the\n // previous image.\n for (let i = 0; i < images.length; i += 1) {\n // Calculate the y-coordinate.\n let y = i * 20;\n\n // Draw the image.\n image(img, 0, y, 100, 100);\n }\n\n describe('A gray square with a file input beneath it. If the user selects multiple image files to load, they are displayed on the square.');\n}\n\n// Create an image if the file is an image,\n// then add it to the images array.\nfunction handleImage(file) {\n if (file.type === 'image') {\n let img = createImg(file.data, '');\n img.hide();\n images.push(img);\n }\n}\n
\nCreates a <video>
element for simple audio/video playback.
createVideo()
returns a new\np5.MediaElement object. Videos are shown by\ndefault. They can be hidden by calling video.hide()
and drawn to the\ncanvas using image().
The first parameter, src
, is the path the video. If a single string is\npassed, as in 'assets/topsecret.mp4'
, a single video is loaded. An array\nof strings can be used to load the same video in different formats. For\nexample, ['assets/topsecret.mp4', 'assets/topsecret.ogv', 'assets/topsecret.webm']
.\nThis is useful for ensuring that the video can play across different browsers with\ndifferent capabilities. See\nMDN\nfor more information about supported formats.
The second parameter, callback
, is optional. It's a function to call once\nthe video is ready to play.
path to a video file, or an array of paths for\n supporting different browsers.
\n", "type": "String|String[]" }, { "name": "callback", "description": "function to call once the video is ready to play.
\n", "type": "Function", "optional": true } ], "return": { "description": "new p5.MediaElement object.", "type": "p5.MediaElement" }, "example": [ "\n\nfunction setup() {\n noCanvas();\n\n // Load a video and add it to the page.\n // Note: this may not work in some browsers.\n let video = createVideo('assets/small.mp4');\n\n // Show the default video controls.\n video.showControls();\n\n describe('A video of a toy robot with playback controls beneath it.');\n}\n
\n\nfunction setup() {\n noCanvas();\n\n // Load a video and add it to the page.\n // Provide an array options for different file formats.\n let video = createVideo(\n ['assets/small.mp4', 'assets/small.ogv', 'assets/small.webm']\n );\n\n // Show the default video controls.\n video.showControls();\n\n describe('A video of a toy robot with playback controls beneath it.');\n}\n
\n\nlet video;\n\nfunction setup() {\n noCanvas();\n\n // Load a video and add it to the page.\n // Provide an array options for different file formats.\n // Call mute() once the video loads.\n video = createVideo(\n ['assets/small.mp4', 'assets/small.ogv', 'assets/small.webm'],\n muteVideo\n );\n\n // Show the default video controls.\n video.showControls();\n\n describe('A video of a toy robot with playback controls beneath it.');\n}\n\n// Mute the video once it loads.\nfunction muteVideo() {\n video.volume(0);\n}\n
\nCreates a hidden <audio>
element for simple audio playback.
createAudio()
returns a new\np5.MediaElement object.
The first parameter, src
, is the path the video. If a single string is\npassed, as in 'assets/video.mp4'
, a single video is loaded. An array\nof strings can be used to load the same video in different formats. For\nexample, ['assets/video.mp4', 'assets/video.ogv', 'assets/video.webm']
.\nThis is useful for ensuring that the video can play across different\nbrowsers with different capabilities. See\nMDN\nfor more information about supported formats.
The second parameter, callback
, is optional. It's a function to call once\nthe audio is ready to play.
path to an audio file, or an array of paths\n for supporting different browsers.
\n", "type": "String|String[]", "optional": true }, { "name": "callback", "description": "function to call once the audio is ready to play.
\n", "type": "Function", "optional": true } ], "return": { "description": "new p5.MediaElement object.", "type": "p5.MediaElement" }, "example": [ "\n\nfunction setup() {\n noCanvas();\n\n // Load the audio.\n let beat = createAudio('assets/beat.mp3');\n\n // Show the default audio controls.\n beat.showControls();\n\n describe('An audio beat plays when the user double-clicks the square.');\n}\n
\nCreates a <video>
element that \"captures\" the audio/video stream from\nthe webcam and microphone.
createCapture()
returns a new\np5.MediaElement object. Videos are shown by\ndefault. They can be hidden by calling capture.hide()
and drawn to the\ncanvas using image().
The first parameter, type
, is optional. It sets the type of capture to\nuse. By default, createCapture()
captures both audio and video. If VIDEO
\nis passed, as in createCapture(VIDEO)
, only video will be captured.\nIf AUDIO
is passed, as in createCapture(AUDIO)
, only audio will be\ncaptured. A constraints object can also be passed to customize the stream.\nSee the \nW3C documentation for possible properties. Different browsers support different\nproperties.
The 'flipped' property is an optional property which can be set to {flipped:true}
\nto mirror the video output.If it is true then it means that video will be mirrored\nor flipped and if nothing is mentioned then by default it will be false
.
The second parameter,callback
, is optional. It's a function to call once\nthe capture is ready for use. The callback function should have one\nparameter, stream
, that's a\nMediaStream object.
Note: createCapture()
only works when running a sketch locally or using HTTPS. Learn more\nhere\nand here.
type of capture, either AUDIO or VIDEO,\n or a constraints object. Both video and audio\n audio streams are captured by default.
\n", "type": "String|Constant|Object", "optional": true }, { "name": "flipped", "description": "flip the capturing video and mirror the output with {flipped:true}
. By\n default it is false.
function to call once the stream\n has loaded.
\n", "type": "Function", "optional": true } ], "return": { "description": "new p5.MediaElement object.", "type": "p5.MediaElement" }, "example": [ "\n\nfunction setup() {\n noCanvas();\n\n // Create the video capture.\n createCapture(VIDEO);\n\n describe('A video stream from the webcam.');\n}\n
\n\nlet capture;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create the video capture and hide the element.\n capture = createCapture(VIDEO);\n capture.hide();\n\n describe('A video stream from the webcam with inverted colors.');\n}\n\nfunction draw() {\n // Draw the video capture within the canvas.\n image(capture, 0, 0, width, width * capture.height / capture.width);\n\n // Invert the colors in the stream.\n filter(INVERT);\n}\n
\n\nlet capture;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create the video capture with mirrored output.\n capture = createCapture(VIDEO,{ flipped:true });\n capture.size(100,100);\n\n describe('A video stream from the webcam with flipped or mirrored output.');\n}\n\n
\n\nfunction setup() {\n createCanvas(480, 120);\n\n // Create a constraints object.\n let constraints = {\n video: {\n mandatory: {\n minWidth: 1280,\n minHeight: 720\n },\n optional: [{ maxFrameRate: 10 }]\n },\n audio: false\n };\n\n // Create the video capture.\n createCapture(constraints);\n\n describe('A video stream from the webcam.');\n}\n
\nCreates a new p5.Element object.
\nThe first parameter, tag
, is a string an HTML tag such as 'h5'
.
The second parameter, content
, is optional. It's a string that sets the\nHTML content to insert into the new element. New elements have no content\nby default.
tag for the new element.
\n", "type": "String" }, { "name": "content", "description": "HTML content to insert into the element.
\n", "type": "String", "optional": true } ], "return": { "description": "new p5.Element object.", "type": "p5.Element" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an h5 element with nothing in it.\n createElement('h5');\n\n describe('A gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an h5 element with the content \"p5*js\".\n let h5 = createElement('h5', 'p5*js');\n\n // Set the element's style and position.\n h5.style('color', 'deeppink');\n h5.position(30, 15);\n\n describe('The text \"p5*js\" written in pink in the middle of a gray square.');\n}\n
\nAdds a 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 function setup() {\n createCanvas(100, 100);\n background(200);\n // Create a div element.\n let div = createDiv('div');\n // Add a class to the div.\n div.addClass('myClass');\n describe('A gray square.');\n }\n
\n Removes a 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.\n\nlet div;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a div element.\n div = createDiv('div');\n\n // Add a class to the div.\n div.addClass('myClass');\n\n describe('A gray square.');\n}\n\n// Remove 'myClass' from the div when the user presses the mouse.\nfunction mousePressed() {\n div.removeClass('myClass');\n}\n
\nChecks if a 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": "name of class to check.
\n", "type": "String" } ], "example": [ "\n\nlet div;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a div element.\n div = createDiv('div');\n\n // Add the class 'show' to the div.\n div.addClass('show');\n\n describe('A gray square.');\n}\n\n// Toggle the class 'show' when the mouse is pressed.\nfunction mousePressed() {\n if (div.hasClass('show')) {\n div.addClass('show');\n } else {\n div.removeClass('show');\n }\n}\n
\nToggles whether a class is applied to the element.
\n", "itemtype": "method", "name": "toggleClass", "params": [ { "name": "c", "description": "class name to toggle.
\n", "type": "String" } ], "chainable": 1, "example": [ "\n\nlet div;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a div element.\n div = createDiv('div');\n\n // Add the 'show' class to the div.\n div.addClass('show');\n\n describe('A gray square.');\n}\n\n// Toggle the 'show' class when the mouse is pressed.\nfunction mousePressed() {\n div.toggleClass('show');\n}\n
\nAttaches the element as a child of another element.
\nmyElement.child()
accepts either a string ID, DOM node, or\np5.Element. For example,\nmyElement.child(otherElement)
. If no argument is provided, an array of\nchildren DOM nodes is returned.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create the div elements.\n let div0 = createDiv('Parent');\n let div1 = createDiv('Child');\n\n // Make div1 the child of div0\n // using the p5.Element.\n div0.child(div1);\n\n describe('A gray square with the words \"Parent\" and \"Child\" written beneath it.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create the div elements.\n let div0 = createDiv('Parent');\n let div1 = createDiv('Child');\n\n // Give div1 an ID.\n div1.id('apples');\n\n // Make div1 the child of div0\n // using its ID.\n div0.child('apples');\n\n describe('A gray square with the words \"Parent\" and \"Child\" written beneath it.');\n}\n
\n\n// This example assumes there is a div already on the page\n// with id \"myChildDiv\".\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create the div elements.\n let div0 = createDiv('Parent');\n\n // Select the child element by its ID.\n let elt = document.getElementById('myChildDiv');\n\n // Make div1 the child of div0\n // using its HTMLElement object.\n div0.child(elt);\n\n describe('A gray square with the words \"Parent\" and \"Child\" written beneath it.');\n}\n
\nthe 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": 2801, "description": "Centers the element either vertically, horizontally, or both.
\ncenter()
will center the element relative to its parent or according to\nthe page's body if the element has no parent.
If no argument is passed, as in myElement.center()
the element is aligned\nboth vertically and horizontally.
passing 'vertical', 'horizontal' aligns element accordingly
\n", "type": "String", "optional": true } ], "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create the div element and style it.\n let div = createDiv('');\n div.size(10, 10);\n div.style('background-color', 'orange');\n\n // Center the div relative to the page's body.\n div.center();\n\n describe('A gray square and an orange rectangle. The rectangle is at the center of the page.');\n}\n
\nSets the inner HTML of the element, replacing any existing HTML.
\nThe second parameter, append
, is optional. If true
is passed, as in\nmyElement.html('hi', true)
, the HTML is appended instead of replacing\nexisting HTML.
If no arguments are passed, as in myElement.html()
, the element's inner\nHTML is returned.
\nfunction setup() {\n createCanvas(100, 100);\n\n // Create the div element and set its size.\n let div = createDiv('');\n div.size(100, 100);\n\n // Set the inner HTML to \"hi\".\n div.html('hi');\n\n describe('A gray square with the word \"hi\" written beneath it.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create the div element and set its size.\n let div = createDiv('Hello ');\n div.size(100, 100);\n\n // Append \"World\" to the div's HTML.\n div.html('World', true);\n\n describe('A gray square with the text \"Hello World\" written beneath it.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create the div element.\n let div = createDiv('Hello');\n\n // Prints \"Hello\" to the console.\n print(div.html());\n\n describe('A gray square with the word \"Hello!\" written beneath it.');\n}\n
\nthe 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": 2954, "description": "Sets the element's position.
\nThe first two parameters, x
and y
, set the element's position relative\nto the top-left corner of the web page.
The third parameter, positionType
, is optional. It sets the element's\npositioning scheme.\npositionType
is a string that can be either 'static'
, 'fixed'
,\n'relative'
, 'sticky'
, 'initial'
, or 'inherit'
.
If no arguments passed, as in myElement.position()
, the method returns\nthe element's position in an object, as in { x: 0, y: 0 }
.
\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Positions the canvas 50px to the right and 100px\n // below the top-left corner of the window.\n cnv.position(50, 100);\n\n describe('A gray square that is 50 pixels to the right and 100 pixels down from the top-left corner of the web page.');\n}\n
\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Positions the canvas at the top-left corner\n // of the window with a 'fixed' position type.\n cnv.position(0, 0, 'fixed');\n\n describe('A gray square in the top-left corner of the web page.');\n}\n
\nx-position relative to top-left of window (optional)
\n", "type": "Number", "optional": true }, { "name": "y", "description": "y-position relative to top-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": 3092, "description": "Applies a style to the element by adding a\nCSS declaration.
\nThe first parameter, property
, is a string. If the name of a style\nproperty is passed, as in myElement.style('color')
, the method returns\nthe current value as a string or null
if it hasn't been set. If a\nproperty:style
string is passed, as in\nmyElement.style('color:deeppink')
, the method sets the style property
\nto value
.
The second parameter, value
, is optional. It sets the property's value.\nvalue
can be a string, as in\nmyElement.style('color', 'deeppink')
, or a\np5.Color object, as in\nmyElement.style('color', myColor)
.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element and set its font color to \"deeppink\".\n let p = createP('p5*js');\n p.position(25, 20);\n p.style('color', 'deeppink');\n\n describe('The text p5*js written in pink on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let c = color('deeppink');\n\n // Create a paragraph element and set its font color using a p5.Color object.\n let p = createP('p5*js');\n p.position(25, 20);\n p.style('color', c);\n\n describe('The text p5*js written in pink on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element and set its font color to \"deeppink\"\n // using property:value syntax.\n let p = createP('p5*js');\n p.position(25, 20);\n p.style('color:deeppink');\n\n describe('The text p5*js written in pink on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an empty paragraph element and set its font color to \"deeppink\".\n let p = createP();\n p.position(5, 5);\n p.style('color', 'deeppink');\n\n // Get the element's color as an RGB color string.\n let c = p.style('color');\n\n // Set the element's inner HTML using the RGB color string.\n p.html(c);\n\n describe('The text \"rgb(255, 20, 147)\" written in pink on a gray background.');\n}\n
\nstyle property to set.
\n", "type": "String" } ], "return": { "description": "value of the property.", "type": "String" } }, { "line": 3192, "params": [ { "name": "property", "description": "", "type": "String" }, { "name": "value", "description": "value to assign to the property.
\n", "type": "String|p5.Color" } ], "chainable": 1, "return": { "description": "value of the property.", "type": "String" } } ] }, { "file": "src/dom/dom.js", "line": 3249, "description": "Adds an\nattribute\nto the element.
\nThis method is useful for advanced tasks. Most commonly-used attributes,\nsuch as id
, can be set with their dedicated methods. For example,\nnextButton.id('next')
sets an element's id
attribute. Calling\nnextButton.attribute('id', 'next')
has the same effect.
The first parameter, attr
, is the attribute's name as a string. Calling\nmyElement.attribute('align')
returns the attribute's current value as a\nstring or null
if it hasn't been set.
The second parameter, value
, is optional. It's a string used to set the\nattribute's value. For example, calling\nmyElement.attribute('align', 'center')
sets the element's horizontal\nalignment to center
.
\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a container div element and place it at the top-left corner.\n let container = createDiv();\n container.position(0, 0);\n\n // Create a paragraph element and place it within the container.\n // Set its horizontal alignment to \"left\".\n let p1 = createP('hi');\n p1.parent(container);\n p1.attribute('align', 'left');\n\n // Create a paragraph element and place it within the container.\n // Set its horizontal alignment to \"center\".\n let p2 = createP('hi');\n p2.parent(container);\n p2.attribute('align', 'center');\n\n // Create a paragraph element and place it within the container.\n // Set its horizontal alignment to \"right\".\n let p3 = createP('hi');\n p3.parent(container);\n p3.attribute('align', 'right');\n\n describe('A gray square with the text \"hi\" written on three separate lines, each placed further to the right.');\n}\n
\nattribute to set.
\n", "type": "String" }, { "name": "value", "description": "value to assign to the attribute.
\n", "type": "String" } ], "chainable": 1 } ] }, { "file": "src/dom/dom.js", "line": 3333, "description": "Removes an attribute from the element.
\nThe parameter attr
is the attribute's name as a string. For example,\ncalling myElement.removeAttribute('align')
removes its align
\nattribute if it's been set.
attribute to remove.
\n", "type": "String" } ], "chainable": 1, "example": [ "\n\nlet p;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element and place it in the center of the canvas.\n // Set its \"align\" attribute to \"center\".\n p = createP('hi');\n p.position(0, 20);\n p.attribute('align', 'center');\n\n describe('The text \"hi\" written in black at the center of a gray square. The text moves to the left edge when double-clicked.');\n}\n\n// Remove the 'align' attribute when the user double-clicks the paragraph.\nfunction doubleClicked() {\n p.removeAttribute('align');\n}\n
\nReturns or sets the element's value.
\nCalling myElement.value()
returns the element's current value.
The parameter, value
, is an optional number or string. If provided,\nas in myElement.value(123)
, it's used to set the element's value.
\nlet input;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a text input and place it beneath the canvas.\n // Set its default value to \"hello\".\n input = createInput('hello');\n input.position(0, 100);\n\n describe('The text from an input box is displayed on a gray square.');\n}\n\nfunction draw() {\n background(200);\n\n // Use the input's value to display a message.\n let msg = input.value();\n text(msg, 0, 55);\n}\n
\n\nlet input;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a text input and place it beneath the canvas.\n // Set its default value to \"hello\".\n input = createInput('hello');\n input.position(0, 100);\n\n describe('The text from an input box is displayed on a gray square. The text resets to \"hello\" when the user double-clicks the square.');\n}\n\nfunction draw() {\n background(200);\n\n // Use the input's value to display a message.\n let msg = input.value();\n text(msg, 0, 55);\n}\n\n// Reset the input's value.\nfunction doubleClicked() {\n input.value('hello');\n}\n
\nShows the current element.
\n", "itemtype": "method", "name": "show", "chainable": 1, "example": [ "\n\nlet p;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element and hide it.\n p = createP('p5*js');\n p.position(10, 10);\n p.hide();\n\n describe('A gray square. The text \"p5*js\" appears when the user double-clicks the square.');\n}\n\n// Show the paragraph when the user double-clicks.\nfunction doubleClicked() {\n p.show();\n}\n
\nHides the current element.
\n", "itemtype": "method", "name": "hide", "chainable": 1, "example": [ "\nlet p;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element.\n p = createP('p5*js');\n p.position(10, 10);\n\n describe('The text \"p5*js\" at the center of a gray square. The text disappears when the user double-clicks the square.');\n}\n\n// Hide the paragraph when the user double-clicks.\nfunction doubleClicked() {\n p.hide();\n}\n\n" ], "class": "p5.Element", "module": "DOM", "submodule": "DOM" }, { "file": "src/dom/dom.js", "line": 3536, "description": "Sets the element's width and height.
\nCalling myElement.size()
without an argument returns the element's size\nas an object with the properties width
and height
. For example,\n { width: 20, height: 10 }
.
The first parameter, width
, is optional. It's a number used to set the\nelement's width. Calling myElement.size(10)
The second parameter, 'height, is also optional. It's a number used to set the element's height. For example, calling
myElement.size(20, 10)` sets the element's width to 20 pixels and height\nto 10 pixels.
The constant AUTO
can be used to adjust one dimension at a time while\nmaintaining the aspect ratio, which is width / height
. For example,\nconsider an element that's 200 pixels wide and 100 pixels tall. Calling\nmyElement.size(20, AUTO)
sets the width to 20 pixels and height to 10\npixels.
Note: In the case of elements that need to load data, such as images, wait\nto call myElement.size()
until after the data loads.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a pink div element and place it at the top-left corner.\n let div = createDiv();\n div.position(10, 10);\n div.style('background-color', 'deeppink');\n\n // Set the div's width to 80 pixels and height to 20 pixels.\n div.size(80, 20);\n\n describe('A gray square with a pink rectangle near its top.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a pink div element and place it at the top-left corner.\n let div = createDiv();\n div.position(10, 10);\n div.style('background-color', 'deeppink');\n\n // Set the div's width to 80 pixels and height to 40 pixels.\n div.size(80, 40);\n\n // Get the div's size as an object.\n let s = div.size();\n\n // Display the div's dimensions.\n div.html(`${s.width} x ${s.height}`);\n\n describe('A gray square with a pink rectangle near its top. The text \"80 x 40\" is written within the rectangle.');\n}\n
\n\nlet img1;\nlet img2;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Load an image of an astronaut on the moon\n // and place it at the top-left of the canvas.\n img1 = createImg(\n 'assets/moonwalk.jpg',\n 'An astronaut walking on the moon',\n ''\n );\n img1.position(0, 0);\n\n // Load an image of an astronaut on the moon\n // and place it at the top-left of the canvas.\n // Resize the image once it's loaded.\n img2 = createImg(\n 'assets/moonwalk.jpg',\n 'An astronaut walking on the moon',\n '',\n resizeImage\n );\n img2.position(0, 0);\n\n describe('A gray square two copies of a space image at the top-left. The copy in front is smaller.');\n}\n\n// Resize img2 and keep its aspect ratio.\nfunction resizeImage() {\n img2.size(50, AUTO);\n}\n
\nwidth of the element, either AUTO, or a number.
\n", "type": "Number|Constant", "optional": true }, { "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": 3705, "description": "Removes the element, stops all audio/video streams, and removes all\ncallback functions.
\n", "itemtype": "method", "name": "remove", "example": [ "\n\nlet p;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element.\n p = createP('p5*js');\n p.position(10, 10);\n\n describe('The text \"p5*js\" written at the center of a gray square. ');\n}\n\n// Remove the paragraph when the user double-clicks.\nfunction doubleClicked() {\n p.remove();\n}\n
\nCalls a function when the user drops a file on the element.
\nThe first parameter, callback
, is a function to call once the file loads.\nThe callback function should have one parameter, file
, that's a\np5.File object. If the user drops multiple files on\nthe element, callback
, is called once for each file.
The second parameter, fxn
, is a function to call when the browser detects\none or more dropped files. The callback function should have one\nparameter, event
, that's a\nDragEvent.
called when a file loads. Called once for each file dropped.
\n", "type": "Function" }, { "name": "fxn", "description": "called once when any files are dropped.
\n", "type": "Function", "optional": true } ], "chainable": 1, "example": [ "\n\n// Drop an image on the canvas to view\n// this example.\nlet img;\n\nfunction setup() {\n let c = createCanvas(100, 100);\n\n background(200);\n\n // Call handleFile() when a file that's dropped on the canvas has loaded.\n c.drop(handleFile);\n\n describe('A gray square. When the user drops an image on the square, it is displayed.');\n}\n\n// Remove the existing image and display the new one.\nfunction handleFile(file) {\n // Remove the current image, if any.\n if (img) {\n img.remove();\n }\n\n // Create an element with the\n // dropped file.\n img = createImg(file.data, '');\n img.hide();\n\n // Draw the image.\n image(img, 0, 0, width, height);\n}\n
\n\n// Drop an image on the canvas to view\n// this example.\nlet img;\nlet msg;\n\nfunction setup() {\n let c = createCanvas(100, 100);\n\n background(200);\n\n // Call functions when the user drops a file on the canvas\n // and when the file loads.\n c.drop(handleFile, handleDrop);\n\n describe('A gray square. When the user drops an image on the square, it is displayed. The id attribute of canvas element is also displayed.');\n}\n\n// Display the image when it loads.\nfunction handleFile(file) {\n // Remove the current image, if any.\n if (img) {\n img.remove();\n }\n\n // Create an img element with the dropped file.\n img = createImg(file.data, '');\n img.hide();\n\n // Draw the image.\n image(img, 0, 0, width, height);\n}\n\n// Display the file's name when it loads.\nfunction handleDrop(event) {\n // Remove current paragraph, if any.\n if (msg) {\n msg.remove();\n }\n\n // Use event to get the drop target's id.\n let id = event.target.id;\n\n // Write the canvas' id beneath it.\n msg = createP(id);\n msg.position(0, 100);\n\n // Set the font color randomly for each drop.\n let c = random(['red', 'green', 'blue']);\n msg.style('color', c);\n msg.style('font-size', '12px');\n}\n
\nMakes the element draggable.
\nThe parameter, elmnt
, is optional. If another\np5.Element object is passed, as in\nmyElement.draggable(otherElement)
, the other element will become draggable.
another p5.Element.
\n", "type": "p5.Element", "optional": true } ], "chainable": 1, "example": [ "\n\nlet stickyNote;\nlet textInput;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a div element and style it.\n stickyNote = createDiv('Note');\n stickyNote.position(5, 5);\n stickyNote.size(80, 20);\n stickyNote.style('font-size', '16px');\n stickyNote.style('font-family', 'Comic Sans MS');\n stickyNote.style('background', 'orchid');\n stickyNote.style('padding', '5px');\n\n // Make the note draggable.\n stickyNote.draggable();\n\n // Create a panel div and style it.\n let panel = createDiv('');\n panel.position(5, 40);\n panel.size(80, 50);\n panel.style('background', 'orchid');\n panel.style('font-size', '16px');\n panel.style('padding', '5px');\n panel.style('text-align', 'center');\n\n // Make the panel draggable.\n panel.draggable();\n\n // Create a text input and style it.\n textInput = createInput('Note');\n textInput.size(70);\n\n // Add the input to the panel.\n textInput.parent(panel);\n\n // Call handleInput() when text is input.\n textInput.input(handleInput);\n\n describe(\n 'A gray square with two purple rectangles that move when dragged. The top rectangle displays the text that is typed into the bottom rectangle.'\n );\n}\n\n// Update stickyNote's HTML when text is input.\nfunction handleInput() {\n stickyNote.html(textInput.value());\n}\n
\nPath to the media element's source as a string.
\n", "itemtype": "property", "name": "src", "return": { "description": "src", "type": "String" }, "example": [ "\n\nlet beat;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n beat = createAudio('assets/beat.mp3');\n\n describe('The text \"https://p5js.org/reference/assets/beat.mp3\" written in black on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n textWrap(CHAR);\n text(beat.src, 10, 10, 80, 80);\n}\n
\nPlays audio or video from a media element.
\n", "itemtype": "method", "name": "play", "chainable": 1, "example": [ "\n\nlet beat;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display a message.\n text('Click to play', 50, 50);\n\n // Create a p5.MediaElement using createAudio().\n beat = createAudio('assets/beat.mp3');\n\n describe('The text \"Click to play\" written in black on a gray background. A beat plays when the user clicks the square.');\n}\n\n// Play the beat when the user presses the mouse.\nfunction mousePressed() {\n beat.play();\n}\n
\nStops a media element and sets its current time to 0.
\nCalling media.play()
will restart playing audio/video from the beginning.
\nlet beat;\nlet isStopped = true;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n beat = createAudio('assets/beat.mp3');\n\n describe('The text \"Click to start\" written in black on a gray background. The beat starts or stops when the user presses the mouse.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display different instructions based on playback.\n if (isStopped === true) {\n text('Click to start', 50, 50);\n } else {\n text('Click to stop', 50, 50);\n }\n}\n\n// Adjust playback when the user presses the mouse.\nfunction mousePressed() {\n if (isStopped === true) {\n // If the beat is stopped, play it.\n beat.play();\n isStopped = false;\n } else {\n // If the beat is playing, stop it.\n beat.stop();\n isStopped = true;\n }\n}\n
\nPauses a media element.
\nCalling media.play()
will resume playing audio/video from the moment it paused.
\nlet beat;\nlet isPaused = true;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n beat = createAudio('assets/beat.mp3');\n\n describe('The text \"Click to play\" written in black on a gray background. The beat plays or pauses when the user clicks the square.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display different instructions based on playback.\n if (isPaused === true) {\n text('Click to play', 50, 50);\n } else {\n text('Click to pause', 50, 50);\n }\n}\n\n// Adjust playback when the user presses the mouse.\nfunction mousePressed() {\n if (isPaused === true) {\n // If the beat is paused,\n // play it.\n beat.play();\n isPaused = false;\n } else {\n // If the beat is playing,\n // pause it.\n beat.pause();\n isPaused = true;\n }\n}\n
\nPlays the audio/video repeatedly in a loop.
\n", "itemtype": "method", "name": "loop", "chainable": 1, "example": [ "\n\nlet beat;\nlet isLooping = false;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.MediaElement using createAudio().\n beat = createAudio('assets/beat.mp3');\n\n describe('The text \"Click to loop\" written in black on a gray background. A beat plays repeatedly in a loop when the user clicks. The beat stops when the user clicks again.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display different instructions based on playback.\n if (isLooping === true) {\n text('Click to stop', 50, 50);\n } else {\n text('Click to loop', 50, 50);\n }\n}\n\n// Adjust playback when the user presses the mouse.\nfunction mousePressed() {\n if (isLooping === true) {\n // If the beat is looping, stop it.\n beat.stop();\n isLooping = false;\n } else {\n // If the beat is stopped, loop it.\n beat.loop();\n isLooping = true;\n }\n}\n
\nStops the audio/video from playing in a loop.
\nThe media will stop when it finishes playing.
\n", "itemtype": "method", "name": "noLoop", "chainable": 1, "example": [ "\n\nlet beat;\nlet isPlaying = false;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.MediaElement using createAudio().\n beat = createAudio('assets/beat.mp3');\n\n describe('The text \"Click to play\" written in black on a gray background. A beat plays when the user clicks. The beat stops when the user clicks again.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display different instructions based on playback.\n if (isPlaying === true) {\n text('Click to stop', 50, 50);\n } else {\n text('Click to play', 50, 50);\n }\n}\n\n// Adjust playback when the user presses the mouse.\nfunction mousePressed() {\n if (isPlaying === true) {\n // If the beat is playing, stop it.\n beat.stop();\n isPlaying = false;\n } else {\n // If the beat is stopped, play it.\n beat.play();\n isPlaying = true;\n }\n}\n
\nSets the audio/video to play once it's loaded.
\nThe parameter, shouldAutoplay
, is optional. Calling\nmedia.autoplay()
without an argument causes the media to play\nautomatically. If true
is passed, as in media.autoplay(true)
, the\nmedia will automatically play. If false
is passed, as in\nmedia.autoPlay(false)
, it won't play automatically.
whether the element should autoplay.
\n", "type": "Boolean", "optional": true } ], "chainable": 1, "example": [ "\n\nlet video;\n\nfunction setup() {\n noCanvas();\n\n // Call handleVideo() once the video loads.\n video = createVideo('assets/fingers.mov', handleVideo);\n\n describe('A video of fingers walking on a treadmill.');\n}\n\n// Set the video's size and play it.\nfunction handleVideo() {\n video.size(100, 100);\n video.autoplay();\n}\n
\n\nfunction setup() {\n noCanvas();\n\n // Load a video, but don't play it automatically.\n let video = createVideo('assets/fingers.mov', handleVideo);\n\n // Play the video when the user clicks on it.\n video.mousePressed(handlePress);\n\n describe('An image of fingers on a treadmill. They start walking when the user double-clicks on them.');\n}\n
\nSets the audio/video volume.
\nCalling media.volume()
without an argument returns the current volume\nas a number in the range 0 (off) to 1 (maximum).
The parameter, val
, is optional. It's a number that sets the volume\nfrom 0 (off) to 1 (maximum). For example, calling media.volume(0.5)
\nsets the volume to half of its maximum.
\nlet dragon;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n dragon = createAudio('assets/lucky_dragons.mp3');\n\n // Show the default media controls.\n dragon.showControls();\n\n describe('The text \"Volume: V\" on a gray square with media controls beneath it. The number \"V\" oscillates between 0 and 1 as the music plays.');\n}\n\nfunction draw() {\n background(200);\n\n // Produce a number between 0 and 1.\n let n = 0.5 * sin(frameCount * 0.01) + 0.5;\n\n // Use n to set the volume.\n dragon.volume(n);\n\n // Get the current volume and display it.\n let v = dragon.volume();\n\n // Round v to 1 decimal place for display.\n v = round(v, 1);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the volume.\n text(`Volume: ${v}`, 50, 50);\n}\n
\nvolume between 0.0 and 1.0.
\n", "type": "Number" } ], "chainable": 1 } ] }, { "file": "src/dom/dom.js", "line": 4665, "description": "Sets the audio/video playback speed.
\nThe parameter, val
, is optional. It's a number that sets the playback\nspeed. 1 plays the media at normal speed, 0.5 plays it at half speed, 2\nplays it at double speed, and so on. -1 plays the media at normal speed\nin reverse.
Calling media.speed()
returns the current speed as a number.
Note: Not all browsers support backward playback. Even if they do,\nplayback might not be smooth.
\n", "itemtype": "method", "name": "speed", "return": { "description": "current playback speed.", "type": "Number" }, "example": [ "\n\nlet dragon;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n dragon = createAudio('assets/lucky_dragons.mp3');\n\n // Show the default media controls.\n dragon.showControls();\n\n describe('The text \"Speed: S\" on a gray square with media controls beneath it. The number \"S\" oscillates between 0 and 1 as the music plays.');\n}\n\nfunction draw() {\n background(200);\n\n // Produce a number between 0 and 2.\n let n = sin(frameCount * 0.01) + 1;\n\n // Use n to set the playback speed.\n dragon.speed(n);\n\n // Get the current speed and display it.\n let s = dragon.speed();\n\n // Round s to 1 decimal place for display.\n s = round(s, 1);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the speed.\n text(`Speed: ${s}`, 50, 50);\n}\n
"
],
"class": "p5.MediaElement",
"module": "DOM",
"submodule": "DOM",
"overloads": [
{
"line": 4665,
"params": [],
"return": {
"description": "current playback speed.",
"type": "Number"
}
},
{
"line": 4723,
"params": [
{
"name": "speed",
"description": "speed multiplier for playback.
\n", "type": "Number" } ], "chainable": 1 } ] }, { "file": "src/dom/dom.js", "line": 4740, "description": "Sets the media element's playback time.
\nThe parameter, time
, is optional. It's a number that specifies the\ntime, in seconds, to jump to when playback begins.
Calling media.time()
without an argument returns the number of seconds\nthe audio/video has played.
Note: Time resets to 0 when looping media restarts.
\n", "itemtype": "method", "name": "time", "return": { "description": "current time (in seconds).", "type": "Number" }, "example": [ "\n\nlet dragon;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n dragon = createAudio('assets/lucky_dragons.mp3');\n\n // Show the default media controls.\n dragon.showControls();\n\n describe('The text \"S seconds\" on a gray square with media controls beneath it. The number \"S\" increases as the song plays.');\n}\n\nfunction draw() {\n background(200);\n\n // Get the current playback time.\n let s = dragon.time();\n\n // Round s to 1 decimal place for display.\n s = round(s, 1);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the playback time.\n text(`${s} seconds`, 50, 50);\n}\n
\n\nlet dragon;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n dragon = createAudio('assets/lucky_dragons.mp3');\n\n // Show the default media controls.\n dragon.showControls();\n\n // Jump to 2 seconds to start.\n dragon.time(2);\n\n describe('The text \"S seconds\" on a gray square with media controls beneath it. The number \"S\" increases as the song plays.');\n}\n\nfunction draw() {\n background(200);\n\n // Get the current playback time.\n let s = dragon.time();\n\n // Round s to 1 decimal place for display.\n s = round(s, 1);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the playback time.\n text(`${s} seconds`, 50, 50);\n}\n
\ntime to jump to (in seconds).
\n", "type": "Number" } ], "chainable": 1 } ] }, { "file": "src/dom/dom.js", "line": 4842, "description": "Returns the audio/video's duration in seconds.
\n", "itemtype": "method", "name": "duration", "return": { "description": "duration (in seconds).", "type": "Number" }, "example": [ "\n\nlet dragon;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.MediaElement using createAudio().\n dragon = createAudio('assets/lucky_dragons.mp3');\n\n // Show the default media controls.\n dragon.showControls();\n\n describe('The text \"S seconds left\" on a gray square with media controls beneath it. The number \"S\" decreases as the song plays.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the time remaining.\n let s = dragon.duration() - dragon.time();\n\n // Round s to 1 decimal place for display.\n s = round(s, 1);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the time remaining.\n text(`${s} seconds left`, 50, 50);\n}\n
\nCalls a function when the audio/video reaches the end of its playback.
\nThe element is passed as an argument to the callback function.
\nNote: The function won't be called if the media is looping.
\n", "itemtype": "method", "name": "onended", "params": [ { "name": "callback", "description": "function to call when playback ends.\n The p5.MediaElement
is passed as\n the argument.
\nlet beat;\nlet isPlaying = false;\nlet isDone = false;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n beat = createAudio('assets/beat.mp3');\n\n // Call handleEnd() when the beat finishes.\n beat.onended(handleEnd);\n\n describe('The text \"Click to play\" written in black on a gray square. A beat plays when the user clicks. The text \"Done!\" appears when the beat finishes playing.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display different messages based on playback.\n if (isDone === true) {\n text('Done!', 50, 50);\n } else if (isPlaying === false) {\n text('Click to play', 50, 50);\n } else {\n text('Playing...', 50, 50);\n }\n}\n\n// Play the beat when the user presses the mouse.\nfunction mousePressed() {\n if (isPlaying === false) {\n isPlaying = true;\n beat.play();\n }\n}\n\n// Set isDone when playback ends.\nfunction handleEnd() {\n isDone = false;\n}\n
\nSends the element's audio to an output.
\nThe parameter, audioNode
, can be an AudioNode
or an object from the\np5.sound
library.
If no element is provided, as in myElement.connect()
, the element\nconnects to the main output. All connections are removed by the\n.disconnect()
method.
Note: This method is meant to be used with the p5.sound.js addon library.
\n", "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": 5122, "description": "Disconnect all Web Audio routing, including to the main output.
\nThis is useful if you want to re-route the output through audio effects,\nfor example.
\n", "itemtype": "method", "name": "disconnect", "class": "p5.MediaElement", "module": "DOM", "submodule": "DOM" }, { "file": "src/dom/dom.js", "line": 5138, "class": "p5.MediaElement", "module": "DOM", "submodule": "DOM" }, { "file": "src/dom/dom.js", "line": 5140, "description": "Show the default\nHTMLMediaElement\ncontrols.
\nNote: The controls vary between web browsers.
\n", "itemtype": "method", "name": "showControls", "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background('cornflowerblue');\n\n // Style the text.\n textAlign(CENTER);\n textSize(50);\n\n // Display a dragon.\n text('🐉', 50, 50);\n\n // Create a p5.MediaElement using createAudio().\n let dragon = createAudio('assets/lucky_dragons.mp3');\n\n // Show the default media controls.\n dragon.showControls();\n\n describe('A dragon emoji, 🐉, drawn in the center of a blue square. A song plays in the background. Audio controls are displayed beneath the canvas.');\n}\n
\nHide the default\nHTMLMediaElement\ncontrols.
\n", "itemtype": "method", "name": "hideControls", "example": [ "\n\nlet dragon;\nlet isHidden = false;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n dragon = createAudio('assets/lucky_dragons.mp3');\n\n // Show the default media controls.\n dragon.showControls();\n\n describe('The text \"Double-click to hide controls\" written in the middle of a gray square. A song plays in the background. Audio controls are displayed beneath the canvas. The controls appear/disappear when the user double-clicks the square.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n\n // Display a different message when controls are hidden or shown.\n if (isHidden === true) {\n text('Double-click to show controls', 10, 20, 80, 80);\n } else {\n text('Double-click to hide controls', 10, 20, 80, 80);\n }\n}\n\n// Show/hide controls based on a double-click.\nfunction doubleClicked() {\n if (isHidden === true) {\n dragon.showControls();\n isHidden = false;\n } else {\n dragon.hideControls();\n isHidden = true;\n }\n}\n
\nSchedules a function to call when the audio/video reaches a specific time\nduring its playback.
\nThe first parameter, time
, is the time, in seconds, when the function\nshould run. This value is passed to callback
as its first argument.
The second parameter, callback
, is the function to call at the specified\ncue time.
The third parameter, value
, is optional and can be any type of value.\nvalue
is passed to callback
.
Calling media.addCue()
returns an ID as a string. This is useful for\nremoving the cue later.
cue time to run the callback function.
\n", "type": "Number" }, { "name": "callback", "description": "function to call at the cue time.
\n", "type": "Function" }, { "name": "value", "description": "object to pass as the argument to\n callback
.
\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n let beat = createAudio('assets/beat.mp3');\n\n // Play the beat in a loop.\n beat.loop();\n\n // Schedule a few events.\n beat.addCue(0, changeBackground, 'red');\n beat.addCue(2, changeBackground, 'deeppink');\n beat.addCue(4, changeBackground, 'orchid');\n beat.addCue(6, changeBackground, 'lavender');\n\n describe('A red square with a beat playing in the background. Its color changes every 2 seconds while the audio plays.');\n}\n\n// Change the background color.\nfunction changeBackground(c) {\n background(c);\n}\n
\nRemoves a callback based on its ID.
\n", "itemtype": "method", "name": "removeCue", "params": [ { "name": "id", "description": "ID of the cue, created by media.addCue()
.
\nlet lavenderID;\nlet isRemoved = false;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n let beat = createAudio('assets/beat.mp3');\n\n // Play the beat in a loop.\n beat.loop();\n\n // Schedule a few events.\n beat.addCue(0, changeBackground, 'red');\n beat.addCue(2, changeBackground, 'deeppink');\n beat.addCue(4, changeBackground, 'orchid');\n\n // Record the ID of the \"lavender\" callback.\n lavenderID = beat.addCue(6, changeBackground, 'lavender');\n\n describe('The text \"Double-click to remove lavender.\" written on a red square. The color changes every 2 seconds while the audio plays. The lavender option is removed when the user double-clicks the square.');\n}\n\nfunction draw() {\n background(200);\n\n // Display different instructions based on the available callbacks.\n if (isRemoved === false) {\n text('Double-click to remove lavender.', 10, 10, 80, 80);\n } else {\n text('No more lavender.', 10, 10, 80, 80);\n }\n}\n\n// Change the background color.\nfunction changeBackground(c) {\n background(c);\n}\n\n// Remove the lavender color-change cue when the user double-clicks.\nfunction doubleClicked() {\n if (isRemoved === false) {\n beat.removeCue(lavenderID);\n isRemoved = true;\n }\n}\n
\nRemoves all functions scheduled with media.addCue()
.
\nlet isChanging = true;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.MediaElement using createAudio().\n let beat = createAudio('assets/beat.mp3');\n\n // Play the beat in a loop.\n beat.loop();\n\n // Schedule a few events.\n beat.addCue(0, changeBackground, 'red');\n beat.addCue(2, changeBackground, 'deeppink');\n beat.addCue(4, changeBackground, 'orchid');\n beat.addCue(6, changeBackground, 'lavender');\n\n describe('The text \"Double-click to stop changing.\" written on a square. The color changes every 2 seconds while the audio plays. The color stops changing when the user double-clicks the square.');\n}\n\nfunction draw() {\n background(200);\n\n // Display different instructions based on the available callbacks.\n if (isChanging === true) {\n text('Double-click to stop changing.', 10, 10, 80, 80);\n } else {\n text('No more changes.', 10, 10, 80, 80);\n }\n}\n\n// Change the background color.\nfunction changeBackground(c) {\n background(c);\n}\n\n// Remove cued functions and stop changing colors when the user\n// double-clicks.\nfunction doubleClicked() {\n if (isChanging === true) {\n beat.clearCues();\n isChanging = false;\n }\n}\n
\nUnderlying\nFile\nobject. All File
properties and methods are accessible.
\n// Use the file input to load a\n// file and display its info.\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a file input and place it beneath the canvas.\n // Call displayInfo() when the file loads.\n let input = createFileInput(displayInfo);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user loads a file, its info is written in black.');\n}\n\n// Use the p5.File once it loads.\nfunction displayInfo(file) {\n background(200);\n\n // Display the p5.File's name.\n text(file.name, 10, 10, 80, 40);\n\n // Display the p5.File's type and subtype.\n text(`${file.type}/${file.subtype}`, 10, 70);\n\n // Display the p5.File's size in bytes.\n text(file.size, 10, 90);\n}\n
\nThe file\nMIME type\nas a string.
\nFor example, 'image'
and 'text'
are both MIME types.
\n// Use the file input to load a file and display its info.\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a file input and place it beneath the canvas.\n // Call displayType() when the file loads.\n let input = createFileInput(displayType);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user loads a file, its type is written in black.');\n}\n\n// Display the p5.File's type once it loads.\nfunction displayType(file) {\n background(200);\n\n // Display the p5.File's type.\n text(`This is file's type is: ${file.type}`, 10, 10, 80, 80);\n}\n
\nThe file subtype as a string.
\nFor example, a file with an 'image'
\nMIME type\nmay have a subtype such as png
or jpeg
.
\n// Use the file input to load a\n// file and display its info.\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a file input and place it beneath the canvas.\n // Call displaySubtype() when the file loads.\n let input = createFileInput(displaySubtype);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user loads a file, its subtype is written in black.');\n}\n\n// Display the p5.File's type once it loads.\nfunction displaySubtype(file) {\n background(200);\n\n // Display the p5.File's subtype.\n text(`This is file's subtype is: ${file.subtype}`, 10, 10, 80, 80);\n}\n
\nThe file name as a string.
\n", "itemtype": "property", "name": "name", "example": [ "\n\n// Use the file input to load a\n// file and display its info.\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a file input and place it beneath the canvas.\n // Call displayName() when the file loads.\n let input = createFileInput(displayName);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user loads a file, its name is written in black.');\n}\n\n// Display the p5.File's name once it loads.\nfunction displayName(file) {\n background(200);\n\n // Display the p5.File's name.\n text(`This is file's name is: ${file.name}`, 10, 10, 80, 80);\n}\n
\nThe number of bytes in the file.
\n", "itemtype": "property", "name": "size", "example": [ "\n\n// Use the file input to load a file and display its info.\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a file input and place it beneath the canvas.\n // Call displaySize() when the file loads.\n let input = createFileInput(displaySize);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user loads a file, its size in bytes is written in black.');\n}\n\n// Display the p5.File's size in bytes once it loads.\nfunction displaySize(file) {\n background(200);\n\n // Display the p5.File's size.\n text(`This is file has ${file.size} bytes.`, 10, 10, 80, 80);\n}\n
\nA string containing the file's data.
\nData can be either image data, text contents, or a parsed object in the\ncase of JSON and p5.XML objects.
\n", "itemtype": "property", "name": "data", "example": [ "\n\n// Use the file input to load a file and display its info.\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a file input and place it beneath the canvas.\n // Call displayData() when the file loads.\n let input = createFileInput(displayData);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user loads a file, its data is written in black.');\n}\n\n// Display the p5.File's data once it loads.\nfunction displayData(file) {\n background(200);\n\n // Display the p5.File's data, which looks like a random string of characters.\n text(file.data, 10, 10, 80, 80);\n}\n
\nThe 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": "KeyboardEvent", "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": "KeyboardEvent", "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": "KeyboardEvent", "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(50, y, 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": "MouseEvent", "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": "MouseEvent", "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": "MouseEvent", "optional": true } ], "example": [ "\n\n// Click anywhere in the webpage to change\n// the color value of the rectangle\n\nlet colorValue = 0;\nfunction draw() {\n fill(colorValue);\n rect(25, 25, 50, 50);\n describe('black 50-by-50 rect turns white with mouse click/press.');\n}\nfunction mousePressed() {\n if (colorValue === 0) {\n colorValue = 255;\n } else {\n colorValue = 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": "MouseEvent", "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": "MouseEvent", "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": "MouseEvent", "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": "WheelEvent", "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": "TouchEvent", "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": "TouchEvent", "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": "TouchEvent", "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 object.
\ncreateImage()
uses the width
and height
parameters to set the new\np5.Image object's dimensions in pixels. The new\np5.Image can be modified by updating its\npixels array or by calling its\nget() and\nset() methods. The\nloadPixels() method must be called\nbefore reading or modifying pixel values. The\nupdatePixels() method must be called\nfor updates to take effect.
Note: The new p5.Image object is transparent by\ndefault.
\n", "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": "new p5.Image object.", "type": "p5.Image" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the image's pixels into memory.\n img.loadPixels();\n\n // Set all the image's pixels to black.\n for (let x = 0; x < img.width; x += 1) {\n for (let y = 0; y < img.height; y += 1) {\n img.set(x, y, 0);\n }\n }\n\n // Update the image's pixel values.\n img.updatePixels();\n\n // Draw the image.\n image(img, 17, 17);\n\n describe('A black square drawn in the middle of a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the image's pixels into memory.\n img.loadPixels();\n\n // Create a color gradient.\n for (let x = 0; x < img.width; x += 1) {\n for (let y = 0; y < img.height; y += 1) {\n // Calculate the transparency.\n let a = map(x, 0, img.width, 0, 255);\n\n // Create a p5.Color object.\n let c = color(0, a);\n\n // Set the pixel's color.\n img.set(x, y, c);\n }\n }\n\n // Update the image's pixels.\n img.updatePixels();\n\n // Display the image.\n image(img, 17, 17);\n\n describe('A square with a horizontal color gradient that transitions from gray to black.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the pixels into memory.\n img.loadPixels();\n // Get the current pixel density.\n let d = pixelDensity();\n\n // Calculate the pixel that is halfway through the image's pixel array.\n let halfImage = 4 * (d * img.width) * (d * img.height / 2);\n\n // Set half of the image's pixels to black.\n for (let i = 0; i < halfImage; i += 4) {\n // Red.\n img.pixels[i] = 0;\n // Green.\n img.pixels[i + 1] = 0;\n // Blue.\n img.pixels[i + 2] = 0;\n // Alpha.\n img.pixels[i + 3] = 255;\n }\n\n // Update the image's pixels.\n img.updatePixels();\n\n // Display the image.\n image(img, 17, 17);\n\n describe('A black square drawn in the middle of a gray square.');\n}\n
\nSaves the current canvas as an image.
\nBy default, saveCanvas()
saves the canvas as a PNG image called\nuntitled.png
.
The first parameter, filename
, is optional. It's a string that sets the\nfile's name. If a file extension is included, as in\nsaveCanvas('drawing.png')
, then the image will be saved using that\nformat.
The second parameter, extension
, is also optional. It sets the files format.\nEither 'png'
or 'jpg'
can be used. For example, saveCanvas('drawing', 'jpg')
\nsaves the canvas to a file called drawing.jpg
.
Note: The browser will either save the file immediately or prompt the user\nwith a dialogue window.
\n", "itemtype": "method", "name": "saveCanvas", "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n background(255);\n\n // Save the canvas to 'untitled.png'.\n saveCanvas();\n\n describe('A white square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(255);\n\n // Save the canvas to 'myCanvas.jpg'.\n saveCanvas('myCanvas.jpg');\n\n describe('A white square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(255);\n\n // Save the canvas to 'myCanvas.jpg'.\n saveCanvas('myCanvas', 'jpg');\n\n describe('A white square.');\n}\n
\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n background(255);\n\n // Save the canvas to 'untitled.png'.\n saveCanvas(cnv);\n\n describe('A white square.');\n}\n
\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n background(255);\n\n // Save the canvas to 'myCanvas.jpg'.\n saveCanvas(cnv, 'myCanvas.jpg');\n\n describe('A white square.');\n}\n
\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n background(255);\n\n // Save the canvas to 'myCanvas.jpg'.\n saveCanvas(cnv, 'myCanvas', 'jpg');\n\n describe('A white square.');\n}\n
\nreference to a\n specific HTML5 canvas element.
\n", "type": "p5.Framebuffer|p5.Element|HTMLCanvasElement" }, { "name": "filename", "description": "file name. Defaults to 'untitled'.
\n", "type": "String", "optional": true }, { "name": "extension", "description": "file extension, either 'jpg' or 'png'. Defaults to 'png'.
\n", "type": "String", "optional": true } ] }, { "line": 267, "params": [ { "name": "filename", "description": "", "type": "String", "optional": true }, { "name": "extension", "description": "", "type": "String", "optional": true } ] } ] }, { "file": "src/image/image.js", "line": 558, "description": "Captures a sequence of frames from the canvas that can be saved as images.
\nsaveFrames()
creates an array of frame objects. Each frame is stored as\nan object with its file type, file name, and image data as a string. For\nexample, the first saved frame might have the following properties:
{ ext: 'png', filenmame: 'frame0', imageData: 'data:image/octet-stream;base64, abc123' }
.
The first parameter, filename
, sets the prefix for the file names. For\nexample, setting the prefix to 'frame'
would generate the image files\nframe0.png
, frame1.png
, and so on.
The second parameter, extension
, sets the file type to either 'png'
or\n'jpg'
.
The third parameter, duration
, sets the duration to record in seconds.\nThe maximum duration is 15 seconds.
The fourth parameter, framerate
, sets the number of frames to record per\nsecond. The maximum frame rate value is 22. Limits are placed on duration
\nand framerate
to avoid using too much memory. Recording large canvases\ncan easily crash sketches or even web browsers.
The fifth parameter, callback
, is optional. If a function is passed,\nimage files won't be saved by default. The callback function can be used\nto process an array containing the data for each captured frame. The array\nof image data contains a sequence of objects with three properties for each\nframe: imageData
, filename
, and extension
.
Note: Frames are downloaded as individual image files by default.
\n", "itemtype": "method", "name": "saveFrames", "params": [ { "name": "filename", "description": "prefix of file name.
\n", "type": "String" }, { "name": "extension", "description": "file extension, either 'jpg' or 'png'.
\n", "type": "String" }, { "name": "duration", "description": "duration in seconds to record. This parameter will be constrained to be less or equal to 15.
\n", "type": "Number" }, { "name": "framerate", "description": "number of frames to save per second. This parameter will be constrained to be less or equal to 22.
\n", "type": "Number" }, { "name": "callback", "description": "callback function that will be executed\n to handle the image data. This function\n should accept an array as argument. The\n array will contain the specified number of\n frames of objects. Each object has three\n properties: imageData
, filename
, and extension
.
\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A square repeatedly changes color from blue to pink.');\n}\n\nfunction draw() {\n let r = frameCount % 255;\n let g = 50;\n let b = 100;\n background(r, g, b);\n}\n\n// Save the frames when the user presses the 's' key.\nfunction keyPressed() {\n if (key === 's') {\n saveFrames('frame', 'png', 1, 5);\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A square repeatedly changes color from blue to pink.');\n}\n\nfunction draw() {\n let r = frameCount % 255;\n let g = 50;\n let b = 100;\n background(r, g, b);\n}\n\n// Print 5 frames when the user presses the mouse.\nfunction mousePressed() {\n saveFrames('frame', 'png', 1, 5, printFrames);\n}\n\n// Prints an array of objects containing raw image data, filenames, and extensions.\nfunction printFrames(frames) {\n for (let frame of frames) {\n print(frame);\n }\n}\n
\nLoads an image to create a p5.Image object.
\nloadImage()
interprets the first parameter one of three ways. If the path\nto an image file is provided, loadImage()
will load it. Paths to local\nfiles should be relative, such as 'assets/thundercat.jpg'
. URLs such as\n'https://example.com/thundercat.jpg'
may be blocked due to browser\nsecurity. Raw image data can also be passed as a base64 encoded image in\nthe form 'data:image/png;base64,arandomsequenceofcharacters'
.
The second parameter is optional. If a function is passed, it will be\ncalled once the image has loaded. The callback function can optionally use\nthe new p5.Image object.
\nThe third parameter is also optional. If a function is passed, it will be\ncalled if the image fails to load. The callback function can optionally use\nthe event error.
\nImages can take time to load. Calling loadImage()
in\npreload() ensures images load before they're\nused in setup() or draw().
path of the image to be loaded or base64 encoded image.
\n", "type": "String" }, { "name": "successCallback", "description": "function called with\n p5.Image once it\n loads.
\n", "type": "function(p5.Image)", "optional": true }, { "name": "failureCallback", "description": "function called with event\n error if the image fails to load.
\n", "type": "Function(Event)", "optional": true } ], "return": { "description": "the p5.Image object.", "type": "p5.Image" }, "example": [ "\n\nlet img;\n\n// Load the image and create a p5.Image object.\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Draw the image.\n image(img, 0, 0);\n\n describe('Image of the underside of a white umbrella and a gridded ceiling.');\n}\n
\n\nfunction setup() {\n // Call handleImage() once the image loads.\n loadImage('assets/laDefense.jpg', handleImage);\n\n describe('Image of the underside of a white umbrella and a gridded ceiling.');\n}\n\n// Display the image.\nfunction handleImage(img) {\n image(img, 0, 0);\n}\n
\n\nfunction setup() {\n // Call handleImage() once the image loads or\n // call handleError() if an error occurs.\n loadImage('assets/laDefense.jpg', handleImage, handleError);\n}\n\n// Display the image.\nfunction handleImage(img) {\n image(img, 0, 0);\n\n describe('Image of the underside of a white umbrella and a gridded ceiling.');\n}\n\n// Log the error.\nfunction handleError(event) {\n console.error('Oops!', event);\n}\n
\nGenerates a gif from a sketch and saves it to a file.
\nsaveGif()
may be called in setup() or at any\npoint while a sketch is running.
The first parameter, fileName
, sets the gif's file name.
The second parameter, duration
, sets the gif's duration in seconds.
The third parameter, options
, is optional. If an object is passed,\nsaveGif()
will use its properties to customize the gif. saveGif()
\nrecognizes the properties delay
, units
, silent
,\nnotificationDuration
, and notificationID
.
file name of gif.
\n", "type": "String" }, { "name": "duration", "description": "duration in seconds to capture from the sketch.
\n", "type": "Number" }, { "name": "options", "description": "an object that can contain five more properties:\n delay
, a Number specifying how much time to wait before recording;\n units
, a String that can be either 'seconds' or 'frames'. By default it's 'seconds’;\n silent
, a Boolean that defines presence of progress notifications. By default it’s false
;\n notificationDuration
, a Number that defines how long in seconds the final notification\n will live. By default it's 0
, meaning the notification will never be removed;\n notificationID
, a String that specifies the id of the notification's DOM element. By default it’s 'progressBar’
.
\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A circle drawn in the middle of a gray square. The circle changes color from black to white, then repeats.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the circle.\n let c = frameCount % 255;\n fill(c);\n\n // Display the circle.\n circle(50, 50, 25);\n}\n\n// Save a 5-second gif when the user presses the 's' key.\nfunction keyPressed() {\n if (key === 's') {\n saveGif('mySketch', 5);\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A circle drawn in the middle of a gray square. The circle changes color from black to white, then repeats.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the circle.\n let c = frameCount % 255;\n fill(c);\n\n // Display the circle.\n circle(50, 50, 25);\n}\n\n// Save a 5-second gif when the user presses the 's' key.\n// Wait 1 second after the key press before recording.\nfunction keyPressed() {\n if (key === 's') {\n saveGif('mySketch', 5, { delay: 1 });\n }\n}\n
\nHelper function for loading GIF-based images
\n", "class": "p5", "module": "Image", "submodule": "Loading & Displaying" }, { "file": "src/image/loading_displaying.js", "line": 888, "description": "Draws an image to the canvas.
\nThe first parameter, img
, is the source image to be drawn. img
can be\nany of the following objects:
The second and third parameters, dx
and dy
, set the coordinates of the\ndestination image's top left corner. See\nimageMode() for other ways to position images.
Here's a diagram that explains how optional parameters work in image()
:
The fourth and fifth parameters, dw
and dh
, are optional. They set the\nthe width and height to draw the destination image. By default, image()
\ndraws the full source image at its original size.
The sixth and seventh parameters, sx
and sy
, are also optional.\nThese coordinates define the top left corner of a subsection to draw from\nthe source image.
The eighth and ninth parameters, sw
and sh
, are also optional.\nThey define the width and height of a subsection to draw from the source\nimage. By default, image()
draws the full subsection that begins at\n(sx, sy)
and extends to the edges of the source image.
The ninth parameter, fit
, is also optional. It enables a subsection of\nthe source image to be drawn without affecting its aspect ratio. If\nCONTAIN
is passed, the full subsection will appear within the destination\nrectangle. If COVER
is passed, the subsection will completely cover the\ndestination rectangle. This may have the effect of zooming into the\nsubsection.
The tenth and eleventh paremeters, xAlign
and yAlign
, are also\noptional. They determine how to align the fitted subsection. xAlign
can\nbe set to either LEFT
, RIGHT
, or CENTER
. yAlign
can be set to\neither TOP
, BOTTOM
, or CENTER
. By default, both xAlign
and yAlign
\nare set to CENTER
.
\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Draw the image.\n image(img, 0, 0);\n\n describe('An image of the underside of a white umbrella with a gridded ceiling above.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Draw the image.\n image(img, 10, 10);\n\n describe('An image of the underside of a white umbrella with a gridded ceiling above. The image has dark gray borders on its left and top.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Draw the image 50x50.\n image(img, 0, 0, 50, 50);\n\n describe('An image of the underside of a white umbrella with a gridded ceiling above. The image is drawn in the top left corner of a dark gray square.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Draw the center of the image.\n image(img, 25, 25, 50, 50, 25, 25, 50, 50);\n\n describe('An image of a gridded ceiling drawn in the center of a dark gray square.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/moonwalk.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Draw the image and scale it to fit within the canvas.\n image(img, 0, 0, width, height, 0, 0, img.width, img.height, CONTAIN);\n\n describe('An image of an astronaut on the moon. The top and bottom borders of the image are dark gray.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n // Image is 50 x 50 pixels.\n img = loadImage('assets/laDefense50.png');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Draw the image and scale it to cover the canvas.\n image(img, 0, 0, width, height, 0, 0, img.width, img.height, COVER);\n\n describe('A pixelated image of the underside of a white umbrella with a gridded ceiling above.');\n}\n
\nimage to display.
\n", "type": "p5.Image|p5.Element|p5.Texture|p5.Framebuffer|p5.FramebufferTexture" }, { "name": "x", "description": "x-coordinate of the top-left corner of the image.
\n", "type": "Number" }, { "name": "y", "description": "y-coordinate of the top-left corner of the image.
\n", "type": "Number" }, { "name": "width", "description": "width to draw the image.
\n", "type": "Number", "optional": true }, { "name": "height", "description": "height to draw the image.
\n", "type": "Number", "optional": true } ] }, { "line": 1074, "params": [ { "name": "img", "description": "", "type": "p5.Image|p5.Element|p5.Texture|p5.Framebuffer|p5.FramebufferTexture" }, { "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": 1192, "description": "Tints images using a color.
\nThe version of tint()
with one parameter interprets it one of four ways.\nIf the parameter is a number, it's interpreted as a grayscale value. If the\nparameter is a string, it's interpreted as a CSS color string. An array of\n[R, G, B, A]
values or a p5.Color object can\nalso be used to set the tint color.
The version of tint()
with two parameters uses the first one as a\ngrayscale value and the second as an alpha value. For example, calling\ntint(255, 128)
will make an image 50% transparent.
The version of tint()
with three parameters interprets them as RGB or\nHSB values, depending on the current\ncolorMode(). The optional fourth parameter\nsets the alpha value. For example, tint(255, 0, 0, 100)
will give images\na red tint and make them transparent.
\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Left image.\n image(img, 0, 0);\n\n // Right image.\n // Tint with a CSS color string.\n tint('red');\n image(img, 50, 0);\n\n describe('Two images of an umbrella and a ceiling side-by-side. The image on the right has a red tint.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Left image.\n image(img, 0, 0);\n\n // Right image.\n // Tint with RGB values.\n tint(255, 0, 0);\n image(img, 50, 0);\n\n describe('Two images of an umbrella and a ceiling side-by-side. The image on the right has a red tint.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Left.\n image(img, 0, 0);\n\n // Right.\n // Tint with RGBA values.\n tint(255, 0, 0, 100);\n image(img, 50, 0);\n\n describe('Two images of an umbrella and a ceiling side-by-side. The image on the right has a transparent red tint.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Left.\n image(img, 0, 0);\n\n // Right.\n // Tint with grayscale and alpha values.\n tint(255, 180);\n image(img, 50, 0);\n\n describe('Two images of an umbrella and a ceiling side-by-side. The image on the right is transparent.');\n}\n
\nred or hue value.
\n", "type": "Number" }, { "name": "v2", "description": "green or saturation value.
\n", "type": "Number" }, { "name": "v3", "description": "blue or brightness.
\n", "type": "Number" }, { "name": "alpha", "description": "", "type": "Number", "optional": true } ] }, { "line": 1318, "params": [ { "name": "value", "description": "CSS color string.
\n", "type": "String" } ] }, { "line": 1323, "params": [ { "name": "gray", "description": "grayscale value.
\n", "type": "Number" }, { "name": "alpha", "description": "", "type": "Number", "optional": true } ] }, { "line": 1329, "params": [ { "name": "values", "description": "array containing the red, green, blue &\n alpha components of the color.
\n", "type": "Number[]" } ] }, { "line": 1335, "params": [ { "name": "color", "description": "the tint color
\n", "type": "p5.Color" } ] } ] }, { "file": "src/image/loading_displaying.js", "line": 1345, "description": "Removes the current tint set by tint().
\nnoTint()
restores images to their original colors.
\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Left.\n // Tint with a CSS color string.\n tint('red');\n image(img, 0, 0);\n\n // Right.\n // Remove the tint.\n noTint();\n image(img, 50, 0);\n\n describe('Two images of an umbrella and a ceiling side-by-side. The image on the left has a red tint.');\n}\n
\nChanges the location from which images are drawn when\nimage() is called.
\nBy default, the first\ntwo parameters of image() are the x- and\ny-coordinates of the image's upper-left corner. The next parameters are\nits width and height. This is the same as calling imageMode(CORNER)
.
imageMode(CORNERS)
also uses the first two parameters of\nimage() as the x- and y-coordinates of the image's\ntop-left corner. The third and fourth parameters are the coordinates of its\nbottom-right corner.
imageMode(CENTER)
uses the first two parameters of\nimage() as the x- and y-coordinates of the image's\ncenter. The next parameters are its width and height.
either CORNER, CORNERS, or CENTER.
\n", "type": "Constant" } ], "example": [ "\n\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use CORNER mode.\n imageMode(CORNER);\n\n // Display the image.\n image(img, 10, 10, 50, 50);\n\n describe('A square image of a brick wall is drawn at the top left of a gray square.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use CORNERS mode.\n imageMode(CORNERS);\n\n // Display the image.\n image(img, 10, 10, 90, 40);\n\n describe('An image of a brick wall is drawn on a gray square. The image is squeezed into a small rectangular area.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use CENTER mode.\n imageMode(CENTER);\n\n // Display the image.\n image(img, 50, 50, 80, 80);\n\n describe('A square image of a brick wall is drawn on a gray square.');\n}\n
\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": 114, "description": "The image's width in pixels.
\n", "type": "{Number}", "itemtype": "property", "name": "width", "readonly": "", "example": [ "\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Calculate the center coordinates.\n let x = img.width / 2;\n let y = img.height / 2;\n\n // Draw a circle at the image's center.\n circle(x, y, 20);\n\n describe('An image of a mountain landscape with a white circle drawn in the middle.');\n}\n
\nThe image's height in pixels.
\n", "type": "{Number}", "itemtype": "property", "name": "height", "readonly": "", "example": [ "\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Calculate the center coordinates.\n let x = img.width / 2;\n let y = img.height / 2;\n\n // Draw a circle at the image's center.\n circle(x, y, 20);\n\n describe('An image of a mountain landscape with a white circle drawn in the middle.');\n}\n
\nAn array containing the color of each pixel in the image.
\nColors are stored as numbers representing red, green, blue, and alpha\n(RGBA) values. img.pixels
is a one-dimensional array for performance\nreasons.
Each pixel occupies four elements in the pixels array, one for each\nRGBA value. For example, the pixel at coordinates (0, 0) stores its\nRGBA values at img.pixels[0]
, img.pixels[1]
, img.pixels[2]
,\nand img.pixels[3]
, respectively. The next pixel at coordinates (1, 0)\nstores its RGBA values at img.pixels[4]
, img.pixels[5]
,\nimg.pixels[6]
, and img.pixels[7]
. And so on. The img.pixels
array\nfor a 100×100 p5.Image object has\n100 × 100 × 4 = 40,000 elements.
Accessing the RGBA values for a pixel in the image requires a little\nmath as shown in the examples below. The\nimg.loadPixels()\nmethod must be called before accessing the img.pixels
array. The\nimg.updatePixels() method must be\ncalled after any changes are made.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the image's pixels.\n img.loadPixels();\n\n for (let i = 0; i < img.pixels.length; i += 4) {\n // Red.\n img.pixels[i] = 0;\n // Green.\n img.pixels[i + 1] = 0;\n // Blue.\n img.pixels[i + 2] = 0;\n // Alpha.\n img.pixels[i + 3] = 255;\n }\n\n // Update the image.\n img.updatePixels();\n\n // Display the image.\n image(img, 17, 17);\n\n describe('A black square drawn in the middle of a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the image's pixels.\n img.loadPixels();\n\n // Set the pixels to red.\n for (let i = 0; i < img.pixels.length; i += 4) {\n // Red.\n img.pixels[i] = 255;\n // Green.\n img.pixels[i + 1] = 0;\n // Blue.\n img.pixels[i + 2] = 0;\n // Alpha.\n img.pixels[i + 3] = 255;\n }\n\n // Update the image.\n img.updatePixels();\n\n // Display the image.\n image(img, 17, 17);\n\n describe('A red square drawn in the middle of a gray square.');\n}\n
\nGets or sets the pixel density for high pixel density displays.
\nBy default, the density will be set to 1.
\nCall this method with no arguments to get the default density, or pass\nin a number to set the density. If a non-positive number is provided,\nit defaults to 1.
\n", "itemtype": "method", "name": "pixelDensity", "params": [ { "name": "density", "description": "A scaling factor for the number of pixels per\nside
\n", "type": "Number", "optional": true } ], "return": { "description": "The current density if called without arguments, or the instance for chaining if setting density.", "type": "Number" }, "class": "p5.Image", "module": "Image", "submodule": "Image" }, { "file": "src/image/p5.Image.js", "line": 342, "description": "Helper function for animating GIF-based images with time
\n", "class": "p5.Image", "module": "Image", "submodule": "Image" }, { "file": "src/image/p5.Image.js", "line": 373, "description": "Helper fxn for sharing pixel methods
\n", "class": "p5.Image", "module": "Image", "submodule": "Image" }, { "file": "src/image/p5.Image.js", "line": 381, "description": "Loads the current value of each pixel in the image into the img.pixels
\narray.
img.loadPixels()
must be called before reading or modifying pixel\nvalues.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the image's pixels.\n img.loadPixels();\n\n // Set the pixels to black.\n for (let x = 0; x < img.width; x += 1) {\n for (let y = 0; y < img.height; y += 1) {\n img.set(x, y, 0);\n }\n }\n\n // Update the image.\n img.updatePixels();\n\n // Display the image.\n image(img, 17, 17);\n\n describe('A black square drawn in the middle of a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the image's pixels.\n img.loadPixels();\n\n for (let i = 0; i < img.pixels.length; i += 4) {\n // Red.\n img.pixels[i] = 0;\n // Green.\n img.pixels[i + 1] = 0;\n // Blue.\n img.pixels[i + 2] = 0;\n // Alpha.\n img.pixels[i + 3] = 255;\n }\n\n // Update the image.\n img.updatePixels();\n\n // Display the image.\n image(img, 17, 17);\n\n describe('A black square drawn in the middle of a gray square.');\n}\n
\nUpdates the canvas with the RGBA values in the\nimg.pixels array.
\nimg.updatePixels()
only needs to be called after changing values in\nthe img.pixels array. Such changes can be\nmade directly after calling\nimg.loadPixels() or by calling\nimg.set().
The optional parameters x
, y
, width
, and height
define a\nsubsection of the image to update. Doing so can improve performance in\nsome cases.
If the image was loaded from a GIF, then calling img.updatePixels()
\nwill update the pixels in current frame.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the image's pixels.\n img.loadPixels();\n\n // Set the pixels to black.\n for (let x = 0; x < img.width; x += 1) {\n for (let y = 0; y < img.height; y += 1) {\n img.set(x, y, 0);\n }\n }\n\n // Update the image.\n img.updatePixels();\n\n // Display the image.\n image(img, 17, 17);\n\n describe('A black square drawn in the middle of a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the image's pixels.\n img.loadPixels();\n\n // Set the pixels to black.\n for (let i = 0; i < img.pixels.length; i += 4) {\n // Red.\n img.pixels[i] = 0;\n // Green.\n img.pixels[i + 1] = 0;\n // Blue.\n img.pixels[i + 2] = 0;\n // Alpha.\n img.pixels[i + 3] = 255;\n }\n\n // Update the image.\n img.updatePixels();\n\n // Display the image.\n image(img, 17, 17);\n\n describe('A black square drawn in the middle of a gray square.');\n}\n
\nx-coordinate of the upper-left corner\n of the subsection to update.
\n", "type": "Integer" }, { "name": "y", "description": "y-coordinate of the upper-left corner\n of the subsection to update.
\n", "type": "Integer" }, { "name": "w", "description": "width of the subsection to update.
\n", "type": "Integer" }, { "name": "h", "description": "height of the subsection to update.
\n", "type": "Integer" } ] }, { "line": 555, "params": [] } ] }, { "file": "src/image/p5.Image.js", "line": 563, "description": "Gets a pixel or a region of pixels from the image.
\nimg.get()
is easy to use but it's not as fast as\nimg.pixels. Use\nimg.pixels to read many pixel values.
The version of img.get()
with no parameters returns the entire image.
The version of img.get()
with two parameters, as in img.get(10, 20)
,\ninterprets them as coordinates. It returns an array with the\n[R, G, B, A]
values of the pixel at the given point.
The version of img.get()
with four parameters, as in\nimg,get(10, 20, 50, 90)
, interprets them as\ncoordinates and dimensions. The first two parameters are the coordinates\nof the upper-left corner of the subsection. The last two parameters are\nthe width and height of the subsection. It returns a subsection of the\ncanvas in a new p5.Image object.
Use img.get()
instead of get() to work directly\nwith images.
\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Display the image.\n image(img, 0, 0);\n\n // Copy the image.\n let img2 = get();\n\n // Display the copied image on the right.\n image(img2, 50, 0);\n\n describe('Two identical mountain landscapes shown side-by-side.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Get a pixel's color.\n let c = img.get(50, 90);\n\n // Style the square using the pixel's color.\n fill(c);\n noStroke();\n\n // Draw the square.\n square(25, 25, 50);\n\n describe('A mountain landscape with an olive green square in its center.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Copy half of the image.\n let img2 = img.get(0, 0, img.width / 2, img.height / 2);\n\n // Display half of the image.\n image(img2, 50, 50);\n\n describe('A mountain landscape drawn on top of another mountain landscape.');\n}\n
\nx-coordinate of the pixel.
\n", "type": "Number" }, { "name": "y", "description": "y-coordinate of the pixel.
\n", "type": "Number" }, { "name": "w", "description": "width of the subsection to be returned.
\n", "type": "Number" }, { "name": "h", "description": "height of the subsection to be returned.
\n", "type": "Number" } ], "return": { "description": "subsection as a p5.Image object.", "type": "p5.Image" } }, { "line": 678, "params": [], "return": { "description": "whole p5.Image", "type": "p5.Image" } }, { "line": 682, "params": [ { "name": "x", "description": "", "type": "Number" }, { "name": "y", "description": "", "type": "Number" } ], "return": { "description": "color of the pixel at (x, y) in array format `[R, G, B, A]`.", "type": "Number[]" } } ] }, { "file": "src/image/p5.Image.js", "line": 697, "description": "Sets the color of one or more pixels within an image.
\nimg.set()
is easy to use but it's not as fast as\nimg.pixels. Use\nimg.pixels to set many pixel values.
img.set()
interprets the first two parameters as x- and y-coordinates. It\ninterprets the last parameter as a grayscale value, a [R, G, B, A]
pixel\narray, a p5.Color object, or another\np5.Image object.
img.updatePixels() must be called\nafter using img.set()
for changes to appear.
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 p5.Color object |\n p5.Image to copy.
\n", "type": "Number|Number[]|Object" } ], "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(100, 100);\n\n // Set four pixels to black.\n img.set(30, 20, 0);\n img.set(85, 20, 0);\n img.set(85, 75, 0);\n img.set(30, 75, 0);\n\n // Update the image.\n img.updatePixels();\n\n // Display the image.\n image(img, 0, 0);\n\n describe('Four black dots arranged in a square drawn on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(100, 100);\n\n // Create a p5.Color object.\n let black = color(0);\n\n // Set four pixels to black.\n img.set(30, 20, black);\n img.set(85, 20, black);\n img.set(85, 75, black);\n img.set(30, 75, black);\n\n // Update the image.\n img.updatePixels();\n\n // Display the image.\n image(img, 0, 0);\n\n describe('Four black dots arranged in a square drawn on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Draw a color gradient.\n for (let x = 0; x < img.width; x += 1) {\n for (let y = 0; y < img.height; y += 1) {\n let c = map(x, 0, img.width, 0, 255);\n img.set(x, y, c);\n }\n }\n\n // Update the image.\n img.updatePixels();\n\n // Display the image.\n image(img, 17, 17);\n\n describe('A square with a horiztonal color gradient from black to white drawn on a gray background.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Image object.\n let img2 = createImage(100, 100);\n\n // Set the blank image's pixels using the landscape.\n img2.set(0, 0, img);\n\n // Display the second image.\n image(img2, 0, 0);\n\n describe('An image of a mountain landscape.');\n}\n
\nResizes the image to a given width and height.
\nThe image's original aspect ratio can be kept by passing 0 for either\nwidth
or height
. For example, calling img.resize(50, 0)
on an image\nthat was 500 × 300 pixels will resize it to 50 × 30 pixels.
resized image width.
\n", "type": "Number" }, { "name": "height", "description": "resized image height.
\n", "type": "Number" } ], "example": [ "\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Resize the image.\n img.resize(50, 100);\n\n // Display the resized image.\n image(img, 0, 0);\n\n describe('Two images of a mountain landscape. One copy of the image is squeezed horizontally.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Resize the image, keeping the aspect ratio.\n img.resize(0, 30);\n\n // Display the resized image.\n image(img, 0, 0);\n\n describe('Two images of a mountain landscape. The small copy of the image covers the top-left corner of the larger image.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Resize the image, keeping the aspect ratio.\n img.resize(60, 0);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('Two images of a mountain landscape. The small copy of the image covers the top-left corner of the larger image.');\n}\n
\nCopies pixels from a source image to this image.
\nThe first parameter, srcImage
, is an optional\np5.Image object to copy. If a source image isn't\npassed, then img.copy()
can copy a region of this image to another\nregion.
The next four parameters, sx
, sy
, sw
, and sh
determine the region\nto copy from the source image. (sx, sy)
is the top-left corner of the\nregion. sw
and sh
are the region's width and height.
The next four parameters, dx
, dy
, dw
, and dh
determine the region\nof this image to copy into. (dx, dy)
is the top-left corner of the\nregion. dw
and dh
are the region's width and height.
Calling img.copy()
will scale pixels from the source region if it isn't\nthe same size as the destination region.
\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Copy one region of the image to another.\n img.copy(7, 22, 10, 10, 35, 25, 50, 50);\n\n // Display the image.\n image(img, 0, 0);\n\n // Outline the copied region.\n stroke(255);\n noFill();\n square(7, 22, 10);\n\n describe('An image of a mountain landscape. A square region is outlined in white. A larger square contains a pixelated view of the outlined region.');\n}\n
\n\nlet mountains;\nlet bricks;\n\n// Load the images.\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Calculate the center of the bricks image.\n let x = bricks.width / 2;\n let y = bricks.height / 2;\n\n // Copy the bricks to the mountains image.\n mountains.copy(bricks, 0, 0, x, y, 0, 0, x, y);\n\n // Display the mountains image.\n image(mountains, 0, 0);\n\n describe('An image of a brick wall drawn at the top-left of an image of a mountain landscape.');\n}\n
\nsource 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": 1094, "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": 1109, "description": "Masks part of the image with another.
\nimg.mask()
uses another p5.Image object's\nalpha channel as the alpha channel for this image. Masks are cumulative\nand can't be removed once applied.
source image.
\n", "type": "p5.Image" } ], "example": [ "\n\nlet photo;\nlet maskImage;\n\n// Load the images.\nfunction preload() {\n photo = loadImage('assets/rockies.jpg');\n maskImage = loadImage('assets/mask2.png');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Apply the mask.\n photo.mask(maskImage);\n\n // Display the image.\n image(photo, 0, 0);\n\n describe('An image of a mountain landscape. The right side of the image has a faded patch of white.');\n}\n
\nApplies an image filter to the image.
\nThe preset options are:
\nINVERT
\nInverts the colors in the image. No parameter is used.
GRAY
\nConverts the image to grayscale. No parameter is used.
THRESHOLD
\nConverts the image to black and white. Pixels with a grayscale value\nabove a given threshold are converted to white. The rest are converted to\nblack. The threshold must be between 0.0 (black) and 1.0 (white). If no\nvalue is specified, 0.5 is used.
OPAQUE
\nSets the alpha channel to be entirely opaque. No parameter is used.
POSTERIZE
\nLimits the number of colors in the image. Each color channel is limited to\nthe number of colors specified. Values between 2 and 255 are valid, but\nresults are most noticeable with lower values. The default value is 4.
BLUR
\nBlurs the image. The level of blurring is specified by a blur radius. Larger\nvalues increase the blur. The default value is 4. A gaussian blur is used\nin P2D
mode. A box blur is used in WEBGL
mode.
ERODE
\nReduces the light areas. No parameter is used.
DILATE
\nIncreases the light areas. No parameter is used.
either THRESHOLD, GRAY, OPAQUE, INVERT,\n POSTERIZE, ERODE, DILATE or BLUR.
\n", "type": "Constant" }, { "name": "filterParam", "description": "parameter unique to each filter.
\n", "type": "Number", "optional": true } ], "example": [ "\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Apply the INVERT filter.\n img.filter(INVERT);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('A blue brick wall.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Apply the GRAY filter.\n img.filter(GRAY);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('A brick wall drawn in grayscale.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Apply the THRESHOLD filter.\n img.filter(THRESHOLD);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('A brick wall drawn in black and white.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Apply the OPAQUE filter.\n img.filter(OPAQUE);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('A red brick wall.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Apply the POSTERIZE filter.\n img.filter(POSTERIZE, 3);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('An image of a red brick wall drawn with a limited color palette.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Apply the BLUR filter.\n img.filter(BLUR, 3);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('A blurry image of a red brick wall.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Apply the DILATE filter.\n img.filter(DILATE);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('A red brick wall with bright lines between each brick.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Apply the ERODE filter.\n img.filter(ERODE);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('A red brick wall with faint lines between each brick.');\n}\n
\nCopies a region of pixels from another image into this one.
\nThe first parameter, srcImage
, is the\np5.Image object to blend.
The next four parameters, sx
, sy
, sw
, and sh
determine the region\nto blend from the source image. (sx, sy)
is the top-left corner of the\nregion. sw
and sh
are the regions width and height.
The next four parameters, dx
, dy
, dw
, and dh
determine the region\nof the canvas to blend into. (dx, dy)
is the top-left corner of the\nregion. dw
and dh
are the regions width and height.
The tenth parameter, blendMode
, sets the effect used to blend the images'\ncolors. The options are BLEND
, DARKEST
, LIGHTEST
, DIFFERENCE
,\nMULTIPLY
, EXCLUSION
, SCREEN
, REPLACE
, OVERLAY
, HARD_LIGHT
,\nSOFT_LIGHT
, DODGE
, BURN
, ADD
, or NORMAL
.
\nlet mountains;\nlet bricks;\n\n// Load the images.\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Blend the bricks image into the mountains.\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n\n // Display the mountains image.\n image(mountains, 0, 0);\n\n // Display the bricks image.\n image(bricks, 0, 0);\n\n describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears faded on the right of the image.');\n}\n
\n\nlet mountains;\nlet bricks;\n\n// Load the images.\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Blend the bricks image into the mountains.\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n\n // Display the mountains image.\n image(mountains, 0, 0);\n\n // Display the bricks image.\n image(bricks, 0, 0);\n\n describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears transparent on the right of the image.');\n}\n
\n\nlet mountains;\nlet bricks;\n\n// Load the images.\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Blend the bricks image into the mountains.\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n\n // Display the mountains image.\n image(mountains, 0, 0);\n\n // Display the bricks image.\n image(bricks, 0, 0);\n\n describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears washed out on the right of the image.');\n}\n
\nsource 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": 1554, "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": 1598, "description": "Saves the image to a file.
\nBy default, img.save()
saves the image as a PNG image called\nuntitled.png
.
The first parameter, filename
, is optional. It's a string that sets the\nfile's name. If a file extension is included, as in\nimg.save('drawing.png')
, then the image will be saved using that\nformat.
The second parameter, extension
, is also optional. It sets the files format.\nEither 'png'
or 'jpg'
can be used. For example, img.save('drawing', 'jpg')
\nsaves the canvas to a file called drawing.jpg
.
Note: The browser will either save the file immediately or prompt the user\nwith a dialogue window.
\nThe image will only be downloaded as an animated GIF if it was loaded\nfrom a GIF file. See saveGif() to create new\nGIFs.
\n", "itemtype": "method", "name": "save", "params": [ { "name": "filename", "description": "filename. Defaults to 'untitled'.
\n", "type": "String" }, { "name": "extension", "description": "file extension, either 'png' or 'jpg'.\n Defaults to 'png'.
\n", "type": "String", "optional": true } ], "example": [ "\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n describe('An image of a mountain landscape. The image is downloaded when the user presses the \"s\", \"j\", or \"p\" key.');\n}\n\n// Save the image with different options when the user presses a key.\nfunction keyPressed() {\n if (key === 's') {\n img.save();\n } else if (key === 'j') {\n img.save('rockies.jpg');\n } else if (key === 'p') {\n img.save('rockies', 'png');\n }\n}\n
\nRestarts an animated GIF at its first frame.
\n", "itemtype": "method", "name": "reset", "example": [ "\n\nlet gif;\n\n// Load the image.\nfunction preload() {\n gif = loadImage('assets/arnott-wallace-wink-loop-once.gif');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A cartoon face winks once and then freezes. Clicking resets the face and makes it wink again.');\n}\n\nfunction draw() {\n background(255);\n\n // Display the image.\n image(gif, 0, 0);\n}\n\n// Reset the GIF when the user presses the mouse.\nfunction mousePressed() {\n gif.reset();\n}\n
\nGets the index of the current frame in an animated GIF.
\n", "itemtype": "method", "name": "getCurrentFrame", "return": { "description": "index of the GIF's current frame.", "type": "Number" }, "example": [ "\n\nlet gif;\n\n// Load the image.\nfunction preload() {\n gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A cartoon eye repeatedly looks around, then outwards. A number displayed in the bottom-left corner increases from 0 to 124, then repeats.');\n}\n\nfunction draw() {\n // Get the index of the current GIF frame.\n let index = gif.getCurrentFrame();\n\n // Display the image.\n image(gif, 0, 0);\n\n // Display the current frame.\n text(index, 10, 90);\n}\n
\nSets the current frame in an animated GIF.
\n", "itemtype": "method", "name": "setFrame", "params": [ { "name": "index", "description": "index of the frame to display.
\n", "type": "Number" } ], "example": [ "\n\nlet gif;\nlet frameSlider;\n\n// Load the image.\nfunction preload() {\n gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Get the index of the last frame.\n let maxFrame = gif.numFrames() - 1;\n\n // Create a slider to control which frame is drawn.\n frameSlider = createSlider(0, maxFrame);\n frameSlider.position(10, 80);\n frameSlider.size(80);\n\n describe('A cartoon eye looks around when a slider is moved.');\n}\n\nfunction draw() {\n // Get the slider's value.\n let index = frameSlider.value();\n\n // Set the GIF's frame.\n gif.setFrame(index);\n\n // Display the image.\n image(gif, 0, 0);\n}\n
\nReturns the number of frames in an animated GIF.
\n", "itemtype": "method", "name": "numFrames", "return": { "description": "number of frames in the GIF.", "type": "Number" }, "example": [ "\n\nlet gif;\n\n// Load the image.\nfunction preload() {\n gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A cartoon eye looks around. The text \"n / 125\" is shown at the bottom of the canvas.');\n}\n\nfunction draw() {\n // Display the image.\n image(gif, 0, 0);\n\n // Display the current state of playback.\n let total = gif.numFrames();\n let index = gif.getCurrentFrame();\n text(`${index} / ${total}`, 30, 90);\n}\n
\nPlays an animated GIF that was paused with\nimg.pause().
\n", "itemtype": "method", "name": "play", "example": [ "\n\nlet gif;\n\n// Load the image.\nfunction preload() {\n gif = loadImage('assets/nancy-liang-wind-loop-forever.gif');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A drawing of a child with hair blowing in the wind. The animation freezes when clicked and resumes when released.');\n}\n\nfunction draw() {\n background(255);\n image(gif, 0, 0);\n}\n\n// Pause the GIF when the user presses the mouse.\nfunction mousePressed() {\n gif.pause();\n}\n\n// Play the GIF when the user releases the mouse.\nfunction mouseReleased() {\n gif.play();\n}\n
\nPauses an animated GIF.
\nThe GIF can be resumed by calling\nimg.play().
\n", "itemtype": "method", "name": "pause", "example": [ "\n\nlet gif;\n\n// Load the image.\nfunction preload() {\n gif = loadImage('assets/nancy-liang-wind-loop-forever.gif');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A drawing of a child with hair blowing in the wind. The animation freezes when clicked and resumes when released.');\n}\n\nfunction draw() {\n background(255);\n\n // Display the image.\n image(gif, 0, 0);\n}\n\n// Pause the GIF when the user presses the mouse.\nfunction mousePressed() {\n gif.pause();\n}\n\n// Play the GIF when the user presses the mouse.\nfunction mouseReleased() {\n gif.play();\n}\n
\nChanges the delay between frames in an animated GIF.
\nThe first parameter, delay
, is the length of the delay in milliseconds.
The second parameter, index
, is optional. If provided, only the frame\nat index
will have its delay modified. All other frames will keep\ntheir default delay.
delay in milliseconds between switching frames.
\n", "type": "Number" }, { "name": "index", "description": "index of the frame that will have its delay modified.
\n", "type": "Number", "optional": true } ], "example": [ "\n\nlet gifFast;\nlet gifSlow;\n\n// Load the images.\nfunction preload() {\n gifFast = loadImage('assets/arnott-wallace-eye-loop-forever.gif');\n gifSlow = loadImage('assets/arnott-wallace-eye-loop-forever.gif');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Resize the images.\n gifFast.resize(50, 50);\n gifSlow.resize(50, 50);\n\n // Set the delay lengths.\n gifFast.delay(10);\n gifSlow.delay(100);\n\n describe('Two animated eyes looking around. The eye on the left moves faster than the eye on the right.');\n}\n\nfunction draw() {\n // Display the images.\n image(gifFast, 0, 0);\n image(gifSlow, 50, 0);\n}\n
\n\nlet gif;\n\n// Load the image.\nfunction preload() {\n gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Set the delay of frame 67.\n gif.delay(3000, 67);\n\n describe('An animated eye looking around. It pauses for three seconds while it looks down.');\n}\n\nfunction draw() {\n // Display the image.\n image(gif, 0, 0);\n}\n
\nAn array containing the color of each pixel on the canvas.
\nColors are stored as numbers representing red, green, blue, and alpha\n(RGBA) values. pixels
is a one-dimensional array for performance reasons.
Each pixel occupies four elements in the pixels
array, one for each RGBA\nvalue. For example, the pixel at coordinates (0, 0) stores its RGBA values\nat pixels[0]
, pixels[1]
, pixels[2]
, and pixels[3]
, respectively.\nThe next pixel at coordinates (1, 0) stores its RGBA values at pixels[4]
,\npixels[5]
, pixels[6]
, and pixels[7]
. And so on. The pixels
array\nfor a 100×100 canvas has 100 × 100 × 4 = 40,000 elements.
Some displays use several smaller pixels to set the color at a single\npoint. The pixelDensity() function returns\nthe pixel density of the canvas. High density displays often have a\npixelDensity() of 2. On such a display, the\npixels
array for a 100×100 canvas has 200 × 200 × 4 =\n160,000 elements.
Accessing the RGBA values for a point on the canvas requires a little math\nas shown below. The loadPixels() function\nmust be called before accessing the pixels
array. The\nupdatePixels() function must be called\nafter any changes are made.
\nfunction setup() {\n createCanvas(100, 100);\n\n // Load the pixels array.\n loadPixels();\n\n // Set the dot's coordinates.\n let x = 50;\n let y = 50;\n\n // Get the pixel density.\n let d = pixelDensity();\n\n // Set the pixel(s) at the center of the canvas black.\n for (let i = 0; i < d; i += 1) {\n for (let j = 0; j < d; j += 1) {\n let index = 4 * ((y * d + j) * width * d + (x * d + i));\n // Red.\n pixels[index] = 0;\n // Green.\n pixels[index + 1] = 0;\n // Blue.\n pixels[index + 2] = 0;\n // Alpha.\n pixels[index + 3] = 255;\n }\n }\n\n // Update the canvas.\n updatePixels();\n\n describe('A black dot in the middle of a gray rectangle.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Load the pixels array.\n loadPixels();\n\n // Get the pixel density.\n let d = pixelDensity();\n\n // Calculate the halfway index in the pixels array.\n let halfImage = 4 * (d * width) * (d * height / 2);\n\n // Make the top half of the canvas red.\n for (let i = 0; i < halfImage; i += 4) {\n // Red.\n pixels[i] = 255;\n // Green.\n pixels[i + 1] = 0;\n // Blue.\n pixels[i + 2] = 0;\n // Alpha.\n pixels[i + 3] = 255;\n }\n\n // Update the canvas.\n updatePixels();\n\n describe('A red rectangle drawn above a gray rectangle.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Color object.\n let pink = color(255, 102, 204);\n\n // Load the pixels array.\n loadPixels();\n\n // Get the pixel density.\n let d = pixelDensity();\n\n // Calculate the halfway index in the pixels array.\n let halfImage = 4 * (d * width) * (d * height / 2);\n\n // Make the top half of the canvas red.\n for (let i = 0; i < halfImage; i += 4) {\n pixels[i] = red(pink);\n pixels[i + 1] = green(pink);\n pixels[i + 2] = blue(pink);\n pixels[i + 3] = alpha(pink);\n }\n\n // Update the canvas.\n updatePixels();\n\n describe('A pink rectangle drawn above a gray rectangle.');\n}\n
\nCopies a region of pixels from one image to another.
\nThe first parameter, srcImage
, is the\np5.Image object to blend.
The next four parameters, sx
, sy
, sw
, and sh
determine the region\nto blend from the source image. (sx, sy)
is the top-left corner of the\nregion. sw
and sh
are the regions width and height.
The next four parameters, dx
, dy
, dw
, and dh
determine the region\nof the canvas to blend into. (dx, dy)
is the top-left corner of the\nregion. dw
and dh
are the regions width and height.
The tenth parameter, blendMode
, sets the effect used to blend the images'\ncolors. The options are BLEND
, DARKEST
, LIGHTEST
, DIFFERENCE
,\nMULTIPLY
, EXCLUSION
, SCREEN
, REPLACE
, OVERLAY
, HARD_LIGHT
,\nSOFT_LIGHT
, DODGE
, BURN
, ADD
, or NORMAL
\nlet img0;\nlet img1;\n\n// Load the images.\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use the mountains as the background.\n background(img0);\n\n // Display the bricks.\n image(img1, 0, 0);\n\n // Display the bricks faded into the landscape.\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n\n describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears faded on the right of the image.');\n}\n
\n\nlet img0;\nlet img1;\n\n// Load the images.\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use the mountains as the background.\n background(img0);\n\n // Display the bricks.\n image(img1, 0, 0);\n\n // Display the bricks partially transparent.\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n\n describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears transparent on the right of the image.');\n}\n
\n\nlet img0;\nlet img1;\n\n// Load the images.\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use the mountains as the background.\n background(img0);\n\n // Display the bricks.\n image(img1, 0, 0);\n\n // Display the bricks washed out into the landscape.\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n\n describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears washed out on the right of the image.');\n}\n
\nsource 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": 267, "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": 288, "description": "Copies pixels from a source image to a region of the canvas.
\nThe first parameter, srcImage
, is the\np5.Image object to blend. The source image can be\nthe canvas itself or a\np5.Image object. copy()
will scale pixels from\nthe source region if it isn't the same size as the destination region.
The next four parameters, sx
, sy
, sw
, and sh
determine the region\nto copy from the source image. (sx, sy)
is the top-left corner of the\nregion. sw
and sh
are the region's width and height.
The next four parameters, dx
, dy
, dw
, and dh
determine the region\nof the canvas to copy into. (dx, dy)
is the top-left corner of the\nregion. dw
and dh
are the region's width and height.
\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use the mountains as the background.\n background(img);\n\n // Copy a region of pixels to another spot.\n copy(img, 7, 22, 10, 10, 35, 25, 50, 50);\n\n // Outline the copied region.\n stroke(255);\n noFill();\n square(7, 22, 10);\n\n describe('An image of a mountain landscape. A square region is outlined in white. A larger square contains a pixelated view of the outlined region.');\n}\n
\nsource 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": 345, "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": 442, "description": "Applies an image filter to the canvas.
\nThe preset options are:
\nINVERT
\nInverts the colors in the image. No parameter is used.
GRAY
\nConverts the image to grayscale. No parameter is used.
THRESHOLD
\nConverts the image to black and white. Pixels with a grayscale value\nabove a given threshold are converted to white. The rest are converted to\nblack. The threshold must be between 0.0 (black) and 1.0 (white). If no\nvalue is specified, 0.5 is used.
OPAQUE
\nSets the alpha channel to entirely opaque. No parameter is used.
POSTERIZE
\nLimits the number of colors in the image. Each color channel is limited to\nthe number of colors specified. Values between 2 and 255 are valid, but\nresults are most noticeable with lower values. The default value is 4.
BLUR
\nBlurs the image. The level of blurring is specified by a blur radius. Larger\nvalues increase the blur. The default value is 4. A gaussian blur is used\nin P2D
mode. A box blur is used in WEBGL
mode.
ERODE
\nReduces the light areas. No parameter is used.
DILATE
\nIncreases the light areas. No parameter is used.
filter()
uses WebGL in the background by default because it's faster.\nThis can be disabled in P2D
mode by adding a false
argument, as in\nfilter(BLUR, false)
. This may be useful to keep computation off the GPU\nor to work around a lack of WebGL support.
In WebgL mode, filter()
can also use custom shaders. See\ncreateFilterShader() for more\ninformation.
\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the INVERT filter.\n filter(INVERT);\n\n describe('A blue brick wall.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the GRAY filter.\n filter(GRAY);\n\n describe('A brick wall drawn in grayscale.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the THRESHOLD filter.\n filter(THRESHOLD);\n\n describe('A brick wall drawn in black and white.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the OPAQUE filter.\n filter(OPAQUE);\n\n describe('A red brick wall.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the POSTERIZE filter.\n filter(POSTERIZE, 3);\n\n describe('An image of a red brick wall drawn with limited color palette.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the BLUR filter.\n filter(BLUR, 3);\n\n describe('A blurry image of a red brick wall.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the DILATE filter.\n filter(DILATE);\n\n describe('A red brick wall with bright lines between each brick.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the ERODE filter.\n filter(ERODE);\n\n describe('A red brick wall with faint lines between each brick.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the BLUR filter.\n // Don't use WebGL.\n filter(BLUR, 3, false);\n\n describe('A blurry image of a red brick wall.');\n}\n
\neither THRESHOLD, GRAY, OPAQUE, INVERT,\n POSTERIZE, BLUR, ERODE, DILATE or BLUR.
\n", "type": "Constant" }, { "name": "filterParam", "description": "parameter unique to each filter.
\n", "type": "Number", "optional": true }, { "name": "useWebGL", "description": "flag to control whether to use fast\n WebGL filters (GPU) or original image\n filters (CPU); defaults to true
.
shader that's been loaded, with the\n frag shader using a tex0
uniform.
Gets a pixel or a region of pixels from the canvas.
\nget()
is easy to use but it's not as fast as\npixels. Use pixels\nto read many pixel values.
The version of get()
with no parameters returns the entire canvas.
The version of get()
with two parameters interprets them as\ncoordinates. It returns an array with the [R, G, B, A]
values of the\npixel at the given point.
The version of get()
with four parameters interprets them as coordinates\nand dimensions. It returns a subsection of the canvas as a\np5.Image object. The first two parameters are the\ncoordinates for the upper-left corner of the subsection. The last two\nparameters are the width and height of the subsection.
Use p5.Image.get() to work directly with\np5.Image objects.
\n", "itemtype": "method", "name": "get", "return": { "description": "subsection as a p5.Image object.", "type": "p5.Image" }, "example": [ "\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Get the entire canvas.\n let c = get();\n\n // Display half the canvas.\n image(c, 50, 0);\n\n describe('Two identical mountain landscapes shown side-by-side.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Get the color of a pixel.\n let c = get(50, 90);\n\n // Style the square with the pixel's color.\n fill(c);\n noStroke();\n\n // Display the square.\n square(25, 25, 50);\n\n describe('A mountain landscape with an olive green square in its center.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Get a region of the image.\n let c = get(0, 0, 50, 50);\n\n // Display the region.\n image(c, 50, 50);\n\n describe('A mountain landscape drawn on top of another mountain landscape.');\n}\n
\nx-coordinate of the pixel.
\n", "type": "Number" }, { "name": "y", "description": "y-coordinate of the pixel.
\n", "type": "Number" }, { "name": "w", "description": "width of the subsection to be returned.
\n", "type": "Number" }, { "name": "h", "description": "height of the subsection to be returned.
\n", "type": "Number" } ], "return": { "description": "subsection as a p5.Image object.", "type": "p5.Image" } }, { "line": 931, "params": [], "return": { "description": "whole canvas as a p5.Image.", "type": "p5.Image" } }, { "line": 935, "params": [ { "name": "x", "description": "", "type": "Number" }, { "name": "y", "description": "", "type": "Number" } ], "return": { "description": "color of the pixel at (x, y) in array format `[R, G, B, A]`.", "type": "Number[]" } } ] }, { "file": "src/image/pixels.js", "line": 946, "description": "Loads the current value of each pixel on the canvas into the\npixels array.
\nloadPixels()
must be called before reading from or writing to\npixels.
\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0, 100, 100);\n\n // Get the pixel density.\n let d = pixelDensity();\n\n // Calculate the halfway index in the pixels array.\n let halfImage = 4 * (d * width) * (d * height / 2);\n\n // Load the pixels array.\n loadPixels();\n\n // Copy the top half of the canvas to the bottom.\n for (let i = 0; i < halfImage; i += 1) {\n pixels[i + halfImage] = pixels[i];\n }\n\n // Update the canvas.\n updatePixels();\n\n describe('Two identical images of mountain landscapes, one on top of the other.');\n}\n
\nSets the color of a pixel or draws an image to the canvas.
\nset()
is easy to use but it's not as fast as\npixels. Use pixels\nto set many pixel values.
set()
interprets the first two parameters as x- and y-coordinates. It\ninterprets the last parameter as a grayscale value, a [R, G, B, A]
pixel\narray, a p5.Color object, or a\np5.Image object. If an image is passed, the first\ntwo parameters set the coordinates for the image's upper-left corner,\nregardless of the current imageMode().
updatePixels() must be called after using\nset()
for changes to appear.
x-coordinate of the pixel.
\n", "type": "Number" }, { "name": "y", "description": "y-coordinate of the pixel.
\n", "type": "Number" }, { "name": "c", "description": "grayscale value | pixel array |\n p5.Color object | p5.Image to copy.
\n", "type": "Number|Number[]|Object" } ], "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Set four pixels to black.\n set(30, 20, 0);\n set(85, 20, 0);\n set(85, 75, 0);\n set(30, 75, 0);\n\n // Update the canvas.\n updatePixels();\n\n describe('Four black dots arranged in a square drawn on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let black = color(0);\n\n // Set four pixels to black.\n set(30, 20, black);\n set(85, 20, black);\n set(85, 75, black);\n set(30, 75, black);\n\n // Update the canvas.\n updatePixels();\n\n describe('Four black dots arranged in a square drawn on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(255);\n\n // Draw a horizontal color gradient.\n for (let x = 0; x < 100; x += 1) {\n for (let y = 0; y < 100; y += 1) {\n // Calculate the grayscale value.\n let c = map(x, 0, 100, 0, 255);\n\n // Set the pixel using the grayscale value.\n set(x, y, c);\n }\n }\n\n // Update the canvas.\n updatePixels();\n\n describe('A horiztonal color gradient from black to white.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use the image to set all pixels.\n set(0, 0, img);\n\n // Update the canvas.\n updatePixels();\n\n describe('An image of a mountain landscape.');\n}\n
\nUpdates the canvas with the RGBA values in the\npixels array.
\nupdatePixels()
only needs to be called after changing values in the\npixels array. Such changes can be made directly\nafter calling loadPixels() or by calling\nset().
x-coordinate of the upper-left corner of region\n to update.
\n", "type": "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;\n\n// Load the image.\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0, 100, 100);\n\n // Get the pixel density.\n let d = pixelDensity();\n\n // Calculate the halfway index in the pixels array.\n let halfImage = 4 * (d * width) * (d * height / 2);\n\n // Load the pixels array.\n loadPixels();\n\n // Copy the top half of the canvas to the bottom.\n for (let i = 0; i < halfImage; i += 1) {\n pixels[i + halfImage] = pixels[i];\n }\n\n // Update the canvas.\n updatePixels();\n\n describe('Two identical images of mountain landscapes, one on top of the other.');\n}\n
\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 may 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": 794, "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": 802, "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": 816, "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": 883, "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": 891, "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": 905, "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": 976, "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": 1141, "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", "type": "{String[]}", "itemtype": "property", "name": "columns", "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", "type": "{p5.TableRow[]}", "itemtype": "property", "name": "rows", "class": "p5.Table", "module": "IO", "submodule": "Table" }, { "file": "src/io/p5.Table.js", "line": 90, "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 of a number.
\nA number's absolute value is its distance from zero on the number line.\n-5 and 5 are both five units away from zero, so calling abs(-5)
and\nabs(5)
both return 5. The absolute value of a number is always positive.
number to compute.
\n", "type": "Number" } ], "return": { "description": "absolute value of given number.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A gray square with a vertical black line that divides it in half. A white rectangle gets taller when the user moves the mouse away from the line.');\n}\n\nfunction draw() {\n background(200);\n\n // Divide the canvas.\n line(50, 0, 50, 100);\n\n // Calculate the mouse's distance from the middle.\n let h = abs(mouseX - 50);\n\n // Draw a rectangle based on the mouse's distance\n // from the middle.\n rect(0, 100 - h, 100, h);\n}\n
\nCalculates the closest integer value that is greater than or equal to a\nnumber.
\nFor example, calling ceil(9.03)
and ceil(9.97)
both return the value\n10.
number to round up.
\n", "type": "Number" } ], "return": { "description": "rounded up number.", "type": "Integer" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use RGB color with values from 0 to 1.\n colorMode(RGB, 1);\n\n noStroke();\n\n // Draw the left rectangle.\n let r = 0.3;\n fill(r, 0, 0);\n rect(0, 0, 50, 100);\n\n // Round r up to 1.\n r = ceil(r);\n\n // Draw the right rectangle.\n fill(r, 0, 0);\n rect(50, 0, 50, 100);\n\n describe('Two rectangles. The one on the left is dark red and the one on the right is bright red.');\n}\n
\nConstrains a number 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 setup() {\n createCanvas(100, 100);\n\n describe('A black dot drawn on a gray square follows the mouse from left to right. Its movement is constrained to the middle third of the square.');\n}\n\nfunction draw() {\n background(200);\n\n let x = constrain(mouseX, 33, 67);\n let y = 50;\n\n strokeWeight(5);\n point(x, y);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Two vertical lines. Two circles move horizontally with the mouse. One circle stops at the vertical lines.');\n}\n\nfunction draw() {\n background(200);\n\n // Set boundaries and draw them.\n let leftWall = 25;\n let rightWall = 75;\n line(leftWall, 0, leftWall, 100);\n line(rightWall, 0, rightWall, 100);\n\n // Draw a circle that follows the mouse freely.\n fill(255);\n circle(mouseX, 33, 9);\n\n // Draw a circle that's constrained.\n let xc = constrain(mouseX, leftWall, rightWall);\n fill(0);\n circle(xc, 67, 9);\n}\n
\nCalculates the distance between two points.
\nThe version of dist()
with four parameters calculates distance in two\ndimensions.
The version of dist()
with six parameters calculates distance in three\ndimensions.
Use p5.Vector.dist() to calculate the\ndistance between two p5.Vector objects.
\n", "itemtype": "method", "name": "dist", "return": { "description": "distance between the two points.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Set the coordinates.\n let x1 = 10;\n let y1 = 50;\n let x2 = 90;\n let y2 = 50;\n\n // Draw the points and a line connecting them.\n line(x1, y1, x2, y2);\n strokeWeight(5);\n point(x1, y1);\n point(x2, y2);\n\n // Calculate the distance.\n let d = dist(x1, y1, x2, y2);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the distance.\n text(d, 43, 40);\n\n describe('Two dots connected by a horizontal line. The number 80 is written above the center of the line.');\n}\n
\nx-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": 209, "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": 230, "description": "Calculates the value of Euler's number e (2.71828...) raised to the power\nof a number.
\n", "itemtype": "method", "name": "exp", "params": [ { "name": "n", "description": "exponent to raise.
\n", "type": "Number" } ], "return": { "description": "e^n", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Top-left.\n let d = exp(1);\n circle(10, 10, d);\n\n // Left-center.\n d = exp(2);\n circle(20, 20, d);\n\n // Right-center.\n d = exp(3);\n circle(40, 40, d);\n\n // Bottom-right.\n d = exp(4);\n circle(80, 80, d);\n\n describe('A series of circles that grow exponentially from top left to bottom right.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots that grow exponentially from left to right.');\n}\n\nfunction draw() {\n // Invert the y-axis.\n scale(1, -1);\n translate(0, -100);\n\n // Calculate the coordinates.\n let x = frameCount;\n let y = 0.005 * exp(x * 0.1);\n\n // Draw a point.\n point(x, y);\n}\n
\nCalculates the closest integer value that is less than or equal to the\nvalue of a number.
\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 setup() {\n createCanvas(100, 100);\n\n // Use RGB color with values from 0 to 1.\n colorMode(RGB, 1);\n\n noStroke();\n\n // Draw the left rectangle.\n let r = 0.8;\n fill(r, 0, 0);\n rect(0, 0, 50, 100);\n\n // Round r down to 0.\n r = floor(r);\n\n // Draw the right rectangle.\n fill(r, 0, 0);\n rect(50, 0, 50, 100);\n\n describe('Two rectangles. The one on the left is bright red and the one on the right is black.');\n}\n
\nCalculates a number between two numbers at a specific increment.
\nThe amt
parameter is the amount to interpolate between the two numbers.\n0.0 is equal to the first number, 0.1 is very near the first number, 0.5 is\nhalf-way in between, and 1.0 is equal to the second number. The lerp()
\nfunction is convenient for creating motion along a straight path and for\ndrawing dotted lines.
If the value of amt
is less than 0 or more than 1, lerp()
will return a\nnumber outside of the original interval. For example, calling\nlerp(0, 10, 1.5)
will return 15.
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 createCanvas(100, 100);\n\n background(200);\n\n // Declare variables for coordinates.\n let a = 20;\n let b = 80;\n let c = lerp(a, b, 0.2);\n let d = lerp(a, b, 0.5);\n let e = lerp(a, b, 0.8);\n\n strokeWeight(5);\n\n // Draw the original points in black.\n stroke(0);\n point(a, 50);\n point(b, 50);\n\n // Draw the lerped points in gray.\n stroke(100);\n point(c, 50);\n point(d, 50);\n point(e, 50);\n\n describe('Five points in a horizontal line. The outer points are black and the inner points are gray.');\n}\n
\n\nlet x = 50;\nlet y = 50;\nlet targetX = 50;\nlet targetY = 50;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A white circle at the center of a gray canvas. The circle moves to where the user clicks, then moves smoothly back to the center.');\n}\n\nfunction draw() {\n background(220);\n\n // Move x and y toward the target.\n x = lerp(x, targetX, 0.05);\n y = lerp(y, targetY, 0.05);\n\n // Draw the circle.\n circle(x, y, 20);\n}\n\n// Set x and y when the user clicks the mouse.\nfunction mouseClicked() {\n x = mouseX;\n y = mouseY;\n}\n
\nCalculates the natural logarithm (the base-e logarithm) of a number.
\nlog()
expects the n
parameter to be a value greater than 0 because\nthe natural logarithm is defined that way.
number greater than 0.
\n", "type": "Number" } ], "return": { "description": "natural logarithm of n.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Top-left.\n let d = log(50);\n circle(33, 33, d);\n\n // Bottom-right.\n d = log(500000000);\n circle(67, 67, d);\n\n describe('Two white circles. The circle at the top-left is small. The circle at the bottom-right is about five times larger.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots that get higher slowly from left to right.');\n}\n\nfunction draw() {\n // Invert the y-axis.\n scale(1, -1);\n translate(0, -100);\n\n // Calculate coordinates.\n let x = frameCount;\n let y = 15 * log(x);\n\n // Draw a point.\n point(x, y);\n}\n
\nCalculates the magnitude, or length, of a vector.
\nA vector can be thought of in different ways. In one view, a vector is a\npoint in space. The vector's components, x
and y
, are the point's\ncoordinates (x, y)
. A vector's magnitude is the distance from the origin\n(0, 0)
to (x, y)
. mag(x, y)
is a shortcut for calling\ndist(0, 0, x, y)
.
A vector can also be thought of as an arrow pointing in space. This view is\nhelpful for programming motion. See p5.Vector for\nmore details.
\nUse p5.Vector.mag() to calculate the\nmagnitude of a p5.Vector object.
\n", "itemtype": "method", "name": "mag", "params": [ { "name": "x", "description": "first component.
\n", "type": "Number" }, { "name": "y", "description": "second component.
\n", "type": "Number" } ], "return": { "description": "magnitude of vector.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Set the vector's components.\n let x = 30;\n let y = 40;\n\n // Calculate the magnitude.\n let m = mag(x, y);\n\n // Style the text.\n textSize(16);\n\n // Display the vector and its magnitude.\n line(0, 0, x, y);\n text(m, x, y);\n\n describe('A diagonal line is drawn from the top left of the canvas. The number 50 is written at the end of the line.');\n}\n
\nRe-maps a number from one range to another.
\nFor example, calling map(2, 0, 10, 0, 100)
returns 20. The first three\narguments set the original value to 2 and the original range from 0 to 10.\nThe last two arguments set the target range from 0 to 100. 20's position\nin the target range [0, 100] is proportional to 2's position in the\noriginal range [0, 10].
The sixth parameter, withinBounds
, is optional. By default, map()
can\nreturn values outside of the target range. For example,\nmap(11, 0, 10, 0, 100)
returns 110. Passing true
as the sixth parameter\nconstrains the remapped value to the target range. For example,\nmap(11, 0, 10, 0, 100, true)
returns 100.
the value to be remapped.
\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\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Two horizontal lines. The top line grows horizontally as the mouse moves to the right. The bottom line also grows horizontally but is scaled to stay on the left half of the canvas.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw the top line.\n line(0, 25, mouseX, 25);\n\n // Remap mouseX from [0, 100] to [0, 50].\n let x = map(mouseX, 0, 100, 0, 50);\n\n // Draw the bottom line.\n line(0, 75, 0, x);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A circle changes color from black to white as the mouse moves from left to right.');\n}\n\nfunction draw() {\n background(200);\n\n // Remap mouseX from [0, 100] to [0, 255]\n let c = map(mouseX, 0, 100, 0, 255);\n\n // Style the circle.\n fill(c);\n\n // Draw the circle.\n circle(50, 50, 20);\n}\n
\nReturns the largest value in a sequence of numbers.
\nThe version of max()
with one parameter interprets it as an array of\nnumbers and returns the largest number.
The version of max()
with two or more parameters interprets them as\nindividual numbers and returns the largest number.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate the maximum of 10, 5, and 20.\n let m = max(10, 5, 20);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the max.\n text(m, 50, 50);\n\n describe('The number 20 written in the middle of a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of numbers.\n let numbers = [10, 5, 20];\n\n // Calculate the maximum of the array.\n let m = max(numbers);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the max.\n text(m, 50, 50);\n\n describe('The number 20 written in the middle of a gray square.');\n}\n
\nfirst number to compare.
\n", "type": "Number" }, { "name": "n1", "description": "second number to compare.
\n", "type": "Number" } ], "return": { "description": "maximum number.", "type": "Number" } }, { "line": 680, "params": [ { "name": "nums", "description": "numbers to compare.
\n", "type": "Number[]" } ], "return": { "description": "", "type": "Number" } } ] }, { "file": "src/math/calculation.js", "line": 695, "description": "Returns the smallest value in a sequence of numbers.
\nThe version of min()
with one parameter interprets it as an array of\nnumbers and returns the smallest number.
The version of min()
with two or more parameters interprets them as\nindividual numbers and returns the smallest number.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate the minimum of 10, 5, and 20.\n let m = min(10, 5, 20);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the min.\n text(m, 50, 50);\n\n describe('The number 5 written in the middle of a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of numbers.\n let numbers = [10, 5, 20];\n\n // Calculate the minimum of the array.\n let m = min(numbers);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the min.\n text(m, 50, 50);\n\n describe('The number 5 written in the middle of a gray square.');\n}\n
\nfirst number to compare.
\n", "type": "Number" }, { "name": "n1", "description": "second number to compare.
\n", "type": "Number" } ], "return": { "description": "minimum number.", "type": "Number" } }, { "line": 757, "params": [ { "name": "nums", "description": "numbers to compare.
\n", "type": "Number[]" } ], "return": { "description": "", "type": "Number" } } ] }, { "file": "src/math/calculation.js", "line": 772, "description": "Maps a number from one range to a value between 0 and 1.
\nFor example, norm(2, 0, 10)
returns 0.2. 2's position in the original\nrange [0, 10] is proportional to 0.2's position in the range [0, 1]. This\nis the same as calling map(2, 0, 10, 0, 1)
.
Numbers outside of the original range are not constrained between 0 and 1.\nOut-of-range values are often intentional and useful.
\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 setup() {\n createCanvas(100, 100);\n\n // Use RGB color with values from 0 to 1.\n colorMode(RGB, 1);\n\n describe('A square changes color from black to red as the mouse moves from left to right.');\n}\n\nfunction draw() {\n // Calculate the redValue.\n let redValue = norm(mouseX, 0, 100);\n\n // Paint the background.\n background(redValue, 0, 0);\n}\n
\nCalculates exponential expressions such as 23.
\nFor example, pow(2, 3)
evaluates the expression\n2 × 2 × 2. pow(2, -3)
evaluates 1 ÷\n(2 × 2 × 2).
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 createCanvas(100, 100);\n\n background(200);\n\n // Set the base of the exponent.\n let base = 3;\n\n // Top-left.\n let d = pow(base, 1);\n circle(10, 10, d);\n\n // Left-center.\n d = pow(base, 2);\n circle(20, 20, d);\n\n // Right-center.\n d = pow(base, 3);\n circle(40, 40, d);\n\n // Bottom-right.\n d = pow(base, 4);\n circle(80, 80, d);\n\n describe('A series of circles that grow exponentially from top left to bottom right.');\n}\n
\nCalculates the integer closest to a number.
\nFor example, round(133.8)
returns the value 134.
The second parameter, decimals
, is optional. It sets the number of\ndecimal places to use when rounding. For example, round(12.34, 1)
returns\n12.3. decimals
is 0 by default.
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\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Round a number.\n let x = round(4.2);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the rounded number.\n text(x, 50, 50);\n\n describe('The number 4 written in middle of the canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Round a number to 2 decimal places.\n let x = round(12.782383, 2);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the rounded number.\n text(x, 50, 50);\n\n describe('The number 12.78 written in middle of canvas.');\n}\n
\nCalculates the square of a number.
\nSquaring a number means multiplying the number by itself. For example,\nsq(3)
evaluates 3 × 3 which is 9. sq(-3)
evaluates -3 × -3\nwhich is also 9. Multiplying two negative numbers produces a positive\nnumber. The value returned by sq()
is always positive.
number to square.
\n", "type": "Number" } ], "return": { "description": "squared number.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Top-left.\n let d = sq(3);\n circle(33, 33, d);\n\n // Bottom-right.\n d = sq(6);\n circle(67, 67, d);\n\n describe('Two white circles. The circle at the top-left is small. The circle at the bottom-right is four times larger.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots that get higher quickly from left to right.');\n}\n\nfunction draw() {\n // Invert the y-axis.\n scale(1, -1);\n translate(0, -100);\n\n // Calculate the coordinates.\n let x = frameCount;\n let y = 0.01 * sq(x);\n\n // Draw the point.\n point(x, y);\n}\n
\nCalculates the square root of a number.
\nA number's square root can be multiplied by itself to produce the original\nnumber. For example, sqrt(9)
returns 3 because 3 × 3 = 9. sqrt()
\nalways returns a positive value. sqrt()
doesn't work with negative arguments\nsuch as sqrt(-9)
.
non-negative number to square root.
\n", "type": "Number" } ], "return": { "description": "square root of number.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Top-left.\n let d = sqrt(16);\n circle(33, 33, d);\n\n // Bottom-right.\n d = sqrt(1600);\n circle(67, 67, d);\n\n describe('Two white circles. The circle at the top-left is small. The circle at the bottom-right is ten times larger.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots that get higher slowly from left to right.');\n}\n\nfunction draw() {\n // Invert the y-axis.\n scale(1, -1);\n translate(0, -100);\n\n // Calculate the coordinates.\n let x = frameCount;\n let y = 5 * sqrt(x);\n\n // Draw the point.\n point(x, y);\n}\n
\nCalculates the fractional part of a number.
\nA number's fractional part includes its decimal values. For example,\nfract(12.34)
returns 0.34.
number whose fractional part will be found.
\n", "type": "Number" } ], "return": { "description": "fractional part of n.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Original number.\n let n = 56.78;\n text(n, 50, 33);\n\n // Fractional part.\n let f = fract(n);\n text(f, 50, 67);\n\n describe('The number 56.78 written above the number 0.78.');\n}\n
\nCreates a new p5.Vector object.
\nA vector can be thought of in different ways. In one view, a vector is like\nan arrow pointing in space. Vectors have both magnitude (length) and\ndirection. This view is helpful for programming motion.
\nA vector's components determine its magnitude and direction. For example,\ncalling createVector(3, 4)
creates a new\np5.Vector object with an x-component of 3 and a\ny-component of 4. From the origin, this vector's tip is 3 units to the\nright and 4 units down.
p5.Vector objects are often used to program\nmotion because they simplify the math. For example, a moving ball has a\nposition and a velocity. Position describes where the ball is in space. The\nball's position vector extends from the origin to the ball's center.\nVelocity describes the ball's speed and the direction it's moving. If the\nball is moving straight up, its velocity vector points straight up. Adding\nthe ball's velocity vector to its position vector moves it, as in\npos.add(vel)
. Vector math relies on methods inside the\np5.Vector class.
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": "new p5.Vector object.", "type": "p5.Vector" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create p5.Vector objects.\n let p1 = createVector(25, 25);\n let p2 = createVector(50, 50);\n let p3 = createVector(75, 75);\n\n // Draw the dots.\n strokeWeight(5);\n point(p1);\n point(p2);\n point(p3);\n\n describe('Three black dots form a diagonal line from top left to bottom right.');\n}\n
\n\nlet pos;\nlet vel;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create p5.Vector objects.\n pos = createVector(50, 100);\n vel = createVector(0, -1);\n\n describe('A black dot moves from bottom to top on a gray square. The dot reappears at the bottom when it reaches the top.');\n}\n\nfunction draw() {\n background(200);\n\n // Add velocity to position.\n pos.add(vel);\n\n // If the dot reaches the top of the canvas,\n // restart from the bottom.\n if (pos.y < 0) {\n pos.y = 100;\n }\n\n // Draw the dot.\n strokeWeight(5);\n point(pos);\n}\n
\nReturns random numbers that can be tuned to feel organic.
\nValues returned by random() and\nrandomGaussian() can change by large\namounts between function calls. By contrast, values returned by noise()
\ncan be made \"smooth\". Calls to noise()
with similar inputs will produce\nsimilar outputs. noise()
is used to create textures, motion, shapes,\nterrains, and so on. Ken Perlin invented noise()
while animating the\noriginal Tron film in the 1980s.
noise()
always returns values between 0 and 1. It returns the same value\nfor a given input while a sketch is running. noise()
produces different\nresults each time a sketch runs. The\nnoiseSeed() function can be used to generate\nthe same sequence of Perlin noise values each time a sketch runs.
The character of the noise can be adjusted in two ways. The first way is to\nscale the inputs. noise()
interprets inputs as coordinates. The sequence\nof noise values will be smoother when the input coordinates are closer. The\nsecond way is to use the noiseDetail()\nfunction.
The version of noise()
with one parameter computes noise values in one\ndimension. This dimension can be thought of as space, as in noise(x)
, or\ntime, as in noise(t)
.
The version of noise()
with two parameters computes noise values in two\ndimensions. These dimensions can be thought of as space, as in\nnoise(x, y)
, or space and time, as in noise(x, t)
.
The version of noise()
with three parameters computes noise values in\nthree dimensions. These dimensions can be thought of as space, as in\nnoise(x, y, z)
, or space and time, as in noise(x, y, t)
.
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 at specified coordinates.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A black dot moves randomly on a gray square.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the coordinates.\n let x = 100 * noise(0.005 * frameCount);\n let y = 100 * noise(0.005 * frameCount + 10000);\n\n // Draw the point.\n strokeWeight(5);\n point(x, y);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A black dot moves randomly on a gray square.');\n}\n\nfunction draw() {\n background(200);\n\n // Set the noise level and scale.\n let noiseLevel = 100;\n let noiseScale = 0.005;\n\n // Scale the input coordinate.\n let nt = noiseScale * frameCount;\n\n // Compute the noise values.\n let x = noiseLevel * noise(nt);\n let y = noiseLevel * noise(nt + 10000);\n\n // Draw the point.\n strokeWeight(5);\n point(x, y);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A hilly terrain drawn in gray against a black sky.');\n}\n\nfunction draw() {\n // Set the noise level and scale.\n let noiseLevel = 100;\n let noiseScale = 0.02;\n\n // Scale the input coordinate.\n let x = frameCount;\n let nx = noiseScale * x;\n\n // Compute the noise value.\n let y = noiseLevel * noise(nx);\n\n // Draw the line.\n line(x, 0, x, y);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A calm sea drawn in gray against a black sky.');\n}\n\nfunction draw() {\n background(200);\n\n // Set the noise level and scale.\n let noiseLevel = 100;\n let noiseScale = 0.002;\n\n // Iterate from left to right.\n for (let x = 0; x < 100; x += 1) {\n // Scale the input coordinates.\n let nx = noiseScale * x;\n let nt = noiseScale * frameCount;\n\n // Compute the noise value.\n let y = noiseLevel * noise(nx, nt);\n\n // Draw the line.\n line(x, 0, x, y);\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Set the noise level and scale.\n let noiseLevel = 255;\n let noiseScale = 0.01;\n\n // Iterate from top to bottom.\n for (let y = 0; y < 100; y += 1) {\n // Iterate from left to right.\n for (let x = 0; x < 100; x += 1) {\n // Scale the input coordinates.\n let nx = noiseScale * x;\n let ny = noiseScale * y;\n\n // Compute the noise value.\n let c = noiseLevel * noise(nx, ny);\n\n // Draw the point.\n stroke(c);\n point(x, y);\n }\n }\n\n describe('A gray cloudy pattern.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A gray cloudy pattern that changes.');\n}\n\nfunction draw() {\n // Set the noise level and scale.\n let noiseLevel = 255;\n let noiseScale = 0.009;\n\n // Iterate from top to bottom.\n for (let y = 0; y < 100; y += 1) {\n // Iterate from left to right.\n for (let x = 0; x < width; x += 1) {\n // Scale the input coordinates.\n let nx = noiseScale * x;\n let ny = noiseScale * y;\n let nt = noiseScale * frameCount;\n\n // Compute the noise value.\n let c = noiseLevel * noise(nx, ny, nt);\n\n // Draw the point.\n stroke(c);\n point(x, y);\n }\n }\n}\n
\nAdjusts the character of the noise produced by the\nnoise() function.
\nPerlin noise values are created by adding layers of noise together. The\nnoise layers, called octaves, are similar to harmonics in music. Lower\noctaves contribute more to the output signal. They define the overall\nintensity of the noise. Higher octaves create finer-grained details.
\nBy default, noise values are created by combining four octaves. Each higher\noctave contributes half as much (50% less) compared to its predecessor.\nnoiseDetail()
changes the number of octaves and the falloff amount. For\nexample, calling noiseDetail(6, 0.25)
ensures that\nnoise() will use six octaves. Each higher octave\nwill contribute 25% as much (75% less) compared to its predecessor. Falloff\nvalues between 0 and 1 are valid. However, falloff values greater than 0.5\nmight result in noise values greater than 1.
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\nfunction setup() {\n createCanvas(100, 100);\n\n // Set the noise level and scale.\n let noiseLevel = 255;\n let noiseScale = 0.02;\n\n // Iterate from top to bottom.\n for (let y = 0; y < 100; y += 1) {\n // Iterate from left to right.\n for (let x = 0; x < 50; x += 1) {\n // Scale the input coordinates.\n let nx = noiseScale * x;\n let ny = noiseScale * y;\n\n // Compute the noise value with six octaves\n // and a low falloff factor.\n noiseDetail(6, 0.25);\n let c = noiseLevel * noise(nx, ny);\n\n // Draw the left side.\n stroke(c);\n point(x, y);\n\n // Compute the noise value with four octaves\n // and a high falloff factor.\n noiseDetail(4, 0.5);\n c = noiseLevel * noise(nx, ny);\n\n // Draw the right side.\n stroke(c);\n point(x + 50, y);\n }\n }\n\n describe('Two gray cloudy patterns. The pattern on the right is cloudier than the pattern on the left.');\n}\n
\nSets the seed value for the noise() function.
\nBy default, noise() produces different results\neach time a sketch is run. Calling noiseSeed()
with a constant argument,\nsuch as noiseSeed(99)
, makes noise() produce the\nsame results each time a sketch is run.
seed value.
\n", "type": "Number" } ], "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Set the noise seed for consistent results.\n noiseSeed(99);\n\n describe('A black rectangle that grows randomly, first to the right and then to the left.');\n}\n\nfunction draw() {\n // Set the noise level and scale.\n let noiseLevel = 100;\n let noiseScale = 0.005;\n\n // Scale the input coordinate.\n let nt = noiseScale * frameCount;\n\n // Compute the noise value.\n let x = noiseLevel * noise(nt);\n\n // Draw the line.\n line(x, 0, x, height);\n}\n
\nThe x component of the vector
\n", "type": "{Number}", "itemtype": "property", "name": "x", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 120, "description": "The y component of the vector
\n", "type": "{Number}", "itemtype": "property", "name": "y", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 127, "description": "The z component of the vector
\n", "type": "{Number}", "itemtype": "property", "name": "z", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 136, "description": "Returns a string representation of a vector.
\nCalling toString()
is useful for printing vectors to the console while\ndebugging.
\nfunction setup() {\n let v = createVector(20, 30);\n\n // Prints 'p5.Vector Object : [20, 30, 0]'.\n print(v.toString());\n}\n
\nSets the vector's x
, y
, and z
components.
set()
can use separate numbers, as in v.set(1, 2, 3)
, a\np5.Vector object, as in v.set(v2)
, or an\narray of numbers, as in v.set([1, 2, 3])
.
If a value isn't provided for a component, it will be set to 0. For\nexample, v.set(4, 5)
sets v.x
to 4, v.y
to 5, and v.z
to 0.\nCalling set()
with no arguments, as in v.set()
, sets all the vector's\ncomponents to 0.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Top left.\n let pos = createVector(25, 25);\n point(pos);\n\n // Top right.\n // set() with numbers.\n pos.set(75, 25);\n point(pos);\n\n // Bottom right.\n // set() with a p5.Vector.\n let p2 = createVector(75, 75);\n pos.set(p2);\n point(pos);\n\n // Bottom left.\n // set() with an array.\n let arr = [25, 75];\n pos.set(arr);\n point(pos);\n\n describe('Four black dots arranged in a square on a gray background.');\n}\n
\nx 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 } ], "chainable": 1 }, { "line": 215, "params": [ { "name": "value", "description": "vector to set.
\n", "type": "p5.Vector|Number[]" } ], "chainable": 1 } ] }, { "file": "src/math/p5.Vector.js", "line": 239, "description": "Returns a copy of the p5.Vector object.
\n", "itemtype": "method", "name": "copy", "return": { "description": "copy of the p5.Vector object.", "type": "p5.Vector" }, "example": [ "\n\nfunction setup() {\n createCanvas(100 ,100);\n\n background(200);\n\n // Create a p5.Vector object.\n let pos = createVector(50, 50);\n\n // Make a copy.\n let pc = pos.copy();\n\n // Draw the point.\n strokeWeight(5);\n point(pc);\n\n describe('A black point drawn in the middle of a gray square.');\n}\n
\nthe p5.Vector to create a copy of
\n", "type": "p5.Vector" } ], "static": 1, "return": { "description": "the copy of the p5.Vector object", "type": "p5.Vector" } } ] }, { "file": "src/math/p5.Vector.js", "line": 282, "description": "Adds to a vector's x
, y
, and z
components.
add()
can use separate numbers, as in v.add(1, 2, 3)
,\nanother p5.Vector object, as in v.add(v2)
, or\nan array of numbers, as in v.add([1, 2, 3])
.
If a value isn't provided for a component, it won't change. For\nexample, v.add(4, 5)
adds 4 to v.x
, 5 to v.y
, and 0 to v.z
.\nCalling add()
with no arguments, as in v.add()
, has no effect.
The static version of add()
, as in p5.Vector.add(v2, v1)
, returns a new\np5.Vector object and doesn't change the\noriginals.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Top left.\n let pos = createVector(25, 25);\n point(pos);\n\n // Top right.\n // Add numbers.\n pos.add(50, 0);\n point(pos);\n\n // Bottom right.\n // Add a p5.Vector.\n let p2 = createVector(0, 50);\n pos.add(p2);\n point(pos);\n\n // Bottom left.\n // Add an array.\n let arr = [-50, 0];\n pos.add(arr);\n point(pos);\n\n describe('Four black dots arranged in a square on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Top left.\n let p1 = createVector(25, 25);\n\n // Center.\n let p2 = createVector(50, 50);\n\n // Bottom right.\n // Add p1 and p2.\n let p3 = p5.Vector.add(p1, p2);\n\n // Draw the points.\n strokeWeight(5);\n point(p1);\n point(p2);\n point(p3);\n\n describe('Three black dots in a diagonal line from top left to bottom right.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Three arrows drawn on a gray square. A red arrow extends from the top left corner to the center. A blue arrow extends from the tip of the red arrow. A purple arrow extends from the origin to the tip of the blue arrow.');\n}\n\nfunction draw() {\n background(200);\n\n let origin = createVector(0, 0);\n\n // Draw the red arrow.\n let v1 = createVector(50, 50);\n drawArrow(origin, v1, 'red');\n\n // Draw the blue arrow.\n let v2 = createVector(-30, 20);\n drawArrow(v1, v2, 'blue');\n\n // Purple arrow.\n let v3 = p5.Vector.add(v1, v2);\n drawArrow(origin, v3, 'purple');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nx component of the vector to be added.
\n", "type": "Number" }, { "name": "y", "description": "y component of the vector to be added.
\n", "type": "Number", "optional": true }, { "name": "z", "description": "z component of the vector to be added.
\n", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 411, "params": [ { "name": "value", "description": "The vector to add
\n", "type": "p5.Vector|Number[]" } ], "chainable": 1 }, { "line": 3363, "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": "vector to receive the result.
\n", "type": "p5.Vector", "optional": true } ], "static": 1, "return": { "description": "resulting p5.Vector.", "type": "p5.Vector" } } ] }, { "file": "src/math/p5.Vector.js", "line": 466, "description": "Performs modulo (remainder) division with a vector's x
, y
, and z
\ncomponents.
rem()
can use separate numbers, as in v.rem(1, 2, 3)
,\nanother p5.Vector object, as in v.rem(v2)
, or\nan array of numbers, as in v.rem([1, 2, 3])
.
If only one value is provided, as in v.rem(2)
, then all the components\nwill be set to their values modulo 2. If two values are provided, as in\nv.rem(2, 3)
, then v.z
won't change. Calling rem()
with no\narguments, as in v.rem()
, has no effect.
The static version of rem()
, as in p5.Vector.rem(v2, v1)
, returns a\nnew p5.Vector object and doesn't change the\noriginals.
\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(3, 4, 5);\n\n // Divide numbers.\n v.rem(2);\n\n // Prints 'p5.Vector Object : [1, 0, 1]'.\n print(v.toString());\n}\n
\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(3, 4, 5);\n\n // Divide numbers.\n v.rem(2, 3);\n\n // Prints 'p5.Vector Object : [1, 1, 5]'.\n print(v.toString());\n}\n
\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(3, 4, 5);\n\n // Divide numbers.\n v.rem(2, 3, 4);\n\n // Prints 'p5.Vector Object : [1, 1, 1]'.\n print(v.toString());\n}\n
\n\nfunction setup() {\n // Create p5.Vector objects.\n let v1 = createVector(3, 4, 5);\n let v2 = createVector(2, 3, 4);\n\n // Divide a p5.Vector.\n v1.rem(v2);\n\n // Prints 'p5.Vector Object : [1, 1, 1]'.\n print(v1.toString());\n}\n
\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(3, 4, 5);\n\n // Divide an array.\n let arr = [2, 3, 4];\n v.rem(arr);\n\n // Prints 'p5.Vector Object : [1, 1, 1]'.\n print(v.toString());\n}\n
\n\nfunction setup() {\n // Create p5.Vector objects.\n let v1 = createVector(3, 4, 5);\n let v2 = createVector(2, 3, 4);\n\n // Divide without modifying the original vectors.\n let v3 = p5.Vector.rem(v1, v2);\n\n // Prints 'p5.Vector Object : [1, 1, 1]'.\n print(v3.toString());\n}\n
\nx component of divisor vector.
\n", "type": "Number" }, { "name": "y", "description": "y component of divisor vector.
\n", "type": "Number" }, { "name": "z", "description": "z component of divisor vector.
\n", "type": "Number" } ], "chainable": 1 }, { "line": 583, "params": [ { "name": "value", "description": "divisor vector.
\n", "type": "p5.Vector | Number[]" } ], "chainable": 1 }, { "line": 3389, "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": 3395, "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": 640, "description": "Subtracts from a vector's x
, y
, and z
components.
sub()
can use separate numbers, as in v.sub(1, 2, 3)
, another\np5.Vector object, as in v.sub(v2)
, or an array\nof numbers, as in v.sub([1, 2, 3])
.
If a value isn't provided for a component, it won't change. For\nexample, v.sub(4, 5)
adds 4 to v.x
, 5 to v.y
, and 0 to v.z
.\nCalling sub()
with no arguments, as in v.sub()
, has no effect.
The static version of sub()
, as in p5.Vector.sub(v2, v1)
, returns a new\np5.Vector object and doesn't change the\noriginals.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Bottom right.\n let pos = createVector(75, 75);\n point(pos);\n\n // Top right.\n // Subtract numbers.\n pos.sub(0, 50);\n point(pos);\n\n // Top left.\n // Subtract a p5.Vector.\n let p2 = createVector(50, 0);\n pos.sub(p2);\n point(pos);\n\n // Bottom left.\n // Subtract an array.\n let arr = [0, -50];\n pos.sub(arr);\n point(pos);\n\n describe('Four black dots arranged in a square on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create p5.Vector objects.\n let p1 = createVector(75, 75);\n let p2 = createVector(50, 50);\n\n // Subtract with modifying the original vectors.\n let p3 = p5.Vector.sub(p1, p2);\n\n // Draw the points.\n strokeWeight(5);\n point(p1);\n point(p2);\n point(p3);\n\n describe('Three black dots in a diagonal line from top left to bottom right.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Three arrows drawn on a gray square. A red and a blue arrow extend from the top left. A purple arrow extends from the tip of the red arrow to the tip of the blue arrow.');\n}\n\nfunction draw() {\n background(200);\n\n let origin = createVector(0, 0);\n\n // Draw the red arrow.\n let v1 = createVector(50, 50);\n drawArrow(origin, v1, 'red');\n\n // Draw the blue arrow.\n let v2 = createVector(20, 70);\n drawArrow(origin, v2, 'blue');\n\n // Purple arrow.\n let v3 = p5.Vector.sub(v2, v1);\n drawArrow(v1, v3, 'purple');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nx component of the vector to subtract.
\n", "type": "Number" }, { "name": "y", "description": "y component of the vector to subtract.
\n", "type": "Number", "optional": true }, { "name": "z", "description": "z component of the vector to subtract.
\n", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 766, "params": [ { "name": "value", "description": "the vector to subtract
\n", "type": "p5.Vector|Number[]" } ], "chainable": 1 }, { "line": 3414, "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": "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": 790, "description": "Multiplies a vector's x
, y
, and z
components.
mult()
can use separate numbers, as in v.mult(1, 2, 3)
, another\np5.Vector object, as in v.mult(v2)
, or an array\nof numbers, as in v.mult([1, 2, 3])
.
If only one value is provided, as in v.mult(2)
, then all the components\nwill be multiplied by 2. If a value isn't provided for a component, it\nwon't change. For example, v.mult(4, 5)
multiplies v.x
by, v.y
by 5,\nand v.z
by 1. Calling mult()
with no arguments, as in v.mult()
, has\nno effect.
The static version of mult()
, as in p5.Vector.mult(v, 2)
, returns a new\np5.Vector object and doesn't change the\noriginals.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Top-left.\n let p = createVector(25, 25);\n point(p);\n\n // Center.\n // Multiply all components by 2.\n p.mult(2);\n point(p);\n\n describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the center.');\n}\n
\n\nfunction setup() {\n strokeWeight(5);\n\n // Top-left.\n let p = createVector(25, 25);\n point(p);\n\n // Bottom-right.\n // Multiply p.x * 2 and p.y * 3\n p.mult(2, 3);\n point(p);\n\n describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Top-left.\n let p = createVector(25, 25);\n point(p);\n\n // Bottom-right.\n // Multiply p.x * 2 and p.y * 3\n let arr = [2, 3];\n p.mult(arr);\n point(p);\n\n describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Top-left.\n let p = createVector(25, 25);\n point(p);\n\n // Bottom-right.\n // Multiply p.x * p2.x and p.y * p2.y\n let p2 = createVector(2, 3);\n p.mult(p2);\n point(p);\n\n describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Top-left.\n let p = createVector(25, 25);\n point(p);\n\n // Bottom-right.\n // Create a new p5.Vector with\n // p3.x = p.x * p2.x\n // p3.y = p.y * p2.y\n let p2 = createVector(2, 3);\n let p3 = p5.Vector.mult(p, p2);\n point(p3);\n\n describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Two arrows extending from the top left corner. The blue arrow is twice the length of the red arrow.');\n}\nfunction draw() {\n background(200);\n\n let origin = createVector(0, 0);\n\n // Draw the red arrow.\n let v1 = createVector(25, 25);\n drawArrow(origin, v1, 'red');\n\n // Draw the blue arrow.\n let v2 = p5.Vector.mult(v1, 2);\n drawArrow(origin, v2, 'blue');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nThe number to multiply with the vector
\n", "type": "Number" } ], "chainable": 1 }, { "line": 970, "params": [ { "name": "x", "description": "number to multiply with the x component of the vector.
\n", "type": "Number" }, { "name": "y", "description": "number to multiply with the y component of the vector.
\n", "type": "Number" }, { "name": "z", "description": "number to multiply with the z component of the vector.
\n", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 978, "params": [ { "name": "arr", "description": "array to multiply with the components of the vector.
\n", "type": "Number[]" } ], "chainable": 1 }, { "line": 984, "params": [ { "name": "v", "description": "vector to multiply with the components of the original vector.
\n", "type": "p5.Vector" } ], "chainable": 1 }, { "line": 3443, "params": [ { "name": "x", "description": "", "type": "Number" }, { "name": "y", "description": "", "type": "Number" }, { "name": "z", "description": "", "type": "Number", "optional": true } ], "static": 1, "return": { "description": "resulting new p5.Vector.", "type": "p5.Vector" } }, { "line": 3452, "params": [ { "name": "v", "description": "", "type": "p5.Vector" }, { "name": "n", "description": "", "type": "Number" }, { "name": "target", "description": "vector to receive the result.
\n", "type": "p5.Vector", "optional": true } ], "static": 1 }, { "line": 3460, "params": [ { "name": "v0", "description": "", "type": "p5.Vector" }, { "name": "v1", "description": "", "type": "p5.Vector" }, { "name": "target", "description": "", "type": "p5.Vector", "optional": true } ], "static": 1 }, { "line": 3468, "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": 1069, "description": "Divides a vector's x
, y
, and z
components.
div()
can use separate numbers, as in v.div(1, 2, 3)
, another\np5.Vector object, as in v.div(v2)
, or an array\nof numbers, as in v.div([1, 2, 3])
.
If only one value is provided, as in v.div(2)
, then all the components\nwill be divided by 2. If a value isn't provided for a component, it\nwon't change. For example, v.div(4, 5)
divides v.x
by, v.y
by 5,\nand v.z
by 1. Calling div()
with no arguments, as in v.div()
, has\nno effect.
The static version of div()
, as in p5.Vector.div(v, 2)
, returns a new\np5.Vector object and doesn't change the\noriginals.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Center.\n let p = createVector(50, 50);\n point(p);\n\n // Top-left.\n // Divide p.x / 2 and p.y / 2\n p.div(2);\n point(p);\n\n describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the center.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Bottom-right.\n let p = createVector(50, 75);\n point(p);\n\n // Top-left.\n // Divide p.x / 2 and p.y / 3\n p.div(2, 3);\n point(p);\n\n describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Bottom-right.\n let p = createVector(50, 75);\n point(p);\n\n // Top-left.\n // Divide p.x / 2 and p.y / 3\n let arr = [2, 3];\n p.div(arr);\n point(p);\n\n describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Bottom-right.\n let p = createVector(50, 75);\n point(p);\n\n // Top-left.\n // Divide p.x / 2 and p.y / 3\n let p2 = createVector(2, 3);\n p.div(p2);\n point(p);\n\n describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the points.\n strokeWeight(5);\n\n // Bottom-right.\n let p = createVector(50, 75);\n point(p);\n\n // Top-left.\n // Create a new p5.Vector with\n // p3.x = p.x / p2.x\n // p3.y = p.y / p2.y\n let p2 = createVector(2, 3);\n let p3 = p5.Vector.div(p, p2);\n point(p3);\n\n describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.');\n}\n
\n\nfunction draw() {\n background(200);\n\n let origin = createVector(0, 0);\n\n // Draw the red arrow.\n let v1 = createVector(50, 50);\n drawArrow(origin, v1, 'red');\n\n // Draw the blue arrow.\n let v2 = p5.Vector.div(v1, 2);\n drawArrow(origin, v2, 'blue');\n\n describe('Two arrows extending from the top left corner. The blue arrow is half the length of the red arrow.');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nThe number to divide the vector by
\n", "type": "Number" } ], "chainable": 1 }, { "line": 1251, "params": [ { "name": "x", "description": "number to divide with the x component of the vector.
\n", "type": "Number" }, { "name": "y", "description": "number to divide with the y component of the vector.
\n", "type": "Number" }, { "name": "z", "description": "number to divide with the z component of the vector.
\n", "type": "Number", "optional": true } ], "chainable": 1 }, { "line": 1259, "params": [ { "name": "arr", "description": "array to divide the components of the vector by.
\n", "type": "Number[]" } ], "chainable": 1 }, { "line": 1265, "params": [ { "name": "v", "description": "vector to divide the components of the original vector by.
\n", "type": "p5.Vector" } ], "chainable": 1 }, { "line": 3522, "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": 3531, "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": 3539, "params": [ { "name": "v0", "description": "", "type": "p5.Vector" }, { "name": "v1", "description": "", "type": "p5.Vector" }, { "name": "target", "description": "", "type": "p5.Vector", "optional": true } ], "static": 1 }, { "line": 3547, "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": 1366, "description": "Calculates the magnitude (length) of the vector.
\nUse mag() to calculate the magnitude of a 2D vector\nusing components as in mag(x, y)
.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Vector object.\n let p = createVector(30, 40);\n\n // Draw a line from the origin.\n line(0, 0, p.x, p.y);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the vector's magnitude.\n let m = p.mag();\n text(m, p.x, p.y);\n\n describe('A diagonal black line extends from the top left corner of a gray square. The number 50 is written at the end of the line.');\n}\n
\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": 1406, "description": "Calculates the magnitude (length) of the vector squared.
\n", "itemtype": "method", "name": "magSq", "return": { "description": "squared magnitude of the vector.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Vector object.\n let p = createVector(30, 40);\n\n // Draw a line from the origin.\n line(0, 0, p.x, p.y);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the vector's magnitude squared.\n let m = p.magSq();\n text(m, p.x, p.y);\n\n describe('A diagonal black line extends from the top left corner of a gray square. The number 2500 is written at the end of the line.');\n}\n
\nthe vector to return the squared magnitude of
\n", "type": "p5.Vector" } ], "static": 1, "return": { "description": "the squared magnitude of vecT", "type": "Number" } } ] }, { "file": "src/math/p5.Vector.js", "line": 1445, "description": "Calculates the dot product of two vectors.
\nThe dot product is a number that describes the overlap between two vectors.\nVisually, the dot product can be thought of as the \"shadow\" one vector\ncasts on another. The dot product's magnitude is largest when two vectors\npoint in the same or opposite directions. Its magnitude is 0 when two\nvectors form a right angle.
\nThe version of dot()
with one parameter interprets it as another\np5.Vector object.
The version of dot()
with multiple parameters interprets them as the\nx
, y
, and z
components of another vector.
The static version of dot()
, as in p5.Vector.dot(v1, v2)
, is the same\nas calling v1.dot(v2)
.
\nfunction setup() {\n // Create p5.Vector objects.\n let v1 = createVector(3, 4);\n let v2 = createVector(3, 0);\n\n // Calculate the dot product.\n let dp = v1.dot(v2);\n\n // Prints \"9\" to the console.\n print(dp);\n}\n
\n\nfunction setup() {\n // Create p5.Vector objects.\n let v1 = createVector(1, 0);\n let v2 = createVector(0, 1);\n\n // Calculate the dot product.\n let dp = p5.Vector.dot(v1, v2);\n\n // Prints \"0\" to the console.\n print(dp);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Two arrows drawn on a gray square. A black arrow points to the right and a red arrow follows the mouse. The text \"v1 • v2 = something\" changes as the mouse moves.');\n}\n\nfunction draw() {\n background(200);\n\n // Center.\n let v0 = createVector(50, 50);\n\n // Draw the black arrow.\n let v1 = createVector(30, 0);\n drawArrow(v0, v1, 'black');\n\n // Draw the red arrow.\n let v2 = createVector(mouseX - 50, mouseY - 50);\n drawArrow(v0, v2, 'red');\n\n // Display the dot product.\n let dp = v2.dot(v1);\n text(`v2 • v1 = ${dp}`, 10, 20);\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nx component of the vector.
\n", "type": "Number" }, { "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": "dot product.", "type": "Number" } }, { "line": 1546, "params": [ { "name": "v", "description": "p5.Vector to be dotted.
\n", "type": "p5.Vector" } ], "return": { "description": "", "type": "Number" } }, { "line": 3574, "params": [ { "name": "v1", "description": "first p5.Vector.
\n", "type": "p5.Vector" }, { "name": "v2", "description": "second p5.Vector.
\n", "type": "p5.Vector" } ], "static": 1, "return": { "description": "dot product.", "type": "Number" } } ] }, { "file": "src/math/p5.Vector.js", "line": 1558, "description": "Calculates the cross product of two vectors.
\nThe cross product is a vector that points straight out of the plane created\nby two vectors. The cross product's magnitude is the area of the parallelogram\nformed by the original two vectors.
\nThe static version of cross()
, as in p5.Vector.cross(v1, v2)
, is the same\nas calling v1.cross(v2)
.
\nfunction setup() {\n // Create p5.Vector objects.\n let v1 = createVector(1, 0);\n let v2 = createVector(3, 4);\n\n // Calculate the cross product.\n let cp = v1.cross(v2);\n\n // Prints \"p5.Vector Object : [0, 0, 4]\" to the console.\n print(cp.toString());\n}\n
\n\nfunction setup() {\n // Create p5.Vector objects.\n let v1 = createVector(1, 0);\n let v2 = createVector(3, 4);\n\n // Calculate the cross product.\n let cp = p5.Vector.cross(v1, v2);\n\n // Prints \"p5.Vector Object : [0, 0, 4]\" to the console.\n print(cp.toString());\n}\n
\np5.Vector to be crossed.
\n", "type": "p5.Vector" } ], "return": { "description": "cross product as a p5.Vector.", "type": "p5.Vector" } }, { "line": 3588, "params": [ { "name": "v1", "description": "first p5.Vector.
\n", "type": "p5.Vector" }, { "name": "v2", "description": "second p5.Vector.
\n", "type": "p5.Vector" } ], "static": 1, "return": { "description": "cross product.", "type": "Number" } } ] }, { "file": "src/math/p5.Vector.js", "line": 1616, "description": "Calculates the distance between two points represented by vectors.
\nA point's coordinates can be represented by the components of a vector\nthat extends from the origin to the point.
\nThe static version of dist()
, as in p5.Vector.dist(v1, v2)
, is the same\nas calling v1.dist(v2)
.
Use dist() to calculate the distance between points\nusing coordinates as in dist(x1, y1, x2, y2)
.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create p5.Vector objects.\n let v1 = createVector(1, 0);\n let v2 = createVector(0, 1);\n\n // Calculate the distance between them.\n let d = v1.dist(v2);\n\n // Prints \"1.414...\" to the console.\n print(d);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create p5.Vector objects.\n let v1 = createVector(1, 0);\n let v2 = createVector(0, 1);\n\n // Calculate the distance between them.\n let d = p5.Vector.dist(v1, v2);\n\n // Prints \"1.414...\" to the console.\n print(d);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Three arrows drawn on a gray square. A red and a blue arrow extend from the top left. A purple arrow extends from the tip of the red arrow to the tip of the blue arrow. The number 36 is written in black near the purple arrow.');\n}\n\nfunction draw() {\n background(200);\n\n let origin = createVector(0, 0);\n\n // Draw the red arrow.\n let v1 = createVector(50, 50);\n drawArrow(origin, v1, 'red');\n\n // Draw the blue arrow.\n let v2 = createVector(20, 70);\n drawArrow(origin, v2, 'blue');\n\n // Purple arrow.\n let v3 = p5.Vector.sub(v2, v1);\n drawArrow(v1, v3, 'purple');\n\n // Style the text.\n textAlign(CENTER);\n\n // Display the magnitude.\n let m = floor(v3.mag());\n text(m, 50, 75);\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nx, y, and z coordinates of a p5.Vector.
\n", "type": "p5.Vector" } ], "return": { "description": "distance.", "type": "Number" } }, { "line": 3603, "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": 1730, "description": "Scales the components of a p5.Vector object so\nthat its magnitude is 1.
\nThe static version of normalize()
, as in p5.Vector.normalize(v)
,\nreturns a new p5.Vector object and doesn't change\nthe original.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Vector.\n let v = createVector(10, 20, 2);\n\n // Normalize.\n v.normalize();\n\n // Prints \"p5.Vector Object : [0.445..., 0.890..., 0.089...]\" to the console.\n print(v.toString());\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Vector.\n let v0 = createVector(10, 20, 2);\n\n // Create a normalized copy.\n let v1 = p5.Vector.normalize(v0);\n\n // Prints \"p5.Vector Object : [10, 20, 2]\" to the console.\n print(v0.toString());\n // Prints \"p5.Vector Object : [0.445..., 0.890..., 0.089...]\" to the console.\n print(v1.toString());\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\"A red and blue arrow extend from the center of a circle. Both arrows follow the mouse, but the blue arrow's length is fixed to the circle's radius.\");\n}\n\nfunction draw() {\n background(240);\n\n // Vector to the center.\n let v0 = createVector(50, 50);\n\n // Vector from the center to the mouse.\n let v1 = createVector(mouseX - 50, mouseY - 50);\n\n // Circle's radius.\n let r = 25;\n\n // Draw the red arrow.\n drawArrow(v0, v1, 'red');\n\n // Draw the blue arrow.\n v1.normalize();\n drawArrow(v0, v1.mult(r), 'blue');\n\n // Draw the circle.\n noFill();\n circle(50, 50, r * 2);\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\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": 1839, "description": "Limits a vector's magnitude to a maximum value.
\nThe static version of limit()
, as in p5.Vector.limit(v, 5)
, returns a\nnew p5.Vector object and doesn't change the\noriginal.
\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(10, 20, 2);\n\n // Limit its magnitude.\n v.limit(5);\n\n // Prints \"p5.Vector Object : [2.227..., 4.454..., 0.445...]\" to the console.\n print(v.toString());\n}\n
\n\nfunction setup() {\n // Create a p5.Vector object.\n let v0 = createVector(10, 20, 2);\n\n // Create a copy an limit its magintude.\n let v1 = p5.Vector.limit(v0, 5);\n\n // Prints \"p5.Vector Object : [2.227..., 4.454..., 0.445...]\" to the console.\n print(v1.toString());\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\"A red and blue arrow extend from the center of a circle. Both arrows follow the mouse, but the blue arrow never crosses the circle's edge.\");\n}\nfunction draw() {\n background(240);\n\n // Vector to the center.\n let v0 = createVector(50, 50);\n\n // Vector from the center to the mouse.\n let v1 = createVector(mouseX - 50, mouseY - 50);\n\n // Circle's radius.\n let r = 25;\n\n // Draw the red arrow.\n drawArrow(v0, v1, 'red');\n\n // Draw the blue arrow.\n drawArrow(v0, v1.limit(r), 'blue');\n\n // Draw the circle.\n noFill();\n circle(50, 50, r * 2);\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nmaximum magnitude for the vector.
\n", "type": "Number" } ], "chainable": 1 }, { "line": 3733, "params": [ { "name": "v", "description": "the vector to limit
\n", "type": "p5.Vector" }, { "name": "max", "description": "", "type": "Number" }, { "name": "target", "description": "the vector to receive the result (Optional)
\n", "type": "p5.Vector", "optional": true } ], "static": 1, "return": { "description": "v with a magnitude limited to max", "type": "p5.Vector" } } ] }, { "file": "src/math/p5.Vector.js", "line": 1937, "description": "Sets a vector's magnitude to a given value.
\nThe static version of setMag()
, as in p5.Vector.setMag(v, 10)
, returns\na new p5.Vector object and doesn't change the\noriginal.
\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(3, 4, 0);\n\n // Prints \"5\" to the console.\n print(v.mag());\n\n // Set its magnitude to 10.\n v.setMag(10);\n\n // Prints \"p5.Vector Object : [6, 8, 0]\" to the console.\n print(v.toString());\n}\n
\n\nfunction setup() {\n // Create a p5.Vector object.\n let v0 = createVector(3, 4, 0);\n\n // Create a copy with a magnitude of 10.\n let v1 = p5.Vector.setMag(v0, 10);\n\n // Prints \"5\" to the console.\n print(v0.mag());\n\n // Prints \"p5.Vector Object : [6, 8, 0]\" to the console.\n print(v1.toString());\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Two arrows extend from the top left corner of a square toward its center. The red arrow reaches the center and the blue arrow only extends part of the way.');\n}\n\nfunction draw() {\n background(240);\n\n let origin = createVector(0, 0);\n let v = createVector(50, 50);\n\n // Draw the red arrow.\n drawArrow(origin, v, 'red');\n\n // Set v's magnitude to 30.\n v.setMag(30);\n\n // Draw the blue arrow.\n drawArrow(origin, v, 'blue');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nnew length for this vector.
\n", "type": "Number" } ], "chainable": 1 }, { "line": 3760, "params": [ { "name": "v", "description": "the vector to set the magnitude of
\n", "type": "p5.Vector" }, { "name": "len", "description": "", "type": "Number" }, { "name": "target", "description": "the vector to receive the result (Optional)
\n", "type": "p5.Vector", "optional": true } ], "static": 1, "return": { "description": "v with a magnitude set to len", "type": "p5.Vector" } } ] }, { "file": "src/math/p5.Vector.js", "line": 2030, "description": "Calculates the angle a 2D vector makes with the positive x-axis.
\nBy convention, the positive x-axis has an angle of 0. Angles increase in\nthe clockwise direction.
\nIf the vector was created with\ncreateVector(), heading()
returns angles\nin the units of the current angleMode().
The static version of heading()
, as in p5.Vector.heading(v)
, works the\nsame way.
\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(1, 1);\n\n // Prints \"0.785...\" to the console.\n print(v.heading());\n\n // Use degrees.\n angleMode(DEGREES);\n\n // Prints \"45\" to the console.\n print(v.heading());\n}\n
\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(1, 1);\n\n // Prints \"0.785...\" to the console.\n print(p5.Vector.heading(v));\n\n // Use degrees.\n angleMode(DEGREES);\n\n // Prints \"45\" to the console.\n print(p5.Vector.heading(v));\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A black arrow extends from the top left of a square to its center. The text \"Radians: 0.79\" and \"Degrees: 45\" is written near the tip of the arrow.');\n}\n\nfunction draw() {\n background(200);\n\n let origin = createVector(0, 0);\n let v = createVector(50, 50);\n\n // Draw the black arrow.\n drawArrow(origin, v, 'black');\n\n // Use radians.\n angleMode(RADIANS);\n\n // Display the heading in radians.\n let h = round(v.heading(), 2);\n text(`Radians: ${h}`, 20, 70);\n\n // Use degrees.\n angleMode(DEGREES);\n\n // Display the heading in degrees.\n h = v.heading();\n text(`Degrees: ${h}`, 20, 85);\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nthe vector to find the angle of
\n", "type": "p5.Vector" } ], "static": 1, "return": { "description": "the angle of rotation", "type": "Number" } } ] }, { "file": "src/math/p5.Vector.js", "line": 2138, "description": "Rotates a 2D vector to a specific angle without changing its magnitude.
\nBy convention, the positive x-axis has an angle of 0. Angles increase in\nthe clockwise direction.
\nIf the vector was created with\ncreateVector(), setHeading()
uses\nthe units of the current angleMode().
angle of rotation.
\n", "type": "Number" } ], "chainable": 1, "example": [ "\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(0, 1);\n\n // Prints \"1.570...\" to the console.\n print(v.heading());\n\n // Point to the left.\n v.setHeading(PI);\n\n // Prints \"3.141...\" to the console.\n print(v.heading());\n}\n
\n\nfunction setup() {\n // Use degrees.\n angleMode(DEGREES);\n\n // Create a p5.Vector object.\n let v = createVector(0, 1);\n\n // Prints \"90\" to the console.\n print(v.heading());\n\n // Point to the left.\n v.setHeading(180);\n\n // Prints \"180\" to the console.\n print(v.heading());\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Two arrows extend from the center of a gray square. The red arrow points to the right and the blue arrow points down.');\n}\n\nfunction draw() {\n background(200);\n\n // Create p5.Vector objects.\n let v0 = createVector(50, 50);\n let v1 = createVector(30, 0);\n\n // Draw the red arrow.\n drawArrow(v0, v1, 'red');\n\n // Point down.\n v1.setHeading(HALF_PI);\n\n // Draw the blue arrow.\n drawArrow(v0, v1, 'blue');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nRotates a 2D vector by an angle without changing its magnitude.
\nBy convention, the positive x-axis has an angle of 0. Angles increase in\nthe clockwise direction.
\nIf the vector was created with\ncreateVector(), rotate()
uses\nthe units of the current angleMode().
The static version of rotate()
, as in p5.Vector.rotate(v, PI)
,\nreturns a new p5.Vector object and doesn't change\nthe original.
\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(1, 0);\n\n // Prints \"p5.Vector Object : [1, 0, 0]\" to the console.\n print(v.toString());\n\n // Rotate a quarter turn.\n v.rotate(HALF_PI);\n\n // Prints \"p5.Vector Object : [0, 1, 0]\" to the console.\n print(v.toString());\n}\n
\n\nfunction setup() {\n // Use degrees.\n angleMode(DEGREES);\n\n // Create a p5.Vector object.\n let v = createVector(1, 0);\n\n // Prints \"p5.Vector Object : [1, 0, 0]\" to the console.\n print(v.toString());\n\n // Rotate a quarter turn.\n v.rotate(90);\n\n // Prints \"p5.Vector Object : [0, 1, 0]\" to the console.\n print(v.toString());\n}\n
\n\nfunction setup() {\n // Create a p5.Vector object.\n let v0 = createVector(1, 0);\n\n // Create a rotated copy.\n let v1 = p5.Vector.rotate(v0, HALF_PI);\n\n // Prints \"p5.Vector Object : [1, 0, 0]\" to the console.\n print(v0.toString());\n // Prints \"p5.Vector Object : [0, 1, 0]\" to the console.\n print(v1.toString());\n}\n
\n\nfunction setup() {\n // Use degrees.\n angleMode(DEGREES);\n\n // Create a p5.Vector object.\n let v0 = createVector(1, 0);\n\n // Create a rotated copy.\n let v1 = p5.Vector.rotate(v0, 90);\n\n // Prints \"p5.Vector Object : [1, 0, 0]\" to the console.\n print(v0.toString());\n\n // Prints \"p5.Vector Object : [0, 1, 0]\" to the console.\n print(v1.toString());\n}\n
\n\nlet v0;\nlet v1;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create p5.Vector objects.\n v0 = createVector(50, 50);\n v1 = createVector(30, 0);\n\n describe('A black arrow extends from the center of a gray square. The arrow rotates clockwise.');\n}\n\nfunction draw() {\n background(240);\n\n // Rotate v1.\n v1.rotate(0.01);\n\n // Draw the black arrow.\n drawArrow(v0, v1, 'black');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nangle of rotation.
\n", "type": "Number" } ], "chainable": 1 }, { "line": 3495, "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": 2388, "description": "Calculates the angle between two vectors.
\nThe angles returned are signed, which means that\nv1.angleBetween(v2) === -v2.angleBetween(v1)
.
If the vector was created with\ncreateVector(), angleBetween()
returns\nangles in the units of the current\nangleMode().
\nfunction setup() {\n // Create p5.Vector objects.\n let v0 = createVector(1, 0);\n let v1 = createVector(0, 1);\n\n // Prints \"1.570...\" to the console.\n print(v0.angleBetween(v1));\n\n // Prints \"-1.570...\" to the console.\n print(v1.angleBetween(v0));\n}\n
\n\nfunction setup() {\n // Use degrees.\n angleMode(DEGREES);\n // Create p5.Vector objects.\n let v0 = createVector(1, 0);\n let v1 = createVector(0, 1);\n\n // Prints \"90\" to the console.\n print(v0.angleBetween(v1));\n\n // Prints \"-90\" to the console.\n print(v1.angleBetween(v0));\n}\n
\n\nfunction setup() {\n // Create p5.Vector objects.\n let v0 = createVector(1, 0);\n let v1 = createVector(0, 1);\n\n // Prints \"1.570...\" to the console.\n print(p5.Vector.angleBetween(v0, v1));\n\n // Prints \"-1.570...\" to the console.\n print(p5.Vector.angleBetween(v1, v0));\n}\n
\n\nfunction setup() {\n // Use degrees.\n angleMode(DEGREES);\n\n // Create p5.Vector objects.\n let v0 = createVector(1, 0);\n let v1 = createVector(0, 1);\n\n // Prints \"90\" to the console.\n print(p5.Vector.angleBetween(v0, v1));\n\n // Prints \"-90\" to the console.\n print(p5.Vector.angleBetween(v1, v0));\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Two arrows extend from the center of a gray square. A red arrow points to the right and a blue arrow points down. The text \"Radians: 1.57\" and \"Degrees: 90\" is written above the arrows.');\n}\nfunction draw() {\n background(200);\n\n // Create p5.Vector objects.\n let v0 = createVector(50, 50);\n let v1 = createVector(30, 0);\n let v2 = createVector(0, 30);\n\n // Draw the red arrow.\n drawArrow(v0, v1, 'red');\n\n // Draw the blue arrow.\n drawArrow(v0, v2, 'blue');\n\n // Use radians.\n angleMode(RADIANS);\n\n // Display the angle in radians.\n let angle = round(v1.angleBetween(v2), 2);\n text(`Radians: ${angle}`, 20, 20);\n\n // Use degrees.\n angleMode(DEGREES);\n\n // Display the angle in degrees.\n angle = round(v1.angleBetween(v2), 2);\n text(`Degrees: ${angle}`, 20, 35);\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nx, y, and z components of a p5.Vector.
\n", "type": "p5.Vector" } ], "return": { "description": "angle between the vectors.", "type": "Number" } }, { "line": 3804, "params": [ { "name": "v1", "description": "the first vector.
\n", "type": "p5.Vector" }, { "name": "v2", "description": "the second vector.
\n", "type": "p5.Vector" } ], "static": 1, "return": { "description": "angle between the two vectors.", "type": "Number" } } ] }, { "file": "src/math/p5.Vector.js", "line": 2542, "description": "Calculates new x
, y
, and z
components that are proportionally the\nsame distance between two vectors.
The amt
parameter is the amount to interpolate between the old vector and\nthe new vector. 0.0 keeps all components equal to the old vector's, 0.5 is\nhalfway between, and 1.0 sets all components equal to the new vector's.
The static version of lerp()
, as in p5.Vector.lerp(v0, v1, 0.5)
,\nreturns a new p5.Vector object and doesn't change\nthe original.
\nfunction setup() {\n // Create a p5.Vector object.\n let v0 = createVector(1, 1, 1);\n let v1 = createVector(3, 3, 3);\n\n // Interpolate.\n v0.lerp(v1, 0.5);\n\n // Prints \"p5.Vector Object : [2, 2, 2]\" to the console.\n print(v0.toString());\n}\n
\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(1, 1, 1);\n\n // Interpolate.\n v.lerp(3, 3, 3, 0.5);\n\n // Prints \"p5.Vector Object : [2, 2, 2]\" to the console.\n print(v.toString());\n}\n
\n\nfunction setup() {\n // Create p5.Vector objects.\n let v0 = createVector(1, 1, 1);\n let v1 = createVector(3, 3, 3);\n\n // Interpolate.\n let v2 = p5.Vector.lerp(v0, v1, 0.5);\n\n // Prints \"p5.Vector Object : [2, 2, 2]\" to the console.\n print(v2.toString());\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Three arrows extend from the center of a gray square. A red arrow points to the right, a blue arrow points down, and a purple arrow points to the bottom right.');\n}\nfunction draw() {\n background(200);\n\n // Create p5.Vector objects.\n let v0 = createVector(50, 50);\n let v1 = createVector(30, 0);\n let v2 = createVector(0, 30);\n\n // Interpolate.\n let v3 = p5.Vector.lerp(v1, v2, 0.5);\n\n // Draw the red arrow.\n drawArrow(v0, v1, 'red');\n\n // Draw the blue arrow.\n drawArrow(v0, v2, 'blue');\n\n // Draw the purple arrow.\n drawArrow(v0, v3, 'purple');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nx component.
\n", "type": "Number" }, { "name": "y", "description": "y component.
\n", "type": "Number" }, { "name": "z", "description": "z component.
\n", "type": "Number" }, { "name": "amt", "description": "amount of interpolation between 0.0 (old vector)\n and 1.0 (new vector). 0.5 is halfway between.
\n", "type": "Number" } ], "chainable": 1 }, { "line": 2655, "params": [ { "name": "v", "description": "p5.Vector to lerp toward.
\n", "type": "p5.Vector" }, { "name": "amt", "description": "", "type": "Number" } ], "chainable": 1 }, { "line": 3618, "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": 2671, "description": "Calculates a new heading and magnitude that are between two vectors.
\nThe amt
parameter is the amount to interpolate between the old vector and\nthe new vector. 0.0 keeps the heading and magnitude equal to the old\nvector's, 0.5 sets them halfway between, and 1.0 sets the heading and\nmagnitude equal to the new vector's.
slerp()
differs from lerp() because\nit interpolates magnitude. Calling v0.slerp(v1, 0.5)
sets v0
's\nmagnitude to a value halfway between its original magnitude and v1
's.\nCalling v0.lerp(v1, 0.5)
makes no such guarantee.
The static version of slerp()
, as in p5.Vector.slerp(v0, v1, 0.5)
,\nreturns a new p5.Vector object and doesn't change\nthe original.
\nfunction setup() {\n // Create a p5.Vector object.\n let v0 = createVector(3, 0);\n\n // Prints \"3\" to the console.\n print(v0.mag());\n\n // Prints \"0\" to the console.\n print(v0.heading());\n\n // Create a p5.Vector object.\n let v1 = createVector(0, 1);\n\n // Prints \"1\" to the console.\n print(v1.mag());\n\n // Prints \"1.570...\" to the console.\n print(v1.heading());\n\n // Interpolate halfway between v0 and v1.\n v0.slerp(v1, 0.5);\n\n // Prints \"2\" to the console.\n print(v0.mag());\n\n // Prints \"0.785...\" to the console.\n print(v0.heading());\n}\n
\n\nfunction setup() {\n // Create a p5.Vector object.\n let v0 = createVector(3, 0);\n\n // Prints \"3\" to the console.\n print(v0.mag());\n\n // Prints \"0\" to the console.\n print(v0.heading());\n\n // Create a p5.Vector object.\n let v1 = createVector(0, 1);\n\n // Prints \"1\" to the console.\n print(v1.mag());\n\n // Prints \"1.570...\" to the console.\n print(v1.heading());\n\n // Create a p5.Vector that's halfway between v0 and v1.\n let v3 = p5.Vector.slerp(v0, v1, 0.5);\n\n // Prints \"2\" to the console.\n print(v3.mag());\n\n // Prints \"0.785...\" to the console.\n print(v3.heading());\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Three arrows extend from the center of a gray square. A red arrow points to the right, a blue arrow points to the left, and a purple arrow points down.');\n}\n\nfunction draw() {\n background(200);\n\n // Create p5.Vector objects.\n let v0 = createVector(50, 50);\n let v1 = createVector(20, 0);\n let v2 = createVector(-40, 0);\n\n // Create a p5.Vector that's halfway between v1 and v2.\n let v3 = p5.Vector.slerp(v1, v2, 0.5);\n\n // Draw the red arrow.\n drawArrow(v0, v1, 'red');\n\n // Draw the blue arrow.\n drawArrow(v0, v2, 'blue');\n\n // Draw the purple arrow.\n drawArrow(v0, v3, 'purple');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\np5.Vector to slerp toward.
\n", "type": "p5.Vector" }, { "name": "amt", "description": "amount of interpolation between 0.0 (old vector)\n and 1.0 (new vector). 0.5 is halfway between.
\n", "type": "Number" } ], "return": { "description": "", "type": "p5.Vector" } }, { "line": 3649, "params": [ { "name": "v1", "description": "old vector.
\n", "type": "p5.Vector" }, { "name": "v2", "description": "new vector.
\n", "type": "p5.Vector" }, { "name": "amt", "description": "", "type": "Number" }, { "name": "target", "description": "vector to receive the result.
\n", "type": "p5.Vector", "optional": true } ], "static": 1, "return": { "description": "slerped vector between v1 and v2", "type": "p5.Vector" } } ] }, { "file": "src/math/p5.Vector.js", "line": 2873, "description": "Reflects a vector about a line in 2D or a plane in 3D.
\nThe orientation of the line or plane is described by a normal vector that\npoints away from the shape.
\nThe static version of reflect()
, as in p5.Vector.reflect(v, n)
,\nreturns a new p5.Vector object and doesn't change\nthe original.
\nfunction setup() {\n // Create a normal vector.\n let n = createVector(0, 1);\n // Create a vector to reflect.\n let v = createVector(4, 6);\n\n // Reflect v about n.\n v.reflect(n);\n\n // Prints \"p5.Vector Object : [4, -6, 0]\" to the console.\n print(v.toString());\n}\n
\n\nfunction setup() {\n // Create a normal vector.\n let n = createVector(0, 1);\n\n // Create a vector to reflect.\n let v0 = createVector(4, 6);\n\n // Create a reflected vector.\n let v1 = p5.Vector.reflect(v0, n);\n\n // Prints \"p5.Vector Object : [4, -6, 0]\" to the console.\n print(v1.toString());\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Three arrows extend from the center of a gray square with a vertical line down its middle. A black arrow points to the right, a blue arrow points to the bottom left, and a red arrow points to the bottom right.');\n}\nfunction draw() {\n background(200);\n\n // Draw a vertical line.\n line(50, 0, 50, 100);\n\n // Create a normal vector.\n let n = createVector(1, 0);\n\n // Center.\n let v0 = createVector(50, 50);\n\n // Create a vector to reflect.\n let v1 = createVector(30, 40);\n\n // Create a reflected vector.\n let v2 = p5.Vector.reflect(v1, n);\n\n // Scale the normal vector for drawing.\n n.setMag(30);\n\n // Draw the black arrow.\n drawArrow(v0, n, 'black');\n\n // Draw the red arrow.\n drawArrow(v0, v1, 'red');\n\n // Draw the blue arrow.\n drawArrow(v0, v2, 'blue');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\np5.Vector\n to reflect about.
\n", "type": "p5.Vector" } ], "chainable": 1 }, { "line": 3819, "params": [ { "name": "incidentVector", "description": "vector to be reflected.
\n", "type": "p5.Vector" }, { "name": "surfaceNormal", "description": "", "type": "p5.Vector" }, { "name": "target", "description": "vector to receive the result.
\n", "type": "p5.Vector", "optional": true } ], "static": 1, "return": { "description": "the reflected vector", "type": "p5.Vector" } } ] }, { "file": "src/math/p5.Vector.js", "line": 2983, "description": "Returns the vector's components as an array of numbers.
\n", "itemtype": "method", "name": "array", "return": { "description": "array with the vector's components.", "type": "Number[]" }, "example": [ "\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = createVector(20, 30);\n\n // Prints \"[20, 30, 0]\" to the console.\n print(v.array());\n}\n
\nthe vector to convert to an array
\n", "type": "p5.Vector" } ], "static": 1, "return": { "description": "an Array with the 3 values", "type": "Number[]" } } ] }, { "file": "src/math/p5.Vector.js", "line": 3005, "description": "Checks whether all the vector's components are equal to another vector's.
\nequals()
returns true
if the vector's components are all the same as another\nvector's and false
if not.
The version of equals()
with one parameter interprets it as another\np5.Vector object.
The version of equals()
with multiple parameters interprets them as the\ncomponents of another vector. Any missing parameters are assigned the value\n0.
The static version of equals()
, as in p5.Vector.equals(v0, v1)
,\ninterprets both parameters as p5.Vector objects.
\nfunction setup() {\n // Create p5.Vector objects.\n let v0 = createVector(10, 20, 30);\n let v1 = createVector(10, 20, 30);\n let v2 = createVector(0, 0, 0);\n\n // Prints \"true\" to the console.\n print(v0.equals(v1));\n\n // Prints \"false\" to the console.\n print(v0.equals(v2));\n}\n
\n\nfunction setup() {\n // Create p5.Vector objects.\n let v0 = createVector(5, 10, 20);\n let v1 = createVector(5, 10, 20);\n let v2 = createVector(13, 10, 19);\n\n // Prints \"true\" to the console.\n print(v0.equals(v1.x, v1.y, v1.z));\n\n // Prints \"false\" to the console.\n print(v0.equals(v2.x, v2.y, v2.z));\n}\n
\n\nfunction setup() {\n // Create p5.Vector objects.\n let v0 = createVector(10, 20, 30);\n let v1 = createVector(10, 20, 30);\n let v2 = createVector(0, 0, 0);\n\n // Prints \"true\" to the console.\n print(p5.Vector.equals(v0, v1));\n\n // Prints \"false\" to the console.\n print(p5.Vector.equals(v0, v2));\n}\n
\nx 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": "whether the vectors are equal.", "type": "Boolean" } }, { "line": 3078, "params": [ { "name": "value", "description": "vector to compare.
\n", "type": "p5.Vector|Array" } ], "return": { "description": "", "type": "Boolean" } }, { "line": 3861, "params": [ { "name": "v1", "description": "the first vector to compare
\n", "type": "p5.Vector|Array" }, { "name": "v2", "description": "the second vector to compare
\n", "type": "p5.Vector|Array" } ], "static": 1, "return": { "description": "", "type": "Boolean" } } ] }, { "file": "src/math/p5.Vector.js", "line": 3103, "description": "Creates a new 2D vector from an angle.
\n", "itemtype": "method", "name": "fromAngle", "static": 1, "params": [ { "name": "angle", "description": "desired angle, in radians. Unaffected by angleMode().
\n", "type": "Number" }, { "name": "length", "description": "length of the new vector (defaults to 1).
\n", "type": "Number", "optional": true } ], "return": { "description": "new p5.Vector object.", "type": "p5.Vector" }, "example": [ "\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = p5.Vector.fromAngle(0);\n\n // Prints \"p5.Vector Object : [1, 0, 0]\" to the console.\n print(v.toString());\n}\n
\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = p5.Vector.fromAngle(0, 30);\n\n // Prints \"p5.Vector Object : [30, 0, 0]\" to the console.\n print(v.toString());\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A black arrow extends from the center of a gray square. It points to the right.');\n}\nfunction draw() {\n background(200);\n\n // Create a p5.Vector to the center.\n let v0 = createVector(50, 50);\n\n // Create a p5.Vector with an angle 0 and magnitude 30.\n let v1 = p5.Vector.fromAngle(0, 30);\n\n // Draw the black arrow.\n drawArrow(v0, v1, 'black');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nCreates a new 3D vector from a pair of ISO spherical angles.
\n", "itemtype": "method", "name": "fromAngles", "static": 1, "params": [ { "name": "theta", "description": "polar angle in radians (zero is up).
\n", "type": "Number" }, { "name": "phi", "description": "azimuthal angle in radians\n (zero is out of the screen).
\n", "type": "Number" }, { "name": "length", "description": "length of the new vector (defaults to 1).
\n", "type": "Number", "optional": true } ], "return": { "description": "new p5.Vector object.", "type": "p5.Vector" }, "example": [ "\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = p5.Vector.fromAngles(0, 0);\n\n // Prints \"p5.Vector Object : [0, -1, 0]\" to the console.\n print(v.toString());\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A light shines on a pink sphere as it orbits.');\n}\n\nfunction draw() {\n background(0);\n\n // Calculate the ISO angles.\n let theta = frameCount * 0.05;\n let phi = 0;\n\n // Create a p5.Vector object.\n let v = p5.Vector.fromAngles(theta, phi, 100);\n\n // Create a point light using the p5.Vector.\n let c = color('deeppink');\n pointLight(c, v);\n\n // Style the sphere.\n fill(255);\n noStroke();\n\n // Draw the sphere.\n sphere(35);\n}\n
\nCreates a new 2D unit vector with a random heading.
\n", "itemtype": "method", "name": "random2D", "static": 1, "return": { "description": "new p5.Vector object.", "type": "p5.Vector" }, "example": [ "\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = p5.Vector.random2D();\n\n // Prints \"p5.Vector Object : [x, y, 0]\" to the console\n // where x and y are small random numbers.\n print(v.toString());\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(1);\n\n describe('A black arrow in extends from the center of a gray square. It changes direction once per second.');\n}\n\nfunction draw() {\n background(200);\n\n // Create a p5.Vector to the center.\n let v0 = createVector(50, 50);\n\n // Create a random p5.Vector.\n let v1 = p5.Vector.random2D();\n\n // Scale v1 for drawing.\n v1.mult(30);\n\n // Draw the black arrow.\n drawArrow(v0, v1, 'black');\n}\n\n// Draws an arrow between two vectors.\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\nCreates a new 3D unit vector with a random heading.
\n", "itemtype": "method", "name": "random3D", "static": 1, "return": { "description": "new p5.Vector object.", "type": "p5.Vector" }, "example": [ "\n\nfunction setup() {\n // Create a p5.Vector object.\n let v = p5.Vector.random3D();\n\n // Prints \"p5.Vector Object : [x, y, z]\" to the console\n // where x, y, and z are small random numbers.\n print(v.toString());\n}\n
\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": 3491, "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": 3518, "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": 3571, "description": "Calculates the dot product of two vectors.
\n", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 3585, "description": "Calculates the cross product of two vectors.
\n", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 3599, "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": 3614, "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": 3643, "description": "Performs spherical linear interpolation with the other vector\nand returns the resulting vector.\nThis works in both 3D and 2D. As for 2D, the result of slerping\nbetween 2D vectors is always a 2D vector.
\n", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 3674, "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)
.)
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", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 3704, "description": "Normalize the vector to length 1 (make it a unit vector).
\n", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 3729, "description": "Limit the magnitude of the vector to the value used for the max\nparameter.
\n", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 3756, "description": "Set the magnitude of the vector to the value used for the len\nparameter.
\n", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 3783, "description": "Calculate 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 degrees accordingly.
\n", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 3799, "description": "Calculates and returns the angle between two vectors. This function will take\nthe angleMode on v1 into consideration, and\ngive the angle in radians or degrees accordingly.
\n", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 3815, "description": "Reflect a vector about a normal to a line in 2D, or about a normal to a\nplane in 3D.
\n", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 3842, "description": "Return 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()\nmethod to copy into your own vector.
\n", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/p5.Vector.js", "line": 3858, "description": "Equality check against a p5.Vector
\n", "class": "p5.Vector", "module": "Math", "submodule": "Vector" }, { "file": "src/math/random.js", "line": 37, "description": "Sets the seed value for the random() and\nrandomGaussian() functions.
\nBy default, random() and\nrandomGaussian() produce different\nresults each time a sketch is run. Calling randomSeed()
with a constant\nargument, such as randomSeed(99)
, makes these functions produce the same\nresults each time a sketch is run.
seed value.
\n", "type": "Number" } ], "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get random coordinates.\n let x = random(0, 100);\n let y = random(0, 100);\n\n // Draw the white circle.\n circle(x, y, 10);\n\n // Set a random seed for consistency.\n randomSeed(99);\n\n // Get random coordinates.\n x = random(0, 100);\n y = random(0, 100);\n\n // Draw the black circle.\n fill(0);\n circle(x, y, 10);\n\n describe('A white circle appears at a random position. A black circle appears at (27.4, 25.8).');\n}\n
\nReturns a random number or a random element from an array.
\nrandom()
follows uniform distribution, which means that all outcomes are\nequally likely. When random()
is used to generate numbers, all\nnumbers in the output range are equally likely to be returned. When\nrandom()
is used to select elements from an array, all elements are\nequally likely to be chosen.
By default, random()
produces different results each time a sketch runs.\nThe randomSeed() function can be used to\ngenerate the same sequence of numbers or choices each time a sketch runs.
The version of random()
with no parameters returns a random number from 0\nup to but not including 1.
The version of random()
with one parameter works one of two ways. If the\nargument passed is a number, random()
returns a random number from 0 up\nto but not including the number. For example, calling random(5)
returns\nvalues between 0 and 5. If the argument passed is an array, random()
\nreturns a random element from that array. For example, calling\nrandom(['🦁', '🐯', '🐻'])
returns either a lion, tiger, or bear emoji.
The version of random()
with two parameters returns a random number from\na given range. The arguments passed set the range's lower and upper bounds.\nFor example, calling random(-5, 10.2)
returns values from -5 up to but\nnot including 10.2.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get random coordinates between 0 and 100.\n let x = random(0, 100);\n let y = random(0, 100);\n\n // Draw a point.\n strokeWeight(5);\n point(x, y);\n\n describe('A black dot appears in a random position on a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get random coordinates between 0 and 100.\n let x = random(100);\n let y = random(100);\n\n // Draw the point.\n strokeWeight(5);\n point(x, y);\n\n describe('A black dot appears in a random position on a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of emoji strings.\n let animals = ['🦁', '🐯', '🐻'];\n\n // Choose a random element from the array.\n let choice = random(animals);\n\n // Style the text.\n textAlign(CENTER);\n textSize(20);\n\n // Display the emoji.\n text(choice, 50, 50);\n\n describe('An animal face is displayed at random. Either a lion, tiger, or bear.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(5);\n\n describe('A black dot moves around randomly on a gray square.');\n}\n\nfunction draw() {\n background(200);\n\n // Get random coordinates between 0 and 100.\n let x = random(100);\n let y = random(100);\n\n // Draw the point.\n strokeWeight(5);\n point(x, y);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(5);\n\n describe('A black dot moves around randomly in the middle of a gray square.');\n}\n\nfunction draw() {\n background(200);\n\n // Get random coordinates between 45 and 55.\n let x = random(45, 55);\n let y = random(45, 55);\n\n // Draw the point.\n strokeWeight(5);\n point(x, y);\n}\n
\n\nlet x = 50;\nlet y = 50;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A black dot moves around randomly leaving a trail.');\n}\n\nfunction draw() {\n // Update x and y randomly.\n x += random(-1, 1);\n y += random(-1, 1);\n\n // Draw the point.\n point(x, y);\n}\n
\nlower bound (inclusive).
\n", "type": "Number", "optional": true }, { "name": "max", "description": "upper bound (exclusive).
\n", "type": "Number", "optional": true } ], "return": { "description": "random number.", "type": "Number" } }, { "line": 259, "params": [ { "name": "choices", "description": "array to choose from.
\n", "type": "Array" } ], "return": { "description": "random element from the array.", "type": "*" } } ] }, { "file": "src/math/random.js", "line": 293, "description": "Returns a random number fitting a Gaussian, or normal, distribution.
\nNormal distributions look like bell curves when plotted. Values from a\nnormal distribution cluster around a central value called the mean. The\ncluster's standard deviation describes its spread.
\nBy default, randomGaussian()
produces different results each time a\nsketch runs. The randomSeed() function can be\nused to generate the same sequence of numbers each time a sketch runs.
There's no minimum or maximum value that randomGaussian()
might return.\nValues far from the mean are very unlikely and values near the mean are\nvery likely.
The version of randomGaussian()
with no parameters returns values with a\nmean of 0 and standard deviation of 1.
The version of randomGaussian()
with one parameter interprets the\nargument passed as the mean. The standard deviation is 1.
The version of randomGaussian()
with two parameters interprets the first\nargument passed as the mean and the second as the standard deviation.
mean.
\n", "type": "Number", "optional": true }, { "name": "sd", "description": "standard deviation.
\n", "type": "Number", "optional": true } ], "return": { "description": "random number.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('Three horizontal black lines are filled in randomly. The top line spans entire canvas. The middle line is very short. The bottom line spans two-thirds of the canvas.');\n}\n\nfunction draw() {\n // Style the circles.\n noStroke();\n fill(0, 10);\n\n // Uniform distribution between 0 and 100.\n let x = random(100);\n let y = 25;\n circle(x, y, 5);\n\n // Gaussian distribution with a mean of 50 and sd of 1.\n x = randomGaussian(50);\n y = 50;\n circle(x, y, 5);\n\n // Gaussian distribution with a mean of 50 and sd of 10.\n x = randomGaussian(50, 10);\n y = 75;\n circle(x, y, 5);\n}\n
\nCalculates the arc cosine of a number.
\nacos()
is the inverse of cos(). It expects\narguments in the range -1 to 1. By default, acos()
returns values in the\nrange 0 to π (about 3.14). If the\nangleMode() is DEGREES
, then values are\nreturned in the range 0 to 180.
value whose arc cosine is to be returned.
\n", "type": "Number" } ], "return": { "description": "arc cosine of the given value.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate cos() and acos() values.\n let a = PI;\n let c = cos(a);\n let ac = acos(c);\n\n // Display the values.\n text(`${round(a, 3)}`, 35, 25);\n text(`${round(c, 3)}`, 35, 50);\n text(`${round(ac, 3)}`, 35, 75);\n\n describe('The numbers 3.142, -1, and 3.142 written on separate rows.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate cos() and acos() values.\n let a = PI + QUARTER_PI;\n let c = cos(a);\n let ac = acos(c);\n\n // Display the values.\n text(`${round(a, 3)}`, 35, 25);\n text(`${round(c, 3)}`, 35, 50);\n text(`${round(ac, 3)}`, 35, 75);\n\n describe('The numbers 3.927, -0.707, and 2.356 written on separate rows.');\n}\n
\nCalculates the arc sine of a number.
\nasin()
is the inverse of sin(). It expects input\nvalues in the range of -1 to 1. By default, asin()
returns values in the\nrange -π ÷ 2 (about -1.57) to π ÷ 2 (about 1.57). If\nthe angleMode() is DEGREES
then values are\nreturned in the range -90 to 90.
value whose arc sine is to be returned.
\n", "type": "Number" } ], "return": { "description": "arc sine of the given value.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate sin() and asin() values.\n let a = PI / 3;\n let s = sin(a);\n let as = asin(s);\n\n // Display the values.\n text(`${round(a, 3)}`, 35, 25);\n text(`${round(s, 3)}`, 35, 50);\n text(`${round(as, 3)}`, 35, 75);\n\n describe('The numbers 1.047, 0.866, and 1.047 written on separate rows.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate sin() and asin() values.\n let a = PI + PI / 3;\n let s = sin(a);\n let as = asin(s);\n\n // Display the values.\n text(`${round(a, 3)}`, 35, 25);\n text(`${round(s, 3)}`, 35, 50);\n text(`${round(as, 3)}`, 35, 75);\n\n describe('The numbers 4.189, -0.866, and -1.047 written on separate rows.');\n}\n
\nCalculates the arc tangent of a number.
\natan()
is the inverse of tan(). It expects input\nvalues in the range of -Infinity to Infinity. By default, atan()
returns\nvalues in the range -π ÷ 2 (about -1.57) to π ÷ 2\n(about 1.57). If the angleMode() is DEGREES
\nthen values are returned in the range -90 to 90.
value whose arc tangent is to be returned.
\n", "type": "Number" } ], "return": { "description": "arc tangent of the given value.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate tan() and atan() values.\n let a = PI / 3;\n let t = tan(a);\n let at = atan(t);\n\n // Display the values.\n text(`${round(a, 3)}`, 35, 25);\n text(`${round(t, 3)}`, 35, 50);\n text(`${round(at, 3)}`, 35, 75);\n\n describe('The numbers 1.047, 1.732, and 1.047 written on separate rows.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate tan() and atan() values.\n let a = PI + PI / 3;\n let t = tan(a);\n let at = atan(t);\n\n // Display the values.\n text(`${round(a, 3)}`, 35, 25);\n text(`${round(t, 3)}`, 35, 50);\n text(`${round(at, 3)}`, 35, 75);\n\n describe('The numbers 4.189, 1.732, and 1.047 written on separate rows.');\n}\n
\nCalculates the angle formed by a point, the origin, and the positive\nx-axis.
\natan2()
is most often used for orienting geometry to the mouse's\nposition, as in atan2(mouseY, mouseX)
. The first parameter is the point's\ny-coordinate and the second parameter is its x-coordinate.
By default, atan2()
returns values in the range\n-π (about -3.14) to π (3.14). If the\nangleMode() is DEGREES
, then values are\nreturned in the range -180 to 180.
y-coordinate of the point.
\n", "type": "Number" }, { "name": "x", "description": "x-coordinate of the point.
\n", "type": "Number" } ], "return": { "description": "arc tangent of the given point.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A rectangle at the top-left of the canvas rotates with mouse movements.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the angle between the mouse\n // and the origin.\n let a = atan2(mouseY, mouseX);\n\n // Rotate.\n rotate(a);\n\n // Draw the shape.\n rect(0, 0, 60, 10);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A rectangle at the center of the canvas rotates with mouse movements.');\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Get the mouse's coordinates relative to the origin.\n let x = mouseX - 50;\n let y = mouseY - 50;\n\n // Calculate the angle between the mouse and the origin.\n let a = atan2(y, x);\n\n // Rotate.\n rotate(a);\n\n // Draw the shape.\n rect(-30, -5, 60, 10);\n}\n
\nCalculates the cosine of an angle.
\ncos()
is useful for many geometric tasks in creative coding. The values\nreturned oscillate between -1 and 1 as the input angle increases. cos()
\ntakes into account the current angleMode().
the angle.
\n", "type": "Number" } ], "return": { "description": "cosine of the angle.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white ball on a string oscillates left and right.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the coordinates.\n let x = 30 * cos(frameCount * 0.05) + 50;\n let y = 50;\n\n // Draw the oscillator.\n line(50, y, x, y);\n circle(x, y, 20);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots form a wave pattern.');\n}\n\nfunction draw() {\n // Calculate the coordinates.\n let x = frameCount;\n let y = 30 * cos(x * 0.1) + 50;\n\n // Draw the point.\n point(x, y);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots form an infinity symbol.');\n}\n\nfunction draw() {\n // Calculate the coordinates.\n let x = 30 * cos(frameCount * 0.1) + 50;\n let y = 10 * sin(frameCount * 0.2) + 50;\n\n // Draw the point.\n point(x, y);\n}\n
\nCalculates the sine of an angle.
\nsin()
is useful for many geometric tasks in creative coding. The values\nreturned oscillate between -1 and 1 as the input angle increases. sin()
\ntakes into account the current angleMode().
the angle.
\n", "type": "Number" } ], "return": { "description": "sine of the angle.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white ball on a string oscillates up and down.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the coordinates.\n let x = 50;\n let y = 30 * sin(frameCount * 0.05) + 50;\n\n // Draw the oscillator.\n line(50, y, x, y);\n circle(x, y, 20);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots form a wave pattern.');\n}\n\nfunction draw() {\n // Calculate the coordinates.\n let x = frameCount;\n let y = 30 * sin(x * 0.1) + 50;\n\n // Draw the point.\n point(x, y);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots form an infinity symbol.');\n}\n\nfunction draw() {\n // Calculate the coordinates.\n let x = 30 * cos(frameCount * 0.1) + 50;\n let y = 10 * sin(frameCount * 0.2) + 50;\n\n // Draw the point.\n point(x, y);\n}\n
\nCalculates the tangent of an angle.
\ntan()
is useful for many geometric tasks in creative coding. The values\nreturned range from -Infinity to Infinity and repeat periodically as the\ninput angle increases. tan()
takes into account the current\nangleMode().
the angle.
\n", "type": "Number" } ], "return": { "description": "tangent of the angle.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of identical curves drawn with black dots. Each curve starts from the top of the canvas, continues down at a slight angle, flattens out at the middle of the canvas, then continues to the bottom.');\n}\n\nfunction draw() {\n // Calculate the coordinates.\n let x = frameCount;\n let y = 5 * tan(x * 0.1) + 50;\n\n // Draw the point.\n point(x, y);\n}\n
\nConverts an angle measured in radians to its value in degrees.
\nDegrees and radians are both units for measuring angles. There are 360˚ in\none full rotation. A full rotation is 2 × π (about 6.28) radians.
\nThe same angle can be expressed in with either unit. For example, 90° is a\nquarter of a full rotation. The same angle is 2 × π ÷ 4\n(about 1.57) radians.
\n", "itemtype": "method", "name": "degrees", "params": [ { "name": "radians", "description": "radians value to convert to degrees.
\n", "type": "Number" } ], "return": { "description": "converted angle.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate the angle conversion.\n let rad = QUARTER_PI;\n let deg = degrees(rad);\n\n // Display the conversion.\n text(`${round(rad, 2)} rad = ${deg}˚`, 10, 50);\n\n describe('The text \"0.79 rad = 45˚\".');\n}\n
\nConverts an angle measured in degrees to its value in radians.
\nDegrees and radians are both units for measuring angles. There are 360˚ in\none full rotation. A full rotation is 2 × π (about 6.28) radians.
\nThe same angle can be expressed in with either unit. For example, 90° is a\nquarter of a full rotation. The same angle is 2 × π ÷ 4\n(about 1.57) radians.
\n", "itemtype": "method", "name": "radians", "params": [ { "name": "degrees", "description": "degree value to convert to radians.
\n", "type": "Number" } ], "return": { "description": "converted angle.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Caclulate the angle conversion.\n let deg = 45;\n let rad = radians(deg);\n\n // Display the angle conversion.\n text(`${deg}˚ = ${round(rad, 3)} rad`, 10, 50);\n\n describe('The text \"45˚ = 0.785 rad\".');\n}\n
\nChanges the unit system used to measure angles.
\nDegrees and radians are both units for measuring angles. There are 360˚ in\none full rotation. A full rotation is 2 × π (about 6.28) radians.
\nFunctions such as rotate() and\nsin() expect angles measured radians by default.\nCalling angleMode(DEGREES)
switches to degrees. Calling\nangleMode(RADIANS)
switches back to radians.
Calling angleMode()
with no arguments returns current angle mode, which\nis either RADIANS
or DEGREES
.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Rotate 1/8 turn.\n rotate(QUARTER_PI);\n\n // Draw a line.\n line(0, 0, 80, 0);\n\n describe('A diagonal line radiating from the top-left corner of a square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use degrees.\n angleMode(DEGREES);\n\n // Rotate 1/8 turn.\n rotate(45);\n\n // Draw a line.\n line(0, 0, 80, 0);\n\n describe('A diagonal line radiating from the top-left corner of a square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Calculate the angle to rotate.\n let angle = TWO_PI / 7;\n\n // Move the origin to the center.\n translate(50, 50);\n\n // Style the flower.\n noStroke();\n fill(255, 50);\n\n // Draw the flower.\n for (let i = 0; i < 7; i += 1) {\n ellipse(0, 0, 80, 20);\n rotate(angle);\n }\n\n describe('A translucent white flower on a dark background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Use degrees.\n angleMode(DEGREES);\n\n // Calculate the angle to rotate.\n let angle = 360 / 7;\n\n // Move the origin to the center.\n translate(50, 50);\n\n // Style the flower.\n noStroke();\n fill(255, 50);\n\n // Draw the flower.\n for (let i = 0; i < 7; i += 1) {\n ellipse(0, 0, 80, 20);\n rotate(angle);\n }\n\n describe('A translucent white flower on a dark background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white ball on a string oscillates left and right.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the coordinates.\n let x = 30 * cos(frameCount * 0.05) + 50;\n let y = 50;\n\n // Draw the oscillator.\n line(50, y, x, y);\n circle(x, y, 20);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use degrees.\n angleMode(DEGREES);\n\n describe('A white ball on a string oscillates left and right.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the coordinates.\n let x = 30 * cos(frameCount * 2.86) + 50;\n let y = 50;\n\n // Draw the oscillator.\n line(50, y, x, y);\n circle(x, y, 20);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw the upper line.\n rotate(PI / 6);\n line(0, 0, 80, 0);\n\n // Use degrees.\n angleMode(DEGREES);\n\n // Draw the lower line.\n rotate(30);\n line(0, 0, 80, 0);\n\n describe('Two diagonal lines radiating from the top-left corner of a square. The lines are oriented 30 degrees from the edges of the square and 30 degrees apart from each other.');\n}\n
\neither RADIANS or DEGREES.
\n", "type": "Constant" } ] }, { "line": 737, "params": [], "return": { "description": "mode either RADIANS or DEGREES", "type": "Constant" } } ] }, { "file": "src/typography/attributes.js", "line": 11, "description": "Sets the way text is aligned when text() is called.
\nBy default, calling text('hi', 10, 20)
places the bottom-left corner of\nthe text's bounding box at (10, 20).
The first parameter, horizAlign
, changes the way\ntext() interprets x-coordinates. By default, the\nx-coordinate sets the left edge of the bounding box. textAlign()
accepts\nthe following values for horizAlign
: LEFT
, CENTER
, or RIGHT
.
The second parameter, vertAlign
, is optional. It changes the way\ntext() interprets y-coordinates. By default, the\ny-coordinate sets the bottom edge of the bounding box. textAlign()
\naccepts the following values for vertAlign
: TOP
, BOTTOM
, CENTER
,\nor BASELINE
.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw a vertical line.\n strokeWeight(0.5);\n line(50, 0, 50, 100);\n\n // Top line.\n textSize(16);\n textAlign(RIGHT);\n text('ABCD', 50, 30);\n\n // Middle line.\n textAlign(CENTER);\n text('EFGH', 50, 50);\n\n // Bottom line.\n textAlign(LEFT);\n text('IJKL', 50, 70);\n\n describe('The letters ABCD displayed at top-left, EFGH at center, and IJKL at bottom-right. A vertical line divides the canvas in half.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n strokeWeight(0.5);\n\n // First line.\n line(0, 12, width, 12);\n textAlign(CENTER, TOP);\n text('TOP', 50, 12);\n\n // Second line.\n line(0, 37, width, 37);\n textAlign(CENTER, CENTER);\n text('CENTER', 50, 37);\n\n // Third line.\n line(0, 62, width, 62);\n textAlign(CENTER, BASELINE);\n text('BASELINE', 50, 62);\n\n // Fourth line.\n line(0, 97, width, 97);\n textAlign(CENTER, BOTTOM);\n text('BOTTOM', 50, 97);\n\n describe('The words \"TOP\", \"CENTER\", \"BASELINE\", and \"BOTTOM\" each drawn relative to a horizontal line. Their positions demonstrate different vertical alignments.');\n}\n
\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": 98, "params": [], "return": { "description": "", "type": "Object" } } ] }, { "file": "src/typography/attributes.js", "line": 107, "description": "Sets the spacing between lines of text when\ntext() is called.
\nNote: Spacing is measured in pixels.
\nCalling textLeading()
without an argument returns the current spacing.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // \"\\n\" starts a new line of text.\n let lines = 'one\\ntwo';\n\n // Left.\n text(lines, 10, 25);\n\n // Right.\n textLeading(30);\n text(lines, 70, 25);\n\n describe('The words \"one\" and \"two\" written on separate lines twice. The words on the left have less vertical spacing than the words on the right.');\n}\n
\nspacing between lines of text in units of pixels.
\n", "type": "Number" } ], "chainable": 1 }, { "line": 142, "params": [], "return": { "description": "", "type": "Number" } } ] }, { "file": "src/typography/attributes.js", "line": 151, "description": "Sets the font size when\ntext() is called.
\nNote: Font size is measured in pixels.
\nCalling textSize()
without an arugment returns the current size.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Top.\n textSize(12);\n text('Font Size 12', 10, 30);\n\n // Middle.\n textSize(14);\n text('Font Size 14', 10, 60);\n\n // Bottom.\n textSize(16);\n text('Font Size 16', 10, 90);\n\n describe('The text \"Font Size 12\" drawn small, \"Font Size 14\" drawn medium, and \"Font Size 16\" drawn large.');\n}\n
\nsize of the letters in units of pixels.
\n", "type": "Number" } ], "chainable": 1 }, { "line": 188, "params": [], "return": { "description": "", "type": "Number" } } ] }, { "file": "src/typography/attributes.js", "line": 197, "description": "Sets the style for system fonts when\ntext() is called.
\nThe parameter, style
, can be either NORMAL
, ITALIC
, BOLD
, or\nBOLDITALIC
.
textStyle()
may be overridden by CSS styling. This function doesn't\naffect fonts loaded with loadFont().
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textSize(12);\n textAlign(CENTER);\n\n // First row.\n textStyle(NORMAL);\n text('Normal', 50, 15);\n\n // Second row.\n textStyle(ITALIC);\n text('Italic', 50, 40);\n\n // Third row.\n textStyle(BOLD);\n text('Bold', 50, 65);\n\n // Fourth row.\n textStyle(BOLDITALIC);\n text('Bold Italic', 50, 90);\n\n describe('The words \"Normal\" displayed normally, \"Italic\" in italic, \"Bold\" in bold, and \"Bold Italic\" in bold italics.');\n}\n
\nstyling for text, either NORMAL,\n ITALIC, BOLD or BOLDITALIC.
\n", "type": "Constant" } ], "chainable": 1 }, { "line": 244, "params": [], "return": { "description": "", "type": "String" } } ] }, { "file": "src/typography/attributes.js", "line": 253, "description": "Calculates the maximum width of a string of text drawn when\ntext() is called.
\n", "itemtype": "method", "name": "textWidth", "params": [ { "name": "str", "description": "string of text to measure.
\n", "type": "String" } ], "return": { "description": "width measured in units of pixels.", "type": "Number" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textSize(28);\n strokeWeight(0.5);\n\n // Calculate the text width.\n let s = 'yoyo';\n let w = textWidth(s);\n\n // Display the text.\n text(s, 22, 55);\n\n // Underline the text.\n line(22, 55, 22 + w, 55);\n\n describe('The word \"yoyo\" underlined.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textSize(28);\n strokeWeight(0.5);\n\n // Calculate the text width.\n // \"\\n\" starts a new line.\n let s = 'yo\\nyo';\n let w = textWidth(s);\n\n // Display the text.\n text(s, 22, 55);\n\n // Underline the text.\n line(22, 55, 22 + w, 55);\n\n describe('The word \"yo\" written twice, one copy beneath the other. The words are divided by a horizontal line.');\n}\n
\nCalculates the ascent of the current font at its current size.
\nThe ascent represents the distance, in pixels, of the tallest character\nabove the baseline.
\n", "itemtype": "method", "name": "textAscent", "return": { "description": "ascent measured in units of pixels.", "type": "Number" }, "example": [ "\n\nlet font;\n\nfunction preload() {\n font = loadFont('assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textFont(font);\n\n // Different for each font.\n let fontScale = 0.8;\n\n let baseY = 75;\n strokeWeight(0.5);\n\n // Draw small text.\n textSize(24);\n text('dp', 0, baseY);\n\n // Draw baseline and ascent.\n let a = textAscent() * fontScale;\n line(0, baseY, 23, baseY);\n line(23, baseY - a, 23, baseY);\n\n // Draw large text.\n textSize(48);\n text('dp', 45, baseY);\n\n // Draw baseline and ascent.\n a = textAscent() * fontScale;\n line(45, baseY, 91, baseY);\n line(91, baseY - a, 91, baseY);\n\n describe('The letters \"dp\" written twice in different sizes. Each version has a horizontal baseline. A vertical line extends upward from each baseline to the top of the \"d\".');\n}\n
\nCalculates the descent of the current font at its current size.
\nThe descent represents the distance, in pixels, of the character with the\nlongest descender below the baseline.
\n", "itemtype": "method", "name": "textDescent", "return": { "description": "descent measured in units of pixels.", "type": "Number" }, "example": [ "\n\nlet font;\n\nfunction preload() {\n font = loadFont('assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the font.\n textFont(font);\n\n // Different for each font.\n let fontScale = 0.9;\n\n let baseY = 75;\n strokeWeight(0.5);\n\n // Draw small text.\n textSize(24);\n text('dp', 0, baseY);\n\n // Draw baseline and descent.\n let d = textDescent() * fontScale;\n line(0, baseY, 23, baseY);\n line(23, baseY, 23, baseY + d);\n\n // Draw large text.\n textSize(48);\n text('dp', 45, baseY);\n\n // Draw baseline and descent.\n d = textDescent() * fontScale;\n line(45, baseY, 91, baseY);\n line(91, baseY, 91, baseY + d);\n\n describe('The letters \"dp\" written twice in different sizes. Each version has a horizontal baseline. A vertical line extends downward from each baseline to the bottom of the \"p\".');\n}\n
\nHelper function to measure ascent and descent.
\n", "class": "p5", "module": "Typography", "submodule": "Attributes" }, { "file": "src/typography/attributes.js", "line": 462, "description": "Sets the style for wrapping text when\ntext() is called.
\nThe parameter, style
, can be one of the following values:
WORD
starts new lines of text at spaces. If a string of text doesn't\nhave spaces, it may overflow the text box and the canvas. This is the\ndefault style.
CHAR
starts new lines as needed to stay within the text box.
textWrap()
only works when the maximum width is set for a text box. For\nexample, calling text('Have a wonderful day', 0, 10, 100)
sets the\nmaximum width to 100 pixels.
Calling textWrap()
without an argument returns the current style.
text wrapping style, either WORD or CHAR.
\n", "type": "Constant" } ], "return": { "description": "style", "type": "String" }, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textSize(20);\n textWrap(WORD);\n\n // Display the text.\n text('Have a wonderful day', 0, 10, 100);\n\n describe('The text \"Have a wonderful day\" written across three lines.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textSize(20);\n textWrap(CHAR);\n\n // Display the text.\n text('Have a wonderful day', 0, 10, 100);\n\n describe('The text \"Have a wonderful day\" written across two lines.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textSize(20);\n textWrap(CHAR);\n\n // Display the text.\n text('祝你有美好的一天', 0, 10, 100);\n\n describe('The text \"祝你有美好的一天\" written across two lines.');\n}\n
\nLoads a font and creates a p5.Font object.\nloadFont()
can load fonts in either .otf or .ttf format. Loaded fonts can\nbe used to style text on the canvas and in HTML elements.
The first parameter, path
, is the path to a font file.\nPaths to local files should be relative. For example,\n'assets/inconsolata.otf'
. The Inconsolata font used in the following\nexamples can be downloaded for free\nhere.\nPaths to remote files should be URLs. For example,\n'https://example.com/inconsolata.otf'
. URLs may be blocked due to browser\nsecurity.
The second parameter, successCallback
, is optional. If a function is\npassed, it will be called once the font has loaded. The callback function\nmay use the new p5.Font object if needed.
The third parameter, failureCallback
, is also optional. If a function is\npassed, it will be called if the font fails to load. The callback function\nmay use the error\nEvent\nobject if needed.
Fonts can take time to load. Calling loadFont()
in\npreload() ensures fonts load before they're\nused in setup() or\ndraw().
path of the font to be loaded.
\n", "type": "String" }, { "name": "successCallback", "description": "function called with the\n p5.Font object after it\n loads.
\n", "type": "Function", "optional": true }, { "name": "failureCallback", "description": "function called with the error\n Event\n object if the font fails to load.
\n", "type": "Function", "optional": true } ], "return": { "description": "p5.Font object.", "type": "p5.Font" }, "example": [ "\n\n\nlet font;\n\nfunction preload() {\n font = loadFont('assets/inconsolata.otf');\n}\n\nfunction setup() {\n fill('deeppink');\n textFont(font);\n textSize(36);\n text('p5*js', 10, 50);\n\n describe('The text \"p5*js\" written in pink on a white background.');\n}\n
\n\nfunction setup() {\n loadFont('assets/inconsolata.otf', font => {\n fill('deeppink');\n textFont(font);\n textSize(36);\n text('p5*js', 10, 50);\n\n describe('The text \"p5*js\" written in pink on a white background.');\n });\n}\n
\n\nfunction setup() {\n loadFont('assets/inconsolata.otf', success, failure);\n}\n\nfunction success(font) {\n fill('deeppink');\n textFont(font);\n textSize(36);\n text('p5*js', 10, 50);\n\n describe('The text \"p5*js\" written in pink on a white background.');\n}\n\nfunction failure(event) {\n console.error('Oops!', event);\n}\n
\n\nfunction preload() {\n loadFont('assets/inconsolata.otf');\n}\n\nfunction setup() {\n let p = createP('p5*js');\n p.style('color', 'deeppink');\n p.style('font-family', 'Inconsolata');\n p.style('font-size', '36px');\n p.position(10, 50);\n\n describe('The text \"p5*js\" written in pink on a white background.');\n}\n
\nDraws text to the canvas.
\nThe first parameter, str
, is the text to be drawn. The second and third\nparameters, x
and y
, set the coordinates of the text's bottom-left\ncorner. See textAlign() for other ways to\nalign text.
The fourth and fifth parameters, maxWidth
and maxHeight
, are optional.\nThey set the dimensions of the invisible rectangle containing the text. By\ndefault, they set its maximum width and height. See\nrectMode() for other ways to define the\nrectangular text box. Text will wrap to fit within the text box. Text\noutside of the box won't be drawn.
Text can be styled a few ways. Call the fill()\nfunction to set the text's fill color. Call\nstroke() and\nstrokeWeight() to set the text's outline.\nCall textSize() and\ntextFont() to set the text's size and font,\nrespectively.
\nNote: WEBGL
mode only supports fonts loaded with\nloadFont(). Calling\nstroke() has no effect in WEBGL
mode.
text to be displayed.
\n", "type": "String|Object|Array|Number|Boolean" }, { "name": "x", "description": "x-coordinate of the text box.
\n", "type": "Number" }, { "name": "y", "description": "y-coordinate of the text box.
\n", "type": "Number" }, { "name": "maxWidth", "description": "maximum width of the text box. See\n rectMode() for\n other options.
\n", "type": "Number", "optional": true }, { "name": "maxHeight", "description": "maximum height of the text box. See\n rectMode() for\n other options.
\n", "type": "Number", "optional": true } ], "chainable": 1, "example": [ "\n\nfunction setup() {\n background(200);\n text('hi', 50, 50);\n\n describe('The text \"hi\" written in black in the middle of a gray square.');\n}\n
\n\nfunction setup() {\n background('skyblue');\n textSize(100);\n text('🌈', 0, 100);\n\n describe('A rainbow in a blue sky.');\n}\n
\n\nfunction setup() {\n textSize(32);\n fill(255);\n stroke(0);\n strokeWeight(4);\n text('hi', 50, 50);\n\n describe('The text \"hi\" written in white with a black outline.');\n}\n
\n\nfunction setup() {\n background('black');\n textSize(22);\n fill('yellow');\n text('rainbows', 6, 20);\n fill('cornflowerblue');\n text('rainbows', 6, 45);\n fill('tomato');\n text('rainbows', 6, 70);\n fill('limegreen');\n text('rainbows', 6, 95);\n\n describe('The text \"rainbows\" written on several lines, each in a different color.');\n}\n
\n\nfunction setup() {\n background(200);\n let s = 'The quick brown fox jumps over the lazy dog.';\n text(s, 10, 10, 70, 80);\n\n describe('The sample text \"The quick brown fox...\" written in black across several lines.');\n}\n
\n\nfunction setup() {\n background(200);\n rectMode(CENTER);\n let s = 'The quick brown fox jumps over the lazy dog.';\n text(s, 50, 50, 70, 80);\n\n describe('The sample text \"The quick brown fox...\" written in black across several lines.');\n}\n
\n\nlet font;\n\nfunction preload() {\n font = loadFont('assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n textFont(font);\n textSize(32);\n textAlign(CENTER, CENTER);\n}\n\nfunction draw() {\n background(0);\n rotateY(frameCount / 30);\n text('p5*js', 0, 0);\n\n describe('The text \"p5*js\" written in white and spinning in 3D.');\n}\n
\nSets the font used by the text() function.
\nThe first parameter, font
, sets the font. textFont()
recognizes either\na p5.Font object or a string with the name of a\nsystem font. For example, 'Courier New'
.
The second parameter, size
, is optional. It sets the font size in pixels.\nThis has the same effect as calling textSize().
Note: WEBGL
mode only supports fonts loaded with\nloadFont().
\nfunction setup() {\n background(200);\n textFont('Courier New');\n textSize(24);\n text('hi', 35, 55);\n\n describe('The text \"hi\" written in a black, monospace font on a gray background.');\n}\n
\n\nfunction setup() {\n background('black');\n fill('palegreen');\n textFont('Courier New', 10);\n text('You turn to the left and see a door. Do you enter?', 5, 5, 90, 90);\n text('>', 5, 70);\n\n describe('A text prompt from a game is written in a green, monospace font on a black background.');\n}\n
\n\nfunction setup() {\n background(200);\n textFont('Verdana');\n let currentFont = textFont();\n text(currentFont, 25, 50);\n\n describe('The text \"Verdana\" written in a black, sans-serif font on a gray background.');\n}\n
\n\nlet fontRegular;\nlet fontItalic;\nlet fontBold;\n\nfunction preload() {\n fontRegular = loadFont('assets/Regular.otf');\n fontItalic = loadFont('assets/Italic.ttf');\n fontBold = loadFont('assets/Bold.ttf');\n}\n\nfunction setup() {\n background(200);\n textFont(fontRegular);\n text('I am Normal', 10, 30);\n textFont(fontItalic);\n text('I am Italic', 10, 50);\n textFont(fontBold);\n text('I am Bold', 10, 70);\n\n describe('The statements \"I am Normal\", \"I am Italic\", and \"I am Bold\" written in black on separate lines. The statements have normal, italic, and bold fonts, respectively.');\n}\n
\nfont as a p5.Font object or a string.
\n", "type": "Object|String" }, { "name": "size", "description": "font size in pixels.
\n", "type": "Number", "optional": true } ], "chainable": 1 } ] }, { "file": "src/typography/p5.Font.js", "line": 51, "description": "The font's underlying\nopentype.js\nfont object.
\n", "itemtype": "property", "name": "font", "class": "p5.Font", "module": "Typography", "submodule": "Loading & Displaying" }, { "file": "src/typography/p5.Font.js", "line": 62, "description": "Returns the bounding box for a string of text written using the font.
\nThe bounding box is the smallest rectangle that can contain a string of\ntext. font.textBounds()
returns an object with the bounding box's\nlocation and size. For example, calling font.textBounds('p5*js', 5, 20)
\nreturns an object in the format\n{ x: 5.7, y: 12.1 , w: 9.9, h: 28.6 }
. The x
and y
properties are\nalways the coordinates of the bounding box's top-left corner.
The first parameter, str
, is a string of text. The second and third\nparameters, x
and y
, are the text's position. By default, they set the\ncoordinates of the bounding box's bottom-left corner. See\ntextAlign() for more ways to align text.
The fourth parameter, fontSize
, is optional. It sets the font size used to\ndetermine the bounding box. By default, font.textBounds()
will use the\ncurrent textSize().
string of text.
\n", "type": "String" }, { "name": "x", "description": "x-coordinate of the text.
\n", "type": "Number" }, { "name": "y", "description": "y-coordinate of the text.
\n", "type": "Number" }, { "name": "fontSize", "description": "font size. Defaults to the current\n textSize().
\n", "type": "Number", "optional": true } ], "return": { "description": "object describing the bounding box with\n properties x, y, w, and h.", "type": "Object" }, "example": [ "\n\nlet font;\n\nfunction preload() {\n font = loadFont('assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Display the bounding box.\n let bbox = font.textBounds('p5*js', 35, 53);\n rect(bbox.x, bbox.y, bbox.w, bbox.h);\n\n // Style the text.\n textFont(font);\n\n // Display the text.\n text('p5*js', 35, 53);\n\n describe('The text \"p5*js\" written in black inside a white rectangle.');\n}\n
\n\nlet font;\n\nfunction preload() {\n font = loadFont('assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textFont(font);\n textSize(15);\n textAlign(CENTER, CENTER);\n\n // Display the bounding box.\n let bbox = font.textBounds('p5*js', 50, 50);\n rect(bbox.x, bbox.y, bbox.w, bbox.h);\n\n // Display the text.\n text('p5*js', 50, 50);\n\n describe('The text \"p5*js\" written in black inside a white rectangle.');\n}\n
\n\nlet font;\n\nfunction preload() {\n font = loadFont('assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Display the bounding box.\n let bbox = font.textBounds('p5*js', 31, 53, 15);\n rect(bbox.x, bbox.y, bbox.w, bbox.h);\n\n // Style the text.\n textFont(font);\n textSize(15);\n\n // Display the text.\n text('p5*js', 31, 53);\n\n describe('The text \"p5*js\" written in black inside a white rectangle.');\n}\n
\nReturns an array of points outlining a string of text written using the\nfont.
\nEach point object in the array has three properties that describe the\npoint's location and orientation, called its path angle. For example,\n{ x: 10, y: 20, alpha: 450 }
.
The first parameter, str
, is a string of text. The second and third\nparameters, x
and y
, are the text's position. By default, they set the\ncoordinates of the bounding box's bottom-left corner. See\ntextAlign() for more ways to align text.
The fourth parameter, fontSize
, is optional. It sets the text's font\nsize. By default, font.textToPoints()
will use the current\ntextSize().
The fifth parameter, options
, is also optional. font.textToPoints()
\nexpects an object with the following properties:
sampleFactor
is the ratio of the text's path length to the number of\nsamples. It defaults to 0.1. Higher values produce more points along the\npath and are more precise.
simplifyThreshold
removes collinear points if it's set to a number other\nthan 0. The value represents the threshold angle to use when determining\nwhether two edges are collinear.
string of text.
\n", "type": "String" }, { "name": "x", "description": "x-coordinate of the text.
\n", "type": "Number" }, { "name": "y", "description": "y-coordinate of the text.
\n", "type": "Number" }, { "name": "fontSize", "description": "font size. Defaults to the current\n textSize().
\n", "type": "Number", "optional": true }, { "name": "options", "description": "object with sampleFactor and simplifyThreshold\n properties.
\n", "type": "Object", "optional": true } ], "return": { "description": "array of point objects, each with x, y, and alpha (path angle) properties.", "type": "Array" }, "example": [ "\n\nlet font;\n\nfunction preload() {\n font = loadFont('assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the point array.\n let points = font.textToPoints('p5*js', 6, 60, 35, { sampleFactor: 0.5 });\n\n // Draw a dot at each point.\n for (let p of points) {\n point(p.x, p.y);\n }\n\n describe('A set of black dots outlining the text \"p5*js\" on a gray background.');\n}\n
\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);\ndescribe('20-by-20 white ellipse in the center of the canvas');\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": 64, "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": 86, "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": 166, "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": 180, "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": 199, "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": 214, "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": 230, "params": [ { "name": "ns", "description": "values to parse
\n", "type": "Array" } ], "return": { "description": "integer representation of values", "type": "Number[]" } } ] }, { "file": "src/utilities/conversion.js", "line": 243, "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": 263, "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": 293, "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": 309, "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);\ndescribe('“Hello world!” displayed middle left of canvas.');\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);\ndescribe('“p5js*” displayed middle left of canvas.');\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 describe('“0321.00” middle top, “-1321.00” middle bottom canvas');\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": 171, "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": 216, "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 describe('“11,253,106.115” top middle and “1.00,1.00,2.00” displayed bottom mid');\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": 253, "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": 289, "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 describe('“+11253106.11” top middle and “-11253106.11” displayed bottom middle');\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": 329, "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": 350, "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 describe('“0321.00” top middle and “-1321.00” displayed bottom middle');\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": 406, "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": 427, "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);\ndescribe('“Pat” top left, “Xio” mid left, and “Alex” displayed bottom left');\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);\ndescribe('“No new lines here” displayed center canvas');\n
\na String to be trimmed
\n", "type": "String" } ], "return": { "description": "a trimmed String", "type": "String" } }, { "line": 529, "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);\ndescribe('Current day is displayed');\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);\ndescribe('Current hour is displayed');\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);\ndescribe('Current minute is displayed');\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);\ndescribe('number of milliseconds since sketch has started displayed');\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);\ndescribe('Current month is displayed');\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);\ndescribe('Current second is displayed');\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);\ndescribe('Current year is displayed');\n
\nStarts creating a new p5.Geometry. Subsequent shapes drawn will be added\nto the geometry and then returned when\nendGeometry() is called. One can also use\nbuildGeometry() to pass a function that\ndraws shapes.
\nIf you need to draw complex shapes every frame which don't change over time,\ncombining them upfront with beginGeometry()
and endGeometry()
and then\ndrawing that will run faster than repeatedly drawing the individual pieces.
\nlet shapes;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n makeShapes();\n}\n\nfunction makeShapes() {\n beginGeometry();\n scale(0.18);\n\n push();\n translate(100, -50);\n scale(0.5);\n rotateX(PI/4);\n cone();\n pop();\n cone();\n\n beginShape();\n vertex(-20, -50);\n quadraticVertex(\n -40, -70,\n 0, -60\n );\n endShape();\n\n beginShape(TRIANGLE_STRIP);\n for (let y = 20; y <= 60; y += 10) {\n for (let x of [20, 60]) {\n vertex(x, y);\n }\n }\n endShape();\n\n beginShape();\n vertex(-100, -120);\n vertex(-120, -110);\n vertex(-105, -100);\n endShape();\n\n shapes = endGeometry();\n}\n\nfunction draw() {\n background(255);\n lights();\n orbitControl();\n model(shapes);\n}\n
\nFinishes creating a new p5.Geometry that was\nstarted using beginGeometry(). One can also\nuse buildGeometry() to pass a function that\ndraws shapes.
\n", "itemtype": "method", "name": "endGeometry", "return": { "description": "The model that was built.", "type": "p5.Geometry" }, "class": "p5", "module": "Shape", "submodule": "3D Primitives" }, { "file": "src/webgl/3d_primitives.js", "line": 102, "description": "Creates a new p5.Geometry that contains all\nthe shapes drawn in a provided callback function. The returned combined shape\ncan then be drawn all at once using model().
\nIf you need to draw complex shapes every frame which don't change over time,\ncombining them with buildGeometry()
once and then drawing that will run\nfaster than repeatedly drawing the individual pieces.
One can also draw shapes directly between\nbeginGeometry() and\nendGeometry() instead of using a callback\nfunction.
\n", "itemtype": "method", "name": "buildGeometry", "params": [ { "name": "callback", "description": "A function that draws shapes.
\n", "type": "Function" } ], "return": { "description": "The model that was built from the callback function.", "type": "p5.Geometry" }, "example": [ "\n\nlet particles;\nlet button;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n button = createButton('New');\n button.mousePressed(makeParticles);\n makeParticles();\n}\n\nfunction makeParticles() {\n if (particles) freeGeometry(particles);\n\n particles = buildGeometry(() => {\n for (let i = 0; i < 60; i++) {\n push();\n translate(\n randomGaussian(0, 20),\n randomGaussian(0, 20),\n randomGaussian(0, 20)\n );\n sphere(5);\n pop();\n }\n });\n}\n\nfunction draw() {\n background(255);\n noStroke();\n lights();\n orbitControl();\n model(particles);\n}\n
\nClears the resources of a model to free up browser memory. A model whose\nresources have been cleared can still be drawn, but the first time it is\ndrawn again, it might take longer.
\nThis method works on models generated with\nbuildGeometry() as well as those loaded\nfrom loadModel().
\n", "itemtype": "method", "name": "freeGeometry", "params": [ { "name": "geometry", "description": "The geometry whose resources should be freed
\n", "type": "p5.Geometry" } ], "class": "p5", "module": "Shape", "submodule": "3D Primitives" }, { "file": "src/webgl/3d_primitives.js", "line": 183, "description": "Draw 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 camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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 camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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 camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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 camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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
\nAdds geometry from the renderer's immediate mode into the builder's\ncombined geometry.
\n", "class": "p5", "module": "Shape" }, { "file": "src/webgl/GeometryBuilder.js", "line": 114, "description": "Adds geometry from the renderer's retained mode into the builder's\ncombined geometry.
\n", "class": "p5", "module": "Shape" }, { "file": "src/webgl/GeometryBuilder.js", "line": 122, "description": "Cleans up the state of the renderer and returns the combined geometry that\nwas built.
\n", "return": { "description": "p5.Geometry The flattened, combined geometry" }, "class": "p5", "module": "Shape" }, { "file": "src/webgl/GeometryBuilder.js", "line": 133, "description": "Keeps track of how many custom geometry objects have been made so that each\ncan be assigned a unique ID.
\n", "class": "p5", "module": "Shape" }, { "file": "src/webgl/interaction.js", "line": 11, "description": "Allows movement around a 3D sketch using a mouse or trackpad or touch.\nLeft-clicking and dragging or swipe motion will rotate the camera position\nabout the center of the sketch, right-clicking and dragging or multi-swipe\nwill pan the camera position without rotation, and using the mouse wheel\n(scrolling) or pinch in/out will move the camera further or closer\nfrom the center of the sketch. This function can be called with parameters\ndictating sensitivity to mouse/touch movement along the X and Y axes.\nCalling this function without parameters is equivalent to calling\norbitControl(1,1). To reverse direction of movement in either axis,\nenter a negative number for 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 }, { "name": "options", "description": "An optional object that can contain additional settings,\ndisableTouchActions - Boolean, default value is true.\nSetting this to true makes mobile interactions smoother by preventing\naccidental interactions with the page while orbiting. But if you're already\ndoing it via css or want the default touch actions, consider setting it to false.\nfreeRotation - Boolean, default value is false.\nBy default, horizontal movement of the mouse or touch pointer rotates the camera\naround the y-axis, and vertical movement rotates the camera around the x-axis.\nBut if setting this option to true, the camera always rotates in the direction\nthe pointer is moving. For zoom and move, the behavior is the same regardless of\ntrue/false.
\n", "type": "Object", "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 camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\n}\nfunction draw() {\n background(200);\n\n // If you execute the line commented out instead of next line, the direction of rotation\n // will be the direction the mouse or touch pointer moves, not around the X or Y axis.\n orbitControl();\n // orbitControl(1, 1, 1, {freeRotation: true});\n\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 perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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 perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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 perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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 perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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 perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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": 532, "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": 542, "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": 551, "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": 602, "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 perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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
\n\nfunction setup() {\n createCanvas(100,100,WEBGL);\n camera(0,-100,300);\n}\nfunction draw() {\n background(230);\n ambientMaterial(237,34,93); //Pink Material\n ambientLight(mouseY);\n //As you move the mouse up to down it changes from no ambient light to full ambient light.\n rotateY(millis()/2000);\n box(100);\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": 92, "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": 100, "params": [ { "name": "value", "description": "a color string
\n", "type": "String" } ], "chainable": 1 }, { "line": 106, "params": [ { "name": "values", "description": "an array containing the red,green,blue &\n and alpha components of the color
\n", "type": "Number[]" } ], "chainable": 1 }, { "line": 113, "params": [ { "name": "color", "description": "color as a p5.Color
\n", "type": "p5.Color" } ], "chainable": 1 } ] }, { "file": "src/webgl/light.js", "line": 134, "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": 207, "params": [ { "name": "gray", "description": "number specifying value between\n white and black
\n", "type": "Number" } ], "chainable": 1 }, { "line": 214, "params": [ { "name": "value", "description": "color as a CSS string
\n", "type": "String" } ], "chainable": 1 }, { "line": 220, "params": [ { "name": "values", "description": "color as an array containing the\n red, green, and blue components
\n", "type": "Number[]" } ], "chainable": 1 }, { "line": 227, "params": [ { "name": "color", "description": "color as a p5.Color
\n", "type": "p5.Color" } ], "chainable": 1 } ] }, { "file": "src/webgl/light.js", "line": 246, "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": 304, "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": 314, "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": 324, "params": [ { "name": "color", "description": "", "type": "p5.Color|Number[]|String" }, { "name": "direction", "description": "", "type": "p5.Vector" } ], "chainable": 1 } ] }, { "file": "src/webgl/light.js", "line": 373, "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": 432, "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": 441, "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": 451, "params": [ { "name": "color", "description": "", "type": "p5.Color|Number[]|String" }, { "name": "position", "description": "", "type": "p5.Vector" } ], "chainable": 1 } ] }, { "file": "src/webgl/light.js", "line": 497, "description": "Creates an image light with the given image.
\nThe image light simulates light from all the directions.\nThis is done by using the image as a texture for an infinitely\nlarge sphere light. This sphere contains\nor encapsulates the whole scene/drawing.\nIt will have different effect for varying shininess of the\nobject in the drawing.\nUnder the hood it is mainly doing 2 types of calculations,\nthe first one is creating an irradiance map the\nenvironment map of the input image.\nThe second one is managing reflections based on the shininess\nor roughness of the material used in the scene.
\nNote: The image's diffuse light will be affected by fill()\nand the specular reflections will be affected by specularMaterial()\nand shininess().
\n", "itemtype": "method", "name": "imageLight", "params": [ { "name": "img", "description": "image for the background
\n", "type": "p5.image" } ], "example": [ "\n\nlet img;\n\nfunction preload() {\n img = loadImage('assets/outdoor_image.jpg');\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n camera(0, 0, 50*sqrt(3), 0, 0, 0, 0 ,1, 0);\n perspective(PI/3, 1, 5, 500);\n}\nfunction draw() {\n background(220);\n\n push();\n camera(0, 0, 1, 0, 0, 0, 0, 1, 0);\n ortho(-1, 1, -1, 1, 0, 1);\n noLights();\n noStroke();\n texture(img);\n plane(2);\n pop();\n\n ambientLight(50);\n imageLight(img);\n specularMaterial(20);\n noStroke();\n rotateX(frameCount * 0.005);\n rotateY(frameCount * 0.005);\n box(50);\n}\n
\n\nlet img;\nlet slider;\n\nfunction preload() {\n img = loadImage('assets/outdoor_spheremap.jpg');\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n slider = createSlider(0, 400, 100, 1);\n slider.position(0, height);\n camera(0, 0, 50*sqrt(3), 0, 0, 0, 0 ,1, 0);\n perspective(PI/3, 1, 5, 500);\n}\nfunction draw() {\n background(220);\n\n push();\n camera(0, 0, 1, 0, 0, 0, 0, 1, 0);\n ortho(-1, 1, -1, 1, 0, 1);\n noLights();\n noStroke();\n texture(img);\n plane(2);\n pop();\n\n ambientLight(50);\n imageLight(img);\n specularMaterial(20);\n shininess(slider.value());\n noStroke();\n sphere(30);\n}\n
\nThe panorama(img)
method transforms images containing\n360-degree content, such as maps or HDRIs, into immersive\n3D backgrounds that surround your scene. This is similar to calling\nbackground(color)
; call panorama(img)
before drawing your\nscene to create a 360-degree background from your image. It\noperates on the concept of sphere mapping, where the image is\nmapped onto an infinitely large sphere based on the angles of the\ncamera.
To enable 360-degree viewing, either use orbitControl()
or try changing\nthe orientation of the camera to see different parts of the background.
A 360-degree image to use as a background panorama
\n", "type": "p5.Image" } ], "example": [ "\n\nlet img;\nfunction preload() {\n img = loadImage('assets/outdoor_spheremap.jpg');\n}\nfunction setup() {\n createCanvas(100 ,100 ,WEBGL);\n}\nfunction draw() {\n panorama(img);\n imageMode(CENTER);\n orbitControl();\n noStroke();\n push();\n imageLight(img);\n specularMaterial('green');\n shininess(200);\n metalness(100);\n sphere(25);\n pop();\n}\n
\nPlaces an ambient and directional light in the scene.\nThe lights are set to ambientLight(128, 128, 128) and\ndirectionalLight(128, 128, 128, 0, 0, -1).
\nNote: lights need to be called (whether directly or indirectly)\nwithin draw() to remain persistent in a looping program.\nPlacing them in setup() will cause them to only have an effect\nthe first time through the loop.
\n", "itemtype": "method", "name": "lights", "chainable": 1, "example": [ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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 background(125);\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": 867, "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": 876, "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": 886, "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": 896, "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": 906, "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": 918, "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": 930, "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": 1155, "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.
\nOptions can include:
\npath
: Specifies the location or path of the 3D model file for loading.normalize
: Enables standardized size scaling during loading if set to true.successCallback
: Callback for post-loading actions with the 3D model object.failureCallback
: Handles errors if model loading fails, receiving an event error.fileType
: Defines the file extension of the model.flipU
: Flips the U texture coordinates of the model.flipV
: Flips the V texture coordinates of the model.\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": 477, "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": 504, "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": 631, "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().
\nShaders can alter the positioning of shapes drawn with them.\nTo ensure consistency in rendering, it's recommended to use the vertex shader in the createShader example.
\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.
\nShaders can alter the positioning of shapes drawn with them.\nTo ensure consistency in rendering, it's recommended to use the vertex shader shown in the example below.
\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\n// the vertex shader is called for each vertex\nlet vs = `\nprecision highp float;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n }\n`;\n\n\n// the fragment shader is called for each pixel\nlet fs = `\n precision highp float;\n uniform vec2 p;\n uniform float r;\n const int I = 500;\n varying vec2 vTexCoord;\n void main() {\n vec2 c = p + gl_FragCoord.xy * 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 plane(width, height);\n}\n
\nCreates a new p5.Shader using only a fragment shader, as a convenience method for creating image effects.\nIt's like createShader() but with a default vertex shader included.
\ncreateFilterShader() is intended to be used along with filter() for filtering the contents of a canvas.\nA filter shader will not be applied to any geometries.
\nThe fragment shader receives some uniforms:
\nsampler2D tex0
, which contains the canvas contents as a texturevec2 canvasSize
, which is the p5 width and height of the canvas (not including pixel density)vec2 texelSize
, which is the size of a physical pixel including pixel density (1.0/(width*density)
, 1.0/(height*density)
)For more info about filters and shaders, see Adam Ferriss' repo of shader examples\nor the introduction to shaders page.
\n", "itemtype": "method", "name": "createFilterShader", "params": [ { "name": "fragSrc", "description": "source code for the fragment shader
\n", "type": "String" } ], "return": { "description": "a shader object created from the provided\n fragment shader.", "type": "p5.Shader" }, "example": [ "\n\nfunction setup() {\n let fragSrc = `precision highp float;\n void main() {\n gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0);\n }`;\n\n createCanvas(100, 100, WEBGL);\n let s = createFilterShader(fragSrc);\n filter(s);\n describe('a yellow canvas');\n}\n
\n\nlet img, s;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n let fragSrc = `precision highp float;\n\n // x,y coordinates, given from the vertex shader\n varying vec2 vTexCoord;\n\n // the canvas contents, given from filter()\n uniform sampler2D tex0;\n // other useful information from the canvas\n uniform vec2 texelSize;\n uniform vec2 canvasSize;\n // a custom variable from this sketch\n uniform float darkness;\n\n void main() {\n // get the color at current pixel\n vec4 color = texture2D(tex0, vTexCoord);\n // set the output color\n color.b = 1.0;\n color *= darkness;\n gl_FragColor = vec4(color.rgb, 1.0);\n }`;\n\n createCanvas(100, 100, WEBGL);\n s = createFilterShader(fragSrc);\n}\nfunction draw() {\n image(img, -50, -50);\n s.setUniform('darkness', 0.5);\n filter(s);\n describe('a image of bricks tinted dark blue');\n}\n
\nSets the p5.Shader object to\nbe used to render subsequent shapes.
\nShaders can alter the positioning of shapes drawn with them.\nTo ensure consistency in rendering, it's recommended to use the vertex shader in the createShader example.
\nCustom shaders can be created using the\ncreateShader() and\nloadShader() functions.
\nUse resetShader() to\nrestore the default shaders.
\nAdditional Information:\nThe shader will be used for:
\nsampler2D
.aNormal
, or if it has any of the following uniforms: uUseLighting
, uAmbientLightCount
, uDirectionalLightCount
, uPointLightCount
, uAmbientColor
, uDirectionalDiffuseColors
, uDirectionalSpecularColors
, uPointLightLocation
, uPointLightDiffuseColors
, uPointLightSpecularColors
, uLightingDirection
, or uSpecular
.uStrokeWeight
.\nNote: This behavior is considered experimental, and changes are planned in future releases.Note, 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|p5.Framebuffer|p5.FramebufferTexture" } ], "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 represents the components\nof the ambientLight() color that the object reflects.
\nConsider an ambientMaterial() with the color yellow (255, 255, 0).\nIf the ambientLight() 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 ambientLight() 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 ambientLight() 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": 955, "params": [ { "name": "gray", "description": "number specifying value between\n white and black
\n", "type": "Number" } ], "chainable": 1 }, { "line": 962, "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": 982, "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": 1026, "params": [ { "name": "gray", "description": "number specifying value between\n white and black
\n", "type": "Number" } ], "chainable": 1 }, { "line": 1033, "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": 1053, "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": 1107, "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": 1119, "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": 1139, "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 metalness property of a material used in 3D rendering.
\nThe metalness property controls the degree to which the material\nappears metallic. A higher metalness value makes the material look\nmore metallic, while a lower value makes it appear less metallic.
\nThe default and minimum value is 0, indicating a non-metallic appearance.
\nUnlike other materials, metals exclusively rely on reflections, particularly\nthose produced by specular lights (mirrorLike lights). They don't incorporate\ndiffuse or ambient lighting. Metals use a fill color to influence the overall\ncolor of their reflections. Pick a fill color, and you can easily change the\nappearance of the metal surfaces. When no fill color is provided, it defaults\nto using white.
\n", "itemtype": "method", "name": "metalness", "params": [ { "name": "metallic", "description": "\nlet img;\nlet slider;\nlet slider2;\nfunction preload() {\n img = loadImage('assets/outdoor_spheremap.jpg');\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n slider = createSlider(0, 300, 100, 1);\n let sliderLabel = createP('Metalness');\n sliderLabel.position(100, height - 25);\n slider2 = createSlider(0, 350, 100);\n slider2.position(0, height + 20);\n slider2Label = createP('Shininess');\n slider2Label.position(100, height);\n}\nfunction draw() {\n background(220);\n imageMode(CENTER);\n push();\n image(img, 0, 0, width, height);\n clearDepth();\n pop();\n imageLight(img);\n fill('gray');\n specularMaterial('gray');\n shininess(slider2.value());\n metalness(slider.value());\n noStroke();\n sphere(30);\n}\n
\n\nlet slider;\nlet slider2;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n slider = createSlider(0, 200, 100);\n let sliderLabel = createP('Metalness');\n sliderLabel.position(100, height - 25);\n slider2 = createSlider(0, 200, 2);\n slider2.position(0, height + 25);\n let slider2Label = createP('Shininess');\n slider2Label.position(100, height);\n}\nfunction draw() {\n noStroke();\n background(100);\n fill(255, 215, 0);\n pointLight(255, 255, 255, 5000, 5000, 75);\n specularMaterial('gray');\n ambientLight(100);\n shininess(slider2.value());\n metalness(slider.value());\n rotateY(frameCount * 0.01);\n torus(20, 10);\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, 800, 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 perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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 perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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 default values are used as:
\nfov
: The default field of view for the camera is such that the full height of renderer is visible when it is positioned at a default distance of 800 units from the camera.aspect
: The default aspect ratio is the ratio of renderer's width to renderer's height.near
: The default value for the near clipping plane is 80, which is 0.1 times the default distance from the camera to its subject.far
: The default value for the far clipping plane is 8000, which is 10 times the default distance from the camera to its subject.If you prefer a fixed field of view, follow these steps:
\nfovy
). This is how wide the camera can see.(height / 2) / tan(fovy / 2)
back from its subject.perspective(fovy, width / height, cameraDistance / 10, cameraDistance * 10);
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 camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\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) * 65);\n box(30);\n pop();\n push();\n translate(15, 0, sin(frameCount / 30 + PI) * 65);\n box(30);\n pop();\n}\n
\nEnable or disable perspective for lines in the WebGL renderer.\n The behavior of linePerspective()
is associated with the type of camera projection being used.
perspective()
, which simulates realistic perspective, linePerspective\n is set to true
by default. This means that lines will be affected by the current\n camera's perspective, resulting in a more natural appearance.ortho()
or frustum()
, which do not simulate realistic perspective,\n linePerspective is set to false
by default. In this case, lines will have a uniform\n scale regardless of the camera's perspective, providing a more predictable and\n consistent appearance.linePerspective()
after\n using perspective()
, ortho()
, or frustum()
. This allows you to customize the line\n perspective based on your specific requirements.\n function setup() {\n createCanvas(100, 100, WEBGL);\n setAttributes({ antialias: true });\n strokeWeight(3);\n describe(\n 'rotated 3D boxes have their stroke weights affected if toggled back and forth with mouse clicks.'\n );\n }\nfunction draw() {\n background(220);\n rotateY(PI/24);\n rotateZ(PI/8);\n translate(0, 0, 350);\n for (let i = 0; i < 12; i++) {\n translate(0, 0, -70);\n box(30);\n }\n }\nfunction mousePressed() {\n linePerspective(!linePerspective());\n }\n
\n \n function setup() {\n createCanvas(100, 100, WEBGL);\n strokeWeight(4);\n }\nfunction draw() {\n background(220);\n // Using orthographic projection\n ortho();\n // Enable line perspective explicitly\n linePerspective(true);\n // Draw a rotating cube\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(25);\n // Move to a new position\n translate(0, -60, 0);\n // Using perspective projection\n perspective();\n // Disable line perspective explicitly\n linePerspective(false);\n // Draw another rotating cube with perspective\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(25);\n }\n
\n true
to enable line perspective, false
to disable.Sets 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, 0, max(width, height) + 800).
\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();\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/20, width/20, height/20, -height/20, eyeZ/10, eyeZ*10),\nwhere eyeZ is equal to 800.
\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 camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\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 camera.camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n camera.perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\n describe('An example that creates a camera and moves it around the box.');\n}\n\nfunction draw() {\n background(0);\n // The camera will automatically\n // rotate to look at [0, 0, 0].\n camera.lookAt(0, 0, 0);\n\n // The camera will move on the\n // x axis.\n camera.setPosition(sin(frameCount / 60) * 200, 0, 100);\n box(20);\n\n // A 'ground' box to give the viewer\n // a better idea of where the camera\n // is looking.\n translate(0, 50, 0);\n rotateX(HALF_PI);\n box(150, 150, 20);\n}\n
camera position value on x axis. default value is 0
\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. default value is 0
\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. default value is 800
\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 cam.camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\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) * 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 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 cam.camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\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 cam.camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\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 cam.camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n cam.perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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 cam.camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n cam.perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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 cam.camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n cam.perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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 cam.perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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 cam.camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n cam.perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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 cam.camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n cam.perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\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
\nCopies information about the argument camera's view and projection to\nthe target camera. If the target camera is active, it will be reflected\non the screen.
\n", "itemtype": "method", "name": "set", "params": [ { "name": "cam", "description": "source camera
\n", "type": "p5.Camera" } ], "example": [ "\n\nlet cam, initialCam;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n strokeWeight(3);\n\n // Set the initial state to initialCamera and set it to the camera\n // used for drawing. Then set cam to be the active camera.\n cam = createCamera();\n cam.camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n cam.perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\n initialCam = createCamera();\n initialCam.camera(100, 100, 100, 0, 0, 0, 0, 0, -1);\n initialCam.perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\n cam.set(initialCam);\n\n setCamera(cam);\n}\n\nfunction draw() {\n orbitControl();\n background(255);\n box(50);\n translate(0, 0, -25);\n plane(100);\n}\n\nfunction doubleClicked(){\n // Double-click to return the camera to its initial position.\n cam.set(initialCam);\n}\n
\nFor the cameras cam0 and cam1 with the given arguments, their view are combined\nwith the parameter amt that represents the quantity, and the obtained view is applied.\nFor example, if cam0 is looking straight ahead and cam1 is looking straight\nto the right and amt is 0.5, the applied camera will look to the halfway\nbetween front and right.\nIf the applied camera is active, the applied result will be reflected on the screen.\nWhen applying this function, all cameras involved must have exactly the same projection\nsettings. For example, if one is perspective, ortho, frustum, the other two must also be\nperspective, ortho, frustum respectively. However, if all cameras have ortho settings,\ninterpolation is possible if the ratios of left, right, top and bottom are equal to each other.\nFor example, when it is changed by orbitControl().
\n", "itemtype": "method", "name": "slerp", "params": [ { "name": "cam0", "description": "first p5.Camera
\n", "type": "p5.Camera" }, { "name": "cam1", "description": "second p5.Camera
\n", "type": "p5.Camera" }, { "name": "amt", "description": "amount to use for interpolation during slerp
\n", "type": "Number" } ], "example": [ "\n\nlet cam0, cam1, cam;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n strokeWeight(3);\n\n // camera for slerp.\n cam = createCamera();\n cam.camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n cam.perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\n // cam0 is looking at the cube from the front.\n cam0 = createCamera();\n cam0.camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n cam0.perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\n // cam1 is pointing straight to the right in the cube\n // at the same position as cam0 by doing a pan(-PI/2).\n cam1 = createCamera();\n cam1.camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n cam1.perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\n cam1.pan(-PI/2);\n\n // we only use cam.\n setCamera(cam);\n}\n\nfunction draw() {\n // calculate amount.\n const amt = 0.5 - 0.5 * cos(frameCount * TAU / 120);\n // slerp cam0 and cam1 with amt, set to cam.\n // When amt moves from 0 to 1, cam moves from cam0 to cam1,\n // shaking the camera to the right.\n cam.slerp(cam0, cam1, amt);\n\n background(255);\n // Every time the camera turns right, the cube drifts left.\n box(40);\n}\n
\n\nlet cam, lastCam, initialCam;\nlet countForReset = 30;\n// This sample uses orbitControl() to move the camera.\n// Double-clicking the canvas restores the camera to its initial state.\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n strokeWeight(3);\n\n // main camera\n cam = createCamera();\n cam.camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n cam.perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\n // Camera for recording loc info before reset\n lastCam = createCamera();\n lastCam.camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n lastCam.perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\n // Camera for recording the initial state\n initialCam = createCamera();\n initialCam.camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n initialCam.perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\n\n setCamera(cam); // set main camera\n}\n\nfunction draw() {\n if (countForReset < 30) {\n // if the reset count is less than 30,\n // it will move closer to the original camera as it increases.\n countForReset++;\n cam.slerp(lastCam, initialCam, countForReset / 30);\n } else {\n // if the count is 30,\n // you can freely move the main camera with orbitControl().\n orbitControl();\n }\n\n background(255);\n box(40);\n}\n// A double-click sets countForReset to 0 and initiates a reset.\nfunction doubleClicked() {\n if (countForReset === 30) {\n countForReset = 0;\n lastCam.set(cam);\n }\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 cam1.camera(0, 0, 50*sqrt(3), 0, 0, 0, 0, 1, 0);\n cam1.perspective(PI/3, 1, 5*sqrt(3), 500*sqrt(3));\n cam2 = createCamera();\n cam2.setPosition(30, 0, 50);\n cam2.lookAt(0, 0, 0);\n cam2.ortho(-50, 50, -50, 50, 0, 200);\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 // 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 // camera 1:\n cam1.lookAt(0, 0, 0);\n cam1.setPosition(sin(frameCount / 60) * 200, 0, 100);\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
\nA Uint8ClampedArray\ncontaining the values for all the pixels in the Framebuffer.
\nLike the main canvas pixels property, call\nloadPixels() before reading\nit, and call updatePixels()\nafterwards to update its data.
\nNote that updating pixels via this property will be slower than\ndrawing to the framebuffer directly.\nConsider using a shader instead of looping over pixels.
\n", "itemtype": "property", "name": "pixels", "type": "Number[]", "class": "p5.Framebuffer", "module": "Rendering" }, { "file": "src/webgl/p5.Framebuffer.js", "line": 184, "description": "Resizes the framebuffer to the given width and height.
\n", "itemtype": "method", "name": "resize", "params": [ { "name": "width", "description": "", "type": "Number" }, { "name": "height", "description": "", "type": "Number" } ], "example": [ "\n\nlet framebuffer;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n framebuffer = createFramebuffer();\n noStroke();\n}\n\nfunction mouseMoved() {\n framebuffer.resize(\n max(20, mouseX),\n max(20, mouseY)\n );\n}\n\nfunction draw() {\n // Draw to the framebuffer\n framebuffer.begin();\n background(255);\n normalMaterial();\n sphere(20);\n framebuffer.end();\n\n background(100);\n // Draw the framebuffer to the main canvas\n image(framebuffer, -width/2, -height/2);\n}\n
\nGets or sets the pixel scaling for high pixel density displays. By\ndefault, the density will match that of the canvas the framebuffer was\ncreated on, which will match the display density.
\nCall this method with no arguments to get the current density, or pass\nin a number to set the density.
\n", "itemtype": "method", "name": "pixelDensity", "params": [ { "name": "density", "description": "A scaling factor for the number of pixels per\nside of the framebuffer
\n", "type": "Number", "optional": true } ], "class": "p5.Framebuffer", "module": "Rendering" }, { "file": "src/webgl/p5.Framebuffer.js", "line": 261, "description": "Gets or sets whether or not this framebuffer will automatically resize\nalong with the canvas it's attached to in order to match its size.
\nCall this method with no arguments to see if it is currently auto-sized,\nor pass in a boolean to set this property.
\n", "itemtype": "method", "name": "autoSized", "params": [ { "name": "autoSized", "description": "Whether or not the framebuffer should resize\nalong with the canvas it's attached to
\n", "type": "Boolean", "optional": true } ], "class": "p5.Framebuffer", "module": "Rendering" }, { "file": "src/webgl/p5.Framebuffer.js", "line": 702, "description": "Creates and returns a new\np5.FramebufferCamera to be used\nwhile drawing to this framebuffer. The camera will be set as the\ncurrently active camera.
\n", "itemtype": "method", "name": "createCamera", "return": { "description": "A new camera", "type": "p5.Camera" }, "class": "p5.Framebuffer", "module": "Rendering" }, { "file": "src/webgl/p5.Framebuffer.js", "line": 733, "description": "Removes the framebuffer and frees its resources.
\n", "itemtype": "method", "name": "remove", "example": [ "\n\nlet framebuffer;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n const useFramebuffer = (frameCount % 120) > 60;\n if (useFramebuffer && !framebuffer) {\n // Create a new framebuffer for us to use\n framebuffer = createFramebuffer();\n } else if (!useFramebuffer && framebuffer) {\n // Free the old framebuffer's resources\n framebuffer.remove();\n framebuffer = undefined;\n }\n\n background(255);\n if (useFramebuffer) {\n // Draw to the framebuffer\n framebuffer.begin();\n background(255);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n fill(255, 0, 0);\n box(30);\n framebuffer.end();\n\n image(framebuffer, -width/2, -height/2);\n }\n}\n
\nBegin drawing to this framebuffer. Subsequent drawing functions to the\ncanvas the framebuffer is attached to will not be immediately visible, and\nwill instead be drawn to the framebuffer's texture. Call\nend() when finished to make draw\nfunctions go right to the canvas again and to be able to read the\ncontents of the framebuffer's texture.
\n", "itemtype": "method", "name": "begin", "example": [ "\n\nlet framebuffer;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n framebuffer = createFramebuffer();\n noStroke();\n}\n\nfunction draw() {\n // Draw to the framebuffer\n framebuffer.begin();\n background(255);\n translate(0, 10*sin(frameCount * 0.01), 0);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n fill(255, 0, 0);\n box(50);\n framebuffer.end();\n\n background(100);\n // Draw the framebuffer to the main canvas\n image(framebuffer, -50, -50, 25, 25);\n image(framebuffer, 0, 0, 35, 35);\n}\n
\nAfter having previously called\nbegin(), this method stops drawing\nfunctions from going to the framebuffer's texture, allowing them to go\nright to the canvas again. After this, one can read from the framebuffer's\ntexture.
\n", "itemtype": "method", "name": "end", "class": "p5.Framebuffer", "module": "Rendering" }, { "file": "src/webgl/p5.Framebuffer.js", "line": 951, "description": "Run a function while drawing to the framebuffer rather than to its canvas.\nThis is equivalent to calling framebuffer.begin()
, running the function,\nand then calling framebuffer.end()
, but ensures that one never\naccidentally forgets begin
or end
.
A function to run that draws to the canvas. The\nfunction will immediately be run, but it will draw to the framebuffer\ninstead of the canvas.
\n", "type": "Function" } ], "example": [ "\n\nlet framebuffer;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n framebuffer = createFramebuffer();\n noStroke();\n}\n\nfunction draw() {\n // Draw to the framebuffer\n framebuffer.draw(function() {\n background(255);\n translate(0, 10*sin(frameCount * 0.01), 0);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n fill(255, 0, 0);\n box(50);\n });\n\n background(100);\n // Draw the framebuffer to the main canvas\n image(framebuffer, -50, -50, 25, 25);\n image(framebuffer, 0, 0, 35, 35);\n}\n
\nCall this befpre updating pixels\nand calling updatePixels\nto replace the content of the framebuffer with the data in the pixels\narray.
\n", "class": "p5.Framebuffer", "module": "Rendering" }, { "file": "src/webgl/p5.Framebuffer.js", "line": 1030, "description": "Get a region of pixels from the canvas in the form of a\np5.Image, or a single pixel as an array of\nnumbers.
\nReturns an array of [R,G,B,A] values for any pixel or grabs a section of\nan image. If the Framebuffer has been set up to not store alpha values, then\nonly [R,G,B] will be returned. If no parameters are specified, the entire\nimage 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().
\n", "itemtype": "method", "name": "get", "return": { "description": "the rectangle p5.Image", "type": "p5.Image" }, "class": "p5.Framebuffer", "module": "Rendering", "overloads": [ { "line": 1030, "params": [ { "name": "x", "description": "x-coordinate of the pixel
\n", "type": "Number" }, { "name": "y", "description": "y-coordinate of the pixel
\n", "type": "Number" }, { "name": "w", "description": "width of the section to be returned
\n", "type": "Number" }, { "name": "h", "description": "height of the section to be returned
\n", "type": "Number" } ], "return": { "description": "the rectangle p5.Image", "type": "p5.Image" } }, { "line": 1051, "params": [], "return": { "description": "the whole p5.Image", "type": "p5.Image" } }, { "line": 1055, "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/webgl/p5.Framebuffer.js", "line": 1149, "description": "Call this after initially calling \nloadPixels() and updating pixels\nto replace the content of the framebuffer with the data in the pixels\narray.
\nThis will also clear the depth buffer so that any future drawing done\nafterwards will go on top.
\n", "example": [ "\n\nlet framebuffer;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n framebuffer = createFramebuffer();\n}\n\nfunction draw() {\n noStroke();\n lights();\n\n // Draw a sphere to the framebuffer\n framebuffer.begin();\n background(0);\n sphere(25);\n framebuffer.end();\n\n // Load its pixels and draw a gradient over the lower half of the canvas\n framebuffer.loadPixels();\n for (let y = height/2; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const idx = (y * width + x) * 4;\n framebuffer.pixels[idx] = (x / width) * 255;\n framebuffer.pixels[idx + 1] = (y / height) * 255;\n framebuffer.pixels[idx + 2] = 255;\n framebuffer.pixels[idx + 3] = 255;\n }\n }\n framebuffer.updatePixels();\n\n // Draw a cube on top of the pixels we just wrote\n framebuffer.begin();\n push();\n translate(20, 20);\n rotateX(0.5);\n rotateY(0.5);\n box(20);\n pop();\n framebuffer.end();\n\n image(framebuffer, -width/2, -height/2);\n noLoop();\n}\n
\nA texture with the color information of the framebuffer. Pass this (or the\nframebuffer itself) to texture() to draw it to\nthe canvas, or pass it to a shader with\nsetUniform() to read its data.
\nSince Framebuffers are controlled by WebGL, their y coordinates are stored\nflipped compared to images and videos. When texturing with a framebuffer\ntexture, you may want to flip vertically, e.g. with\nplane(framebuffer.width, -framebuffer.height)
.
\nlet framebuffer;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n framebuffer = createFramebuffer();\n noStroke();\n}\n\nfunction draw() {\n // Draw to the framebuffer\n framebuffer.begin();\n background(255);\n normalMaterial();\n sphere(20);\n framebuffer.end();\n\n // Draw the framebuffer to the main canvas\n image(framebuffer.color, -width/2, -height/2);\n}\n
\nA texture with the depth information of the framebuffer. If the framebuffer\nwas created with { depth: false }
in its settings, then this property will\nbe undefined. Pass this to texture() to draw it to\nthe canvas, or pass it to a shader with\nsetUniform() to read its data.
Since Framebuffers are controlled by WebGL, their y coordinates are stored\nflipped compared to images and videos. When texturing with a framebuffer\ntexture, you may want to flip vertically, e.g. with\nplane(framebuffer.width, -framebuffer.height)
.
\nlet framebuffer;\nlet depthShader;\n\nconst vert = `\nprecision highp float;\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nvarying vec2 vTexCoord;\nvoid main() {\n vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * viewModelPosition;\n vTexCoord = aTexCoord;\n}\n`;\n\nconst frag = `\nprecision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D depth;\nvoid main() {\n float depthVal = texture2D(depth, vTexCoord).r;\n gl_FragColor = mix(\n vec4(1., 1., 0., 1.), // yellow\n vec4(0., 0., 1., 1.), // blue\n pow(depthVal, 6.)\n );\n}\n`;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n framebuffer = createFramebuffer();\n depthShader = createShader(vert, frag);\n noStroke();\n}\n\nfunction draw() {\n // Draw to the framebuffer\n framebuffer.begin();\n background(255);\n rotateX(frameCount * 0.01);\n box(20, 20, 100);\n framebuffer.end();\n\n push();\n shader(depthShader);\n depthShader.setUniform('depth', framebuffer.depth);\n plane(framebuffer.width, framebuffer.height);\n pop();\n}\n
\nCustom bounding box calculation based on the object's vertices.\nThe bounding box is a rectangular prism that encompasses the entire object.\nIt is defined by the minimum and maximum coordinates along each axis, as well\nas the size and offset of the box.
\nIt returns an object containing the bounding box properties:
\nmin
: The minimum coordinates of the bounding box as a p5.Vector.max
: The maximum coordinates of the bounding box as a p5.Vector.size
: The size of the bounding box as a p5.Vector.offset
: The offset of the bounding box as a p5.Vector.\nlet particles;\nlet button;\nlet resultParagraph;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n button = createButton('New');\n button.mousePressed(makeParticles);\n\n resultParagraph = createElement('pre').style('width', '200px' );\n resultParagraph.style('font-family', 'monospace');\n resultParagraph.style('font-size', '12px');\n makeParticles();\n}\n\nfunction makeParticles() {\n if (particles) freeGeometry(particles);\n\n particles = buildGeometry(() => {\n for (let i = 0; i < 60; i++) {\n push();\n translate(\n randomGaussian(0, 200),\n randomGaussian(0, 100),\n randomGaussian(0, 150)\n );\n sphere(10);\n pop();\n }\n });\n\n const boundingBox = particles.calculateBoundingBox();\n resultParagraph.html('Bounding Box: \\n' + JSON.stringify(boundingBox, null, 2));\n}\n\nfunction draw() {\n background(255);\n noStroke();\n lights();\n orbitControl();\n model(particles);\n}\n\n
\nRemoves the internal colors of p5.Geometry.\nUsing clearColors()
, you can use fill()
to supply new colors before drawing each shape.\nIf clearColors()
is not used, the shapes will use their internal colors by ignoring fill()
.
\nlet shape01;\nlet shape02;\nlet points = [];\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n points.push(new p5.Vector(-1, -1, 0), new p5.Vector(-1, 1, 0),\n new p5.Vector(1, -1, 0), new p5.Vector(-1, -1, 0));\n buildShape01();\n buildShape02();\n}\nfunction draw() {\n background(0);\n fill('pink'); // shape01 retains its internal blue color, so it won't turn pink.\n model(shape01);\n fill('yellow'); // Now, shape02 is yellow.\n model(shape02);\n}\n\nfunction buildShape01() {\n beginGeometry();\n fill('blue'); // shape01's color is blue because its internal colors remain.\n beginShape();\n for (let vec of points) vertex(vec.x * 100, vec.y * 100, vec.z * 100);\n endShape(CLOSE);\n shape01 = endGeometry();\n}\n\nfunction buildShape02() {\n beginGeometry();\n fill('red'); // shape02.clearColors() removes its internal colors. Now, shape02 is red.\n beginShape();\n for (let vec of points) vertex(vec.x * 200, vec.y * 200, vec.z * 200);\n endShape(CLOSE);\n shape02 = endGeometry();\n shape02.clearColors(); // Resets shape02's colors.\n}\n
\nFlips the U texture coordinates of the model.
\n", "itemtype": "method", "name": "flipU", "return": { "description": "", "type": "p5.Geometry" }, "example": [ "\n\nlet img;\nlet model1;\nlet model2;\n\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(150, 150, WEBGL);\n background(200);\n\n model1 = createShape(50, 50);\n model2 = createShape(50, 50);\n model2.flipU();\n}\n\nfunction draw() {\n background(0);\n\n // original\n push();\n translate(-40, 0, 0);\n texture(img);\n noStroke();\n plane(50);\n model(model1);\n pop();\n\n // flipped\n push();\n translate(40, 0, 0);\n texture(img);\n noStroke();\n plane(50);\n model(model2);\n pop();\n}\n\nfunction createShape(w, h) {\n return buildGeometry(() => {\n textureMode(NORMAL);\n beginShape();\n vertex(-w / 2, -h / 2, 0, 0);\n vertex(w / 2, -h / 2, 1, 0);\n vertex(w / 2, h / 2, 1, 1);\n vertex(-w / 2, h / 2, 0, 1);\n endShape(CLOSE);\n });\n}\n
\nFlips the V texture coordinates of the model.
\n", "itemtype": "method", "name": "flipV", "return": { "description": "", "type": "p5.Geometry" }, "example": [ "\n\nlet img;\nlet model1;\nlet model2;\n\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(150, 150, WEBGL);\n background(200);\n\n model1 = createShape(50, 50);\n model2 = createShape(50, 50);\n model2.flipV();\n}\n\nfunction draw() {\n background(0);\n\n // original\n push();\n translate(-40, 0, 0);\n texture(img);\n noStroke();\n plane(50);\n model(model1);\n pop();\n\n // flipped\n push();\n translate(40, 0, 0);\n texture(img);\n noStroke();\n plane(50);\n model(model2);\n pop();\n}\n\nfunction createShape(w, h) {\n return buildGeometry(() => {\n textureMode(NORMAL);\n beginShape();\n vertex(-w / 2, -h / 2, 0, 0);\n vertex(w / 2, -h / 2, 1, 0);\n vertex(w / 2, h / 2, 1, 1);\n vertex(-w / 2, h / 2, 0, 1);\n endShape(CLOSE);\n });\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": 472, "description": "This function calculates normals for each face, where each vertex's normal is the average of the normals of all faces it's connected to.\ni.e computes smooth normals per vertex as an average of each face.
\nWhen using FLAT
shading, vertices are disconnected/duplicated i.e each face has its own copy of vertices.\nWhen using SMOOTH
shading, vertices are connected/deduplicated i.e each face has its vertices shared with other faces.
Options can include:
\nroundToPrecision
: Precision value for rounding computations. Defaults to 3.shading type (FLAT
for flat shading or SMOOTH
for smooth shading) for buildGeometry() outputs. Defaults to FLAT
.
An optional object with configuration.
\n", "type": "Object", "optional": true } ], "chainable": 1, "example": [ "\n\nlet helix;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n helix = buildGeometry(() => {\n beginShape();\n\n for (let i = 0; i < TWO_PI * 3; i += 0.6) {\n let radius = 20;\n let x = cos(i) * radius;\n let y = sin(i) * radius;\n let z = map(i, 0, TWO_PI * 3, -30, 30);\n vertex(x, y, z);\n }\n endShape();\n });\n helix.computeNormals();\n}\nfunction draw() {\n background(255);\n stroke(0);\n fill(150, 200, 250);\n lights();\n rotateX(PI*0.2);\n orbitControl();\n model(helix);\n}\n
\n\nlet star;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n star = buildGeometry(() => {\n beginShape();\n for (let i = 0; i < TWO_PI; i += PI / 5) {\n let outerRadius = 60;\n let innerRadius = 30;\n let xOuter = cos(i) * outerRadius;\n let yOuter = sin(i) * outerRadius;\n let zOuter = random(-20, 20);\n vertex(xOuter, yOuter, zOuter);\n\n let nextI = i + PI / 5 / 2;\n let xInner = cos(nextI) * innerRadius;\n let yInner = sin(nextI) * innerRadius;\n let zInner = random(-20, 20);\n vertex(xInner, yInner, zInner);\n }\n endShape(CLOSE);\n });\n star.computeNormals(SMOOTH);\n}\nfunction draw() {\n background(255);\n stroke(0);\n fill(150, 200, 250);\n lights();\n rotateX(PI*0.2);\n orbitControl();\n model(star);\n}\n
\nAverages 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": 664, "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": 974, "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.Immediate.js", "line": 1, "description": "Welcome to RendererGL Immediate Mode.\nImmediate mode is used for drawing custom shapes\nfrom a set of vertices. Immediate Mode is activated\nwhen you call beginShape() & de-activated when you call endShape().\nImmediate mode is a style of programming borrowed\nfrom OpenGL's (now-deprecated) immediate mode.\nIt differs from p5.js' default, Retained Mode, which caches\ngeometries and buffers on the CPU to reduce the number of webgl\ndraw calls. Retained mode is more efficient & performative,\nhowever, Immediate Mode is useful for sketching quick\ngeometric ideas.
\n", "class": "p5", "module": "Shape" }, { "file": "src/webgl/p5.RendererGL.Immediate.js", "line": 191, "description": "End shape drawing and render vertices to screen.
\n", "chainable": 1, "class": "p5", "module": "Shape" }, { "file": "src/webgl/p5.RendererGL.Retained.js", "line": 8, "params": [ { "name": "geometry", "description": "The model whose resources will be freed
\n", "type": "p5.Geometry" } ], "class": "p5", "module": "Shape" }, { "file": "src/webgl/p5.RendererGL.js", "line": 118, "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 true
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 true
\npreserveDrawingBuffer - if true the buffers will not be cleared and\nand will preserve their values until cleared or overwritten by author\n(note that p5 clears automatically on draw loop)\ndefault is true
\nperPixelLighting - if true, per-pixel lighting will be used in the\nlighting shader otherwise per-vertex lighting is used.\ndefault is true.
\nversion - either 1 or 2, to specify which WebGL version to ask for. By\ndefault, WebGL 2 will be requested. If WebGL2 is not available, it will\nfall back to WebGL 1. You can check what version is used with by looking at\nthe global webglVersion
property.
\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": 262, "params": [ { "name": "obj", "description": "object with key-value pairs
\n", "type": "Object" } ] } ] }, { "file": "src/webgl/p5.Shader.js", "line": 106, "description": "Shaders belong to the main canvas or a p5.Graphics. Once they are compiled,\nthey can only be used in the context they were compiled on.
\nUse this method to make a new copy of a shader that gets compiled on a\ndifferent context.
\n", "itemtype": "method", "name": "copyToContext", "params": [ { "name": "context", "description": "The graphic or instance to copy this shader to.\nPass window
if you need to copy to the main canvas.
\nlet graphic = createGraphics(200, 200, WEBGL);\nlet graphicShader = graphic.createShader(vert, frag);\ngraphic.shader(graphicShader); // Use graphicShader on the graphic\n\nlet mainShader = graphicShader.copyToContext(window);\nshader(mainShader); // Use `mainShader` on the main canvas\n
\nUsed 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).
\nHere are some examples of uniforms you can make:
\nsetUniform('x', true)
becomes uniform float x
with the value 1.0
setUniform('x', -2)
becomes uniform float x
with the value -2.0
setUniform('x', [0, 0.5, 1])
becomes uniform vec3 x
with the value vec3(0.0, 0.5, 1.0)
setUniform('x', img)
becomes uniform sampler2D x
the name of the uniform.\nMust correspond to the name used in the vertex and fragment shaders
\n", "type": "String" }, { "name": "data", "description": "The value to assign to the uniform. This 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:223" }, { "message": "replacing incorrect tag: returns with return", "line": " src/core/friendly_errors/fes_core.js:323" }, { "message": "replacing incorrect tag: returns with return", "line": " src/core/friendly_errors/fes_core.js:464" }, { "message": "replacing incorrect tag: returns with return", "line": " src/core/friendly_errors/fes_core.js:1018" }, { "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/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:71" }, { "message": "unknown tag: alt", "line": " src/core/shape/vertex.js:297" }, { "message": "unknown tag: alt", "line": " src/core/shape/vertex.js:419" }, { "message": "unknown tag: alt", "line": " src/core/shape/vertex.js:464" }, { "message": "unknown tag: alt", "line": " src/core/shape/vertex.js:528" }, { "message": "unknown tag: alt", "line": " src/core/shape/vertex.js:591" }, { "message": "unknown tag: alt", "line": " src/core/shape/vertex.js:772" }, { "message": "unknown tag: alt", "line": " src/core/shape/vertex.js:837" }, { "message": "unknown tag: alt", "line": " src/core/shape/vertex.js:930" }, { "message": "unknown tag: alt", "line": " src/core/constants.js:88" }, { "message": "unknown tag: alt", "line": " src/core/constants.js:106" }, { "message": "unknown tag: alt", "line": " src/core/constants.js:124" }, { "message": "unknown tag: alt", "line": " src/core/constants.js:142" }, { "message": "unknown tag: alt", "line": " src/core/constants.js:160" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:590" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:621" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:652" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:680" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:708" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:708" }, { "message": "replacing incorrect tag: returns with return", "line": " src/core/environment.js:1050" }, { "message": "replacing incorrect tag: returns with return", "line": " src/core/environment.js:1069" }, { "message": "unknown tag: alt", "line": " src/core/environment.js:1199" }, { "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:41" }, { "message": "unknown tag: alt", "line": " src/core/main.js:82" }, { "message": "unknown tag: alt", "line": " src/core/main.js:113" }, { "message": "unknown tag: alt", "line": " src/core/main.js:450" }, { "message": "unknown tag: name", "line": " src/core/p5.Element.js:56" }, { "message": "unknown tag: name", "line": " src/core/p5.Element.js:87" }, { "message": "unknown tag: name", "line": " src/core/p5.Element.js:94" }, { "message": "unknown tag: name", "line": " src/core/p5.Element.js:102" }, { "message": "unknown tag: alt", "line": " src/core/p5.Element.js:966" }, { "message": "unknown tag: alt", "line": " src/core/p5.Graphics.js:83" }, { "message": "unknown tag: alt", "line": " src/core/p5.Graphics.js:135" }, { "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:166" }, { "message": "unknown tag: alt", "line": " src/core/rendering.js:232" }, { "message": "unknown tag: alt", "line": " src/core/rendering.js:253" }, { "message": "unknown tag: alt", "line": " src/core/rendering.js:316" }, { "message": "unknown tag: alt", "line": " src/core/rendering.js:391" }, { "message": "unknown tag: alt", "line": " src/core/rendering.js:461" }, { "message": "unknown tag: alt", "line": " src/core/rendering.js:545" }, { "message": "unknown tag: alt", "line": " src/core/structure.js:9" }, { "message": "unknown tag: alt", "line": " src/core/structure.js:82" }, { "message": "replacing incorrect tag: returns with return", "line": " src/core/structure.js:133" }, { "message": "unknown tag: alt", "line": " src/core/structure.js:133" }, { "message": "unknown tag: alt", "line": " src/core/structure.js:192" }, { "message": "unknown tag: alt", "line": " src/core/structure.js:290" }, { "message": "unknown tag: alt", "line": " src/core/structure.js:391" }, { "message": "unknown tag: alt", "line": " src/core/structure.js:494" }, { "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:299" }, { "message": "unknown tag: alt", "line": " src/core/transform.js:337" }, { "message": "unknown tag: alt", "line": " src/core/transform.js:377" }, { "message": "unknown tag: alt", "line": " src/core/transform.js:451" }, { "message": "unknown tag: alt", "line": " src/core/transform.js:490" }, { "message": "unknown tag: alt", "line": " src/core/transform.js:529" }, { "message": "replacing incorrect tag: returns with return", "line": " src/dom/dom.js:2610" }, { "message": "replacing incorrect tag: returns with return", "line": " src/dom/dom.js:2696" }, { "message": "replacing incorrect tag: returns with return", "line": " src/dom/dom.js:2867" }, { "message": "replacing incorrect tag: returns with return", "line": " src/dom/dom.js:2954" }, { "message": "replacing incorrect tag: returns with return", "line": " src/dom/dom.js:3092" }, { "message": "replacing incorrect tag: returns with return", "line": " src/image/loading_displaying.js:761" }, { "message": "replacing incorrect tag: returns with return", "line": " src/image/loading_displaying.js:794" }, { "message": "replacing incorrect tag: returns with return", "line": " src/image/loading_displaying.js:828" }, { "message": "replacing incorrect tag: returns with return", "line": " src/image/loading_displaying.js:871" }, { "message": "unknown tag: name", "line": " src/image/p5.Image.js:114" }, { "message": "unknown tag: name", "line": " src/image/p5.Image.js:151" }, { "message": "unknown tag: name", "line": " src/image/p5.Image.js:198" }, { "message": "replacing incorrect tag: returns with return", "line": " src/image/p5.Image.js:299" }, { "message": "replacing incorrect tag: returns with return", "line": " src/image/pixels.js:706" }, { "message": "replacing incorrect tag: returns with return", "line": " src/io/files.js:683" }, { "message": "unknown tag: name", "line": " src/io/p5.Table.js:43" }, { "message": "unknown tag: name", "line": " src/io/p5.Table.js:80" }, { "message": "replacing incorrect tag: returns with return", "line": " src/math/calculation.js:1048" }, { "message": "unknown tag: name", "line": " src/math/p5.Vector.js:113" }, { "message": "unknown tag: name", "line": " src/math/p5.Vector.js:120" }, { "message": "unknown tag: name", "line": " src/math/p5.Vector.js:127" }, { "message": "replacing incorrect tag: returns with return", "line": " src/math/trigonometry.js:769" }, { "message": "replacing incorrect tag: returns with return", "line": " src/math/trigonometry.js:784" }, { "message": "replacing incorrect tag: returns with return", "line": " src/math/trigonometry.js:799" }, { "message": "replacing incorrect tag: returns with return", "line": " src/math/trigonometry.js:814" }, { "message": "unknown tag: name", "line": " src/typography/p5.Font.js:51" }, { "message": "unknown tag: alt", "line": " src/webgl/3d_primitives.js:13" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/3d_primitives.js:89" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/3d_primitives.js:102" }, { "message": "unknown tag: alt", "line": " src/webgl/3d_primitives.js:102" }, { "message": "unknown tag: alt", "line": " src/webgl/3d_primitives.js:183" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/GeometryBuilder.js:122" }, { "message": "unknown tag: alt", "line": " src/webgl/interaction.js:11" }, { "message": "unknown tag: alt", "line": " src/webgl/interaction.js:378" }, { "message": "unknown tag: alt", "line": " src/webgl/interaction.js:378" }, { "message": "unknown tag: alt", "line": " src/webgl/interaction.js:378" }, { "message": "unknown tag: alt", "line": " src/webgl/interaction.js:378" }, { "message": "unknown tag: alt", "line": " src/webgl/interaction.js:378" }, { "message": "unknown tag: alt", "line": " src/webgl/interaction.js:602" }, { "message": "unknown tag: alt", "line": " src/webgl/light.js:10" }, { "message": "unknown tag: alt", "line": " src/webgl/light.js:10" }, { "message": "unknown tag: alt", "line": " src/webgl/light.js:10" }, { "message": "unknown tag: alt", "line": " src/webgl/light.js:134" }, { "message": "unknown tag: alt", "line": " src/webgl/light.js:246" }, { "message": "unknown tag: alt", "line": " src/webgl/light.js:373" }, { "message": "unknown tag: alt", "line": " src/webgl/light.js:497" }, { "message": "unknown tag: alt", "line": " src/webgl/light.js:497" }, { "message": "unknown tag: alt", "line": " src/webgl/light.js:602" }, { "message": "unknown tag: alt", "line": " src/webgl/light.js:649" }, { "message": "unknown tag: alt", "line": " src/webgl/light.js:693" }, { "message": "unknown tag: alt", "line": " src/webgl/light.js:794" }, { "message": "unknown tag: alt", "line": " src/webgl/light.js:1155" }, { "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:775" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:12" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/material.js:115" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:115" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/material.js:202" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:331" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:440" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:529" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:529" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:529" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:529" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:674" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:674" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:752" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:824" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:869" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:869" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:869" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:982" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:1053" }, { "message": "unknown tag: alt", "line": " src/webgl/material.js:1139" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:13" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:121" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:197" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:306" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:369" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:441" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:511" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:605" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:634" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:662" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:690" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:719" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:748" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:777" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:801" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:825" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:853" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:956" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:1040" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:1171" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:1231" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:1291" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:1360" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:1360" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:1508" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:1582" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:1646" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:1719" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:1719" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Camera.js:2332" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Framebuffer.js:184" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/p5.Framebuffer.js:702" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Framebuffer.js:733" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Framebuffer.js:794" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Framebuffer.js:951" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Framebuffer.js:1149" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Framebuffer.js:1283" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Framebuffer.js:1325" }, { "message": "unknown tag: memberof", "line": " src/webgl/p5.Geometry.js:80" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/p5.Geometry.js:80" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/p5.Geometry.js:285" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/p5.Geometry.js:357" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Geometry.js:472" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Geometry.js:472" }, { "message": "param name missing: {Number}", "line": " src/webgl/p5.Matrix.js:745" }, { "message": "param name missing: {p5.Vector}", "line": " src/webgl/p5.Matrix.js:764" }, { "message": "param name missing: {p5.Vector}", "line": " src/webgl/p5.Matrix.js:779" }, { "message": "param name missing: {p5.Vector}", "line": " src/webgl/p5.Matrix.js:797" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/p5.RendererGL.Immediate.js:320" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/p5.RendererGL.Retained.js:19" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.RendererGL.js:118" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/p5.RendererGL.js:318" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/p5.RendererGL.js:389" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/p5.RendererGL.js:700" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/p5.RendererGL.js:718" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.RendererGL.js:945" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.RendererGL.js:986" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.RendererGL.js:1301" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/p5.RendererGL.js:1415" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/p5.RendererGL.js:2046" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/p5.Shader.js:106" }, { "message": "unknown tag: alt", "line": " src/webgl/p5.Shader.js:361" }, { "message": "replacing incorrect tag: function with method", "line": " src/webgl/text.js:116" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/text.js:160" }, { "message": "replacing incorrect tag: function with method", "line": " src/webgl/text.js:192" }, { "message": "replacing incorrect tag: function with method", "line": " src/webgl/text.js:204" }, { "message": "replacing incorrect tag: function with method", "line": " src/webgl/text.js:253" }, { "message": "replacing incorrect tag: function with method", "line": " src/webgl/text.js:267" }, { "message": "replacing incorrect tag: function with method", "line": " src/webgl/text.js:406" }, { "message": "replacing incorrect tag: returns with return", "line": " src/webgl/text.js:406" }, { "message": "replacing incorrect tag: function with method", "line": " src/webgl/text.js:474" }, { "message": "replacing incorrect tag: function with method", "line": " src/webgl/text.js:489" }, { "message": "replacing incorrect tag: function with method", "line": " src/webgl/text.js:574" }, { "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