diff --git a/client/constants.js b/client/constants.js index cabaa570..ce5960c3 100644 --- a/client/constants.js +++ b/client/constants.js @@ -4,6 +4,9 @@ export const TOGGLE_SKETCH = 'TOGGLE_SKETCH'; export const START_SKETCH = 'START_SKETCH'; export const STOP_SKETCH = 'STOP_SKETCH'; +export const START_TEXT_OUTPUT = 'START_TEXT_OUTPUT'; +export const STOP_TEXT_OUTPUT = 'STOP_TEXT_OUTPUT'; + export const OPEN_PREFERENCES = 'OPEN_PREFERENCES'; export const CLOSE_PREFERENCES = 'CLOSE_PREFERENCES'; export const SET_FONT_SIZE = 'SET_FONT_SIZE'; @@ -61,6 +64,7 @@ export const HIDE_EDIT_FILE_NAME = 'HIDE_EDIT_FILE_NAME'; export const SET_AUTOSAVE = 'SET_AUTOSAVE'; export const SET_LINT_WARNING = 'SET_LINT_WARNING'; export const SET_PREFERENCES = 'SET_PREFERENCES'; +export const SET_TEXT_OUTPUT = 'SET_TEXT_OUTPUT'; // eventually, handle errors more specifically and better export const ERROR = 'ERROR'; diff --git a/client/modules/IDE/actions/ide.js b/client/modules/IDE/actions/ide.js index 1b8b18d8..4cb32913 100644 --- a/client/modules/IDE/actions/ide.js +++ b/client/modules/IDE/actions/ide.js @@ -18,6 +18,18 @@ export function stopSketch() { }; } +export function startTextOutput() { + return { + type: ActionTypes.START_TEXT_OUTPUT + }; +} + +export function stopTextOutput() { + return { + type: ActionTypes.STOP_TEXT_OUTPUT + }; +} + export function setSelectedFile(fileId) { return { type: ActionTypes.SET_SELECTED_FILE, diff --git a/client/modules/IDE/actions/preferences.js b/client/modules/IDE/actions/preferences.js index 82ea107a..f2270905 100644 --- a/client/modules/IDE/actions/preferences.js +++ b/client/modules/IDE/actions/preferences.js @@ -118,3 +118,21 @@ export function setLintWarning(value) { } }; } + +export function setTextOutput(value) { + return (dispatch, getState) => { + dispatch({ + type: ActionTypes.SET_TEXT_OUTPUT, + value + }); + const state = getState(); + if (state.user.authenticated) { + const formParams = { + preferences: { + textOutput: value + } + }; + updatePreferences(formParams, dispatch); + } + }; +} diff --git a/client/modules/IDE/components/Editor.js b/client/modules/IDE/components/Editor.js index d4b6c72e..34658b6f 100644 --- a/client/modules/IDE/components/Editor.js +++ b/client/modules/IDE/components/Editor.js @@ -89,8 +89,6 @@ class Editor extends React.Component { this._cm.setOption('mode', 'htmlmixed'); } } - - console.log('componentDidUpdate in editor'); } componentWillUnmount() { @@ -101,14 +99,14 @@ class Editor extends React.Component { render() { return ( -
+
We define colors to be immutable objects. Each color stores the color mode\nand level maxes that applied at the time of its construction. These are\nused to interpret the input arguments and to format the output e.g. when\nsaturation() is requested.
Internally we store an array representing the ideal RGBA values in floating\npoint form, normalized from 0 to 1. From this we calculate the closest\nscreen color (RGBA levels from 0 to 255) and expose this to the renderer.
We also cache normalized, floating point components of the color in various\nrepresentations as they are calculated. This is done to prevent repeating a\nconversion that has already been performed.
Base class for all elements added to a sketch, including canvas,\ngraphics buffers, and other HTML elements. Methods in blue are\nincluded in the core functionality, methods in brown are added\nwith the p5.dom\nlibrary.\nIt is not called directly, but p5.Element\nobjects are created by calling createCanvas, createGraphics,\nor in the p5.dom library, createDiv, createImg, createInput, etc.
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.
Creates a new p5.Image. A p5.Image is a canvas backed representation of an\nimage.\n\np5 can display .gif, .jpg and .png images. Images may be displayed\nin 2D and 3D space. Before an image is used, it must be loaded with the\nloadImage() function. The p5.Image class contains fields for the width and\nheight of the image, as well as an array called pixels[] that contains the\nvalues for every pixel in the image.\n\nThe methods described below allow easy access to the image's pixels and\nalpha channel and simplify the process of compositing.\n\nBefore using the pixels[] array, be sure to use the loadPixels() method on\nthe image to make sure that the pixel data is properly loaded.
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.
XML is a representation of an XML object, able to parse XML code. Use\nloadXML() to load external XML files and create XML objects.
A class to describe a two or three dimensional vector, specifically\na Euclidean (also known as geometric) vector. A vector is an entity\nthat has both magnitude and direction. The datatype, however, stores\nthe components of the vector (x, y for 2D, and x, y, z for 3D). The magnitude\nand direction can be accessed via the methods mag() and heading().\n\nIn many of the p5.js examples, you will see p5.Vector used to describe a\nposition, velocity, or acceleration. For example, if you consider a rectangle\nmoving across the screen, at any given instant it has a position (a vector\nthat points from the origin to its location), a velocity (the rate at which\nthe object's position changes per time unit, expressed as a vector), and\nacceleration (the rate at which the object's velocity changes per time\nunit, expressed as a vector).\n\nSince vectors represent groupings of values, we cannot simply use\ntraditional addition/multiplication/etc. Instead, we'll need to do some\n"vector" math, which is made easy by the methods inside the p5.Vector class.
This module defines the p5.Font class and functions for\ndrawing text to the display canvas.
The web is much more than just canvas and p5.dom makes it easy to interact\nwith other HTML5 objects, including text, hyperlink, image, input, video,\naudio, and webcam.
There 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.
Methods and properties shown in black are part of the p5.js core, items in\nblue are part of the p5.dom library. You will need to include an extra file\nin order to access the blue functions. See the\nusing a library\nsection for information on how to include this library. p5.dom comes with\np5 complete or you can download the single file\n\nhere.
See tutorial: beyond the canvas\nfor more info on how to use this libary.
p5.sound extends p5 with Web Audio functionality including audio input,\nplayback, analysis and synthesis.\n\np5.SoundFile: Load and play sound files.\np5.Amplitude: Get the current volume of a sound.\np5.AudioIn: Get sound from an input source, typically\n a computer microphone.\np5.FFT: Analyze the frequency of sound. Returns\n results from the frequency spectrum or time domain (waveform).\np5.Oscillator: Generate Sine,\n Triangle, Square and Sawtooth waveforms. Base class of\n p5.Noise and p5.Pulse.\n \np5.Env: An Envelope is a series\n of fades over time. Often used to control an object's\n output gain level as an "ADSR Envelope" (Attack, Decay,\n Sustain, Release). Can also modulate other parameters.\np5.Delay: A delay effect with\n parameters for feedback, delayTime, and lowpass filter.\np5.Filter: Filter the frequency range of a\n sound.\n\np5.Reverb: Add reverb to a sound by specifying\n duration and decay. \np5.Convolver: Extends\np5.Reverb to simulate the sound of real\n physical spaces through convolution.\np5.SoundRecorder: Record sound for playback \n / save the .wav file.\np5.Phrase, p5.Part and\np5.Score: Compose musical sequences.\n\np5.sound is on GitHub.\nDownload the latest version \nhere.
DOM node that is wrapped
pointer to p5 instance
we're using it as main canvas
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, respecitvely.
An instance of a p5 sketch.
An array of p5.TableRow objects
A TableRow object represents a single row of data values,\nstored in columns, from a table.
A Table Row contains both an ordered array, and an unordered\nJSON object.
optional: populate the row with a\n string of values, separated by the\n separator
comma separated values (csv) by default
\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\nvar xml;\n\nfunction preload() {\n xml = loadXML(\"assets/mammals.xml\");\n}\n\nfunction setup() {\n var children = xml.getChildren(\"animal\");\n\n for (var i = 0; i < children.length; i++) {\n var id = children[i].getNumber(\"id\");\n var coloring = children[i].getString(\"species\");\n var name = children[i].getContent();\n println(id + \", \" + coloring + \", \" + name);\n }\n}\n\n// Sketch prints:\n// 0, Capra hircus, Goat\n// 1, Panthera pardus, Leopard\n// 2, Equus zebra, Zebra\n
x component of the vector
y component of the vector
z component of the vector
\nvar v1 = createVector(40, 50);\nvar v2 = createVector(40, 50);\n\nellipse(v1.x, v1.y, 50, 50);\nellipse(v2.x, v2.y, 50, 50);\nv1.add(v2);\nellipse(v1.x, v1.y, 50, 50);\n
Base class for font handling
Extends p5.Element to handle audio and video. In addition to the methods\nof p5.Element, it also contains methods for controlling media. It is not\ncalled directly, but p5.MediaElements are created by calling createVideo,\ncreateAudio, and createCapture.
Base class for a file\nUsing this for createFileInput
File that is wrapped
SoundFile object with a path to a file.
The p5.SoundFile may not be available immediately because\nit loads the file information asynchronously.
To do something with the sound as soon as it loads\npass the name of a function as the second parameter.
Only 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.
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.
Name of a function to call once file loads
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.
Name of a function to call while file\n is loading. That function will\n receive percentage loaded\n (between 0 and 1) as a\n parameter.
\n\nfunction preload() {\n mySound = loadSound('assets/doorbell.mp3');\n}\n\nfunction setup() {\n mySound.setVolume(0.1);\n mySound.play();\n}\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.
between 0.0 and .999 to smooth\n amplitude readings (defaults to 0)
\nvar sound, amplitude, cnv;\n\nfunction preload(){\n sound = loadSound('assets/beat.mp3');\n}\nfunction setup() {\n cnv = createCanvas(100,100);\n amplitude = new p5.Amplitude();\n\n // start / stop the sound when canvas is clicked\n cnv.mouseClicked(function() {\n if (sound.isPlaying() ){\n sound.stop();\n } else {\n sound.play();\n }\n });\n}\nfunction draw() {\n background(0);\n fill(255);\n var level = amplitude.getLevel();\n var size = map(level, 0, 1, 0, 200);\n ellipse(width/2, height/2, size, size);\n}\n\n
FFT (Fast Fourier Transform) is an analysis algorithm that\nisolates individual\n\naudio frequencies within a waveform.
Once 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.waveform()
FFT.analyze()
getEnergy()
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.
bins
Smooth results of Freq Spectrum.\n 0.0 < smoothing < 1.0.\n Defaults to 0.8.
Length of resulting array.\n Must be a power of two between\n 16 and 1024. Defaults to 1024.
\nfunction preload(){\n sound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup(){\n var cnv = createCanvas(100,100);\n cnv.mouseClicked(togglePlay);\n fft = new p5.FFT();\n sound.amp(0.2);\n}\n\nfunction draw(){\n background(0);\n\n var spectrum = fft.analyze(); \n noStroke();\n fill(0,255,0); // spectrum is green\n for (var i = 0; i< spectrum.length; i++){\n var x = map(i, 0, spectrum.length, 0, width);\n var h = -height + map(spectrum[i], 0, 255, height, 0);\n rect(x, height, width / spectrum.length, h )\n }\n\n var waveform = fft.waveform();\n noFill();\n beginShape();\n stroke(255,0,0); // waveform is red\n strokeWeight(1);\n for (var i = 0; i< waveform.length; i++){\n var x = map(i, 0, waveform.length, 0, width);\n var y = map( waveform[i], -1, 1, 0, height);\n vertex(x,y);\n }\n endShape();\n\n text('click to play/pause', 4, 10);\n}\n\n// fade sound if mouse is over canvas\nfunction togglePlay() {\n if (sound.isPlaying()) {\n sound.pause();\n } else {\n sound.loop();\n }\n}\n
p5.Signal is a constant audio-rate signal used by p5.Oscillator\nand p5.Envelope for modulation math.
This is necessary because Web Audio is processed on a seprate clock.\nFor example, the p5 draw loop runs about 60 times per second. But\nthe audio clock must process samples 44100 times per second. If we\nwant to add a value to each of those samples, we can't do it in the\ndraw loop, but we can do it by adding a constant-rate audio signal.This class mostly functions behind the scenes in p5.sound, and returns\na Tone.Signal from the Tone.js library by Yotam Mann.\nIf you want to work directly with audio signals for modular\nsynthesis, check out\ntone.js.
\nfunction setup() {\n carrier = new p5.Oscillator('sine');\n carrier.amp(1); // set amplitude\n carrier.freq(220); // set frequency\n carrier.start(); // start oscillating\n \n modulator = new p5.Oscillator('sawtooth');\n modulator.disconnect();\n modulator.amp(1);\n modulator.freq(4);\n modulator.start();\n\n // Modulator's default amplitude range is -1 to 1.\n // Multiply it by -200, so the range is -200 to 200\n // then add 220 so the range is 20 to 420\n carrier.freq( modulator.mult(-200).add(220) );\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).
Set the type of oscillation with setType(), or by creating a\nspecific oscillator.
new p5.SinOsc(freq)
new p5.TriOsc(freq)
new p5.SqrOsc(freq)
new p5.SawOsc(freq)
frequency defaults to 440Hz
type of oscillator. Options:\n 'sine' (default), 'triangle',\n 'sawtooth', 'square'
\nvar osc;\nvar playing = false;\n\nfunction setup() {\n backgroundColor = color(255,0,255);\n textAlign(CENTER);\n \n osc = new p5.Oscillator();\n osc.setType('sine');\n osc.freq(240);\n osc.amp(0);\n osc.start();\n}\n\nfunction draw() {\n background(backgroundColor)\n text('click to play', width/2, height/2);\n}\n\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY < height && mouseY > 0) {\n if (!playing) {\n // ramp amplitude to 0.5 over 0.1 seconds\n osc.amp(0.5, 0.05);\n playing = true;\n backgroundColor = color(0,255,255);\n } else {\n // ramp amplitude to 0 over 0.5 seconds\n osc.amp(0, 0.5);\n playing = false;\n backgroundColor = color(255,0,255);\n }\n }\n}\n
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.Env can \ncontrol an Oscillator's frequency like this: osc.freq(env).
osc.freq(env)
Use setRange to change the attack/release level.\nUse setADSR to change attackTime, decayTime, sustainPercent and releaseTime.
setRange
setADSR
Use the play method to play the entire envelope,\nthe ramp method for a pingable trigger,\nor triggerAttack/\ntriggerRelease to trigger noteOn/noteOff.
play
ramp
triggerAttack
triggerRelease
\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.2;\nvar susPercent = 0.2;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Env();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv(){\n env.play();\n}\n
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.
p5.Oscillator
Frequency in oscillations per second (Hz)
Width between the pulses (0 to 1.0,\n defaults to 0)
\nvar pulse;\nfunction setup() {\n background(0);\n \n // Create and start the pulse wave oscillator\n pulse = new p5.Pulse();\n pulse.amp(0.5);\n pulse.freq(220);\n pulse.start();\n}\n\nfunction draw() {\n var w = map(mouseX, 0, width, 0, 1);\n w = constrain(w, 0, 1);\n pulse.width(w)\n}\n
Noise is a type of oscillator that generates a buffer with random values.
Type of noise can be 'white' (default),\n 'brown' or 'pink'.
Get audio from an input, i.e. your computer's microphone.
Turn the mic on/off with the start() and stop() methods. When the mic\nis on, its volume can be measured with getLevel or by connecting an\nFFT object.
If you want to hear the AudioIn, use the .connect() method. \nAudioIn does not connect to p5.sound output by default to prevent\nfeedback.
Note: This uses the getUserMedia/\nStream API, which is not supported by certain browsers.
\nvar mic;\nfunction setup(){\n mic = new p5.AudioIn()\n mic.start();\n}\nfunction draw(){\n background(0);\n micLevel = mic.getLevel();\n ellipse(width/2, constrain(height-micLevel*height*5, 0, height), 10, 10);\n}\n
A p5.Filter uses a Web Audio Biquad Filter to filter\nthe frequency response of an input source. Inheriting\nclasses include:
p5.LowPass
p5.HighPass
p5.BandPass
The .res() method controls either width of the\nbandpass, or resonance of the low/highpass cutoff frequency.
.res()
'lowpass' (default), 'highpass', 'bandpass'
\nvar fft, noise, filter;\n\nfunction setup() {\n fill(255, 40, 255);\n\n filter = new p5.BandPass();\n\n noise = new p5.Noise();\n // disconnect unfiltered noise,\n // and connect to filter\n noise.disconnect();\n noise.connect(filter);\n noise.start();\n\n fft = new p5.FFT();\n}\n\nfunction draw() {\n background(30);\n\n // set the BandPass frequency based on mouseX\n var freq = map(mouseX, 0, width, 20, 10000);\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 var spectrum = fft.analyze();\n noStroke();\n for (var i = 0; i < spectrum.length; i++) {\n var x = map(i, 0, spectrum.length, 0, width);\n var h = -height + map(spectrum[i], 0, 255, height, 0);\n rect(x, height, width/spectrum.length, h);\n }\n \n isMouseOverCanvas();\n}\n\nfunction isMouseOverCanvas() {\n var mX = mouseX, mY = mouseY;\n if (mX > 0 && mX < width && mY < height && mY > 0) {\n noise.amp(0.5, 0.2);\n } else {\n noise.amp(0, 0.2);\n }\n}\n
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 will\nproduce a looping delay that decreases in volume by\n50% each repeat. A filter will cut out the high frequencies so\nthat the delay does not sound as piercing as the original source.
\nvar noise, env, delay;\n\nfunction setup() {\n background(0);\n noStroke();\n fill(255);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n \n noise = new p5.Noise('brown');\n noise.amp(0);\n noise.start();\n \n delay = new p5.Delay();\n\n // delay.process() accepts 4 parameters:\n // source, delayTime, feedback, filter frequency\n // play with these numbers!!\n delay.process(noise, .12, .7, 2300);\n \n // play the noise with an envelope,\n // a series of fades ( time / value pairs )\n env = new p5.Env(.01, 0.2, .2, .1);\n}\n\n// mouseClick triggers envelope\nfunction mouseClicked() {\n // is mouse over canvas?\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n env.play(noise);\n }\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.
\nvar soundFile, reverb;\nfunction preload() {\n soundFile = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\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 soundFile.play();\n}\n
p5.Convolver extends p5.Reverb. It can emulate the sound of real\nphysical spaces through a process called \nconvolution.
Convolution 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.
Use the method createConvolution(path) to instantiate a\np5.Convolver with a path to your impulse response audio file.
createConvolution(path)
path to a sound file
function to call when loading succeeds
function to call if loading fails.\n This function will receive an error or\n XMLHttpRequest object with information\n about what went wrong.
\nvar 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 // disconnect from master output...\n sound.disconnect();\n \n // ...and process with cVerb\n // so that we only hear the convolution\n cVerb.process(sound);\n \n sound.play();\n}\n
A phrase is a pattern of musical events over time, i.e.\na series of notes and rests.
Phrases 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.
The 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).
playNote(value){}
Name so that you can access the Phrase.
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.
Array of values to pass into the callback\n at each step of the phrase.
\nvar mySound, myPhrase, myPart;\nvar pattern = [1,0,0,2,0,2,0,0];\nvar msg = 'click to play';\n\nfunction preload() {\n mySound = loadSound('assets/beatbox.mp3');\n}\n\nfunction setup() {\n noStroke();\n fill(255);\n textAlign(CENTER);\n masterVolume(0.1);\n \n myPhrase = new p5.Phrase('bbox', makeSound, pattern);\n myPart = new p5.Part();\n myPart.addPhrase(myPhrase);\n myPart.setBPM(60);\n}\n\nfunction draw() {\n background(0);\n text(msg, width/2, height/2);\n}\n\nfunction makeSound(time, playbackRate) {\n mySound.rate(playbackRate);\n mySound.play(time);\n}\n\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n myPart.start();\n msg = 'playing pattern';\n }\n}\n\n
A p5.Part plays back one or more p5.Phrases. Instantiate a part\nwith steps and tatums. By default, each step represents 1/16th note.
See p5.Phrase for more about musical timing.
Steps in the part
Divisions of a beat (default is 1/16, a quarter note)
\nvar box, drum, myPart;\nvar boxPat = [1,0,0,2,0,2,0,0];\nvar drumPat = [0,1,1,0,2,0,1,0];\nvar msg = 'click to play';\n\nfunction preload() {\n box = loadSound('assets/beatbox.mp3');\n drum = loadSound('assets/drum.mp3');\n}\n\nfunction setup() {\n noStroke();\n fill(255);\n textAlign(CENTER);\n masterVolume(0.1);\n\n var boxPhrase = new p5.Phrase('box', playBox, boxPat);\n var 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 masterVolume(0.1);\n}\n\nfunction draw() {\n background(0);\n text(msg, width/2, height/2);\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 mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n myPart.start();\n msg = 'playing part';\n }\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)
new p5.Score(a, a, b, a, c)
One or multiple parts, to be played in sequence.
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().
The 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.
\nvar mic, recorder, soundFile;\nvar state = 0;\n\nfunction setup() {\n background(200);\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('keyPress to record', 20, 20);\n}\n\nfunction keyPressed() {\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!', 20, 20);\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('Stopped', 20, 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
PeakDetect works in conjunction with p5.FFT to\nlook for onsets in some or all of the frequency spectrum.\n
\nTo use p5.PeakDetect, call update in the draw loop\nand pass in a p5.FFT object.\n
update
\nYou can listen for a specific part of the frequency spectrum by\nsetting the range between freq1 and freq2.\n
freq1
freq2
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.
threshold
\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
framesPerPeak = 60 / (estimatedBPM / 60 );
\nBased on example contribtued by @b2renger, and a simple beat detection\nexplanation by a\nhref="http://www.airtightinteractive.com/2013/10/making-audio-reactive-visuals/"\ntarget="_blank"Felix Turner.\n
lowFrequency - defaults to 20Hz
highFrequency - defaults to 20000 Hz
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.
Defaults to 20.
\n\nvar cnv, soundFile, fft, peakDetect;\nvar ellipseWidth = 10;\n\nfunction setup() {\n background(0);\n noStroke();\n fill(255);\n textAlign(CENTER);\n\n soundFile = loadSound('assets/beat.mp3');\n\n // p5.PeakDetect requires a p5.FFT\n fft = new p5.FFT();\n peakDetect = new p5.PeakDetect();\n\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
A gain node is usefull to set the relative volume of sound.\nIt's typically used to build mixers.
\n\n // load two soundfile and crossfade beetween them\n var sound1,sound2;\n var gain1, gain2, gain3;\n \n function preload(){\n soundFormats('ogg', 'mp3');\n sound1 = loadSound('../_files/Damscray_-_Dancing_Tiger_01');\n sound2 = loadSound('../_files/beat.mp3');\n }\n\n function setup() {\n createCanvas(400,200);\n\n // create a 'master' gain to which we will connect both soundfiles\n gain3 = new p5.Gain();\n gain3.connect();\n\n // setup first sound for playing\n sound1.rate(1);\n sound1.loop();\n sound1.disconnect(); // diconnect from p5 output\n\n gain1 = new p5.Gain(); // setup a gain node\n gain1.setInput(sound1); // connect the first sound to its input\n gain1.connect(gain3); // connect its output to the 'master'\n\n sound2.rate(1);\n sound2.disconnect();\n sound2.loop();\n\n gain2 = new p5.Gain();\n gain2.setInput(sound2);\n gain2.connect(gain3);\n\n }\n\n function draw(){\n background(180);\n\n // calculate the horizontal distance beetween the mouse and the right of the screen\n var d = dist(mouseX,0,width,0);\n\n // map the horizontal position of the mouse to values useable for volume control of sound1\n var vol1 = map(mouseX,0,width,0,1); \n var vol2 = 1-vol1; // when sound1 is loud, sound2 is quiet and vice versa\n\n gain1.amp(vol1,0.5,0);\n gain2.amp(vol2,0.5,0);\n\n // map the vertical position of the mouse to values useable for 'master volume control'\n var vol3 = map(mouseY,0,height,0,1); \n gain3.amp(vol3,0.5,0);\n }\n
module Conversion\nsubmodule Color Conversion
Conversions adapted from http://www.easyrgb.com/math.html.
In these functions, hue is always in the range [0,1); all other components\nare in the range [0,1]. 'Brightness' and 'value' are used interchangeably.
Convert an HSBA array to HSLA.
Convert an HSBA array to RGBA.
Convert an HSLA array to HSBA.
Convert an HSLA array to RGBA.
We 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.
Convert an RGBA array to HSBA.
Convert an RGBA array to HSLA.
Extracts the alpha value from a color or pixel array.
p5.Color object or pixel array
\nnoStroke();\nc = color(0, 126, 255, 102);\nfill(c);\nrect(15, 15, 35, 70);\nvalue = alpha(c); // Sets 'value' to 102\nfill(value);\nrect(50, 15, 35, 70);\n
Extracts the blue value from a color or pixel array.
\nc = color(175, 100, 220); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nblueValue = blue(c); // Get blue in 'c'\nprintln(blueValue); // Prints \"220.0\"\nfill(0, 0, blueValue); // Use 'blueValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n
Extracts the HSB brightness value from a color or pixel array.
\nnoStroke();\ncolorMode(HSB, 255);\nc = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nvalue = brightness(c); // Sets 'value' to 255\nfill(value);\nrect(50, 20, 35, 60);\n
Creates colors for storing in variables of the color datatype. The\nparameters are interpreted as RGB or HSB values depending on the\ncurrent colorMode(). The default mode is RGB values from 0 to 255\nand, therefore, the function call color(255, 204, 0) will return a\nbright yellow color.\n\nNote that if only one value is provided to color(), it will be interpreted\nas a grayscale value. Add a second value, and it will be used for alpha\ntransparency. When three values are specified, they are interpreted as\neither RGB or HSB values. Adding a fourth value applies alpha\ntransparency. If a single string parameter is provided it will be\ninterpreted as a CSS-compatible color string.
Colors are stored as Numbers or Arrays.
\nvar c = color(255, 204, 0); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nnoStroke(); // Don't draw a stroke around shapes\nrect(30, 20, 55, 55); // Draw rectangle\n
\nvar c = color(255, 204, 0); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nnoStroke(); // Don't draw a stroke around shapes\nellipse(25, 25, 80, 80); // Draw left circle\n\n// Using only one value with color()\n// generates a grayscale value.\nvar c = color(65); // Update 'c' with grayscale value\nfill(c); // Use updated 'c' as fill color\nellipse(75, 75, 80, 80); // Draw right circle\n
\n// Named SVG & CSS colors may be used,\nvar c = color('magenta');\nfill(c); // Use 'c' as fill color\nnoStroke(); // Don't draw a stroke around shapes\nrect(20, 20, 60, 60); // Draw rectangle\n
\n// as can hex color codes:\nnoStroke(); // Don't draw a stroke around shapes\nvar c = color('#0f0');\nfill(c); // Use 'c' as fill color\nrect(0, 10, 45, 80); // Draw rectangle\n\nc = color('#00ff00');\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 45, 80); // Draw rectangle\n
\n// RGB and RGBA color strings are also supported:\n// these all set to the same color (solid blue)\nvar c;\nnoStroke(); // Don't draw a stroke around shapes\nc = color('rgb(0,0,255)');\nfill(c); // Use 'c' as fill color\nrect(10, 10, 35, 35); // Draw rectangle\n\nc = color('rgb(0%, 0%, 100%)');\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 35, 35); // Draw rectangle\n\nc = color('rgba(0, 0, 255, 1)');\nfill(c); // Use updated 'c' as fill color\nrect(10, 55, 35, 35); // Draw rectangle\n\nc = color('rgba(0%, 0%, 100%, 1)');\nfill(c); // Use updated 'c' as fill color\nrect(55, 55, 35, 35); // Draw rectangle\n
\n// HSL color is also supported and can be specified\n// by value\nvar c;\nnoStroke(); // Don't draw a stroke around shapes\nc = color('hsl(160, 100%, 50%)');\nfill(c); // Use 'c' as fill color\nrect(0, 10, 45, 80); // Draw rectangle\n\nc = color('hsla(160, 100%, 50%, 0.5)');\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 45, 80); // Draw rectangle\n
\n// HSB color is also supported and can be specified\n// by value\nvar c;\nnoStroke(); // Don't draw a stroke around shapes\nc = color('hsb(160, 100%, 50%)');\nfill(c); // Use 'c' as fill color\nrect(0, 10, 45, 80); // Draw rectangle\n\nc = color('hsba(160, 100%, 50%, 0.5)');\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 45, 80); // Draw rectangle\n
\nvar c; // Declare color 'c'\nnoStroke(); // Don't draw a stroke around shapes\n\n// If no colorMode is specified, then the\n// default of RGB with scale of 0-255 is used.\nc = color(50, 55, 100); // Create a color for 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(0, 10, 45, 80); // Draw left rect\n\ncolorMode(HSB, 100); // Use HSB with scale of 0-100\nc = color(50, 55, 100); // Update 'c' with new color\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 45, 80); // Draw right rect\n
number specifying value between white\n and black.
alpha value relative to current color range\n (default is 0-100)
red or hue value relative to\n the current color range, or a color string
green or saturation value\n relative to the current color range
blue or brightness value\n relative to the current color range
Extracts the green value from a color or pixel array.
\nc = color(20, 75, 200); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\ngreenValue = green(c); // Get green in 'c'\nprintln(greenValue); // Print \"75.0\"\nfill(0, greenValue, 0); // Use 'greenValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n
Extracts the hue value from a color or pixel array.
Hue exists in both HSB and HSL. This function will return the\nHSB-normalized hue when supplied with an HSB color object (or when supplied\nwith a pixel array while the color mode is HSB), but will default to the\nHSL-normalized hue otherwise. (The values will only be different if the\nmaximum hue setting for each system is different.)
\nnoStroke();\ncolorMode(HSB, 255);\nc = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nvalue = hue(c); // Sets 'value' to \"0\"\nfill(value);\nrect(50, 20, 35, 60);\n
Blends two colors to find a third color somewhere between them. The amt\nparameter is the amount to interpolate between the two values where 0.0\nequal to the first color, 0.1 is very near the first color, 0.5 is halfway\nin between, etc. An amount below 0 will be treated as 0. Likewise, amounts\nabove 1 will be capped at 1. This is different from the behavior of lerp(),\nbut necessary because otherwise numbers outside the range will produce\nstrange and unexpected colors.\n\nThe way that colours are interpolated depends on the current color mode.
interpolate from this color
interpolate to this color
number between 0 and 1
\ncolorMode(RGB);\nstroke(255);\nbackground(51);\nfrom = color(218, 165, 32);\nto = color(72, 61, 139);\ncolorMode(RGB); // Try changing to HSB.\ninterA = lerpColor(from, to, .33);\ninterB = lerpColor(from, to, .66);\nfill(from);\nrect(10, 20, 20, 60);\nfill(interA);\nrect(30, 20, 20, 60);\nfill(interB);\nrect(50, 20, 20, 60);\nfill(to);\nrect(70, 20, 20, 60);\n
Extracts the HSL lightness value from a color or pixel array.
\nnoStroke();\ncolorMode(HSL);\nc = color(156, 100, 50, 1);\nfill(c);\nrect(15, 20, 35, 60);\nvalue = lightness(c); // Sets 'value' to 50\nfill(value);\nrect(50, 20, 35, 60);\n
Extracts the red value from a color or pixel array.
\nc = color(255, 204, 0); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nredValue = red(c); // Get red in 'c'\nprintln(redValue); // Print \"255.0\"\nfill(redValue, 0, 0); // Use 'redValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n
\ncolorMode(RGB, 255);\nvar c = color(127, 255, 0);\ncolorMode(RGB, 1);\nvar myColor = red(c);\nprintln(myColor);\n
Extracts the saturation value from a color or pixel array.
Saturation is scaled differently in HSB and HSL. This function will return\nthe HSB saturation when supplied with an HSB color object (or when supplied\nwith a pixel array while the color mode is HSB), but will default to the\nHSL saturation otherwise.
\nnoStroke();\ncolorMode(HSB, 255);\nc = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nvalue = saturation(c); // Sets 'value' to 126\nfill(value);\nrect(50, 20, 35, 60);\n
Hue 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.
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.
CSS named colors.
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.
Note that RGB values of .9 are not parsed by IE, but are supported here for\ncolor string consistency.
Full color string patterns. The capture groups are necessary.
For a number of different inputs, returns a color formatted as [r, g, b, a]\narrays, with each component normalized between 0 and 1.
An 'array-like' object that represents a list of\n arguments
\n// todo\n
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.
The background() function sets the color used for the background of the\np5.js canvas. The default background is light gray. This function is\ntypically used within draw() to clear the display window at the beginning\nof each frame, but it can be used inside setup() to set the background on\nthe first frame of animation or if the background need only be set once.
\n// Grayscale integer value\nbackground(51);\n
\n// R, G & B integer values\nbackground(255, 204, 0);\n
\n// H, S & B integer values\ncolorMode(HSB);\nbackground(255, 204, 100);\n
\n// Named SVG/CSS color string\nbackground('red');\n
\n// three-digit hexadecimal RGB notation\nbackground('#fae');\n
\n// six-digit hexadecimal RGB notation\nbackground('#222222');\n
\n// integer RGB notation\nbackground('rgb(0,255,0)');\n
\n// integer RGBA notation\nbackground('rgba(0,255,0, 0.25)');\n
\n// percentage RGB notation\nbackground('rgb(100%,0%,10%)');\n
\n// percentage RGBA notation\nbackground('rgba(100%,0%,100%,0.5)');\n
\n// p5 Color object\nbackground(color(0, 0, 255));\n
any value created by the color() function
opacity of the background relative to current\n color range (default is 0-100)
color string, possible formats include: integer\n rgb() or rgba(), percentage rgb() or rgba(),\n 3-digit hex, 6-digit hex
specifies a value between white and black
red or hue value (depending on the current color\n mode)
green or saturation value (depending on the current\n color mode)
blue or brightness value (depending on the current\n color mode)
image created with loadImage() or createImage(),\n to set as background\n (must be same size as the sketch window)
Clears the pixels within a buffer. This function only works on p5.Canvas\nobjects created with the createCanvas() function; it won't work with the\nmain display window. Unlike the main graphics context, pixels in\nadditional graphics areas created with createGraphics() can be entirely\nor partially transparent. This function clears everything to make all of\nthe pixels 100% transparent.
\n// Clear the screen on mouse press.\nfunction setup() {\n createCanvas(100, 100);\n}\n\nfunction draw() {\n ellipse(mouseX, mouseY, 20, 20);\n}\n\nfunction mousePressed() {\n clear();\n}\n
colorMode() changes the way p5.js interprets color data. By default, the\nparameters for fill(), stroke(), background(), and color() are defined by\nvalues between 0 and 255 using the RGB color model. This is equivalent to\nsetting colorMode(RGB, 255). Setting colorMode(HSB) lets you use the HSB\nsystem instead. By default, this is colorMode(HSB, 360, 100, 100, 1). You\ncan also use HSL.\n\nNote: existing color objects remember the mode that they were created in,\nso you can change modes as you like without affecting their appearance.
either RGB or HSB, corresponding to\n Red/Green/Blue and Hue/Saturation/Brightness\n (or Lightness)
range for the red or hue depending on the\n current color mode, or range for all values
range for the green or saturation depending\n on the current color mode
range for the blue or brightness/lighntess\n depending on the current color mode
range for the alpha
\nnoStroke();\ncolorMode(RGB, 100);\nfor (i = 0; i < 100; i++) {\n for (j = 0; j < 100; j++) {\n stroke(i, j, 0);\n point(i, j);\n }\n}\n
\nnoStroke();\ncolorMode(HSB, 100);\nfor (i = 0; i < 100; i++) {\n for (j = 0; j < 100; j++) {\n stroke(i, j, 100);\n point(i, j);\n }\n}\n
\ncolorMode(RGB, 255);\nvar c = color(127, 255, 0);\n\ncolorMode(RGB, 1);\nvar myColor = c._getRed();\ntext(myColor, 10, 10, 80, 80);\n
\nnoFill();\ncolorMode(RGB, 255, 255, 255, 1);\nbackground(255);\n\nstrokeWeight(4);\nstroke(255, 0 , 10, 0.3);\nellipse(40, 40, 50, 50);\nellipse(50, 50, 40, 40);\n
Sets the color used to fill shapes. For example, if you run\nfill(204, 102, 0), all subsequent shapes will be filled with orange. This\ncolor is either specified in terms of the RGB or HSB color depending on\nthe current colorMode(). (The default color space is RGB, with each value\nin the range from 0 to 255).\n\nIf a single string argument is provided, RGB, RGBA and Hex CSS color strings\nand all named color strings are supported. A p5 Color object can also be\nprovided to set the fill color.
gray value, red or hue value\n (depending on the current color\n mode), or color Array, or CSS\n color string
green or saturation value\n (depending on the current\n color mode)
blue or brightness value\n (depending on the current\n color mode)
opacity of the background
\n// Grayscale integer value\nfill(51);\nrect(20, 20, 60, 60);\n
\n// R, G & B integer values\nfill(255, 204, 0);\nrect(20, 20, 60, 60);\n
\n// H, S & B integer values\ncolorMode(HSB);\nfill(255, 204, 100);\nrect(20, 20, 60, 60);\n
\n// Named SVG/CSS color string\nfill('red');\nrect(20, 20, 60, 60);\n
\n// three-digit hexadecimal RGB notation\nfill('#fae');\nrect(20, 20, 60, 60);\n
\n// six-digit hexadecimal RGB notation\nfill('#222222');\nrect(20, 20, 60, 60);\n
\n// integer RGB notation\nfill('rgb(0,255,0)');\nrect(20, 20, 60, 60);\n
\n// integer RGBA notation\nfill('rgba(0,255,0, 0.25)');\nrect(20, 20, 60, 60);\n
\n// percentage RGB notation\nfill('rgb(100%,0%,10%)');\nrect(20, 20, 60, 60);\n
\n// percentage RGBA notation\nfill('rgba(100%,0%,100%,0.5)');\nrect(20, 20, 60, 60);\n
\n// p5 Color object\nfill(color(0, 0, 255));\nrect(20, 20, 60, 60);\n
Disables filling geometry. If both noStroke() and noFill() are called,\nnothing will be drawn to the screen.
\nrect(15, 10, 55, 55);\nnoFill();\nrect(20, 20, 60, 60);\n
Disables drawing the stroke (outline). If both noStroke() and noFill()\nare called, nothing will be drawn to the screen.
\nnoStroke();\nrect(20, 20, 60, 60);\n
Sets the color used to draw lines and borders around shapes. This color\nis either specified in terms of the RGB or HSB color depending on the\ncurrent colorMode() (the default color space is RGB, with each value in\nthe range from 0 to 255).\n\nIf a single string argument is provided, RGB, RGBA and Hex CSS color\nstrings and all named color strings are supported. A p5 Color object\ncan also be provided to set the stroke color.
\n// Grayscale integer value\nstrokeWeight(4);\nstroke(51);\nrect(20, 20, 60, 60);\n
\n// R, G & B integer values\nstroke(255, 204, 0);\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n
\n// H, S & B integer values\ncolorMode(HSB);\nstrokeWeight(4);\nstroke(255, 204, 100);\nrect(20, 20, 60, 60);\n
\n// Named SVG/CSS color string\nstroke('red');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n
\n// three-digit hexadecimal RGB notation\nstroke('#fae');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n
\n// six-digit hexadecimal RGB notation\nstroke('#222222');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n
\n// integer RGB notation\nstroke('rgb(0,255,0)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n
\n// integer RGBA notation\nstroke('rgba(0,255,0,0.25)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n
\n// percentage RGB notation\nstroke('rgb(100%,0%,10%)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n
\n// percentage RGBA notation\nstroke('rgba(100%,0%,100%,0.5)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n
\n// p5 Color object\nstroke(color(0, 0, 255));\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n
Draw an arc to the screen. If called with only a, b, c, d, start, and\nstop, the arc will be drawn as an open pie. If mode is provided, the arc\nwill be drawn either open, as a chord, or as a pie as specified. The\norigin may be changed with the ellipseMode() function.\nNote that drawing a full circle (ex: 0 to TWO_PI) will appear blank\nbecause 0 and TWO_PI are the same position on the unit circle. The\nbest way to handle this is by using the ellipse() function instead\nto create a closed ellipse, and to use the arc() function\nonly to draw parts of an ellipse.
x-coordinate of the arc's ellipse
y-coordinate of the arc's ellipse
width of the arc's ellipse by default
height of the arc's ellipse by default
angle to start the arc, specified in radians
angle to stop the arc, specified in radians
optional parameter to determine the way of drawing\n the arc
\narc(50, 55, 50, 50, 0, HALF_PI);\nnoFill();\narc(50, 55, 60, 60, HALF_PI, PI);\narc(50, 55, 70, 70, PI, PI+QUARTER_PI);\narc(50, 55, 80, 80, PI+QUARTER_PI, TWO_PI);\n
\narc(50, 50, 80, 80, 0, PI+QUARTER_PI, OPEN);\n
\narc(50, 50, 80, 80, 0, PI+QUARTER_PI, CHORD);\n
\narc(50, 50, 80, 80, 0, PI+QUARTER_PI, PIE);\n
Draws an ellipse (oval) to the screen. An ellipse with equal width and\nheight is a circle. By default, the first two parameters set the location,\nand the third and fourth parameters set the shape's width and height. If\nno height is specified, the value of width is used for both the width and\nheight. The origin may be changed with the ellipseMode() function.
\nellipse(56, 46, 55, 55);\n
x-coordinate of the ellipse.
y-coordinate of the ellipse.
width of the ellipse.
height of the ellipse.
Draws a line (a direct path between two points) to the screen. The version\nof line() with four parameters draws the line in 2D. To color a line, use\nthe stroke() function. A line cannot be filled, therefore the fill()\nfunction will not affect the color of a line. 2D lines are drawn with a\nwidth of one pixel by default, but this can be changed with the\nstrokeWeight() function.
the x-coordinate of the first point
the y-coordinate of the first point
the x-coordinate of the second point
the y-coordinate of the second point
\nline(30, 20, 85, 75);\n
\nline(30, 20, 85, 20);\nstroke(126);\nline(85, 20, 85, 75);\nstroke(255);\nline(85, 75, 30, 75);\n
Draws a point, a coordinate in space at the dimension of one pixel.\nThe first parameter is the horizontal value for the point, the second\nvalue is the vertical value for the point. The color of the point is\ndetermined by the current stroke.
the x-coordinate
the y-coordinate
\npoint(30, 20);\npoint(85, 20);\npoint(85, 75);\npoint(30, 75);\n
Draw a quad. A quad is a quadrilateral, a four sided polygon. It is\nsimilar to a rectangle, but the angles between its edges are not\nconstrained to ninety degrees. The first pair of parameters (x1,y1)\nsets the first vertex and the subsequent pairs should proceed\nclockwise or counter-clockwise around the defined shape.
\nquad(38, 31, 86, 20, 69, 63, 30, 76);\n
the x-coordinate of the third point
the y-coordinate of the third point
the x-coordinate of the fourth point
the y-coordinate of the fourth point
Draws a rectangle to the screen. A rectangle is a four-sided shape with\nevery angle at ninety degrees. By default, the first two parameters set\nthe location of the upper-left corner, the third sets the width, and the\nfourth sets the height. The way these parameters are interpreted, however,\nmay be changed with the rectMode() function.\n\nThe fifth, sixth, seventh and eighth parameters, if specified,\ndetermine corner radius for the top-right, top-left, lower-right and\nlower-left corners, respectively. An omitted corner radius parameter is set\nto the value of the previously specified radius value in the parameter list.
\n// Draw a rectangle at location (30, 20) with a width and height of 55.\nrect(30, 20, 55, 55);\n
\n// Draw a rectangle with rounded corners, each having a radius of 20.\nrect(30, 20, 55, 55, 20);\n
\n// Draw a rectangle with rounded corners having the following radii:\n// top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5.\nrect(30, 20, 55, 55, 20, 15, 10, 5);\n
x-coordinate of the rectangle.
y-coordinate of the rectangle.
width of the rectangle.
height of the rectangle.
optional radius of top-left corner.
optional radius of top-right corner.
optional radius of bottom-right corner.
optional radius of bottom-left corner.
A triangle is a plane created by connecting three points. The first two\narguments specify the first point, the middle two arguments specify the\nsecond point, and the last two arguments specify the third point.
x-coordinate of the first point
y-coordinate of the first point
x-coordinate of the second point
y-coordinate of the second point
x-coordinate of the third point
y-coordinate of the third point
\ntriangle(30, 75, 58, 20, 86, 75);\n
Modifies the location from which ellipses are drawn by changing the way\nin which parameters given to ellipse() are interpreted.\n\nThe default mode is ellipseMode(CENTER), which interprets the first two\nparameters of ellipse() as the shape's center point, while the third and\nfourth parameters are its width and height.\n\nellipseMode(RADIUS) also uses the first two parameters of ellipse() as\nthe shape's center point, but uses the third and fourth parameters to\nspecify half of the shapes's width and height.\n\nellipseMode(CORNER) interprets the first two parameters of ellipse() as\nthe upper-left corner of the shape, while the third and fourth parameters\nare its width and height.\n\nellipseMode(CORNERS) interprets the first two parameters of ellipse() as\nthe location of one corner of the ellipse's bounding box, and the third\nand fourth parameters as the location of the opposite corner.\n\nThe parameter must be written in ALL CAPS because Javascript is a\ncase-sensitive language.
either CENTER, RADIUS, CORNER, or CORNERS
\nellipseMode(RADIUS); // Set ellipseMode to RADIUS\nfill(255); // Set fill to white\nellipse(50, 50, 30, 30); // Draw white ellipse using RADIUS mode\n\nellipseMode(CENTER); // Set ellipseMode to CENTER\nfill(100); // Set fill to gray\nellipse(50, 50, 30, 30); // Draw gray ellipse using CENTER mode\n
\nellipseMode(CORNER); // Set ellipseMode is CORNER\nfill(255); // Set fill to white\nellipse(25, 25, 50, 50); // Draw white ellipse using CORNER mode\n\nellipseMode(CORNERS); // Set ellipseMode to CORNERS\nfill(100); // Set fill to gray\nellipse(25, 25, 50, 50); // Draw gray ellipse using CORNERS mode\n
Draws all geometry with jagged (aliased) edges. Note that smooth() is\nactive by default, so it is necessary to call noSmooth() to disable\nsmoothing of geometry, images, and fonts.
\nbackground(0);\nnoStroke();\nsmooth();\nellipse(30, 48, 36, 36);\nnoSmooth();\nellipse(70, 48, 36, 36);\n
Modifies the location from which rectangles are drawn by changing the way\nin which parameters given to rect() are interpreted.\n\nThe default mode is rectMode(CORNER), which interprets the first two\nparameters of rect() as the upper-left corner of the shape, while the\nthird and fourth parameters are its width and height.\n\nrectMode(CORNERS) interprets the first two parameters of rect() as the\nlocation of one corner, and the third and fourth parameters as the\nlocation of the opposite corner.\n\nrectMode(CENTER) interprets the first two parameters of rect() as the\nshape's center point, while the third and fourth parameters are its\nwidth and height.\n\nrectMode(RADIUS) also uses the first two parameters of rect() as the\nshape's center point, but uses the third and fourth parameters to specify\nhalf of the shapes's width and height.\n\nThe parameter must be written in ALL CAPS because Javascript is a\ncase-sensitive language.
either CORNER, CORNERS, CENTER, or RADIUS
\nrectMode(CORNER); // Default rectMode is CORNER\nfill(255); // Set fill to white\nrect(25, 25, 50, 50); // Draw white rect using CORNER mode\n\nrectMode(CORNERS); // Set rectMode to CORNERS\nfill(100); // Set fill to gray\nrect(25, 25, 50, 50); // Draw gray rect using CORNERS mode\n
\nrectMode(RADIUS); // Set rectMode to RADIUS\nfill(255); // Set fill to white\nrect(50, 50, 30, 30); // Draw white rect using RADIUS mode\n\nrectMode(CENTER); // Set rectMode to CENTER\nfill(100); // Set fill to gray\nrect(50, 50, 30, 30); // Draw gray rect using CENTER mode\n
Draws all geometry with smooth (anti-aliased) edges. smooth() will also\nimprove image quality of resized images. Note that smooth() is active by\ndefault; noSmooth() can be used to disable smoothing of geometry,\nimages, and fonts.
Sets the style for rendering line endings. These ends are either squared,\nextended, or rounded, each of which specified with the corresponding\nparameters: SQUARE, PROJECT, and ROUND. The default cap is ROUND.
either SQUARE, PROJECT, or ROUND
\nstrokeWeight(12.0);\nstrokeCap(ROUND);\nline(20, 30, 80, 30);\nstrokeCap(SQUARE);\nline(20, 50, 80, 50);\nstrokeCap(PROJECT);\nline(20, 70, 80, 70);\n
Sets the style of the joints which connect line segments. These joints\nare either mitered, beveled, or rounded and specified with the\ncorresponding parameters MITER, BEVEL, and ROUND. The default joint is\nMITER.
either MITER, BEVEL, ROUND
\nnoFill();\nstrokeWeight(10.0);\nstrokeJoin(MITER);\nbeginShape();\nvertex(35, 20);\nvertex(65, 50);\nvertex(35, 80);\nendShape();\n
\nnoFill();\nstrokeWeight(10.0);\nstrokeJoin(BEVEL);\nbeginShape();\nvertex(35, 20);\nvertex(65, 50);\nvertex(35, 80);\nendShape();\n
\nnoFill();\nstrokeWeight(10.0);\nstrokeJoin(ROUND);\nbeginShape();\nvertex(35, 20);\nvertex(65, 50);\nvertex(35, 80);\nendShape();\n
Sets the width of the stroke used for lines, points, and the border\naround shapes. All widths are set in units of pixels.
the weight (in pixels) of the stroke
\nstrokeWeight(1); // Default\nline(20, 20, 80, 20);\nstrokeWeight(4); // Thicker\nline(20, 40, 80, 40);\nstrokeWeight(10); // Beastly\nline(20, 70, 80, 70);\n
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().
\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().
\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().
\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().
\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().
\narc(50, 50, 80, 80, 0, TWO_PI);\n
This is the p5 instance constructor.
A 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(), setup(), and/or\ndraw() properties on it for running a sketch.
A 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
a closure that can set optional preload(),\n setup(), and/or draw() properties on the\n given p5 instance
element to attach canvas to, if a\n boolean is passed in use it as sync
start synchronously (optional)
Called directly before setup(), the preload() function is used to handle\nasynchronous loading of external files. If a preload function is\ndefined, setup() will wait until any load calls within have finished.\nNothing besides load calls should be inside preload (loadImage,\nloadJSON, loadFont, loadStrings, etc).
\nvar img;\nvar c;\nfunction preload() { // preload() runs once\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() { // 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.\n\nNote: Variables declared within setup() are not accessible within other\nfunctions, including draw().
\nvar 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.\n\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.\n\nThe number of times draw() executes in each second may be controlled with\nthe frameRate() function.\n\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.\n\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.
\nvar yPos = 0;\nfunction setup() { // setup() runs once\n frameRate(30);\n}\nfunction draw() { // 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.
\nfunction draw() {\n ellipse(50, 50, 10, 10);\n}\n\nfunction mousePressed() {\n remove(); // remove whole sketch on mouse press\n}\n
Draws 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.Bezier curves were developed by French\nautomotive engineer Pierre Bezier, and are commonly used in computer\ngraphics to define gently sloping curves. See also curve().
\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
x-coordinate for the first anchor point
y-coordinate for the first anchor point
x-coordinate for the first control point
y-coordinate for the first control point
x-coordinate for the second control point
y-coordinate for the second control point
x-coordinate for the second anchor point
y-coordinate for the second anchor point
z-coordinate for the first anchor point
z-coordinate for the first control point
Sets the resolution at which Beziers display.
The default value is 20.
resolution of the curves
\nbackground(204);\nbezierDetail(50);\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\n
Evaluates 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.\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.
coordinate of first point on the curve
coordinate of first control point
coordinate of second control point
coordinate of second point on the curve
value between 0 and 1
\nnoFill();\nx1 = 85, x2 = 10, x3 = 90, x4 = 15;\ny1 = 20, y2 = 10, y3 = 90, y4 = 80;\nbezier(x1, y1, x2, y2, x3, y3, x4, y4);\nfill(255);\nsteps = 10;\nfor (i = 0; i <= steps; i++) {\n t = i / steps;\n x = bezierPoint(x1, x2, x3, x4, t);\n y = bezierPoint(y1, y2, y3, y4, t);\n ellipse(x, y, 5, 5);\n}\n
Evaluates 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.
\nnoFill();\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\nsteps = 6;\nfill(255);\nfor (i = 0; i <= steps; i++) {\n t = i / steps;\n // Get the location of the point\n x = bezierPoint(85, 10, 90, 15, t);\n y = bezierPoint(20, 10, 90, 80, t);\n // Get the tangent points\n tx = bezierTangent(85, 10, 90, 15, t);\n ty = bezierTangent(20, 10, 90, 80, t);\n // Calculate an angle from the tangent points\n 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
\nnoFill();\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\nstroke(255, 102, 0);\nsteps = 16;\nfor (i = 0; i <= steps; i++) {\n t = i / steps;\n x = bezierPoint(85, 10, 90, 15, t);\n y = bezierPoint(20, 10, 90, 80, t);\n tx = bezierTangent(85, 10, 90, 15, t);\n ty = bezierTangent(20, 10, 90, 80, t);\n a = atan2(ty, tx);\n a -= HALF_PI;\n line(x, y, cos(a)*8 + x, sin(a)*8 + y);\n}\n
Draws 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// Define the curve points as JavaScript objects\np1 = {x: 5, y: 26}, p2 = {x: 73, y: 24}\np3 = {x: 73, y: 61}, 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
x-coordinate for the beginning control point
y-coordinate for the beginning control point
x-coordinate for the first point
y-coordinate for the first point
x-coordinate for the second point
y-coordinate for the second point
x-coordinate for the ending control point
y-coordinate for the ending control point
z-coordinate for the beginning control point
z-coordinate for the first point
z-coordinate for the second point
z-coordinate for the ending control point
Sets the resolution at which curves display.
of the curves
\nbackground(204);\ncurveDetail(20);\ncurve(5, 26, 5, 26, 73, 24, 73, 61);\n
Modifies the quality of forms created with curve() and curveVertex().\nThe parameter tightness determines how the curve fits to the vertex\npoints. The value 0.0 is the default value for tightness (this value\ndefines the curves to be Catmull-Rom splines) and the value 1.0 connects\nall the points with straight lines. Values within the range -5.0 and 5.0\nwill deform the curves but will leave them recognizable and as values\nincrease in magnitude, they will continue to deform.
of deformation from the original vertices
\n// Move the mouse left and right to see the curve change\n\nfunction setup() {\n createCanvas(100, 100);\n noFill();\n}\n\nfunction draw() {\n background(204);\n var 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
Evaluates the curve at position t for points a, b, c, d.\nThe parameter t varies between 0 and 1, a and d are points\non the curve, and b and c are the control points.\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.
\nnoFill();\ncurve(5, 26, 5, 26, 73, 24, 73, 61);\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nfill(255);\nellipseMode(CENTER);\nsteps = 6;\nfor (i = 0; i <= steps; i++) {\n t = i / steps;\n x = curvePoint(5, 5, 73, 73, t);\n 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
Evaluates 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.
\nnoFill();\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nsteps = 6;\nfor (i = 0; i <= steps; i++) {\n t = i / steps;\n x = curvePoint(5, 73, 73, 15, t);\n y = curvePoint(26, 24, 61, 65, t);\n //ellipse(x, y, 5, 5);\n tx = curveTangent(5, 73, 73, 15, t);\n ty = curveTangent(26, 24, 61, 65, t);\n a = atan2(ty, tx);\n a -= PI/2.0;\n line(x, y, cos(a)*8 + x, sin(a)*8 + y);\n}\n
The println() function writes to the console area of your browser.\nThis function is often helpful for looking at the data a program is\nproducing. This function creates a new line of text for each call to\nthe function. Individual elements can be\nseparated with quotes ("") and joined with the addition operator (+).\n\nWhile println() is similar to console.log(), it does not directly map to\nit in order to simulate easier to understand behavior than\nconsole.log(). Due to this, it is slower. For fastest results, use\nconsole.log().
any combination of Number, String, Object, Boolean,\n Array to print
\nvar x = 10;\nprintln(\"The value of x is \" + x);\n// prints \"The value of x is 10\"\n
The system variable frameCount contains the number of frames that have\nbeen displayed since the program started. Inside setup() the value is 0,\nafter the first iteration of draw it is 1, etc.
\n function setup() {\n frameRate(30);\n textSize(20);\n textSize(30);\n textAlign(CENTER);\n }\n\n function draw() {\n background(200);\n text(frameCount, width/2, height/2);\n }\n
Confirms if the window a p5.js program is in is "focused," meaning that\nthe sketch will accept mouse or keyboard input. This variable is\n"true" if the window is focused and "false" if not.
\n// To demonstrate, put two windows side by side.\n// Click on the window that the p5 sketch isn't in!\nfunction draw() {\n background(200);\n noStroke();\n fill(0, 200, 0);\n ellipse(25, 25, 50, 50);\n\n if (!focused) { // or \"if (focused === false)\"\n stroke(200,0,0);\n line(0, 0, 100, 100);\n line(100, 0, 0, 100);\n }\n}\n
Sets the cursor to a predefined symbol or an image, or makes it visible\nif already hidden. If you are trying to set an image as the cursor, the\nrecommended size is 16x16 or 32x32 pixels. It is not possible to load an\nimage as the cursor if you are exporting your program for the Web, and not\nall MODES work with all browsers. The values for parameters x and y must\nbe less than the dimensions of the image.
either ARROW, CROSS, HAND, MOVE, TEXT, or\n WAIT, or path for image
the horizontal active spot of the cursor
the vertical active spot of the cursor
\n// Move the mouse left and right across the image\n// to see the cursor change from a cross to a hand\nfunction draw() {\n line(width/2, 0, width/2, height);\n if (mouseX < 50) {\n cursor(CROSS);\n } else {\n cursor(HAND);\n }\n}\n
Specifies the number of frames to be displayed every second. For example,\nthe function call frameRate(30) will attempt to refresh 30 times a second.\nIf the processor is not fast enough to maintain the specified rate, the\nframe rate will not be achieved. Setting the frame rate within setup() is\nrecommended. The default rate is 60 frames per second. This is the same as\nsetFrameRate(val).\n\nCalling frameRate() with no arguments returns the current framerate. This\nis the same as getFrameRate().\n\nCalling frameRate() with arguments that are not of the type numbers\nor are non positive also returns current framerate.
number of frames to be displayed every second
\nvar rectX = 0;\nvar fr = 30; //starting FPS\nvar clr;\n\nfunction setup() {\n background(200);\n frameRate(fr); // Attempt to refresh at starting FPS\n clr = color(255,0,0);\n}\n\nfunction draw() {\n background(200);\n rectX = rectX += 1; // Move Rectangle\n\n if (rectX >= width) { // If you go off screen.\n if (fr == 30) {\n clr = color(0,0,255);\n fr = 10;\n frameRate(fr); // make frameRate 10 FPS\n } else {\n clr = color(255,0,0);\n fr = 30;\n frameRate(fr); // make frameRate 30 FPS\n }\n rectX = 0;\n }\n fill(clr);\n rect(rectX, 40, 20,20);\n}\n
Returns the current framerate.
Specifies the number of frames to be displayed every second. For example,\nthe function call frameRate(30) will attempt to refresh 30 times a second.\nIf the processor is not fast enough to maintain the specified rate, the\nframe rate will not be achieved. Setting the frame rate within setup() is\nrecommended. The default rate is 60 frames per second.
Calling frameRate() with no arguments returns the current framerate.
Hides the cursor from view.
\nfunction setup() {\n noCursor();\n}\n\nfunction draw() {\n background(200);\n ellipse(mouseX, mouseY, 10, 10);\n}\n
System variable that stores the width of the entire screen display. This\nis used to run a full-screen program on any display size.
\ncreateCanvas(displayWidth, displayHeight);\n
System variable that stores the height of the entire screen display. This\nis used to run a full-screen program on any display size.
System variable that stores the width of the inner window, it maps to\nwindow.innerWidth.
\ncreateCanvas(windowWidth, windowHeight);\n
System variable that stores the height of the inner window, it maps to\nwindow.innerHeight.
The windowResized() function is called once every time the browser window\nis resized. This is a good place to resize the canvas or do any other\nadjustements to accomodate the new window size.
\nfunction setup() {\n createCanvas(windowWidth, windowHeight);\n}\n\nfunction draw() {\n background(0, 100, 200);\n}\n\nfunction windowResized() {\n resizeCanvas(windowWidth, windowHeight);\n}\n
System variable that stores the width of the drawing canvas. This value\nis set by the first parameter of the createCanvas() function.\nFor example, the function call createCanvas(320, 240) sets the width\nvariable to the value 320. The value of width defaults to 100 if\ncreateCanvas() is not used in a program.
System variable that stores the height of the drawing canvas. This value\nis set by the second parameter of the createCanvas() function. For\nexample, the function call createCanvas(320, 240) sets the height\nvariable to the value 240. The value of height defaults to 100 if\ncreateCanvas() is not used in a program.
If argument is given, sets the sketch to fullscreen or not based on the\nvalue of the argument. If no argument is given, returns the current\nfullscreen state. Note that due to browser restrictions this can only\nbe called on user input, for example, on mouse press like the example\nbelow.
whether the sketch should be in fullscreen mode\nor not
\n// Clicking in the box toggles fullscreen on and off.\nfunction setup() {\n background(200);\n}\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n var fs = fullscreen();\n fullscreen(!fs);\n }\n}\n
Sets the pixel scaling for high pixel density displays. By default\npixel density is set to match display density, call pixelDensity(1)\nto turn this off. Calling pixelDensity() with no arguments returns\nthe current pixel density of the sketch.
whether or how much the sketch should scale
\nfunction setup() {\n pixelDensity(1);\n createCanvas(100, 100);\n background(200);\n ellipse(width/2, height/2, 50, 50);\n}\n
\nfunction setup() {\n pixelDensity(3.0);\n createCanvas(100, 100);\n background(200);\n ellipse(width/2, height/2, 50, 50);\n}\n
Returns the pixel density of the current display the sketch is running on.
\nfunction setup() {\n var density = displayDensity();\n pixelDensity(density);\n createCanvas(100, 100);\n background(200);\n ellipse(width/2, height/2, 50, 50);\n}\n
Gets the current URL.
\nvar url;\nvar x = 100;\n\nfunction setup() {\n fill(0);\n noStroke();\n url = getURL();\n}\n\nfunction draw() {\n background(200);\n text(url, x, height/2);\n x--;\n}\n
Gets the current URL path as an array.
\nfunction setup() {\n var urlPath = getURLPath();\n for (var i=0; i<urlPath.length; i++) {\n text(urlPath[i], 10, i*20+20);\n }\n}\n
Gets the current URL params as an Object.
\n// Example: http://p5js.org?year=2014&month=May&day=15\n\nfunction setup() {\n var params = getURLParams();\n text(params.day, 10, 20);\n text(params.month, 10, 40);\n text(params.year, 10, 60);\n}\n
Checks the definition type against the argument type\nIf any of these passes (in order), it matches:
Prints out a fancy, colorful message to the console log
the words to be said
the name of the function to link
CSS color string or error type
Validate all the parameters of a function for number and type\nNOTE THIS FUNCTION IS TEMPORARILY DISABLED UNTIL FURTHER WORK\nAND UPDATES ARE IMPLEMENTED. -LMCCART
name of function we're checking
pass of the JS default arguments array
List of types accepted ['Number', 'String, ...] OR\n a list of lists for each format: [\n ['String', 'Number', 'Number'],\n ['String', 'Number', 'Number', 'Number', 'Number'\n ]
Prints out all the colors in the color pallete with white text.\nFor color blindness testing.
Underlying HTML element. All normal HTML methods can be called on this.
Attaches the element to the parent specified. A way of setting\n the container for the element. Accepts either a string ID, DOM\n node, or p5.Element. If no arguments given, parent node is returned.\n For more ways to position the canvas, see the\n \n positioning the canvas wiki page.
the ID, DOM node, or p5.Element\n of desired parent element
\n // in the html file:\n <div id=\"myContainer\"></div>\n // in the js file:\n var cnv = createCanvas(100, 100);\n cnv.parent(\"myContainer\");\n
\n var div0 = createDiv('this is the parent');\n var div1 = createDiv('this is the child');\n div1.parent(div0); // use p5.Element\n
\n var div0 = createDiv('this is the parent');\n div0.id('apples');\n var div1 = createDiv('this is the child');\n div1.parent('apples'); // use id\n
\n var elt = document.getElementById('myParentDiv');\n var div1 = createDiv('this is the child');\n div1.parent(elt); // use element from page\n
Sets the ID of the element. If no ID argument is passed in, it instead\n returns the current ID of the element.
ID of the element
\n function setup() {\n var cnv = createCanvas(100, 100);\n // Assigns a CSS selector ID to\n // the canvas element.\n cnv.id(\"mycanvas\");\n }\n
Adds given class to the element. If no class argument is passed in, it\n instead returns a string containing the current class(es) of the element.
class to add
The .mousePressed() function is called once after every time a\nmouse button is pressed over the element. This can be used to\nattach element specific event listeners.
function to be fired when mouse is\n pressed over the element.
\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mousePressed(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width/2, height/2, d, d);\n}\n\n// this function fires with any click anywhere\nfunction mousePressed() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
The .mouseWheel() function is called once after every time a\nmouse wheel is scrolled over the element. This can be used to\nattach element specific event listeners.\nThe event.wheelDelta or event.detail property returns negative values if\nthe mouse wheel if rotated up or away from the user and positive in the\nother direction. On OS X with "natural" scrolling enabled, the values are\nopposite.
function to be fired when mouse wheel is\n scrolled over the element.
\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseWheel(changeSize); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width/2, height/2, d, d);\n}\n\n// this function fires with mousewheel movement\n// anywhere on screen\nfunction mouseWheel() {\n g = g + 10;\n}\n\n// this function fires with mousewheel movement\n// over canvas only\nfunction changeSize() {\n if (event.wheelDelta > 0) {\n d = d + 10;\n } else {\n d = d - 10;\n }\n}\n
The .mouseReleased() function is called once after every time a\nmouse button is released over the element. This can be used to\nattach element specific event listeners.
function to be fired when mouse is\n released over the element.
\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseReleased(changeGray); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width/2, height/2, d, d);\n}\n\n// this function fires after the mouse has been\n// released\nfunction mouseReleased() {\n d = d + 10;\n}\n\n// this function fires after the mouse has been\n// released while on canvas\nfunction changeGray() {\n g = random(0, 255);\n}\n
The .mouseClicked() function is called once after a mouse button is\npressed and released over the element. This can be used to\nattach element specific event listeners.
function to be fired when mouse is\n clicked over the element.
The .mouseMoved() function is called once every time a\nmouse moves over the element. This can be used to attach an\nelement specific event listener.
function to be fired when mouse is\n moved over the element.
\nvar cnv;\nvar d = 30;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseMoved(changeSize); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n fill(200);\n ellipse(width/2, height/2, d, d);\n}\n\n// this function fires when mouse moves anywhere on\n// page\nfunction mouseMoved() {\n g = g + 5;\n if (g > 255) {\n g = 0;\n }\n}\n\n// this function fires when mouse moves over canvas\nfunction changeSize() {\n d = d + 2;\n if (d > 100) {\n d = 0;\n }\n}\n
The .mouseOver() function is called once after every time a\nmouse moves onto the element. This can be used to attach an\nelement specific event listener.
\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseOver(changeGray);\n d = 10;\n}\n\nfunction draw() {\n ellipse(width/2, height/2, d, d);\n}\n\nfunction changeGray() {\n d = d + 10;\n if (d > 100) {\n d = 0;\n }\n}\n
The .changed() function is called when the value of an\nelement is changed.\nThis can be used to attach an element specific event listener.
function to be fired when the value of an\nelement changes.
\nvar sel;\n\nfunction setup() {\n textAlign(CENTER);\n background(200);\n sel = createSelect();\n sel.position(10, 10);\n sel.option('pear');\n sel.option('kiwi');\n sel.option('grape');\n sel.changed(mySelectEvent);\n}\n\nfunction mySelectEvent() {\n var item = sel.value();\n background(200);\n text(\"it's a \"+item+\"!\", 50, 50);\n}\n
\nvar checkbox;\nvar cnv;\n\nfunction setup() {\n checkbox = createCheckbox(\" fill\");\n checkbox.changed(changeFill);\n cnv = createCanvas(100, 100);\n cnv.position(0, 30);\n noFill();\n}\n\nfunction draw() {\n background(200);\n ellipse(50, 50, 50, 50);\n}\n\nfunction changeFill() {\n if (checkbox.checked()) {\n fill(0);\n } else {\n noFill();\n }\n}\n
The .input() function is called when any user input is\ndetected with an element. The input event is often used\nto detect keystrokes in a input element, or changes on a\nslider element. This can be used to attach an element specific\nevent listener.
function to be fired on user input.
\n// Open your console to see the output\nfunction setup() {\n var inp = createInput('');\n inp.input(myInputEvent);\n}\n\nfunction myInputEvent() {\n console.log('you are typing: ', this.value());\n}\n
The .mouseOut() function is called once after every time a\nmouse moves off the element. This can be used to attach an\nelement specific event listener.
function to be fired when mouse is\n moved off the element.
\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseOut(changeGray);\n d = 10;\n}\n\nfunction draw() {\n ellipse(width/2, height/2, d, d);\n}\n\nfunction changeGray() {\n d = d + 10;\n if (d > 100) {\n d = 0;\n }\n}\n
The .touchStarted() function is called once after every time a touch is\nregistered. This can be used to attach element specific event listeners.
function to be fired when touch is\n started over the element.
\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchStarted(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width/2, height/2, d, d);\n}\n\n// this function fires with any touch anywhere\nfunction touchStarted() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
The .touchMoved() function is called once after every time a touch move is\nregistered. This can be used to attach element specific event listeners.
function to be fired when touch is moved\n over the element.
\nvar cnv;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchMoved(changeGray); // attach listener for\n // canvas click only\n g = 100;\n}\n\nfunction draw() {\n background(g);\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
The .touchEnded() function is called once after every time a touch is\nregistered. This can be used to attach element specific event listeners.
function to be fired when touch is\n ended over the element.
\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchEnded(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width/2, height/2, d, d);\n}\n\n// this function fires with any touch anywhere\nfunction touchEnded() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
The .dragOver() function is called once after every time a\nfile is dragged over the element. This can be used to attach an\nelement specific event listener.
function to be fired when mouse is\n dragged over the element.
The .dragLeave() function is called once after every time a\ndragged file leaves the element area. This can be used to attach an\nelement specific event listener.
The .drop() function is called for each file dropped on the element.\nIt requires a callback that is passed a p5.File object. You can\noptionally pass two callbacks, the first one (required) is triggered\nfor each file dropped when the file is loaded. The second (optional)\nis triggered just once when a file (or files) are dropped.
triggered when files are dropped.
to receive loaded file.
\nfunction setup() {\n var c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('drop image', width/2, height/2);\n c.drop(gotFile);\n}\n\nfunction gotFile(file) {\n var img = createImg(file.data).hide();\n // Draw the image onto the canvas\n image(img, 0, 0, width, height);\n}\n
Helper fxn for sharing pixel methods
Resize our canvas element.
Helper fxn to check font type (system or otf)
Helper fxn to measure ascent and descent.\nAdapted from http://stackoverflow.com/a/25355178
p5.Renderer2D\nThe 2D graphics canvas renderer class.\nextends p5.Renderer
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.
size
start
See www.joecridge.me/bezier.pdf for an explanation of the method.
Creates a canvas element in the document, and sets the dimensions of it\nin pixels. This method should be called only once at the start of setup.\nCalling createCanvas more than once in a sketch will result in very\nunpredicable behavior. If you want more than one drawing canvas\nyou could use createGraphics (hidden by default but it can be shown).\n\nThe system variables width and height are set by the parameters passed\nto this function. If createCanvas() is not used, the window will be\ngiven a default size of 100x100 pixels.\n\nFor more ways to position the canvas, see the\n\npositioning the canvas wiki page.
width of the canvas
height of the canvas
P2D or WEBGL
\nfunction setup() {\n createCanvas(100, 50);\n background(153);\n line(0, 0, width, height);\n}\n
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.
Removes the default canvas for a p5 sketch that doesn't\nrequire a canvas
\nfunction setup() {\n noCanvas();\n}\n
Creates and returns a new p5.Renderer object. Use this class if you need\nto draw into an off-screen graphics buffer. The two parameters define the\nwidth and height in pixels.
width of the offscreen graphics buffer
height of the offscreen graphics buffer
P2D or WEBGL\nundefined defaults to p2d
\nvar pg;\nfunction setup() {\n createCanvas(100, 100);\n pg = createGraphics(100, 100);\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
Blends 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):
BLEND
ADD
DARKEST
LIGHTEST
DIFFERENCE
EXCLUSION
MULTIPLY
SCREEN
REPLACE
OVERLAY
SCREEN\n
HARD_LIGHT
SOFT_LIGHT
DODGE
BURN
blend mode to set for canvas
\nblendMode(LIGHTEST);\nstrokeWeight(30);\nstroke(80, 150, 255);\nline(25, 25, 75, 75);\nstroke(255, 50, 50);\nline(75, 25, 25, 75);\n
\nblendMode(MULTIPLY);\nstrokeWeight(30);\nstroke(80, 150, 255);\nline(25, 25, 75, 75);\nstroke(255, 50, 50);\nline(75, 25, 25, 75);\n
shim for Uint8ClampedArray.slice\n(allows arrayCopy to work with pixels[])\nwith thanks to http://halfpapstudios.com/blog/tag/html5-canvas/\nEnumerable set to false to protect for...in from\nUint8ClampedArray.prototype pollution.
Stops p5.js from continuously executing the code within draw().\nIf loop() is called, the code in draw() begins to run continuously again.\nIf using noLoop() in setup(), it should be the last line inside the block.\n\nWhen noLoop() is used, it's not possible to manipulate or access the\nscreen inside event handling functions such as mousePressed() or\nkeyPressed(). Instead, use those functions to call redraw() or loop(),\nwhich will run draw(), which can update the screen properly. This means\nthat when noLoop() has been called, no drawing can happen, and functions\nlike saveFrame() or loadPixels() may not be used.\n\nNote that if the sketch is resized, redraw() will be called to update\nthe sketch, even after noLoop() has been specified. Otherwise, the sketch\nwould enter an odd state until loop() was called.
\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n noLoop();\n}\n\nfunction draw() {\n line(10, 10, 90, 90);\n}\n
\nvar 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
By default, p5.js loops through draw() continuously, executing the code\nwithin it. However, the draw() loop may be stopped by calling noLoop().\nIn that case, the draw() loop can be resumed with loop().
\nvar 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
The push() function saves the current drawing style settings and\ntransformations, while pop() restores these settings. Note that these\nfunctions are always used together. They allow you to change the style\nand transformation settings and later return to what you had. When a new\nstate is started with push(), it builds on the current style and transform\ninformation. The push() and pop() functions can be embedded to provide\nmore control. (See the second example for a demonstration.)\n\npush() stores information related to the current transformation state\nand style settings controlled by the following functions: fill(),\nstroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(),\nimageMode(), rectMode(), ellipseMode(), colorMode(), textAlign(),\ntextFont(), textMode(), textSize(), textLeading().
\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
\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
\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
Executes the code within draw() one time. This functions allows the\n program to update the display window only when necessary, for example\n when an event registered by mousePressed() or keyPressed() occurs.\n \n In structuring a program, it only makes sense to call redraw() within\n events such as mousePressed(). This is because redraw() does not run\n draw() immediately (it only sets a flag that indicates an update is\n needed).\n \n The redraw() function does not work properly when called inside draw().\n To enable/disable animations, use loop() and noLoop().\n \n In addition you can set the number of redraws per method call. Just\n add an integer as single parameter for the number of redraws.
Redraw for n-times. The default value is 1.
\n var x = 0;\nfunction setup() {\n createCanvas(100, 100);\n noLoop();\n }\nfunction draw() {\n background(204);\n line(x, 0, x, height);\n }\nfunction mousePressed() {\n x += 1;\n redraw();\n }\n
\n var x = 0;\nfunction setup() {\n createCanvas(100, 100);\n noLoop();\n }\nfunction draw() {\n background(204);\n x += 1;\n line(x, 0, x, height);\n }\nfunction mousePressed() {\n redraw(5);\n }\n
Multiplies the current matrix by the one specified through the parameters.\nThis is very slow because it will try to calculate the inverse of the\ntransform, so avoid it whenever possible.
numbers which define the 3x2 matrix to be multiplied
\n// Example in the works.\n
Replaces the current matrix with the identity matrix.
Rotates a shape the amount specified by the angle parameter. This\nfunction accounts for angleMode, so angles can be entered in either\nRADIANS or DEGREES.\n\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 accumulates the effect. For example, calling\nrotate(HALF_PI) and then rotate(HALF_PI) is the same as rotate(PI).\nAll tranformations are reset when draw() begins again.\n\nTechnically, rotate() multiplies the current transformation matrix\nby a rotation matrix. This function can be further controlled by\nthe push() and pop().
\ntranslate(width/2, height/2);\nrotate(PI/3.0);\nrect(-26, -26, 52, 52);\n
the angle of rotation, specified in radians\n or degrees, depending on current angleMode
angle in radians
axis to rotate around
Rotates around X axis.
angles in radians
Rotates around Y axis.
Rotates around Z axis. Webgl mode only.
Increases or decreases the size of a shape by expanding and 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%.\n\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.\n\nUsing this function with the z parameter is only available in WEBGL mode.\nThis function can be further controlled with push() and pop().
percent to scale the object, or percentage to\n scale the object in the x-axis if multiple arguments\n are given
percent to scale the object in the y-axis
percent to scale the object in the z-axis (webgl only)
\nrect(30, 20, 50, 50);\nscale(0.5, 1.3);\nrect(30, 20, 50, 50);\n
Shears a shape around the x-axis 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.\n\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(), the transformation is reset when\nthe loop begins again.\n\nTechnically, shearX() multiplies the current transformation matrix by a\nrotation matrix. This function can be further controlled by the\npush() and pop() functions.
angle of shear specified in radians or degrees,\n depending on current angleMode
\ntranslate(width/4, height/4);\nshearX(PI/4.0);\nrect(0, 0, 30, 30);\n
Shears 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.\n\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.\n\nTechnically, shearY() multiplies the current transformation matrix by a\nrotation matrix. This function can be further controlled by the\npush() and pop() functions.
\ntranslate(width/4, height/4);\nshearY(PI/4.0);\nrect(0, 0, 30, 30);\n
Specifies an amount to displace objects within the display window.\nThe x parameter specifies left/right translation, the y parameter\nspecifies up/down translation.\n\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().
left/right translation
up/down translation
forward/backward translation (webgl only)
\ntranslate(30, 20);\nrect(0, 0, 55, 55);\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
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.\n\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.
\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
Using 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.\n\nThe parameters available for beginShape() are POINTS, LINES, TRIANGLES,\nTRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP. After calling the\nbeginShape() 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.\n\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().
either POINTS, LINES, TRIANGLES, TRIANGLE_FAN\n TRIANGLE_STRIP, QUADS, or QUAD_STRIP
\nbeginShape();\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape(CLOSE);\n
\n// currently not working\nbeginShape(POINTS);\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n
\nbeginShape(LINES);\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n
\nnoFill();\nbeginShape();\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n
\nnoFill();\nbeginShape();\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape(CLOSE);\n
\nbeginShape(TRIANGLES);\nvertex(30, 75);\nvertex(40, 20);\nvertex(50, 75);\nvertex(60, 20);\nvertex(70, 75);\nvertex(80, 20);\nendShape();\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
\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
\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
\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
\nbeginShape();\nvertex(20, 20);\nvertex(40, 20);\nvertex(40, 40);\nvertex(60, 40);\nvertex(60, 60);\nvertex(20, 60);\nendShape(CLOSE);\n
Specifies 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.\n\nThe first time bezierVertex() is used within a\nbeginShape() call, it must be prefaced with a call to vertex()\nto set the first anchor point. This function must be used between\nbeginShape() and endShape() and only when there is no MODE\nparameter specified to beginShape().
x-coordinate for the anchor point
y-coordinate for the anchor point
\nnoFill();\nbeginShape();\nvertex(30, 20);\nbezierVertex(80, 0, 80, 75, 30, 75);\nendShape();\n
\nbeginShape();\nvertex(30, 20);\nbezierVertex(80, 0, 80, 75, 30, 75);\nbezierVertex(50, 80, 60, 25, 30, 20);\nendShape();\n
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().\n\nThe first and last points in a series of curveVertex() lines will be used to\nguide the beginning and end of a 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.
x-coordinate of the vertex
y-coordinate of the vertex
\nnoFill();\nbeginShape();\ncurveVertex(84, 91);\ncurveVertex(84, 91);\ncurveVertex(68, 19);\ncurveVertex(21, 17);\ncurveVertex(32, 100);\ncurveVertex(32, 100);\nendShape();\n
The endShape() function is the companion to beginShape() and may only be\ncalled after beginShape(). When endshape() is called, all of image data\ndefined since the previous call to beginShape() is written into the image\nbuffer. The constant CLOSE as the value for the MODE parameter to close\nthe shape (to connect the beginning and the end).
use CLOSE to close the shape
\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
Specifies 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.\nThis function must be used between beginShape() and endShape() and only\nwhen there is no MODE parameter specified to beginShape().
x-coordinate for the control point
y-coordinate for the control point
\nnoFill();\nstrokeWeight(4);\nbeginShape();\nvertex(20, 20);\nquadraticVertex(80, 20, 50, 50);\nendShape();\n
\nnoFill();\nstrokeWeight(4);\nbeginShape();\nvertex(20, 20);\nquadraticVertex(80, 20, 50, 50);\nquadraticVertex(20, 80, 80, 80);\nvertex(80, 60);\nendShape();\n
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.
\nbeginShape(POINTS);\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n
The system variable deviceOrientation always contains the orientation of\nthe device. The value of this variable will either be set 'landscape'\nor 'portrait'. If no data is available it will be set to 'undefined'.
The system variable accelerationX always contains the acceleration of the\ndevice along the x axis. Value is represented as meters per second squared.
The system variable accelerationY always contains the acceleration of the\ndevice along the y axis. Value is represented as meters per second squared.
The system variable accelerationZ always contains the acceleration of the\ndevice along the z axis. Value is represented as meters per second squared.
The system variable pAccelerationX always contains the acceleration of the\ndevice along the x axis in the frame previous to the current frame. Value\nis represented as meters per second squared.
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.
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.
_updatePAccelerations updates the pAcceleration values
The system variable rotationX always contains the rotation of the\ndevice along the x axis. Value is represented as 0 to +/-180 degrees.\n\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.
\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}\n
The system variable rotationY always contains the rotation of the\ndevice along the y axis. Value is represented as 0 to +/-90 degrees.\n\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.
\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}\n
The system variable rotationZ always contains the rotation of the\ndevice along the z axis. Value is represented as 0 to 359 degrees.\n\nUnlike rotationX and rotationY, this variable is available for devices\nwith a built-in compass only.\n\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.
\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}\n
The system variable pRotationX always contains the rotation of the\ndevice along the x axis in the frame previous to the current frame. Value\nis represented as 0 to +/-180 degrees.\n\npRotationX can also be used with rotationX to determine the rotate\ndirection of the device along the X-axis.
\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.\nvar rotateDirection = 'clockwise';\n\n// Simple range conversion to make things simpler.\n// This is not absolutely neccessary but the logic\n// will be different in that case.\n\nvar rX = rotationX + 180;\nvar 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
The system variable pRotationY always contains the rotation of the\ndevice along the y axis in the frame previous to the current frame. Value\nis represented as 0 to +/-90 degrees.\n\npRotationY can also be used with rotationY to determine the rotate\ndirection of the device along the Y-axis.
\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.\nvar rotateDirection = 'clockwise';\n\n// Simple range conversion to make things simpler.\n// This is not absolutely neccessary but the logic\n// will be different in that case.\n\nvar rY = rotationY + 180;\nvar 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}\n
The system variable pRotationZ always contains the rotation of the\ndevice along the z axis in the frame previous to the current frame. Value\nis represented as 0 to 359 degrees.\n\npRotationZ can also be used with rotationZ to determine the rotate\ndirection of the device along the Z-axis.
\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.\nvar rotateDirection = 'clockwise';\n\nif ((rotationZ - pRotationZ > 0 &&\n rotationZ - pRotationZ < 270)||\n rotationZ - pRotationZ < -270){\n\n rotateDirection = 'clockwise';\n\n} else if (rotationZ - pRotationZ < 0 ||\n rotationZ - pRotationZ > 270){\n\n rotateDirection = 'counter-clockwise';\n\n}\n
The setMoveThreshold() function is used to set the movement threshold for\nthe deviceMoved() function. The default threshold is set to 0.5.
The threshold value
The setShakeThreshold() function is used to set the movement threshold for\nthe deviceShaken() function. The default threshold is set to 30.
The deviceMoved() function is called when the device is moved by more than\nthe threshold value along X, Y or Z axis. The default threshold is set to\n0.5.
\n// Run this example on a mobile device\n// Move the device around\n// to change the value.\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n
The deviceTurned() function is called when the device rotates by\nmore than 90 degrees continuously.\n\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// Run this example on a mobile device\n// Rotate the device by 90 degrees\n// to change the value.\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceTurned() {\n if (value == 0){\n value = 255\n } else if (value == 255) {\n value = 0;\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\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\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
The deviceShaken() function is called when the device total acceleration\nchanges of accelerationX and accelerationY values is more than\nthe threshold value. The default threshold is set to 30.
\n// Run this example on a mobile device\n// Shake the device to change the value.\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceShaken() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n
Holds the key codes of currently pressed keys.
The boolean system variable keyIsPressed is true if any key is pressed\nand false if no keys are pressed.
\nvar value = 0;\nfunction draw() {\n if (keyIsPressed === true) {\n fill(0);\n } else {\n fill(255);\n }\n rect(25, 25, 50, 50);\n}\n
The 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// 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}\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.
\nvar fillVal = 126;\nfunction draw() {\n fill(fillVal);\n rect(25, 25, 50, 50);\n}\n\nfunction keyPressed() {\n if (keyCode == UP_ARROW) {\n fillVal = 255;\n } else if (keyCode == DOWN_ARROW) {\n fillVal = 0;\n }\n return false; // prevent default\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.\n\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.\n\nFor ASCII keys 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.\n\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.
\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyPressed() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyPressed() {\n if (keyCode === LEFT_ARROW) {\n value = 255;\n } else if (keyCode === RIGHT_ARROW) {\n value = 0;\n }\n}\n
\nfunction keyPressed(){\n // Do something\n return false; // prevent any default behaviour\n}\n
The 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 method.
\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\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
The keyTyped() function is called once every time a key is pressed, but\naction keys such as Ctrl, Shift, and Alt are ignored. The most recent\nkey pressed will be stored in the key variable.\n\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 method.
\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\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
The 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.
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.
The key to check for.
\nvar x = 100;\nvar y = 100;\n\nfunction setup() {\n createCanvas(512, 512);\n}\n\nfunction draw() {\n if (keyIsDown(LEFT_ARROW))\n x-=5;\n\n if (keyIsDown(RIGHT_ARROW))\n x+=5;\n\n if (keyIsDown(UP_ARROW))\n y-=5;\n\n if (keyIsDown(DOWN_ARROW))\n y+=5;\n\n clear();\n fill(255, 0, 0);\n ellipse(x, y, 50, 50);\n}\n
The system variable mouseX always contains the current horizontal\nposition of the mouse, relative to (0, 0) of the canvas.
\n// Move the mouse across the canvas\nfunction draw() {\n background(244, 248, 252);\n line(mouseX, 0, mouseX, 100);\n}\n
The system variable mouseY always contains the current vertical position\nof the mouse, relative to (0, 0) of the canvas.
\n// Move the mouse across the canvas\nfunction draw() {\n background(244, 248, 252);\n line(0, mouseY, 100, mouseY);\n}\n
The system variable pmouseX always contains the horizontal position of\nthe mouse in the frame previous to the current frame, relative to (0, 0)\nof the canvas.
\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 println(pmouseX + \" -> \" + mouseX);\n}\n\n
The system variable pmouseY always contains the vertical position of the\nmouse in the frame previous to the current frame, relative to (0, 0) of\nthe canvas.
\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 println(pmouseY + \" -> \" + mouseY);\n}\n\n
The system variable winMouseX always contains the current horizontal\nposition of the mouse, relative to (0, 0) of the window.
\nvar myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\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}\n\n
The system variable winMouseY always contains the current vertical\nposition of the mouse, relative to (0, 0) of the window.
\nvar myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\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}\n\n
The 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.
\n\nvar 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 var 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}\n\n
The 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.
\n\nvar 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 var 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}\n\n
Processing 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.
\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n if (mouseIsPressed) {\n if (mouseButton == LEFT)\n ellipse(50, 50, 50, 50);\n if (mouseButton == RIGHT)\n rect(25, 25, 50, 50);\n if (mouseButton == CENTER)\n triangle(23, 75, 50, 20, 78, 75);\n }\n\n println(mouseButton);\n}\n
The boolean system variable mouseIsPressed is true if the mouse is pressed\nand false if not.
\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n if (mouseIsPressed)\n ellipse(50, 50, 50, 50);\n else\n rect(25, 25, 50, 50);\n\n println(mouseIsPressed);\n}\n
The 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.
\n// Move the mouse across the page\n// to change its value\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n
\nfunction mouseMoved() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
The 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 method.
\n// Drag the mouse across the page\n// to change its value\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseDragged() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n
\nfunction mouseDragged() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
The 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 method.
\n// Click within the image to change\n// the value of the rectangle\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mousePressed() {\n if (value == 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\nfunction mousePressed() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
The 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 method.
\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been clicked\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseReleased() {\n if (value == 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\nfunction mouseReleased() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
The mouseClicked() function is called once after a mouse button has been\npressed and then released.\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.
\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been clicked\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseClicked() {\n if (value == 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\nfunction mouseClicked() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
The 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 OS X 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.
\nvar pos = 25;\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n rect(25, pos, 50, 50);\n}\n\nfunction mouseWheel(event) {\n println(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
The system variable touchX always contains the horizontal position of\none finger, relative to (0, 0) of the canvas. This is best used for\nsingle touch interactions. For multi-touch interactions, use the\ntouches[] array.
\n// Touch and move the finger in horizontally across the canvas\nfunction setup() {\n createCanvas(100, 100);\n}\n\nfunction draw() {\n background(51);\n stroke(255, 204, 0);\n strokeWeight(4);\n rect(touchX, 50, 10, 10);\n}\n
The system variable touchY always contains the vertical position of\none finger, relative to (0, 0) of the canvas. This is best used for\nsingle touch interactions. For multi-touch interactions, use the\ntouches[] array.
\n// Touch and move the finger vertically across the canvas\nfunction setup() {\n createCanvas(100, 100);\n}\n\nfunction draw() {\n background(51);\n stroke(255, 204, 0);\n strokeWeight(4);\n rect(50, touchY, 10, 10);\n}\n
The system variable ptouchX always contains the horizontal position of\none finger, relative to (0, 0) of the canvas, in the frame previous to the\ncurrent frame.
The system variable ptouchY always contains the vertical position of\none finger, relative to (0, 0) of the canvas, in the frame previous to the\ncurrent frame.
The 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.
The boolean system variable touchIsDown is true if the screen is\ntouched and false if not.
The 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.
\n// Touch within the image to change\n// the value of the rectangle\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchStarted() {\n if (value == 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\nfunction touchStarted() {\n ellipse(touchX, touchY, 5, 5);\n // prevent default\n return false;\n}\n
The 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.
\n// Move your finger across the page\n// to change its value\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n
\nfunction touchMoved() {\n ellipse(touchX, touchY, 5, 5);\n // prevent default\n return false;\n}\n
The 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.
\n// Release touch within the image to\n// change the value of the rectangle\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchEnded() {\n if (value == 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\nfunction touchEnded() {\n ellipse(touchX, touchY, 5, 5);\n // prevent default\n return false;\n}\n
This module defines the filters for use with image buffers.
This 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.
Generally speaking users of this module will use the Filters.apply method\non a canvas to create an effect.
A number of functions are borrowed/adapted from\nhttp://www.html5rocks.com/en/tutorials/canvas/imagefilters/\nor the java processing implementation.
Returns the pixel buffer for a canvas
the canvas to get pixels from
Returns a 32 bit number containing ARGB data at ith pixel in the\n1D array containing pixels data.
array returned by _toPixels()
index of a 1D Image Array
Modifies pixels RGBA values to values contained in the data object.
source 1D array where each value\n represents ARGB values
Returns the ImageData object for a canvas\nhttps://developer.mozilla.org/en-US/docs/Web/API/ImageData
canvas to get image data from
Returns a blank ImageData object.
Applys a filter function to a canvas.
The difference between this and the actual filter functions defined below\nis that the filter functions generally modify the pixel buffer but do\nnot actually put that data back to the canvas (where it would actually\nupdate what is visible). By contrast this method does make the changes\nactually visible in the canvas.
The apply method is the method that callers of this module would generally\nuse. It has been separated from the actual filters to support an advanced\nuse case of creating a filter chain that executes without actually updating\nthe canvas in between everystep.
[description]
Converts the image to black and white pixels depending if they are above or\nbelow the threshold defined by the level parameter. The parameter must be\nbetween 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used.
Borrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/
Converts any colors in the image to grayscale equivalents.\nNo parameter is used.
Sets the alpha channel to entirely opaque. No parameter is used.
Sets each pixel to its inverse value. No parameter is used.
Limits each channel of the image to the number of colors specified as\nthe parameter. The parameter can be set to values between 2 and 255, but\nresults are most noticeable in the lower ranges.
Adapted from java based processing implementation
reduces the bright areas in an image
increases the bright areas in an image
This module defines the p5 methods for the p5.Image class\nfor drawing images to the main display canvas.
Creates a new p5.Image (the datatype for storing images). This provides a\nfresh buffer of pixels to play with. Set the size of the buffer with the\nwidth and height parameters.\n\n.pixels gives access to an array containing the values for all the pixels\nin the display window.\nThese values are numbers. This array is the size (including an appropriate\nfactor for the pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. See .pixels for\nmore info. It may also be simpler to use set() or get().\n\nBefore accessing the pixels of an image, the data must loaded with the\nloadPixels() function. After the array data has been modified, the\nupdatePixels() function must be run to update the changes.
width in pixels
height in pixels
\nimg = createImage(66, 66);\nimg.loadPixels();\nfor (i = 0; i < img.width; i++) {\n for (j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\n
\nimg = createImage(66, 66);\nimg.loadPixels();\nfor (i = 0; i < img.width; i++) {\n for (j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102, i % img.width * 2));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\nimage(img, 34, 34);\n
\nvar pink = color(255, 102, 204);\nimg = createImage(66, 66);\nimg.loadPixels();\nvar d = pixelDensity;\nvar halfImage = 4 * (width * d) * (height/2 * d);\nfor (var i = 0; i < halfImage; i+=4) {\n img.pixels[i] = red(pink);\n img.pixels[i+1] = green(pink);\n img.pixels[i+2] = blue(pink);\n img.pixels[i+3] = alpha(pink);\n}\nimg.updatePixels();\nimage(img, 17, 17);\n
Save the current canvas as an image. In Safari, this will open the\nimage in the window and the user must provide their own\nfilename on save-as. Other browsers will either save the\nfile immediately, or prompt the user with a dialogue window.
a variable representing a\n specific html5 canvas (optional)
'jpg' or 'png'
\nfunction setup() {\n var c = createCanvas(100, 100);\n background(255, 0, 0);\n saveCanvas(c, 'myCanvas', 'jpg');\n}\n
\n// note that this example has the same result as above\n// if no canvas is specified, defaults to main canvas\nfunction setup() {\n createCanvas(100, 100);\n background(255, 0, 0);\n saveCanvas('myCanvas', 'jpg');\n}\n
\n// all of the following are valid\nsaveCanvas(c, 'myCanvas', 'jpg');\nsaveCanvas(c, 'myCanvas');\nsaveCanvas(c);\nsaveCanvas('myCanvas', 'png');\nsaveCanvas('myCanvas');\nsaveCanvas();\n
Capture a sequence of frames that can be used to create a movie.\nAccepts a callback. For example, you may wish to send the frames\nto a server where they can be stored or converted into a movie.\nIf no callback is provided, the browser will pop up save dialogues in an\nattempt to download all of the images that have just been created. With the\ncallback provided the image data isn't saved by default but instead passed\nas an argument to the callback function as an array of objects, with the\nsize of array equal to the total number of frames.
Duration in seconds to save the frames for.
Framerate to save the frames in.
A callback function that will be executed\n to handle the image data. This function\n should accept an array as argument. The\n array will contain the specified number of\n frames of objects. Each object has three\n properties: imageData - an\n image/octet-stream, filename and extension.
\nfunction draw() {\n background(mouseX);\n}\n\nfunction mousePressed() {\n saveFrames(\"out\", \"png\", 1, 25, function(data){\n println(data);\n });\n}\n
Loads an image from a path and creates a p5.Image from it.\n\nThe image may not be immediately available for rendering\nIf you want to ensure that the image is ready before doing\nanything with it, place the loadImage() call in preload().\nYou may also supply a callback function to handle the image when it's ready.\n\nThe path to the image should be relative to the HTML file\nthat links in your sketch. Loading an from a URL or other\nremote location may be blocked due to your browser's built-in\nsecurity.
Path of the image to be loaded
Function to be called once\n the image is loaded. Will be passed the\n p5.Image.
called with event error if\n the image fails to load.
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/laDefense.jpg\");\n}\nfunction setup() {\n image(img, 0, 0);\n}\n
\nfunction setup() {\n // here we use a callback to display the image after loading\n loadImage(\"assets/laDefense.jpg\", function(img) {\n image(img, 0, 0);\n });\n}\n
Validates clipping params. Per drawImage spec sWidth and sHight cannot be\nnegative or greater than image intrinsic width and height
Draw an image to the main canvas of the p5js sketch
the image to display
The X coordinate of the top left corner of the\n sub-rectangle of the source image to draw into\n the destination canvas.
The Y coordinate of the top left corner of the\n sub-rectangle of the source image to draw into\n the destination canvas.
The width of the sub-rectangle of the\n source image to draw into the destination\n canvas.
The height of the sub-rectangle of the\n source image to draw into the\n destination context.
The X coordinate in the destination canvas at\n which to place the top-left corner of the\n source image.
The Y coordinate in the destination canvas at\n which to place the top-left corner of the\n source image.
The width to draw the image in the destination\n canvas. This allows scaling of the drawn image.
The height to draw the image in the destination\n canvas. This allows scaling of the drawn image.
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/laDefense.jpg\");\n}\nfunction setup() {\n image(img, 0, 0);\n image(img, 0, 0, 100, 100);\n image(img, 0, 0, 100, 100, 0, 0, 100, 100);\n}\n
Sets the fill value for displaying images. Images can be tinted to\nspecified colors or made transparent by including an alpha value.\n\nTo apply transparency to an image without affecting its color, use\nwhite as the tint color and specify an alpha value. For instance,\ntint(255, 128) will make an image 50% transparent (assuming the default\nalpha range of 0-255, which can be changed with colorMode()).\n\nThe value for the gray parameter must be less than or equal to the current\nmaximum value as specified by colorMode(). The default maximum value is\n255.
gray value, red or hue value (depending on the\n current color mode), or color Array
green or saturation value (depending on the\n current color mode)
blue or brightness value (depending on the\n current color mode)
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/laDefense.jpg\");\n}\nfunction setup() {\n image(img, 0, 0);\n tint(0, 153, 204); // Tint blue\n image(img, 50, 0);\n}\n
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/laDefense.jpg\");\n}\nfunction setup() {\n image(img, 0, 0);\n tint(0, 153, 204, 126); // Tint blue and set transparency\n image(img, 50, 0);\n}\n
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/laDefense.jpg\");\n}\nfunction setup() {\n image(img, 0, 0);\n tint(255, 126); // Apply transparency without changing color\n image(img, 50, 0);\n}\n
Removes the current fill value for displaying images and reverts to\ndisplaying images with their original hues.
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/bricks.jpg\");\n}\nfunction setup() {\n tint(0, 153, 204); // Tint blue\n image(img, 0, 0);\n noTint(); // Disable tint\n image(img, 50, 0);\n}\n
Apply the current tint color to the input image, return the resulting\ncanvas.
image to be tinted
Set image mode. Modifies the location from which images are drawn by\nchanging the way in which parameters given to image() are interpreted.\nThe default mode is imageMode(CORNER), which interprets the second and\nthird parameters of image() as the upper-left corner of the image. If\ntwo additional parameters are specified, they are used to set the image's\nwidth and height.\n\nimageMode(CORNERS) interprets the second and third parameters of image()\nas the location of one corner, and the fourth and fifth parameters as the\nopposite corner.\n\nimageMode(CENTER) interprets the second and third parameters of image()\nas the image's center point. If two additional parameters are specified,\nthey are used to set the image's width and height.
either CORNER, CORNERS, or CENTER
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/bricks.jpg\");\n}\nfunction setup() {\n imageMode(CORNER);\n image(img, 10, 10, 50, 50);\n}\n
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/bricks.jpg\");\n}\nfunction setup() {\n imageMode(CORNERS);\n image(img, 10, 10, 90, 40);\n}\n
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/bricks.jpg\");\n}\nfunction setup() {\n imageMode(CENTER);\n image(img, 50, 50, 80, 80);\n}\n
This module defines the p5.Image class and P5 methods for\ndrawing images to the main display canvas.
Image width.
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/rockies.jpg\");\n}\n\nfunction setup() {\n createCanvas(100, 100);\n image(img, 0, 0);\n for (var i=0; i < img.width; i++) {\n var c = img.get(i, img.height/2);\n stroke(c);\n line(i, height/2, i, height);\n }\n}\n
Image height.
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/rockies.jpg\");\n}\n\nfunction setup() {\n createCanvas(100, 100);\n image(img, 0, 0);\n for (var i=0; i < img.height; i++) {\n var c = img.get(img.width/2, i);\n stroke(c);\n line(0, i, width/2, i);\n }\n}\n
Array containing the values for all the pixels in the display window.\nThese values are numbers. This array is the size (include an appropriate\nfactor for pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. Retina and other\nhigh denisty displays may have more pixels[] (by a factor of\npixelDensity^2).\nFor example, if the image is 100x100 pixels, there will be 40,000. With\npixelDensity = 2, there will be 160,000. The first four values\n(indices 0-3) in the array will be the R, G, B, A values of the pixel at\n(0, 0). The second four values (indices 4-7) will contain the R, G, B, A\nvalues of the pixel at (1, 0). More generally, to set values for a pixel\nat (x, y):\nvar d = pixelDensity;\nfor (var i = 0; i < d; i++) {\n for (var j = 0; j < d; j++) {\n // loop over\n idx = 4((y d + j) width d + (x * d + i));\n pixels[idx] = r;\n pixels[idx+1] = g;\n pixels[idx+2] = b;\n pixels[idx+3] = a;\n }\n}\n\n\nBefore accessing this array, the data must loaded with the loadPixels()\nfunction. After the array data has been modified, the updatePixels()\nfunction must be run to update the changes.
var d = pixelDensity;\nfor (var i = 0; i < d; i++) {\n for (var j = 0; j < d; j++) {\n // loop over\n idx = 4((y d + j) width d + (x * d + i));\n pixels[idx] = r;\n pixels[idx+1] = g;\n pixels[idx+2] = b;\n pixels[idx+3] = a;\n }\n}\n
\nvar pink = color(255, 102, 204);\nimg = createImage(66, 66);\nimg.loadPixels();\nfor (var i = 0; i < 4*(width*height/2); i+=4) {\n img.pixels[i] = red(pink);\n img.pixels[i+1] = green(pink);\n img.pixels[i+2] = blue(pink);\n img.pixels[i+3] = alpha(pink);\n}\nimg.updatePixels();\nimage(img, 17, 17);\n
Loads the pixels data for this image into the [pixels] attribute.
\nvar myImage;\nvar halfImage;\n\nfunction preload() {\n myImage = loadImage(\"assets/rockies.jpg\");\n}\n\nfunction setup() {\n myImage.loadPixels();\n halfImage = 4 * width * height/2;\n for(var i = 0; i < halfImage; i++){\n myImage.pixels[i+halfImage] = myImage.pixels[i];\n }\n myImage.updatePixels();\n}\n\nfunction draw() {\n image(myImage, 0, 0);\n}\n
Updates the backing canvas for this image with the contents of\nthe [pixels] array.
x-offset of the target update area for the\n underlying canvas
y-offset of the target update area for the\n underlying canvas
height of the target update area for the\n underlying canvas
Get a region of pixels from an image.
If no params are passed, those whole image is returned,\nif x and y are the only params passed a single pixel is extracted\nif all params are passed a rectangle region is extracted and a p5.Image\nis returned.
Returns undefined if the region is outside the bounds of the image
x-coordinate of the pixel
y-coordinate of the pixel
width
height
\nvar myImage;\nvar c;\n\nfunction preload() {\n myImage = loadImage(\"assets/rockies.jpg\");\n}\n\nfunction setup() {\n background(myImage);\n noStroke();\n c = myImage.get(60, 90);\n fill(c);\n rect(25, 25, 50, 50);\n}\n\n//get() returns color here\n
Set the color of a single pixel or write an image into\nthis p5.Image.
Note that for a large number of pixels this will\nbe slower than directly manipulating the pixels array\nand then calling updatePixels().
grayscale value | pixel array |\n a p5.Color | image to copy
Resize the image to a new width and height. To make the image scale\nproportionally, use 0 as the value for the wide or high parameter.\nFor instance, to make the width of an image 150 pixels, and change\nthe height using the same proportion, use resize(150, 0).
the resized image width
the resized image height
\nvar img;\n\nfunction setup() {\n img = loadImage(\"assets/rockies.jpg\");\n}\n\nfunction draw() {\n image(img, 0, 0);\n}\n\nfunction mousePressed() {\n img.resize(50, 100);\n}\n
Copies a region of pixels from one image to another. If no\nsrcImage is specified this is used as the source. If the source\nand destination regions aren't the same size, it will\nautomatically resize source pixels to fit the specified\ntarget region.
source image
X coordinate of the source's upper left corner
Y coordinate of the source's upper left corner
source image width
source image height
X coordinate of the destination's upper left corner
Y coordinate of the destination's upper left corner
destination image width
destination image height
\nvar photo;\nvar bricks;\nvar x;\nvar y;\n\nfunction preload() {\n photo = loadImage(\"assets/rockies.jpg\");\n bricks = loadImage(\"assets/bricks.jpg\");\n}\n\nfunction setup() {\n x = bricks.width/2;\n y = bricks.height/2;\n photo.copy(bricks, 0, 0, x, y, 0, 0, x, y);\n image(photo, 0, 0);\n}\n
Masks part of an image from displaying by loading another\nimage and using it's blue channel as an alpha channel for\nthis image.
\nvar photo, maskImage;\nfunction preload() {\n photo = loadImage(\"assets/rockies.jpg\");\n maskImage = loadImage(\"assets/mask2.png\");\n}\n\nfunction setup() {\n createCanvas(100, 100);\n photo.mask(maskImage);\n image(photo, 0, 0);\n}\n
Applies an image filter to a p5.Image
one of threshold, gray, invert, posterize and\n opaque see Filters.js for docs on each available\n filter
\nvar photo1;\nvar photo2;\n\nfunction preload() {\n photo1 = loadImage(\"assets/rockies.jpg\");\n photo2 = loadImage(\"assets/rockies.jpg\");\n}\n\nfunction setup() {\n photo2.filter(\"gray\");\n image(photo1, 0, 0);\n image(photo2, width/2, 0);\n}\n
Copies a region of pixels from one image to another, using a specified\nblend mode to do the operation.
the blend mode
Available 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
http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/
\nvar mountains;\nvar bricks;\n\nfunction preload() {\n mountains = loadImage(\"assets/rockies.jpg\");\n bricks = loadImage(\"assets/bricks_third.jpg\");\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n
\nvar mountains;\nvar bricks;\n\nfunction preload() {\n mountains = loadImage(\"assets/rockies.jpg\");\n bricks = loadImage(\"assets/bricks_third.jpg\");\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n
\nvar mountains;\nvar bricks;\n\nfunction preload() {\n mountains = loadImage(\"assets/rockies.jpg\");\n bricks = loadImage(\"assets/bricks_third.jpg\");\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n
Saves the image to a file and force the browser to download it.\nAccepts two strings for filename and file extension\nSupports png (default) and jpg.
give your file a name
'png' or 'jpg'
\nvar photo;\n\nfunction preload() {\n photo = loadImage(\"assets/rockies.jpg\");\n}\n\nfunction draw() {\n image(photo, 0, 0);\n}\n\nfunction keyTyped() {\n if (key == 's') {\n photo.save(\"photo\", \"png\");\n }\n}\n
Uint8ClampedArray\ncontaining the values for all the pixels in the display window.\nThese values are numbers. This array is the size (include an appropriate\nfactor for pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. Retina and other\nhigh denisty displays will have more pixels[] (by a factor of\npixelDensity^2).\nFor example, if the image is 100x100 pixels, there will be 40,000. On a\nretina display, there will be 160,000.\n\nThe first four values (indices 0-3) in the array will be the R, G, B, A\nvalues of the pixel at (0, 0). The second four values (indices 4-7) will\ncontain the R, G, B, A values of the pixel at (1, 0). More generally, to\nset values for a pixel at (x, y):\n\nvar d = pixelDensity;\nfor (var i = 0; i < d; i++) {\n for (var j = 0; j < d; j++) {\n // loop over\n idx = 4 ((y d + j) width d + (x * d + i));\n pixels[idx] = r;\n pixels[idx+1] = g;\n pixels[idx+2] = b;\n pixels[idx+3] = a;\n }\n}\n
\nvar d = pixelDensity;\nfor (var i = 0; i < d; i++) {\n for (var j = 0; j < d; j++) {\n // loop over\n idx = 4 ((y d + j) width d + (x * d + i));\n pixels[idx] = r;\n pixels[idx+1] = g;\n pixels[idx+2] = b;\n pixels[idx+3] = a;\n }\n}\n
While the above method is complex, it is flexible enough to work with\nany pixelDensity. Note that set() will automatically take care of\nsetting all the appropriate values in pixels[] for a given (x, y) at\nany pixelDensity, but the performance may not be as fast when lots of\nmodifications are made to the pixel array.\n\nBefore accessing this array, the data must loaded with the loadPixels()\nfunction. After the array data has been modified, the updatePixels()\nfunction must be run to update the changes.\n\nNote that this is not a standard javascript array. This means that\nstandard javascript functions such as slice() or\narrayCopy() do not\nwork.
slice()
arrayCopy()
\nvar pink = color(255, 102, 204);\nloadPixels();\nvar d = pixelDensity();\nvar halfImage = 4 * (width * d) * (height/2 * d);\nfor (var i = 0; i < halfImage; i+=4) {\n pixels[i] = red(pink);\n pixels[i+1] = green(pink);\n pixels[i+2] = blue(pink);\n pixels[i+3] = alpha(pink);\n}\nupdatePixels();\n
Copies a region of pixels from one image to another, using a specified\nblend mode to do the operation.\nAvailable blend modes are: BLEND | DARKEST | LIGHTEST | DIFFERENCE |\nMULTIPLY| EXCLUSION | SCREEN | REPLACE | OVERLAY | HARD_LIGHT |\nSOFT_LIGHT | DODGE | BURN | ADD | NORMAL
\nvar img0;\nvar img1;\n\nfunction preload() {\n img0 = loadImage(\"assets/rockies.jpg\");\n img1 = loadImage(\"assets/bricks_third.jpg\");\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n}\n
\nvar img0;\nvar img1;\n\nfunction preload() {\n img0 = loadImage(\"assets/rockies.jpg\");\n img1 = loadImage(\"assets/bricks_third.jpg\");\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n}\n
\nvar img0;\nvar img1;\n\nfunction preload() {\n img0 = loadImage(\"assets/rockies.jpg\");\n img1 = loadImage(\"assets/bricks_third.jpg\");\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n}\n
Copies a region of the canvas to another region of the canvas\nand copies a region of pixels from an image used as the srcImg parameter\ninto the canvas srcImage is specified this is used as the source. If\nthe source and destination regions aren't the same size, it will\nautomatically resize source pixels to fit the specified\ntarget region.
\nvar img;\n\nfunction preload() {\n img = loadImage(\"assets/rockies.jpg\");\n}\n\nfunction setup() {\n background(img);\n copy(img, 7, 22, 10, 10, 35, 25, 50, 50);\n stroke(255);\n noFill();\n // Rectangle shows area being copied\n rect(7, 22, 10, 10);\n}\n
Applies a filter to the canvas.\n
The presets options are:\n
THRESHOLD\nConverts the image to black and white pixels depending if they are above or\nbelow the threshold defined by the level parameter. The parameter must be\nbetween 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used.\n
GRAY\nConverts any colors in the image to grayscale equivalents. No parameter\nis used.\n
OPAQUE\nSets the alpha channel to entirely opaque. No parameter is used.\n
INVERT\nSets each pixel to its inverse value. No parameter is used.\n
POSTERIZE\nLimits each channel of the image to the number of colors specified as the\nparameter. The parameter can be set to values between 2 and 255, but\nresults are most noticeable in the lower ranges.\n
BLUR\nExecutes a Guassian blur with the level parameter specifying the extent\nof the blurring. If no parameter is used, the blur is equivalent to\nGuassian blur of radius 1. Larger values increase the blur.\n
ERODE\nReduces the light areas. No parameter is used.\n
DILATE\nIncreases the light areas. No parameter is used.
an optional parameter unique\n to each filter, see above
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/bricks.jpg\");\n}\nfunction setup() {\n image(img, 0, 0);\n filter(THRESHOLD);\n}\n
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/bricks.jpg\");\n}\nfunction setup() {\n image(img, 0, 0);\n filter(GRAY);\n}\n
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/bricks.jpg\");\n}\nfunction setup() {\n image(img, 0, 0);\n filter(OPAQUE);\n}\n
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/bricks.jpg\");\n}\nfunction setup() {\n image(img, 0, 0);\n filter(INVERT);\n}\n
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/bricks.jpg\");\n}\nfunction setup() {\n image(img, 0, 0);\n filter(POSTERIZE,3);\n}\n
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/bricks.jpg\");\n}\nfunction setup() {\n image(img, 0, 0);\n filter(DILATE);\n}\n
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/bricks.jpg\");\n}\nfunction setup() {\n image(img, 0, 0);\n filter(BLUR,3);\n}\n
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/bricks.jpg\");\n}\nfunction setup() {\n image(img, 0, 0);\n filter(ERODE);\n}\n
Returns an array of [R,G,B,A] values for any pixel or grabs a section of\nan image. If no parameters are specified, the entire image is returned.\nUse the x and y parameters to get the value of one pixel. Get a section of\nthe display window by specifying additional w and h parameters. When\ngetting an image, the x and y parameters define the coordinates for the\nupper-left corner of the image, regardless of the current imageMode().\n\nIf the pixel requested is outside of the image window, [0,0,0,255] is\nreturned. To get the numbers scaled according to the current color ranges\nand taking into account colorMode, use getColor instead of get.\n\nGetting the color of a single pixel with get(x, y) is easy, but not as fast\nas grabbing the data directly from pixels[]. The equivalent statement to\nget(x, y) using pixels[] with pixel density d is\n\nvar off = (y width + x) d * 4;\n[pixels[off],\npixels[off+1],\npixels[off+2],\npixels[off+3]]\n\nSee the reference for pixels[] for more information.
\nvar off = (y width + x) d * 4;\n[pixels[off],\npixels[off+1],\npixels[off+2],\npixels[off+3]]
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/rockies.jpg\");\n}\nfunction setup() {\n image(img, 0, 0);\n var c = get();\n image(c, width/2, 0);\n}\n
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/rockies.jpg\");\n}\nfunction setup() {\n image(img, 0, 0);\n var c = get(50, 90);\n fill(c);\n noStroke();\n rect(25, 25, 50, 50);\n}\n
Loads the pixel data for the display window into the pixels[] array. This\nfunction must always be called before reading from or writing to pixels[].
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/rockies.jpg\");\n}\n\nfunction setup() {\n image(img, 0, 0);\n var d = pixelDensity();\n var halfImage = 4 * (img.width * d) *\n (img.height/2 * d);\n loadPixels();\n for (var i = 0; i < halfImage; i++) {\n pixels[i+halfImage] = pixels[i];\n }\n updatePixels();\n}\n
Changes the color of any pixel, or writes an image directly to the\ndisplay window.
The x and y parameters specify the pixel to change and the c parameter\nspecifies the color value. This can be a p5.Color object, or [R, G, B, A]\npixel array. It can also be a single grayscale value.\nWhen setting an image, the x and y parameters define the coordinates for\nthe upper-left corner of the image, regardless of the current imageMode().\n
\nAfter using set(), you must call updatePixels() for your changes to\nappear. This should be called once all pixels have been set.\n
Setting the color of a single pixel with set(x, y) is easy, but not as\nfast as putting the data directly into pixels[]. Setting the pixels[]\nvalues directly may be complicated when working with a retina display,\nbut will perform better when lots of pixels need to be set directly on\nevery loop.
See the reference for pixels[] for more information.
insert a grayscale value | a pixel array |\n a p5.Color object | a p5.Image to copy
\nvar black = color(0);\nset(30, 20, black);\nset(85, 20, black);\nset(85, 75, black);\nset(30, 75, black);\nupdatePixels();\n
\nfor (var i = 30; i < width-15; i++) {\n for (var j = 20; j < height-25; j++) {\n var c = color(204-j, 153-i, 0);\n set(i, j, c);\n }\n}\nupdatePixels();\n
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/rockies.jpg\");\n}\n\nfunction setup() {\n set(0, 0, img);\n updatePixels();\n line(0, 0, width, height);\n line(0, height, width, 0);\n}\n
Updates the display window with the data in the pixels[] array.\nUse in conjunction with loadPixels(). If you're only reading pixels from\nthe array, there's no need to call updatePixels() — updating is only\nnecessary to apply changes. updatePixels() should be called anytime the\npixels array is manipulated or set() is called.
x-coordinate of the upper-left corner of region\n to update
y-coordinate of the upper-left corner of region\n to update
width of region to update
height of region to update
\nvar img;\nfunction preload() {\n img = loadImage(\"assets/rockies.jpg\");\n}\n\nfunction setup() {\n image(img, 0, 0);\n var halfImage = 4 * (img.width * pixelDensity()) *\n (img.height * pixelDensity()/2);\n loadPixels();\n for (var i = 0; i < halfImage; i++) {\n pixels[i+halfImage] = pixels[i];\n }\n updatePixels();\n}\n
Checks if we are in preload and returns the last arg which will be the\n_decrementPreload function if called from a loadX() function. Should\nonly be used in loadX() functions.
Loads an opentype font file (.otf, .ttf) from a file or a URL,\nand returns a PFont Object. This method is asynchronous,\nmeaning it may not finish before the next line in your sketch\nis executed.\n\nThe path to the font should be relative to the HTML file\nthat links in your sketch. Loading an from a URL or other\nremote location may be blocked due to your browser's built-in\nsecurity.
name of the file or url to load
function to be executed after\n loadFont()\n completes
Calling loadFont() inside preload() guarantees that the load\noperation will have completed before setup() and draw() are called.
\nvar myFont;\nfunction preload() {\n myFont = loadFont('assets/AvenirNextLTPro-Demi.otf');\n}\n\nfunction setup() {\n fill('#ED225D');\n textFont(myFont);\n textSize(36);\n text('p5*js', 10, 50);\n}\n
\nfunction setup() {\n loadFont('assets/AvenirNextLTPro-Demi.otf', drawText);\n}\n\nfunction drawText(font) {\n fill('#ED225D');\n textFont(font, 36);\n text('p5*js', 10, 50);\n}\n\n
You can also use the string name of the font to style other HTML\nelements.
\nvar myFont;\n\nfunction preload() {\n myFont = loadFont('assets/Avenir.otf');\n}\n\nfunction setup() {\n var myDiv = createDiv('hello there');\n myDiv.style('font-family', 'Avenir');\n}\n
Loads a JSON file from a file or a URL, and returns an Object or Array.\nThis method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed.
function to be executed after\n loadJSON() completes, data is passed\n in as first argument
function to be executed if\n there is an error, response is passed\n in as first argument
"json" or "jsonp"
Calling loadJSON() inside preload() guarantees to complete the\noperation before setup() and draw() are called.
\nvar weather;\nfunction preload() {\n var url = 'http://api.openweathermap.org/data/2.5/weather?q=London,UK'+\n '&APPID=7bbbb47522848e8b9c26ba35c226c734';\n weather = loadJSON(url);\n}\n\nfunction setup() {\n noLoop();\n}\n\nfunction draw() {\n background(200);\n // get the humidity value out of the loaded JSON\n var humidity = weather.main.humidity;\n fill(0, humidity); // use the humidity value to set the alpha\n ellipse(width/2, height/2, 50, 50);\n}\n
Outside of preload(), you may supply a callback function to handle the\nobject:
\nfunction setup() {\n noLoop();\n var url = 'http://api.openweathermap.org/data/2.5/weather?q=NewYork'+\n '&APPID=7bbbb47522848e8b9c26ba35c226c734';\n loadJSON(url, drawWeather);\n}\n\nfunction draw() {\n background(200);\n}\n\nfunction drawWeather(weather) {\n // get the humidity value out of the loaded JSON\n var humidity = weather.main.humidity;\n fill(0, humidity); // use the humidity value to set the alpha\n ellipse(width/2, height/2, 50, 50);\n}\n
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.\n\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.\n\nThis method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed.
function to be executed after loadStrings()\n completes, Array is passed in as first\n argument
Calling loadStrings() inside preload() guarantees to complete the\noperation before setup() and draw() are called.
\nvar result;\nfunction preload() {\n result = loadStrings('assets/test.txt');\n}\n\nfunction setup() {\n background(200);\n var ind = floor(random(result.length));\n text(result[ind], 10, 10, 80, 80);\n}\n
\nfunction setup() {\n loadStrings('assets/test.txt', pickString);\n}\n\nfunction pickString(result) {\n background(200);\n var ind = floor(random(result.length));\n text(result[ind], 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.
Possible options include:\n
When passing in multiple options, pass them in as separate parameters,\nseperated by commas. For example:\n\n\n loadTable("my_csv_file.csv", "csv", "header")\n\n
\n loadTable("my_csv_file.csv", "csv", "header")\n
All files loaded and saved use UTF-8 encoding.
This 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.\n
name of the file or URL to load
"header" "csv" "tsv"
function to be executed after\n loadTable() completes. On success, the\n Table object is passed in as the\n first argument; otherwise, false\n is passed in.
\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\nvar 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 println(table.getRowCount() + \" total rows in table\");\n println(table.getColumnCount() + \" total columns in table\");\n\n println(table.getColumn(\"name\"));\n //[\"Goat\", \"Leopard\", \"Zebra\"]\n\n //cycle through the table\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++) {\n println(table.getString(r, c));\n }\n}\n
Reads 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.
Alternatively, 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.
This 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.
function to be executed after loadXML()\n completes, XML object is passed in as\n first argument
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.
param data passed sent with request
"json", "jsonp", "xml", or "text"
function to be executed after\n httpGet() completes, data is passed in\n as first argument
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.
Method for executing an HTTP request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text.\nYou may also pass a single object specifying all parameters for the\nrequest following the examples inside the reqwest() calls here:\n\nhttps://github.com/ded/reqwest#api
either "GET", "POST", or "PUT",\n defaults to "GET"
Save an image, text, json, csv, wav, or html. Prompts download to\nthe client's computer. Note that it is not recommended to call save()\nwithin draw if it's looping, as the save() function will open a new save\ndialog every frame.
The default behavior is to save the canvas as an image. You can\noptionally specify a filename.\nFor example:
\nsave();\nsave('myCanvas.jpg'); // save a specific canvas with a filename\n
Alternately, the first parameter can be a pointer to a canvas\np5.Element, an Array of Strings,\nan Array of JSON, a JSON object, a p5.Table, a p5.Image, or a\np5.SoundFile (requires p5.sound). The second parameter is a filename\n(including extension). The third parameter is for options specific\nto this type of object. This method will save a file that fits the\ngiven paramaters. For example:
\n\nsave('myCanvas.jpg'); // Saves canvas as an image\n\nvar cnv = createCanvas(100, 100);\nsave(cnv, 'myCanvas.jpg'); // Saves canvas as an image\n\nvar gb = createGraphics(100, 100);\nsave(gb, 'myGraphics.jpg'); // Saves p5.Renderer object as an image\n\nsave(myTable, 'myTable.html'); // Saves table as html file\nsave(myTable, 'myTable.csv',); // Comma Separated Values\nsave(myTable, 'myTable.tsv'); // Tab Separated Values\n\nsave(myJSON, 'my.json'); // Saves pretty JSON\nsave(myJSON, 'my.json', true); // Optimizes JSON filesize\n\nsave(img, 'my.png'); // Saves pImage as a png image\n\nsave(arrayOfStrings, 'my.txt'); // Saves strings to a text file with line\n // breaks after each item in the array\n
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).
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).
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.
true
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.
If true, removes line breaks\n and spaces from the output\n file to optimize filesize\n (but not readability).
\nvar json;\n\nfunction setup() {\n\n json = {}; // new JSON Object\n\n json.id = 0;\n json.species = 'Panthera leo';\n json.name = 'Lion';\n\n// To save, un-comment the line below, then click 'run'\n// saveJSON(json, 'lion.json');\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.
string array to be written
filename for output
\nvar words = 'apple bear cat dog';\n\n// .split() outputs an Array\nvar list = split(words, ' ');\n\n// To save the file, un-comment next line and click 'run'\n// saveStrings(list, 'nouns.txt');\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.
the Table object to save to a file
the filename to which the Table should be saved
can be one of "tsv", "csv", or "html"
\nvar table;\n\nfunction setup() {\n table = new p5.Table();\n\n table.addColumn('id');\n table.addColumn('species');\n table.addColumn('name');\n\n var 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\n // Saves the following to a file called 'new.csv':\n // id,species,name\n // 0,Panthera leo,Lion\n
Generate a blob of file data as a url to prepare for download.\nAccepts an array of data, a filename, and an extension (optional).\nThis is a private function because it does not do any formatting,\nbut it is used by saveStrings, saveJSON, saveTable etc.
Forces download. Accepts a url to filedata/blob, a filename,\nand an extension (optional).\nThis is a private function because it does not do any formatting,\nbut it is used by saveStrings, saveJSON, saveTable etc.
i.e. an href generated by createObjectURL
Returns a file extension, or another string\nif the provided parameter has no extension.
Returns true if the browser is Safari, false if not.\nSafari makes trouble for downloading files.
Helper function, a callback for download that deletes\nan invisible anchor element from the DOM once the file\nhas been automatically downloaded.
Table Options
Generic class for handling tabular data, typically from a\nCSV, TSV, or other sort of spreadsheet file.
CSV 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.
File names should end with .csv if they're comma separated.
A rough "spec" for CSV can be found\nhere.
To load files, use the loadTable method.
To save tables to your computer, use the save method\n or the saveTable method.
Possible options include:
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().
If a p5.TableRow object is included as a parameter, then that row is\nduplicated and added to the table.
row to be added to the table
\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 var 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 var 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 (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n println(table.getString(r, c));\n }\n
Removes a row from the table object.
ID number of the row to remove
\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\nvar 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 var r = table.removeRow(0);\n\n //print the results\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n println(table.getString(r, c));\n}\n
Returns a reference to the specified p5.TableRow. The reference\ncan then be used to get and set values of the selected row.
ID number of the row to get
\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\nvar 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 var row = table.getRow(1);\n //print it column by column\n //note: a row is an object, not an array\n for (var c = 0; c < table.getColumnCount(); c++)\n println(row.getString(c));\n}\n
Gets all rows from the table. Returns an array of p5.TableRows.
\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 var 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 var rows = table.getRows();\n\n //warning: rows is an array of objects\n for (var r = 0; r < rows.length; r++)\n rows[r].set(\"name\", \"Unicorn\");\n\n //print the results\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n println(table.getString(r, c));\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.
The value to match
ID number or title of the\n column to search
\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 var 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 var row = table.findRow(\"Zebra\", \"name\");\n //find the corresponding species\n println(row.getString(\"species\"));\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 // 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 var 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 var 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 var rows = table.findRows(\"Goat\", \"name\");\n println(rows.length + \" Goats found\");\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.
The regular expression to match
The column ID (number) or\n title (string)
Finds the rows in the Table that match the regular expression provided,\nand returns references to those rows. Returns an array, so for must be\nused to iterate through all the rows, as shown in the example. The\ncolumn to search may be specified by either its ID or title.
Retrieves all values in the specified column, and returns them\nas an array. The column may be specified by either its ID or title.
String or Number of the column to return
\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 var 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 println(table.getColumn(\"species\"));\n //outputs [\"Capra hircus\", \"Panthera pardus\", \"Equus zebra\"]\n }\n
Removes all rows from a Table. While all rows are removed,\ncolumns and column titles are maintained.
\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 var 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 println(table.getRowCount() + \" total rows in table\");\n println(table.getColumnCount() + \" total columns in table\");\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.)
title of the given column
\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 var 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 (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n println(table.getString(r, c));\n }\n
Returns the total number of columns in a Table.
Returns the total number of rows in a Table.
Removes any of the specified characters (or "tokens").
If 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.
String listing characters to be removed
Column ID (number)\n or name (string)
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.
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.
columnName (string) or ID (number)
\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 var 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 println(table.getColumnCount());\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.
column ID (Number)\n or title (String)
value to assign
\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\nvar 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 (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n println(table.getString(r, c));\n}\n
Stores a Float value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
row ID
\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\nvar 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 println(table.getColumn(0));\n //[\"0\", 1, \"2\"]\n}\n
Stores a String value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
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.
columnName (string) or\n ID (number)
\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\nvar 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 println(table.get(0, 1));\n //Capra hircus\n println(table.get(0, \"species\"));\n //Capra hircus\n}\n
Retrieves a Float value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n// 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\nvar 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 println(table.getNum(1, 0) + 100);\n //id 1 + 100 = 101\n}\n
Retrieves a String value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n// 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\nvar 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 var tableArray = table.getArray();\n\n //output each row as array\n for (var i = 0; i < tableArray.length; i++)\n println(tableArray[i]);\n}\n
Retrieves all table data and returns as an object. If a column name is\npassed in, each row object will be stored with that attribute as its\ntitle.
Name of the column which should be used to\n title each row object (optional)
\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\nvar 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 var tableObject = table.getObject();\n\n println(tableObject);\n //outputs an object\n}\n
Retrieves all table data and returns it as a multidimensional array.
Stores a value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
Column ID (Number)\n or Title (String)
The value to be stored
Stores a Float value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
The value to be stored\n as a Float
Stores a String value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
The value to be stored\n as a String
Retrieves a value from the TableRow's specified column.\nThe column may be specified by either its ID or title.
Retrieves a Float value from the TableRow's specified\ncolumn. The column may be specified by either its ID or\ntitle.
Retrieves an String value from the TableRow's specified\ncolumn. The column may be specified by either its ID or\ntitle.
Gets a copy of the element's parent. Returns the parent as another\np5.XML object.
\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\nvar xml;\n\nfunction preload() {\n xml = loadXML(\"assets/mammals.xml\");\n}\n\nfunction setup() {\n var children = xml.getChildren(\"animal\");\n var parent = children[1].getParent();\n println(parent.getName());\n}\n\n// Sketch prints:\n// mammals\n
Gets the element's full name, which is returned as a String.
\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 var xml;\n\n function preload() {\n xml = loadXML(\"assets/mammals.xml\");\n }\n\n function setup() {\n println(xml.getName());\n }\n\n // Sketch prints:\n // mammals\n
Sets the element's name, which is specified as a String.
new name of the node
\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\nvar xml;\n\nfunction preload() {\n xml = loadXML(\"assets/mammals.xml\");\n}\n\nfunction setup() {\n println(xml.getName());\n xml.setName(\"fish\");\n println(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// 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\nvar xml;\n\nfunction preload() {\n xml = loadXML(\"assets/mammals.xml\");\n}\n\nfunction setup() {\n println(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// 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\nvar xml;\n\nfunction preload() {\n xml = loadXML(\"assets/mammals.xml\");\n}\n\nfunction setup() {\n println(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.
element name
\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\nvar xml;\n\nfunction preload() {\n xml = loadXML(\"assets/mammals.xml\");\n}\n\nfunction setup() {\n var animals = xml.getChildren(\"animal\");\n\n for (var i = 0; i < animals.length; i++) {\n println(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.
element name or index
\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\nvar xml;\n\nfunction preload() {\n xml = loadXML(\"assets/mammals.xml\");\n}\n\nfunction setup() {\n var firstChild = xml.getChild(\"animal\");\n println(firstChild.getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n
\nvar xml;\n\nfunction preload() {\n xml = loadXML(\"assets/mammals.xml\");\n}\n\nfunction setup() {\n var secondChild = xml.getChild(1);\n println(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.
p5.XML Object which will be the child to be added
Removes the element specified by name or index.
\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\nvar xml;\n\nfunction preload() {\n xml = loadXML(\"assets/mammals.xml\");\n}\n\nfunction setup() {\n xml.removeChild(\"animal\");\n var children = xml.getChildren();\n for (var i=0; i
\nvar xml;\n\nfunction preload() {\n xml = loadXML(\"assets/mammals.xml\");\n}\n\nfunction setup() {\n xml.removeChild(1);\n var children = xml.getChildren();\n for (var i=0; i
Counts the specified element's number of attributes, returned as an Number.
\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\nvar xml;\n\nfunction preload() {\n xml = loadXML(\"assets/mammals.xml\");\n}\n\nfunction setup() {\n var firstChild = xml.getChild(\"animal\");\n println(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// 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\nvar xml;\n\nfunction preload() {\n xml = loadXML(\"assets/mammals.xml\");\n}\n\nfunction setup() {\n var firstChild = xml.getChild(\"animal\");\n println(firstChild.listAttributes());\n}\n\n// Sketch prints:\n// [\"id\", \"species\"]\n
Checks whether or not an element has the specified attribute.
attribute to be checked
\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 var xml;\n\n function preload() {\n xml = loadXML(\"assets/mammals.xml\");\n }\n\n function setup() {\n var firstChild = xml.getChild(\"animal\");\n println(firstChild.hasAttribute(\"species\"));\n println(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.
the non-null full name of the attribute
the default value of the attribute
\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\nvar xml;\n\nfunction preload() {\n xml = loadXML(\"assets/mammals.xml\");\n}\n\nfunction setup() {\n var firstChild = xml.getChild(\"animal\");\n println(firstChild.getNumber(\"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// 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\nvar xml;\n\nfunction preload() {\n xml = loadXML(\"assets/mammals.xml\");\n}\n\nfunction setup() {\n var firstChild = xml.getChild(\"animal\");\n println(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.
the full name of the attribute
the value of the attribute
\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\nvar xml;\n\nfunction preload() {\n xml = loadXML(\"assets/mammals.xml\");\n}\n\nfunction setup() {\n var firstChild = xml.getChild(\"animal\");\n println(firstChild.getString(\"species\"));\n firstChild.setAttribute(\"species\", \"Jamides zebra\");\n println(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.
value returned if no content is found
Sets the element's content.
the new content
\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\nvar xml;\n\nfunction preload() {\n xml = loadXML(\"assets/mammals.xml\");\n}\n\nfunction setup() {\n var firstChild = xml.getChild(\"animal\");\n println(firstChild.getContent());\n firstChild.setContent(\"Mountain Goat\");\n println(firstChild.getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Mountain Goat\"\n
This method is called while the parsing of XML (when loadXML() is\ncalled). The difference between this method and the setContent()\nmethod defined later is that this one is used to set the content\nwhen the node in question has more nodes under it and so on and\nnot directly text content. While in the other one is used when\nthe node in question directly has text inside it.
This method is called while the parsing of XML (when loadXML() is\ncalled). The XML node is passed and its attributes are stored in the\np5.XML's attribute Object.
Calculates the absolute value (magnitude) of a number. Maps to Math.abs().\nThe absolute value of a number is always positive.
number to compute
\nfunction setup() {\n var x = -3;\n var y = abs(x);\n\n println(x); // -3\n println(y); // 3\n}\n
Calculates the closest int value that is greater than or equal to the\nvalue of the parameter. Maps to Math.ceil(). For example, ceil(9.03)\nreturns the value 10.
number to round up
\nfunction draw() {\n background(200);\n // map, mouseX between 0 and 5.\n var ax = map(mouseX, 0, 100, 0, 5);\n var ay = 66;\n\n //Get the ceiling of the mapped number.\n var bx = ceil(map(mouseX, 0, 100, 0,5));\n var by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2,2), ax, ay - 5);\n text(nfc(bx,1,1), bx, by - 5);\n}\n
Constrains a value between a minimum and maximum value.
number to constrain
minimum limit
maximum limit
\nfunction draw() {\n background(200);\n\n var leftWall = 25;\n var rightWall = 75;\n\n // xm is just the mouseX, while\n // xc is the mouseX, but constrained\n // between the leftWall and rightWall!\n var xm = mouseX;\n var xc = constrain(mouseX, leftWall, rightWall);\n\n // Draw the walls.\n stroke(150);\n line(leftWall, 0, leftWall, height);\n line(rightWall, 0, rightWall, height);\n\n // Draw xm and xc as circles.\n noStroke();\n fill(150);\n ellipse(xm, 33, 9,9); // Not Constrained\n fill(0);\n ellipse(xc, 66, 9,9); // Constrained\n}\n
Calculates the distance between two points.
z-coordinate of the first point
z-coordinate of the second point
\n// Move your mouse inside the canvas to see the\n// change in distance between two points!\nfunction draw() {\n background(200);\n fill(0);\n\n var x1 = 10;\n var y1 = 90;\n var x2 = mouseX;\n var y2 = mouseY;\n\n line(x1, y1, x2, y2);\n ellipse(x1, y1, 7, 7);\n ellipse(x2, y2, 7, 7);\n\n // d is the length of the line\n // the distance from point 1 to point 2.\n var d = int(dist(x1, y1, x2, y2));\n\n // Let's write d along the line we are drawing!\n push();\n translate( (x1+x2)/2, (y1+y2)/2 );\n rotate( atan2(y2-y1,x2-x1) );\n text(nfc(d,1,1), 0, -5);\n pop();\n // Fancy!\n}\n
Returns Euler's number e (2.71828...) raised to the power of the n\nparameter. Maps to Math.exp().
exponent to raise
\nfunction draw() {\n background(200);\n\n // Compute the exp() function with a value between 0 and 2\n var xValue = map(mouseX, 0, width, 0, 2);\n var yValue = exp(xValue);\n\n var y = map(yValue, 0, 8, height, 0);\n\n var legend = \"exp (\" + nfc(xValue, 3) +\")\\n= \" + nf(yValue, 1, 4);\n stroke(150);\n line(mouseX, y, mouseX, height);\n fill(0);\n text(legend, 5, 15);\n noStroke();\n ellipse (mouseX,y, 7, 7);\n\n // Draw the exp(x) curve,\n // over the domain of x from 0 to 2\n noFill();\n stroke(0);\n beginShape();\n for (var x = 0; x < width; x++) {\n xValue = map(x, 0, width, 0, 2);\n yValue = exp(xValue);\n y = map(yValue, 0, 8, height, 0);\n vertex(x, y);\n }\n\n endShape();\n line(0, 0, 0, height);\n line(0, height-1, width, height-1);\n}\n
Calculates the closest int value that is less than or equal to the\nvalue of the parameter. Maps to Math.floor().
number to round down
\nfunction draw() {\n background(200);\n //map, mouseX between 0 and 5.\n var ax = map(mouseX, 0, 100, 0, 5);\n var ay = 66;\n\n //Get the floor of the mapped number.\n var bx = floor(map(mouseX, 0, 100, 0,5));\n var by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2,2), ax, ay - 5);\n text(nfc(bx,1,1), bx, by - 5);\n}\n
Calculates a number between two numbers at a specific increment. The amt\nparameter is the amount to interpolate between the two values where 0.0\nequal to the first point, 0.1 is very near the first point, 0.5 is\nhalf-way in between, etc. The lerp function is convenient for creating\nmotion along a straight path and for drawing dotted lines.
first value
second value
number between 0.0 and 1.0
\nfunction setup() {\n background(200);\n var a = 20;\n var b = 80;\n var c = lerp(a,b, .2);\n var d = lerp(a,b, .5);\n var e = lerp(a,b, .8);\n\n var y = 50\n\n strokeWeight(5);\n stroke(0); // Draw the original points in black\n point(a, y);\n point(b, y);\n\n stroke(100); // Draw the lerp points in gray\n point(c, y);\n point(d, y);\n point(e, y);\n}\n
Calculates the natural logarithm (the base-e logarithm) of a number. This\nfunction expects the n parameter to be a value greater than 0.0. Maps to\nMath.log().
number greater than 0
\nfunction draw() {\n background(200);\n var maxX = 2.8;\n var maxY = 1.5;\n\n // Compute the natural log of a value between 0 and maxX\n var xValue = map(mouseX, 0, width, 0, maxX);\n if (xValue > 0) { // Cannot take the log of a negative number.\n var yValue = log(xValue);\n var y = map(yValue, -maxY, maxY, height, 0);\n\n // Display the calculation occurring.\n var legend = \"log(\" + nf(xValue, 1, 2) + \")\\n= \" + nf(yValue, 1, 3);\n stroke(150);\n line(mouseX, y, mouseX, height);\n fill(0);\n text (legend, 5, 15);\n noStroke();\n ellipse (mouseX, y, 7, 7);\n }\n\n // Draw the log(x) curve,\n // over the domain of x from 0 to maxX\n noFill();\n stroke(0);\n beginShape();\n for(var x=0; x < width; x++) {\n xValue = map(x, 0, width, 0, maxX);\n yValue = log(xValue);\n y = map(yValue, -maxY, maxY, height, 0);\n vertex(x, y);\n }\n endShape();\n line(0,0,0,height);\n line(0,height/2,width, height/2);\n}\n
Calculates the magnitude (or length) of a vector. A vector is a direction\nin space commonly used in computer graphics and linear algebra. Because it\nhas no "start" position, the magnitude of a vector can be thought of as\nthe distance from the coordinate 0,0 to its x,y value. Therefore, mag() is\na shortcut for writing dist(0, 0, x, y).
\nfunction setup() {\n var x1 = 20;\n var x2 = 80;\n var y1 = 30;\n var y2 = 70;\n\n line(0, 0, x1, y1);\n println(mag(x1, y1)); // Prints \"36.05551\"\n line(0, 0, x2, y1);\n println(mag(x2, y1)); // Prints \"85.44004\"\n line(0, 0, x1, y2);\n println(mag(x1, y2)); // Prints \"72.8011\"\n line(0, 0, x2, y2);\n println(mag(x2, y2)); // Prints \"106.30146\"\n}\n
Re-maps a number from one range to another.\n\nIn the first example above, the number 25 is converted from a value in the\nrange of 0 to 100 into a value that ranges from the left edge of the\nwindow (0) to the right edge (width).
the incoming value to be converted
lower bound of the value's current range
upper bound of the value's current range
lower bound of the value's target range
upper bound of the value's target range
\n var value = 25;\n var m = map(value, 0, 100, 0, width);\n ellipse(m, 50, 10, 10);\n
\n function setup() {\n noStroke();\n }\n\n function draw() {\n background(204);\n var x1 = map(mouseX, 0, width, 25, 75);\n ellipse(x1, 25, 25, 25);\n var x2 = map(mouseX, 0, width, 0, 100);\n ellipse(x2, 75, 25, 25);\n }\n
Determines the largest value in a sequence of numbers, and then returns\nthat value. max() accepts any number of Number parameters, or an Array\nof any length.
Numbers to compare
\nfunction setup() {\n // Change the elements in the array and run the sketch\n // to show how max() works!\n numArray = new Array(2,1,5,4,8,9);\n fill(0);\n noStroke();\n text(\"Array Elements\", 0, 10);\n // Draw all numbers in the array\n var spacing = 15;\n var elemsY = 25;\n for(var i = 0; i < numArray.length; i++) {\n text(numArray[i], i * spacing, elemsY);\n }\n maxX = 33;\n maxY = 80;\n // Draw the Maximum value in the array.\n textSize(32);\n text(max(numArray), maxX, maxY);\n}\n
Determines the smallest value in a sequence of numbers, and then returns\nthat value. min() accepts any number of Number parameters, or an Array\nof any length.
\nfunction setup() {\n // Change the elements in the array and run the sketch\n // to show how min() works!\n numArray = new Array(2,1,5,4,8,9);\n fill(0);\n noStroke();\n text(\"Array Elements\", 0, 10);\n // Draw all numbers in the array\n var spacing = 15;\n var elemsY = 25;\n for(var i = 0; i < numArray.length; i++) {\n text(numArray[i], i * spacing, elemsY);\n }\n maxX = 33;\n maxY = 80;\n // Draw the Minimum value in the array.\n textSize(32);\n text(min(numArray), maxX, maxY);\n}\n
Normalizes a number from another range into a value between 0 and 1.\nIdentical to map(value, low, high, 0, 1).\nNumbers outside of the range are not clamped to 0 and 1, because\nout-of-range values are often intentional and useful. (See the second\nexample above.)
incoming value to be normalized
\nfunction draw() {\n background(200);\n currentNum = mouseX;\n lowerBound = 0;\n upperBound = width; //100;\n normalized = norm(currentNum, lowerBound, upperBound);\n lineY = 70\n line(0, lineY, width, lineY);\n //Draw an ellipse mapped to the non-normalized value.\n noStroke();\n fill(50)\n var s = 7; // ellipse size\n ellipse(currentNum, lineY, s, s);\n\n // Draw the guide\n guideY = lineY + 15;\n text(\"0\", 0, guideY);\n textAlign(RIGHT);\n text(\"100\", width, guideY);\n\n // Draw the normalized value\n textAlign(LEFT);\n fill(0);\n textSize(32);\n normalY = 40;\n normalX = 20;\n text(normalized, normalX, normalY);\n}\n
Facilitates exponential expressions. The pow() function is an efficient\nway of multiplying numbers by themselves (or their reciprocals) in large\nquantities. For example, pow(3, 5) is equivalent to the expression\n33333 and pow(3, -5) is equivalent to 1 / 33333. Maps to\nMath.pow().
base of the exponential expression
power by which to raise the base
\nfunction setup() {\n //Exponentially increase the size of an ellipse.\n eSize = 3; // Original Size\n eLoc = 10; // Original Location\n\n ellipse(eLoc, eLoc, eSize, eSize);\n\n ellipse(eLoc*2, eLoc*2, pow(eSize, 2), pow(eSize, 2));\n\n ellipse(eLoc*4, eLoc*4, pow(eSize, 3), pow(eSize, 3));\n\n ellipse(eLoc*8, eLoc*8, pow(eSize, 4), pow(eSize, 4));\n}\n
Calculates the integer closest to the n parameter. For example,\nround(133.8) returns the value 134. Maps to Math.round().
number to round
\nfunction draw() {\n background(200);\n //map, mouseX between 0 and 5.\n var ax = map(mouseX, 0, 100, 0, 5);\n var ay = 66;\n\n // Round the mapped number.\n var bx = round(map(mouseX, 0, 100, 0,5));\n var by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2,2), ax, ay - 5);\n text(nfc(bx,1,1), bx, by - 5);\n}\n
Squares a number (multiplies a number by itself). The result is always a\npositive number, as multiplying two negative numbers always yields a\npositive result. For example, -1 * -1 = 1.
number to square
\nfunction draw() {\n background(200);\n eSize = 7;\n x1 = map(mouseX, 0, width, 0, 10);\n y1 = 80;\n x2 = sq(x1);\n y2 = 20;\n\n // Draw the non-squared.\n line(0, y1, width, y1);\n ellipse(x1, y1, eSize, eSize);\n\n // Draw the squared.\n line(0, y2, width, y2);\n ellipse(x2, y2, eSize, eSize);\n\n // Draw dividing line.\n stroke(100)\n line(0, height/2, width, height/2);\n\n // Draw text.\n var spacing = 15;\n noStroke();\n fill(0);\n text(\"x = \" + x1, 0, y1 + spacing);\n text(\"sq(x) = \" + x2, 0, y2 + spacing);\n}\n
Calculates the square root of a number. The square root of a number is\nalways positive, even though there may be a valid negative root. The\nsquare root s of number a is such that s*s = a. It is the opposite of\nsquaring. Maps to Math.sqrt().
non-negative number to square root
\nfunction draw() {\n background(200);\n eSize = 7;\n x1 = mouseX;\n y1 = 80;\n x2 = sqrt(x1);\n y2 = 20;\n\n // Draw the non-squared.\n line(0, y1, width, y1);\n ellipse(x1, y1, eSize, eSize);\n\n // Draw the squared.\n line(0, y2, width, y2);\n ellipse(x2, y2, eSize, eSize);\n\n // Draw dividing line.\n stroke(100)\n line(0, height/2, width, height/2);\n\n // Draw text.\n noStroke();\n fill(0);\n var spacing = 15;\n text(\"x = \" + x1, 0, y1 + spacing);\n text(\"sqrt(x) = \" + x2, 0, y2 + spacing);\n}\n
Creates a new p5.Vector (the datatype for storing vectors). This provides a\ntwo or three dimensional vector, specifically a Euclidean (also known as\ngeometric) vector. A vector is an entity that has both magnitude and\ndirection.
Returns the Perlin noise value at specified coordinates. Perlin noise is\na random sequence generator producing a more natural ordered, harmonic\nsuccession of numbers compared to the standard random() function.\nIt was invented by Ken Perlin in the 1980s and been used since in\ngraphical applications to produce procedural textures, natural motion,\nshapes, terrains etc. The main difference to the\nrandom() function is that Perlin noise is defined in an infinite\nn-dimensional space where each pair of coordinates corresponds to a\nfixed semi-random value (fixed only for the lifespan of the program; see\nthe noiseSeed() function). p5.js can compute 1D, 2D and 3D noise,\ndepending on the number of coordinates given. The resulting value will\nalways be between 0.0 and 1.0. The noise value can be animated by moving\nthrough the noise space as demonstrated in the example above. The 2nd\nand 3rd dimension can also be interpreted as time.The actual\nnoise is structured similar to an audio signal, in respect to the\nfunction's use of frequencies. Similar to the concept of harmonics in\nphysics, perlin noise is computed over several octaves which are added\ntogether for the final result. Another way to adjust the\ncharacter of the resulting sequence is the scale of the input\ncoordinates. As the function works within an infinite space the value of\nthe coordinates doesn't matter as such, only the distance between\nsuccessive coordinates does (eg. when using noise() within a\nloop). As a general rule the smaller the difference between coordinates,\nthe smoother the resulting noise sequence will be. Steps of 0.005-0.03\nwork best for most applications, but this will differ depending on use.
x-coordinate in noise space
y-coordinate in noise space
z-coordinate in noise space
var xoff = 0.0;\n\nfunction draw() {\n background(204);\n xoff = xoff + .01;\n var n = noise(xoff) * width;\n line(n, 0, n, height);\n}\n
var noiseScale=0.02;\n\nfunction draw() {\n background(0);\n for (var x=0; x < width; x++) {\n var noiseVal = noise((mouseX+x)*noiseScale, mouseY*noiseScale);\n stroke(noiseVal*255);\n line(x, mouseY+noiseVal*80, x, height);\n }\n}\n
Adjusts the character and level of detail produced by the Perlin noise\n function. Similar to harmonics in physics, noise is computed over\n several octaves. Lower octaves contribute more to the output signal and\n as such define the overall intensity of the noise, whereas higher octaves\n create finer grained details in the noise sequence.\n \n By default, noise is computed over 4 octaves with each octave contributing\n exactly half than its predecessor, starting at 50% strength for the 1st\n octave. This falloff amount can be changed by adding an additional function\n parameter. Eg. a falloff factor of 0.75 means each octave will now have\n 75% impact (25% less) of the previous lower octave. Any value between\n 0.0 and 1.0 is valid, however note that values greater than 0.5 might\n result in greater than 1.0 values returned by noise().\n \n By changing these parameters, the signal created by the noise()\n function can be adapted to fit very specific needs and characteristics.
number of octaves to be used by the noise
falloff factor for each octave
\nvar noiseVal;\n var noiseScale=0.02;\nfunction setup() {\n createCanvas(100,100);\n }\nfunction draw() {\n background(0);\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width/2; x++) {\n noiseDetail(2,0.2);\n noiseVal = noise((mouseX+x) * noiseScale,\n (mouseY+y) * noiseScale);\n stroke(noiseVal*255);\n point(x,y);\n noiseDetail(8,0.65);\n noiseVal = noise((mouseX + x + width/2) * noiseScale,\n (mouseY + y) * noiseScale);\n stroke(noiseVal*255);\n point(x + width/2, y);\n }\n }\n }\n
Sets the seed value for noise(). By default, noise()\nproduces different results each time the program is run. Set the\nvalue parameter to a constant to return the same pseudo-random\nnumbers each time the software is run.
the seed value
var xoff = 0.0;\n\nfunction setup() {\n noiseSeed(99);\n stroke(0, 10);\n}\n\nfunction draw() {\n xoff = xoff + .01;\n var n = noise(xoff) * width;\n line(n, 0, n, height);\n}\n
The x component of the vector
The y component of the vector
The z component of the vector
Returns a string representation of a vector v by calling String(v)\nor v.toString(). This method is useful for logging vectors in the\nconsole.
\nfunction setup() {\n var v = createVector(20,30);\n println(String(v)); // prints \"p5.Vector Object : [20, 30, 0]\"\n}\n
Sets the x, y, and z component of the vector using two or three separate\nvariables, the data from a p5.Vector, or the values from a float array.
the x component of the vector or a\n p5.Vector or an Array
the y component of the vector
the z component of the vector
\nfunction setup() {\n var v = createVector(1, 2, 3);\n v.set(4,5,6); // Sets vector to [4, 5, 6]\n\n var v1 = createVector(0, 0, 0);\n var arr = [1, 2, 3];\n v1.set(arr); // Sets vector to [1, 2, 3]\n}\n
Gets a copy of the vector, returns a p5.Vector object.
\nvar v1 = createVector(1, 2, 3);\nvar v2 = v1.copy();\nprintln(v1.x == v2.x && v1.y == v2.y && v1.z == v2.z);\n// Prints \"true\"\n
Adds x, y, and z components to a vector, adds one vector to another, or\nadds two independent vectors together. The version of the method that adds\ntwo vectors together is a static method and returns a p5.Vector, the others\nacts directly on the vector. See the examples for more context.
the x component of the vector to be\n added or a p5.Vector or an Array
the y component of the vector to be\n added
the z component of the vector to be\n added
\nvar v = createVector(1, 2, 3);\nv.add(4,5,6);\n// v's compnents are set to [5, 7, 9]\n
\n// Static method\nvar v1 = createVector(1, 2, 3);\nvar v2 = createVector(2, 3, 4);\n\nvar v3 = p5.Vector.add(v1, v2);\n// v3 has components [3, 5, 7]\n
Subtracts x, y, and z components from a vector, subtracts one vector from\nanother, or subtracts two independent vectors. The version of the method\nthat subtracts two vectors is a static method and returns a p5.Vector, the\nother acts directly on the vector. See the examples for more context.
\nvar v = createVector(4, 5, 6);\nv.sub(1, 1, 1);\n// v's compnents are set to [3, 4, 5]\n
\n// Static method\nvar v1 = createVector(2, 3, 4);\nvar v2 = createVector(1, 2, 3);\n\nvar v3 = p5.Vector.sub(v1, v2);\n// v3 has compnents [1, 1, 1]\n
Multiply the vector by a scalar. The static version of this method\ncreates a new p5.Vector while the non static version acts on the vector\ndirectly. See the examples for more context.
the number to multiply with the vector
\nvar v = createVector(1, 2, 3);\nv.mult(2);\n// v's compnents are set to [2, 4, 6]\n
\n// Static method\nvar v1 = createVector(1, 2, 3);\nvar v2 = p5.Vector.mult(v1, 2);\n// v2 has compnents [2, 4, 6]\n
Divide the vector by a scalar. The static version of this method creates a\nnew p5.Vector while the non static version acts on the vector directly.\nSee the examples for more context.
the number to divide the vector by
\nvar v = createVector(6, 4, 2);\nv.div(2); //v's compnents are set to [3, 2, 1]\n
\n// Static method\nvar v1 = createVector(6, 4, 2);\nvar v2 = p5.Vector.div(v, 2);\n// v2 has compnents [3, 2, 1]\n
Calculates the magnitude (length) of the vector and returns the result as\na float (this is simply the equation sqrt(xx + yy + z*z).)
\nvar v = createVector(20.0, 30.0, 40.0);\nvar m = v.mag();\nprintln(m); // Prints \"53.85164807134504\"\n
Calculates the squared magnitude of the vector and returns the result\nas a float (this is simply the equation (xx + yy + z*z).)\nFaster if the real length is not required in the\ncase of comparing vectors, etc.
\n// Static method\nvar v1 = createVector(6, 4, 2);\nprintln(v1.magSq()); // Prints \"56\"\n
Calculates the dot product of two vectors. The version of the method\nthat computes the dot product of two independent vectors is a static\nmethod. See the examples for more context.
x component of the vector or a p5.Vector
\nvar v1 = createVector(1, 2, 3);\nvar v2 = createVector(2, 3, 4);\n\nprintln(v1.dot(v2)); // Prints \"20\"\n
\n//Static method\nvar v1 = createVector(1, 2, 3);\nvar v2 = createVector(3, 2, 1);\nprint (p5.Vector.dot(v1, v2)); // Prints \"10\"\n
Calculates and returns a vector composed of the cross product between\ntwo vectors. Both the static and non static methods return a new p5.Vector.\nSee the examples for more context.
p5.Vector to be crossed
\nvar v1 = createVector(1, 2, 3);\nvar v2 = createVector(1, 2, 3);\n\nv1.cross(v2); // v's components are [0, 0, 0]\n
\n// Static method\nvar v1 = createVector(1, 0, 0);\nvar v2 = createVector(0, 1, 0);\n\nvar crossProduct = p5.Vector.cross(v1, v2);\n// crossProduct has components [0, 0, 1]\n
Calculates the Euclidean distance between two points (considering a\npoint as a vector object).
the x, y, and z coordinates of a p5.Vector
\nvar v1 = createVector(1, 0, 0);\nvar v2 = createVector(0, 1, 0);\n\nvar distance = v1.dist(v2); // distance is 1.4142...\n
\n// Static method\nvar v1 = createVector(1, 0, 0);\nvar v2 = createVector(0, 1, 0);\n\nvar distance = p5.Vector.dist(v1,v2);\n// distance is 1.4142...\n
Normalize the vector to length 1 (make it a unit vector).
\nvar v = createVector(10, 20, 2);\n// v has compnents [10.0, 20.0, 2.0]\nv.normalize();\n// v's compnents are set to\n// [0.4454354, 0.8908708, 0.089087084]\n
Limit the magnitude of this vector to the value used for the max\nparameter.
the maximum magnitude for the vector
\nvar v = createVector(10, 20, 2);\n// v has compnents [10.0, 20.0, 2.0]\nv.limit(5);\n// v's compnents are set to\n// [2.2271771, 4.4543543, 0.4454354]\n
Set the magnitude of this vector to the value used for the len\nparameter.
the new length for this vector
\nvar v1 = createVector(10, 20, 2);\n// v has compnents [10.0, 20.0, 2.0]\nv1.setMag(10);\n// v's compnents are set to [6.0, 8.0, 0.0]\n
Calculate the angle of rotation for this vector (only 2D vectors)
\nfunction setup() {\n var v1 = createVector(30,50);\n println(v1.heading()); // 1.0303768265243125\n\n var v1 = createVector(40,50);\n println(v1.heading()); // 0.8960553845713439\n\n var v1 = createVector(30,70);\n println(v1.heading()); // 1.1659045405098132\n}\n
Rotate the vector by an angle (only 2D vectors), magnitude remains the\nsame
the angle of rotation
\nvar v = createVector(10.0, 20.0);\n// v has compnents [10.0, 20.0, 0.0]\nv.rotate(HALF_PI);\n// v's compnents are set to [-20.0, 9.999999, 0.0]\n
Linear interpolate the vector to another vector
the x component or the p5.Vector to lerp to
y the y component
z the z component
the amount of interpolation; some value between 0.0\n (old vector) and 1.0 (new vector). 0.1 is very near\n the new vector. 0.5 is halfway in between.
\nvar v = createVector(1, 1, 0);\n\nv.lerp(3, 3, 0, 0.5); // v now has components [2,2,0]\n
\nvar v1 = createVector(0, 0, 0);\nvar v2 = createVector(100, 100, 0);\n\nvar v3 = p5.Vector.lerp(v1, v2, 0.5);\n// v3 has components [50,50,0]\n
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() method to copy into your own\narray.
\nfunction setup() {\n var v = createVector(20,30);\n println(v.array()); // Prints : Array [20, 30, 0]\n}\n
\nvar v = createVector(10.0, 20.0, 30.0);\nvar f = v.array();\nprintln(f[0]); // Prints \"10.0\"\nprintln(f[1]); // Prints \"20.0\"\nprintln(f[2]); // Prints \"30.0\"\n
Equality check against a p5.Vector
\nv1 = createVector(5,10,20);\nv2 = createVector(5,10,20);\nv3 = createVector(13,10,19);\n\nprintln(v1.equals(v2.x,v2.y,v2.z)); // true\nprintln(v1.equals(v3.x,v3.y,v3.z)); // false\n
\nvar v1 = createVector(10.0, 20.0, 30.0);\nvar v2 = createVector(10.0, 20.0, 30.0);\nvar v3 = createVector(0.0, 0.0, 0.0);\nprint (v1.equals(v2)) // true\nprint (v1.equals(v3)) // false\n
Make a new 2D unit vector from an angle
the desired angle
\nfunction draw() {\n background (200);\n\n // Create a variable, proportional to the mouseX,\n // varying from 0-360, to represent an angle in degrees.\n angleMode(DEGREES);\n var myDegrees = map(mouseX, 0,width, 0,360);\n\n // Display that variable in an onscreen text.\n // (Note the nfc() function to truncate additional decimal places,\n // and the \"\\xB0\" character for the degree symbol.)\n var readout = \"angle = \" + nfc(myDegrees,1,1) + \"\\xB0\"\n noStroke();\n fill (0);\n text (readout, 5, 15);\n\n // Create a p5.Vector using the fromAngle function,\n // and extract its x and y components.\n var v = p5.Vector.fromAngle(radians(myDegrees));\n var vx = v.x;\n var vy = v.y;\n\n push();\n translate (width/2, height/2);\n noFill();\n stroke (150);\n line (0,0, 30,0);\n stroke (0);\n line (0,0, 30*vx, 30*vy);\n pop()\n}\n
Make a new 2D unit vector from a random angle
\nvar v = p5.Vector.random2D();\n// May make v's attributes something like:\n// [0.61554617, -0.51195765, 0.0] or\n// [-0.4695841, -0.14366731, 0.0] or\n// [0.6091097, -0.22805278, 0.0]\n
Make a new random 3D unit vector.
\nvar v = p5.Vector.random3D();\n// May make v's attributes something like:\n// [0.61554617, -0.51195765, 0.599168] or\n// [-0.4695841, -0.14366731, -0.8711202] or\n// [0.6091097, -0.22805278, -0.7595902]\n
Adds two vectors together and returns a new one.
a p5.Vector to add
if undefined a new vector will be created
Subtracts one p5.Vector from another and returns a new one. The second\nvector (v2) is subtracted from the first (v1), resulting in v1-v2.
a p5.Vector to subtract from
a p5.Vector to subtract
Multiplies a vector by a scalar and returns a new vector.
the p5.Vector to multiply
the scalar
Divides a vector by a scalar and returns a new vector.
the p5.Vector to divide
Calculates the dot product of two vectors.
the first p5.Vector
the second p5.Vector
Calculates the cross product of two vectors.
Linear interpolate a vector to another vector and return the result as a\nnew vector.
a starting p5.Vector
the p5.Vector to lerp to
amount of interpolation; some value between 0.0\n (old vector) and 1.0 (new vector). 0.1 is very near\n the new vector. 0.5 is halfway in between.
Calculates and returns the angle (in radians) between two vectors.
the x, y, and z components of a p5.Vector
\nvar v1 = createVector(1, 0, 0);\nvar v2 = createVector(0, 1, 0);\n\nvar angle = p5.Vector.angleBetween(v1, v2);\n// angle is PI/2\n
Sets the seed value for random().
By default, random() produces different results each time the program\nis run. Set the seed parameter to a constant to return the same\npseudo-random numbers each time the software is run.
\nrandomSeed(99);\nfor (var i=0; i < 100; i++) {\n var r = random(0, 255);\n stroke(r);\n line(i, 0, i, 100);\n}\n
Return a random floating-point number.
Takes either 0, 1 or 2 arguments.
If no argument is given, returns a random number from 0\nup to (but not including) 1.
If one argument is given and it is a number, returns a random number from 0\nup to (but not including) the number.
If one argument is given and it is an array, returns a random element from\nthat array.
If two arguments are given, returns a random number from the\nfirst argument up to (but not including) the second argument.
\nfor (var i = 0; i < 100; i++) {\n var r = random(50);\n stroke(r*5);\n line(50, i, 50+r, i);\n}\n
\nfor (var i = 0; i < 100; i++) {\n var r = random(-50, 50);\n line(50,i,50+r,i);\n}\n
\n// Get a random element from an array using the random(Array) syntax\nvar words = [ \"apple\", \"bear\", \"cat\", \"dog\" ];\nvar word = random(words); // select random word\ntext(word,10,50); // draw the word\n
the lower bound (inclusive)
the upper bound (exclusive)
the array to choose from
Returns a random number fitting a Gaussian, or\n normal, distribution. There is theoretically no minimum or maximum\n value that randomGaussian() might return. Rather, there is\n just a very low probability that values far from the mean will be\n returned; and a higher probability that numbers near the mean will\n be returned.\n \n Takes either 0, 1 or 2 arguments.\n If no args, returns a mean of 0 and standard deviation of 1.\n If one arg, that arg is the mean (standard deviation is 1).\n If two args, first is mean, second is standard deviation.
the mean
the standard deviation
for (var y = 0; y < 100; y++) {\n var x = randomGaussian(50,15);\n line(50, y, x, y);\n}\n
\nvar distribution = new Array(360);\n\nfunction setup() {\n createCanvas(100, 100);\n for (var i = 0; i < distribution.length; i++) {\n distribution[i] = floor(randomGaussian(0,15));\n }\n}\n\nfunction draw() {\n background(204);\n translate(width/2, width/2);\n for (var i = 0; i < distribution.length; i++) {\n rotate(TWO_PI/distribution.length);\n stroke(0);\n var dist = abs(distribution[i]);\n line(0, 0, dist, 0);\n }\n}\n
The inverse of cos(), returns the arc cosine of a value. This function\nexpects the values in the range of -1 to 1 and values are returned in\nthe range 0 to PI (3.1415927).
the value whose arc cosine is to be returned
\nvar a = PI;\nvar c = cos(a);\nvar ac = acos(c);\n// Prints: \"3.1415927 : -1.0 : 3.1415927\"\nprintln(a + \" : \" + c + \" : \" + ac);\n
\nvar a = PI + PI/4.0;\nvar c = cos(a);\nvar ac = acos(c);\n// Prints: \"3.926991 : -0.70710665 : 2.3561943\"\nprintln(a + \" : \" + c + \" : \" + ac);\n
The inverse of sin(), returns the arc sine of a value. This function\nexpects the values in the range of -1 to 1 and values are returned\nin the range -PI/2 to PI/2.
the value whose arc sine is to be returned
\nvar a = PI + PI/3;\nvar s = sin(a);\nvar as = asin(s);\n// Prints: \"1.0471976 : 0.86602545 : 1.0471976\"\nprintln(a + \" : \" + s + \" : \" + as);\n
\nvar a = PI + PI/3.0;\nvar s = sin(a);\nvar as = asin(s);\n// Prints: \"4.1887903 : -0.86602545 : -1.0471976\"\nprintln(a + \" : \" + s + \" : \" + as);\n
The inverse of tan(), returns the arc tangent of a value. This function\nexpects the values in the range of -Infinity to Infinity (exclusive) and\nvalues are returned in the range -PI/2 to PI/2.
the value whose arc tangent is to be returned
\nvar a = PI + PI/3;\nvar t = tan(a);\nvar at = atan(t);\n// Prints: \"1.0471976 : 1.7320509 : 1.0471976\"\nprintln(a + \" : \" + t + \" : \" + at);\n
\nvar a = PI + PI/3.0;\nvar t = tan(a);\nvar at = atan(t);\n// Prints: \"4.1887903 : 1.7320513 : 1.0471977\"\nprintln(a + \" : \" + t + \" : \" + at);\n
Calculates the angle (in radians) from a specified point to the coordinate\norigin as measured from the positive x-axis. Values are returned as a\nfloat in the range from PI to -PI. The atan2() function is most often used\nfor orienting geometry to the position of the cursor.\n\nNote: The y-coordinate of the point is the first parameter, and the\nx-coordinate is the second parameter, due the the structure of calculating\nthe tangent.
y-coordinate of the point
x-coordinate of the point
\nfunction draw() {\n background(204);\n translate(width/2, height/2);\n var a = atan2(mouseY-height/2, mouseX-width/2);\n rotate(a);\n rect(-30, -5, 60, 10);\n}\n
Calculates the cosine of an angle. This function takes into account the\ncurrent angleMode. Values are returned in the range -1 to 1.
the angle
\nvar a = 0.0;\nvar inc = TWO_PI/25.0;\nfor (var i = 0; i < 25; i++) {\n line(i*4, 50, i*4, 50+cos(a)*40.0);\n a = a + inc;\n}\n
Calculates the sine of an angle. This function takes into account the\ncurrent angleMode. Values are returned in the range -1 to 1.
\nvar a = 0.0;\nvar inc = TWO_PI/25.0;\nfor (var i = 0; i < 25; i++) {\n line(i*4, 50, i*4, 50+sin(a)*40.0);\n a = a + inc;\n}\n
Calculates the tangent of an angle. This function takes into account\nthe current angleMode. Values are returned in the range -1 to 1.
\n var a = 0.0;\n var inc = TWO_PI/50.0;\n for (var i = 0; i < 100; i = i+2) {\n line(i, 50, i, 50+tan(a)*2.0);\n a = a + inc;\n }\n
Converts a radian measurement to its corresponding value in degrees.\nRadians and degrees are two ways of measuring the same thing. There are\n360 degrees in a circle and 2*PI radians in a circle. For example,\n90° = PI/2 = 1.5707964.
the radians value to convert to degrees
\nvar rad = PI/4;\nvar deg = degrees(rad);\nprintln(rad + \" radians is \" + deg + \" degrees\");\n// Prints: 0.7853981633974483 radians is 45 degrees\n
Converts a degree measurement to its corresponding value in radians.\nRadians and degrees are two ways of measuring the same thing. There are\n360 degrees in a circle and 2*PI radians in a circle. For example,\n90° = PI/2 = 1.5707964.
the degree value to convert to radians
\nvar deg = 45.0;\nvar rad = radians(deg);\nprintln(deg + \" degrees is \" + rad + \" radians\");\n// Prints: 45 degrees is 0.7853981633974483 radians\n
Sets the current mode of p5 to given mode. Default mode is RADIANS.
either RADIANS or DEGREES
\nfunction draw(){\n background(204);\n angleMode(DEGREES); // Change the mode to DEGREES\n var a = atan2(mouseY-height/2, mouseX-width/2);\n translate(width/2, height/2);\n push();\n rotate(a);\n rect(-20, -5, 40, 10); // Larger rectangle is rotating in degrees\n pop();\n angleMode(RADIANS); // Change the mode to RADIANS\n rotate(a); // var a stays the same\n rect(-40, -5, 20, 10); // Smaller rectangle is rotating in radians\n}\n
Sets the current alignment for drawing text. Accepts two\narguments: horizAlign (LEFT, CENTER, or RIGHT) and\nvertAlign (TOP, BOTTOM, CENTER, or BASELINE).
The horizAlign parameter is in reference to the x value\nof the text() function, while the vertAlign parameter is\nin reference to the y value.
So if you write textAlign(LEFT), you are aligning the left\nedge of your text to the x value you give in text(). If you\nwrite textAlign(RIGHT, TOP), you are aligning the right edge\nof your text to the x value and the top of edge of the text\nto the y value.
horizontal alignment, either LEFT,\n CENTER, or RIGHT
vertical alignment, either TOP,\n BOTTOM, CENTER, or BASELINE
\ntextSize(16);\ntextAlign(RIGHT);\ntext(\"ABCD\", 50, 30);\ntextAlign(CENTER);\ntext(\"EFGH\", 50, 50);\ntextAlign(LEFT);\ntext(\"IJKL\", 50, 70);\n
Sets/gets the spacing, in pixels, between lines of text. This\nsetting will be used in all subsequent calls to the text() function.
the size in pixels for spacing between lines
\n// Text to display. The \"\\n\" is a \"new line\" character\nlines = \"L1\\nL2\\nL3\";\ntextSize(12);\n\ntextLeading(10); // Set leading to 10\ntext(lines, 10, 25);\n\ntextLeading(20); // Set leading to 20\ntext(lines, 40, 25);\n\ntextLeading(30); // Set leading to 30\ntext(lines, 70, 25);\n
Sets/gets the current font size. This size will be used in all subsequent\ncalls to the text() function. Font size is measured in pixels.
the size of the letters in units of pixels
\ntextSize(12);\ntext(\"Font Size 12\", 10, 30);\ntextSize(14);\ntext(\"Font Size 14\", 10, 60);\ntextSize(16);\ntext(\"Font Size 16\", 10, 90);\n
Sets/gets the style of the text for system fonts to NORMAL, ITALIC, or BOLD.\nNote: this may be is overridden by CSS styling. For non-system fonts\n(opentype, truetype, etc.) please load styled fonts instead.
styling for text, either NORMAL,\n ITALIC, or BOLD
\nstrokeWeight(0);\ntextSize(12);\ntextStyle(NORMAL);\ntext(\"Font Style Normal\", 10, 30);\ntextStyle(ITALIC);\ntext(\"Font Style Italic\", 10, 60);\ntextStyle(BOLD);\ntext(\"Font Style Bold\", 10, 90);\n
Calculates and returns the width of any character or text string.
the String of characters to measure
\ntextSize(28);\n\nvar aChar = 'P';\nvar cWidth = textWidth(aChar);\ntext(aChar, 0, 40);\nline(cWidth, 0, cWidth, 50);\n\nvar aString = \"p5.js\";\nvar sWidth = textWidth(aString);\ntext(aString, 0, 85);\nline(sWidth, 50, sWidth, 100);\n
Returns the ascent of the current font at its current size. The ascent\nrepresents the distance, in pixels, of the tallest character above\nthe baseline.
\nvar base = height * 0.75;\nvar scalar = 0.8; // Different for each font\n\ntextSize(32); // Set initial text size\nvar asc = textAscent() * scalar; // Calc ascent\nline(0, base - asc, width, base - asc);\ntext(\"dp\", 0, base); // Draw text on baseline\n\ntextSize(64); // Increase text size\nasc = textAscent() * scalar; // Recalc ascent\nline(40, base - asc, width, base - asc);\ntext(\"dp\", 40, base); // Draw text on baseline\n
Returns the descent of the current font at its current size. The descent\nrepresents the distance, in pixels, of the character with the longest\ndescender below the baseline.
\nvar base = height * 0.75;\nvar scalar = 0.8; // Different for each font\n\ntextSize(32); // Set initial text size\nvar desc = textDescent() * scalar; // Calc ascent\nline(0, base+desc, width, base+desc);\ntext(\"dp\", 0, base); // Draw text on baseline\n\ntextSize(64); // Increase text size\ndesc = textDescent() * scalar; // Recalc ascent\nline(40, base + desc, width, base + desc);\ntext(\"dp\", 40, base); // Draw text on baseline\n
Helper function to measure ascent and descent.
Draws text to the screen. Displays the information specified in the first\nparameter on the screen in the position specified by the additional\nparameters. A default font will be used unless a font is set with the\ntextFont() function and a default size will be used unless a font is set\nwith textSize(). Change the color of the text with the fill() function.\nChange the outline of the text with the stroke() and strokeWeight()\nfunctions.\n\nThe text displays in relation to the textAlign() function, which gives the\noption to draw to the left, right, and center of the coordinates.\n\nThe x2 and y2 parameters define a rectangular area to display within and\nmay only be used with string data. When these parameters are specified,\nthey are interpreted based on the current rectMode() setting. Text that\ndoes not fit completely within the rectangle specified will not be drawn\nto the screen.
the alphanumeric symbols to be displayed
x-coordinate of text
y-coordinate of text
by default, the width of the text box,\n see rectMode() for more info
by default, the height of the text box,\n see rectMode() for more info
\ntextSize(32);\ntext(\"word\", 10, 30);\nfill(0, 102, 153);\ntext(\"word\", 10, 60);\nfill(0, 102, 153, 51);\ntext(\"word\", 10, 90);\n
\ns = \"The quick brown fox jumped over the lazy dog.\";\nfill(50);\ntext(s, 10, 10, 70, 80); // Text wraps within text box\n
Sets the current font that will be drawn with the text() function.
a font loaded via loadFont(), or a String\n representing a browser-based default font.
\nfill(0);\ntextSize(12);\ntextFont(\"Georgia\");\ntext(\"Georgia\", 12, 30);\ntextFont(\"Helvetica\");\ntext(\"Helvetica\", 12, 60);\n
\nvar fontRegular, fontItalic, fontBold;\nfunction preload() {\n fontRegular = loadFont(\"assets/Regular.otf\");\n fontItalic = loadFont(\"assets/Italic.ttf\");\n fontBold = loadFont(\"assets/Bold.ttf\");\n}\nfunction setup() {\n background(210);\n fill(0).strokeWeight(0).textSize(10);\n textFont(fontRegular);\n text(\"Font Style Normal\", 10, 30);\n textFont(fontItalic);\n text(\"Font Style Italic\", 10, 50);\n textFont(fontBold);\n text(\"Font Style Bold\", 10, 70);\n}\n
Underlying opentype font implementation
Returns a tight bounding box for the given text string using this\nfont (currently only supports single lines)
a line of text
x-position
y-position
font size to use (optional)
opentype options (optional)
\nvar font;\nvar textString = 'Lorem ipsum dolor sit amet.';\nfunction preload() {\n font = loadFont('./assets/Regular.otf');\n};\nfunction setup() {\n background(210);\n\n var bbox = font.textBounds(textString, 10, 30, 12);\n fill(255);\n stroke(0);\n rect(bbox.x, bbox.y, bbox.w, bbox.h);\n fill(0);\n noStroke();\n\n textFont(font);\n textSize(12);\n text(textString, 10, 30);\n};\n
Computes an array of points following the path for specified text
an (optional) object that can contain:
sampleFactor - the ratio of path-length to number of samples\n(default=.25); higher values yield more points and are therefore\nmore precise
simplifyThreshold - if set to a non-zero value, collinear points will be\nbe removed from the polygon; the value represents the threshold angle to use\nwhen determining whether two edges are collinear
Returns the set of opentype glyphs for the supplied string.
Note that there is not a strict one-to-one mapping between characters\nand glyphs, so the list of returned glyphs can be larger or smaller\n than the length of the given string.
the string to be converted
Returns an opentype path for the supplied string and position.
Adds a value to the end of an array. Extends the length of\nthe array by one. Maps to Array.push().
Array to append
to be added to the Array
\nfunction setup() {\n\nvar myArray = new Array(\"Mango\", \"Apple\", \"Papaya\")\nprintln(myArray) // [\"Mango\", \"Apple\", \"Papaya\"]\n\nappend(myArray, \"Peach\")\nprintln(myArray) // [\"Mango\", \"Apple\", \"Papaya\", \"Peach\"]\n\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().\n\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).\n\nUsing this function is far more efficient for copying array data than\niterating through a for() loop and copying each element individually.
the source Array
starting position in the source Array
the destination Array
starting position in the destination Array
number of Array elements to be copied
\n function setup() {\n\n var src = new Array(\"A\", \"B\", \"C\");\n var dst = new Array( 1 , 2 , 3 );\n var srcPosition = 1;\n var dstPosition = 0;\n var length = 2;\n\n println(src); // [\"A\", \"B\", \"C\"]\n println(dst); // [ 1 , 2 , 3 ]\n\n arrayCopy(src, srcPosition, dst, dstPosition, length);\n println(dst); // [\"B\", \"C\", 3]\n\n }\n
Concatenates two arrays, maps to Array.concat(). Does not modify the\ninput arrays.
first Array to concatenate
second Array to concatenate
\nfunction setup() {\n var arr1 = new Array(\"A\", \"B\", \"C\");\n var arr2 = new Array( 1 , 2 , 3 );\n\n println(arr1); // [\"A\",\"B\",\"C\"]\n println(arr2); // [1,2,3]\n\n var arr3 = concat(arr1, arr2);\n\n println(arr1); // [\"A\",\"B\",\"C\"]\n println(arr2); // [1,2,3]\n println(arr3); // [\"A\",\"B\",\"C\",1,2,3]\n\n}\n
Reverses the order of an array, maps to Array.reverse()
Array to reverse
\nfunction setup() {\n var myArray = new Array(\"A\", \"B\", \"C\");\n println(myArray); // [\"A\",\"B\",\"C\"]\n\n reverse(myArray);\n println(myArray); // [\"C\",\"B\",\"A\"]\n}\n
Decreases an array by one element and returns the shortened array,\nmaps to Array.pop().
Array to shorten
\nfunction setup() {\n var myArray = new Array(\"A\", \"B\", \"C\");\n println(myArray); // [\"A\",\"B\",\"C\"]\n\n var newArray = shorten(myArray);\n println(myArray); // [\"A\",\"B\",\"C\"]\n println(newArray); // [\"A\",\"B\"]\n}\n
Randomizes the order of the elements of an array. Implements\n\nFisher-Yates Shuffle Algorithm.
Array to shuffle
modify passed array
\nfunction setup() {\n var regularArr = ['ABC', 'def', createVector(), TAU, Math.E];\n println(regularArr);\n shuffle(regularArr, true); // force modifications to passed array\n println(regularArr);\n\n // By default shuffle() returns a shuffled cloned array:\n var newArr = shuffle(regularArr);\n println(regularArr);\n println(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.
Array to sort
number of elements to sort, starting from 0
\nfunction setup() {\n var words = new Array(\"banana\", \"apple\", \"pear\",\"lime\");\n println(words); // [\"banana\", \"apple\", \"pear\", \"lime\"]\n var count = 4; // length of array\n\n words = sort(words, count);\n println(words); // [\"apple\", \"banana\", \"lime\", \"pear\"]\n}\n
\nfunction setup() {\n var numbers = new Array(2,6,1,5,14,9,8,12);\n println(numbers); // [2,6,1,5,14,9,8,12]\n var count = 5; // Less than the length of the array\n\n numbers = sort(numbers, count);\n println(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.)
Array to splice into
value to be spliced in
in the array from which to insert data
\nfunction setup() {\n var myArray = new Array(0,1,2,3,4);\n var insArray = new Array(\"A\",\"B\",\"C\");\n println(myArray); // [0,1,2,3,4]\n println(insArray); // [\"A\",\"B\",\"C\"]\n\n splice(myArray, insArray, 3);\n println(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.
Array to extract from
position to begin
number of values to extract
\nfunction setup() {\n var myArray = new Array(1,2,3,4,5);\n println(myArray); // [1,2,3,4,5]\n\n var sub1 = subset(myArray, 0, 3);\n var sub2 = subset(myArray, 2, 2);\n println(sub1); // [1,2,3]\n println(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.
float string to parse
\nvar str = '20';\nvar diameter = float(str);\nellipse(width/2, height/2, diameter, diameter);\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.
value to parse
\nprintln(int(\"10\")); // 10\nprintln(int(10.31)); // 10\nprintln(int(-10)); // -10\nprintln(int(true)); // 1\nprintln(int(false)); // 0\nprintln(int([false, true, \"10.3\", 9.8])); // [0, 1, 10, 9]\n
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.
\nprintln(str(\"10\")); // \"10\"\nprintln(str(10.31)); // \"10.31\"\nprintln(str(-10)); // \"-10\"\nprintln(str(true)); // \"true\"\nprintln(str(false)); // \"false\"\nprintln(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.
\nprintln(boolean(0)); // false\nprintln(boolean(1)); // true\nprintln(boolean(\"true\")); // true\nprintln(boolean(\"abcd\")); // false\nprintln(boolean([0, 12, \"true\"])); // [false, true, false]\n
Converts a number, string or boolean to its byte representation.\nA byte can be only a whole number between -128 and 127, so when a value\noutside of this range is converted, it wraps around to the corresponding\nbyte representation. When an array of number, string or boolean values is\npassed in, then an array of bytes the same length is returned.
\nprintln(byte(127)); // 127\nprintln(byte(128)); // -128\nprintln(byte(23.4)); // 23\nprintln(byte(\"23.4\")); // 23\nprintln(byte(true)); // 1\nprintln(byte([0, 255, \"100\"])); // [0, -1, 100]\n
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.
\nprintln(char(65)); // \"A\"\nprintln(char(\"65\")); // \"A\"\nprintln(char([65, 66, 67])); // [ \"A\", \"B\", \"C\" ]\nprintln(join(char([65, 66, 67]), '')); // \"ABC\"\n
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.
\nprintln(unchar(\"A\")); // 65\nprintln(unchar([\"A\", \"B\", \"C\"])); // [ 65, 66, 67 ]\nprintln(unchar(split(\"ABC\", \"\"))); // [ 65, 66, 67 ]\n
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.
\nprintln(hex(255)); // \"000000FF\"\nprintln(hex(255, 6)); // \"0000FF\"\nprintln(hex([0, 127, 255], 6)); // [ \"000000\", \"00007F\", \"0000FF\" ]\n
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.
\nprintln(unhex(\"A\")); // 10\nprintln(unhex(\"FF\")); // 255\nprintln(unhex([\"FF\", \"AA\", \"00\"])); // [ 255, 170, 0 ]\n
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().
array of Strings to be joined
String to be placed between each item
\nvar array = [\"Hello\", \"world!\"]\nvar separator = \" \"\nvar message = join(array, separator);\ntext(message, 5, 50);\n
This 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.\n\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.\n\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).
the String to be searched
the regexp to be used for matching
\nvar string = \"Hello p5js*!\"\nvar regexp = \"p5js\\\\*\"\nvar match = match(string, regexp);\ntext(match, 5, 50);\n
This 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.\n\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.\n\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).
\nvar string = \"Hello p5js*! Hello world!\"\nvar regexp = \"Hello\"\nmatchAll(string, regexp);\n
Utility 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.
the Number to format
number of digits to the left of the\n decimal point
number of digits to the right of the\n decimal point
\nfunction setup() {\n background(200);\n var num = 112.53106115;\n\n noStroke();\n fill(0);\n textSize(14);\n // Draw formatted numbers\n text(nf(num, 5, 2), 10, 20);\n\n text(nf(num, 4, 3), 10, 55);\n\n text(nf(num, 3, 6), 10, 85);\n\n // Draw dividing lines\n stroke(120);\n line(0, 30, width, 30);\n line(0, 65, width, 65);\n}\n
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.
\nfunction setup() {\n background(200);\n var num = 11253106.115;\n var numArr = new Array(1,1,2);\n\n noStroke();\n fill(0);\n textSize(12);\n\n // Draw formatted numbers\n text(nfc(num, 4, 2), 10, 30);\n text(nfc(numArr, 2, 1), 10, 80);\n\n // Draw dividing line\n stroke(120);\n line(0, 50, width, 50);\n}\n
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.
number of digits to the left of the decimal\n point
\nfunction setup() {\n background(200);\n var num1 = 11253106.115;\n var 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
Utility function for formatting numbers into strings. Similar to nf() but\nputs a " " (space) in front of positive numbers and a "-" in front of\nnegative numbers. There are two versions: one for formatting floats, and\none for formatting ints. The values for the digits, left, and right\nparameters should always be positive integers.
\nfunction setup() {\n background(200);\n var num1 = 11253106.115;\n var num2 = -11253106.115;\n\n noStroke();\n fill(0);\n textSize(12);\n // Draw formatted numbers\n text(nfs(num1, 4, 2), 10, 30);\n\n text(nfs(num2, 4, 2), 10, 80);\n\n // Draw dividing line\n stroke(120);\n line(0, 50, width, 50);\n}\n
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.
The splitTokens() function works in a similar fashion, except that it\nsplits using a range of characters instead of a specific character or\nsequence.
the String to be split
the String used to separate the data
\nvar names = \"Pat,Xio,Alex\"\nvar splitString = split(names, \",\");\ntext(splitString[0], 5, 30);\ntext(splitString[1], 5, 50);\ntext(splitString[2], 5, 70);\n
The 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.\n\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.
list of individual Strings that will be used as\n separators
\nfunction setup() {\n var myStr = \"Mango, Banana, Lime\";\n var myStrArr = splitTokens(myStr, \",\");\n\n println(myStrArr); // prints : [\"Mango\",\" Banana\",\" Lime\"]\n}\n
Removes 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.
a String or Array of Strings to be trimmed
\nvar string = trim(\" No new lines\\n \");\ntext(string +\" here\", 2, 50);\n
p5.js communicates with the clock on your computer. The day() function\nreturns the current day as a value from 1 - 31.
\nvar d = day();\ntext(\"Current day: \\n\" + d, 5, 50);\n
p5.js communicates with the clock on your computer. The hour() function\nreturns the current hour as a value from 0 - 23.
\nvar h = hour();\ntext(\"Current hour:\\n\" + h, 5, 50);\n
p5.js communicates with the clock on your computer. The minute() function\nreturns the current minute as a value from 0 - 59.
\nvar m = minute();\ntext(\"Current minute: \\n\" + m, 5, 50);\n
Returns the number of milliseconds (thousandths of a second) since\nstarting the program. This information is often used for timing events and\nanimation sequences.
\nvar millisecond = millis();\ntext(\"Milliseconds \\nrunning: \\n\" + millisecond, 5, 40);\n
p5.js communicates with the clock on your computer. The month() function\nreturns the current month as a value from 1 - 12.
\nvar m = month();\ntext(\"Current month: \\n\" + m, 5, 50);\n
p5.js communicates with the clock on your computer. The second() function\nreturns the current second as a value from 0 - 59.
\nvar s = second();\ntext(\"Current second: \\n\" + s, 5, 50);\n
p5.js communicates with the clock on your computer. The year() function\nreturns the current year as an integer (2014, 2015, 2016, etc).
\nvar y = year();\ntext(\"Current year: \\n\" + y, 5, 50);\n
Sets camera position
camera position value on x axis
camera position value on y axis
camera position value on z axis
\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\nfunction draw(){\n //move the camera away from the plane by a sin wave\n camera(0, 0, sin(frameCount * 0.01) * 100);\n plane(120, 120);\n}\n
Sets perspective camera
camera frustum vertical field of view,\n from bottom to top of view, in degrees
camera frustum aspect ratio
frustum near plane length
frustum far plane length
\n//drag mouse to toggle the world!\n//you will see there's a vanish point\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n perspective(60 / 180 * PI, width/height, 0.1, 100);\n}\nfunction draw(){\n background(200);\n orbitControl();\n for(var i = -1; i < 2; i++){\n for(var j = -2; j < 3; j++){\n push();\n translate(i*160, 0, j*160);\n box(40, 40, 40);\n pop();\n }\n }\n}\n
Setup ortho camera
camera frustum left plane
camera frustum right plane
camera frustum bottom plane
camera frustum top plane
camera frustum near plane
camera frustum far plane
\n//drag mouse to toggle the world!\n//there's no vanish point\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n ortho(-width/2, width/2, height/2, -height/2, 0.1, 100);\n}\nfunction draw(){\n background(200);\n orbitControl();\n for(var i = -1; i < 2; i++){\n for(var j = -2; j < 3; j++){\n push();\n translate(i*160, 0, j*160);\n box(40, 40, 40);\n pop();\n }\n }\n}\n
Creates an ambient light with a color
gray value,\nred or hue value (depending on the current color mode),\nor color Array, or CSS color string
optional: green or saturation value
optional: blue or brightness value
optional: opacity
\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\nfunction draw(){\n background(0);\n ambientLight(150);\n ambientMaterial(250);\n sphere(200);\n}\n
Creates a directional light with a color and a direction
x axis direction or a p5.Vector
optional: y axis direction
optional: z axis direction
\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\nfunction draw(){\n background(0);\n //move your mouse to change light direction\n var dirX = (mouseX / width - 0.5) *2;\n var dirY = (mouseY / height - 0.5) *(-2);\n directionalLight(250, 250, 250, dirX, dirY, 0.25);\n ambientMaterial(250);\n sphere(200);\n}\n
Creates a point light with a color and a light position
x axis position or a p5.Vector
optional: y axis position
optional: z axis position
\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\nfunction draw(){\n background(0);\n //move your mouse to change light position\n var locY = (mouseY / height - 0.5) *(-2);\n var locX = (mouseX / width - 0.5) *2;\n //to set the light position,\n //think of the world's coordinate as:\n // -1,1 -------- 1,1\n // | |\n // | |\n // | |\n // -1,-1---------1,-1\n pointLight(250, 250, 250, locX, locY, 0);\n ambientMaterial(250);\n sphere(200);\n}\n
Load a 3d model from an OBJ file.\n\nOne of the limitations of the OBJ 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.
Path of the model to be loaded
If true, scale the model to a\n standardized size when loading
Function to be called\n once the model is loaded. Will be passed\n the 3D model object.
\n//draw a spinning teapot\nvar teapot;\n\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n\n teapot = loadModel('assets/teapot.obj');\n}\n\nfunction draw(){\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n model(teapot);\n}\n
Parse OBJ lines into model. For reference, this is what a simple model of a\nsquare might look like:
v -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
f 4 3 2 1
Render a 3d model to the screen.
Loaded 3d model to be rendered
Normal material for geometry. You can view all\npossible materials in this\nexample.
\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(0);\n normalMaterial();\n sphere(200);\n}\n
Texture for geometry. You can view other possible materials in this\nexample.
2-dimensional graphics\n to render as texture
\nvar img;\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n img = loadImage(\"assets/laDefense.jpg\");\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(200, 200, 200);\n}\n
\nvar pg;\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n pg = createGraphics(200, 200);\n pg.textSize(100);\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 plane(200);\n}\n
\nvar vid;\nfunction preload(){\n vid = createVideo(\"assets/fingers.mov\");\n vid.hide();\n vid.loop();\n}\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(0);\n //pass video frame as texture\n texture(vid);\n plane(200);\n}\n
Texture Util functions
Checks whether val is a pot\nmore info on power of 2 here:\nhttps://www.opengl.org/wiki/NPOT_Texture
returns the next highest power of 2 value
Ambient material for geometry with a given color. You can view all\npossible materials in this\nexample.
\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\nfunction draw(){\n background(0);\n ambientLight(100);\n pointLight(250, 250, 250, 100, 100, 0);\n ambientMaterial(250);\n sphere(200);\n}\n
Specular material for geometry with a given color. You can view all\npossible materials in this\nexample.
\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\nfunction draw(){\n background(0);\n ambientLight(100);\n pointLight(250, 250, 250, 100, 100, 0);\n specularMaterial(250);\n sphere(200);\n}\n
p5 Geometry class
callback function or Object\n containing routine(s) for vertex data generation
number of vertices on horizontal surface
function to call upon object instantiation.
computes smooth normals per vertex as an average of each\nface.
Averages the vertex normals. Used in curved\nsurfaces
Averages pole normals. Used in spherical primitives
Modifies all vertices to be centered within the range -100 to 100.
A class to describe a 4x4 matrix\nfor model and view matrix manipulation in the p5js webgl renderer.\nclass p5.Matrix
array literal of our 4x4 matrix
Sets the x, y, and z component of the vector using two or three separate\nvariables, the data from a p5.Matrix, or the values from a float array.
the input p5.Matrix or\n an Array of length 16
Gets a copy of the vector, returns a p5.Matrix object.
return a copy of a matrix
return an identity matrix
transpose according to a given matrix
the matrix to be based on to transpose
invert matrix according to a give matrix
the matrix to be based on to invert
Inverts a 3x3 matrix
transposes a 3x3 p5.Matrix by a mat3
1-dimensional array
converts a 4x4 matrix to its 3x3 inverse tranform\ncommonly used in MVMatrix to NMatrix conversions.
inspired by Toji's mat4 determinant
multiply two mat4s
The matrix we want to multiply by
scales a p5.Matrix by scalars or a vector
vector to scale by
rotate our Matrix around an axis by the given angle.
The angle of rotation in radians
the axis(es) to rotate around
vector to translate by
sets the perspective matrix
near clipping plane
far clipping plane
sets the ortho matrix
PRIVATE
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.
Begin shape drawing. This is a helpful way of generating\ncustom shapes quickly. However in WEBGL mode, application\nperformance will likely drop as a result of too many calls to\nbeginShape() / endShape(). As a high performance alternative,\nplease use p5.js geometry primitives.
webgl primitives mode. beginShape supports the\n following modes:\n POINTS,LINES,LINE_STRIP,LINE_LOOP,TRIANGLES,\n TRIANGLE_STRIP,and TRIANGLE_FAN.
adds a vertex to be drawn in a custom Shape.
x-coordinate of vertex
y-coordinate of vertex
z-coordinate of vertex
End shape drawing and render vertices to screen.
Bind immediateMode buffers to data,\nthen draw gl arrays
Numbers array representing\n vertex positions
initializes buffer defaults. runs each time a new geometry is\nregistered
key of the geometry object
createBuffers description
contains geometry data
Draws buffers given a geometry key ID
ID in our geom hash
turn a two dimensional array into one dimensional array
2-dimensional array
turn a p5.Vector Array into a one dimensional number array
an array of p5.Vector
model view, projection, & normal\nmatrices
[background description]
[_initShaders description]
Sets a shader uniform given a shaderProgram and uniform string
key to material Hash.
location in shader.
data to bind uniform. Float data type.
Basic fill material for geometry with a given color
\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(0);\n fill(250, 0, 0);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n rotateZ(frameCount * 0.01);\n box(200, 200, 200);\n}\n
[strokeWeight description]
stroke point size
[resize description]
clears color and depth buffers\nwith r,g,b,a
normalized red val.
normalized green val.
normalized blue val.
normalized alpha val.
[translate description]
Scales the Model View Matrix by a vector
y-axis scalar
z-axis scalar
pushes a copy of the model view matrix onto the\nMV Matrix stack.
[pop description]
Draw a plane with given a width and height
width of the plane
height of the plane
Optional number of triangle\n subdivisions in x-dimension
Optional number of triangle\n subdivisions in y-dimension
\n//draw a plane with width 200 and height 200\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(200);\n plane(200, 200);\n}\n
Draw a box with given width, height and depth
width of the box
height of the box
depth of the box
\n//draw a spinning box with width, height and depth 200\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(200, 200, 200);\n}\n
Draw a sphere with given radius
radius of circle
optional: number of segments,\n the more segments the smoother geometry\n default is 24
optional: number of segments,\n the more segments the smoother geometry\n default is 16
\n// draw a sphere with radius 200\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(200);\n sphere(200);\n}\n
Draw a cylinder with given radius and height
radius of the surface
height of the cylinder
optional: number of segments in y-dimension,\n the more segments the smoother geometry\n default is 16
\n//draw a spinning cylinder with radius 200 and height 200\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(200);\n rotateX(frameCount * 0.01);\n rotateZ(frameCount * 0.01);\n cylinder(200, 200);\n}\n
Draw a cone with given radius and height
radius of the bottom surface
height of the cone
\n//draw a spinning cone with radius 200 and height 200\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(200);\n rotateX(frameCount * 0.01);\n rotateZ(frameCount * 0.01);\n cone(200, 200);\n}\n
Draw an ellipsoid with given raduis
xradius of circle
yradius of circle
zradius of circle
optional: 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.
optional: 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// draw an ellipsoid with radius 200, 300 and 400 .\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(200);\n ellipsoid(200,300,400);\n}\n
Draw a torus with given radius and tube radius
radius of the whole ring
radius of the tube
optional: number of segments in x-dimension,\n the more segments the smoother geometry\n default is 24
\n//draw a spinning torus with radius 200 and tube radius 60\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n torus(200, 60);\n}\n
_globalInit
TODO: ???\nif sketch is on window\nassume "global" mode\nand instantiate p5 automatically\notherwise do nothing
Searches the page for an element with the given ID, class, or tag name (using the '#' or '.'\nprefixes to specify an ID or class respectively, and none for a tag) and returns it as\na p5.Element. If a class or tag name is given with more than 1 element,\nonly the first element will be returned.\nThe DOM node itself can be accessed with .elt.\nReturns null if none found. You can also specify a container to search within.
id, class, or tag name of element to search for
id, p5.Element, or HTML element to search within
\nfunction setup() {\n createCanvas(100,100);\n //translates canvas 50px down\n select('canvas').position(100, 100);\n}\n
\n// these are all valid calls to select()\nvar a = select('#moo');\nvar b = select('#blah', '#myContainer');\nvar c = select('#foo', b);\nvar d = document.getElementById('beep');\nvar e = select('p', d);\n
Searches the page for elements with the given class or tag name (using the '.' prefix\nto specify a class and no prefix for a tag) and returns them as p5.Elements\nin an array.\nThe DOM node itself can be accessed with .elt.\nReturns an empty array if none found.\nYou can also specify a container to search within.
class or tag name of elements to search for
\nfunction setup() {\n createButton('btn');\n createButton('2nd btn');\n createButton('3rd btn');\n var buttons = selectAll('button');\n\n for (var i = 0; i < buttons.length; i++){\n buttons[i].size(100,100);\n }\n}\n
\n// these are all valid calls to selectAll()\nvar a = selectAll('.moo');\nvar b = selectAll('div');\nvar c = selectAll('button', '#myContainer');\nvar d = select('#container');\nvar e = selectAll('p', d);\nvar f = document.getElementById('beep');\nvar g = select('.blah', f);\n
Helper function for select and selectAll
Helper function for getElement and getElements.
Removes all elements created by p5, except any canvas / graphics\nelements created by createCanvas or createGraphics.\nEvent handlers are removed, and element is removed from the DOM.
\nfunction setup() {\n createCanvas(100, 100);\n createDiv('this is some text');\n createP('this is a paragraph');\n}\nfunction mousePressed() {\n removeElements(); // this will remove the div and p, not canvas\n}\n
Helpers for create methods.
Creates a <div></div> element in the DOM with given inner HTML.\nAppends to the container node if one is specified, otherwise\nappends to body.
inner HTML for element created
\nvar myDiv;\nfunction setup() {\n myDiv = createDiv('this is some text');\n}\n
Creates a <p></p> element in the DOM with given inner HTML. Used\nfor paragraph length text.\nAppends to the container node if one is specified, otherwise\nappends to body.
\nvar myP;\nfunction setup() {\n myP = createP('this is some text');\n}\n
Creates a <span></span> element in the DOM with given inner HTML.\nAppends to the container node if one is specified, otherwise\nappends to body.
\nvar mySpan;\nfunction setup() {\n mySpan = createSpan('this is some text');\n}\n
Creates an <img /> element in the DOM with given src and\nalternate text.\nAppends to the container node if one is specified, otherwise\nappends to body.
src path or url for image
alternate text to be used if image does not load
callback to be called once image data is loaded
\nvar img;\nfunction setup() {\n img = createImg('http://p5js.org/img/asterisk-01.png');\n}\n
Creates an <a></a> element in the DOM for including a hyperlink.\nAppends to the container node if one is specified, otherwise\nappends to body.
url of page to link to
inner html of link element to display
target where new link should open,\n could be _blank, _self, _parent, _top.
\nvar myLink;\nfunction setup() {\n myLink = createA('http://p5js.org/', 'this is a link');\n}\n
Creates a slider <input></input> element in the DOM.\nUse .size() to set the display length of the slider.\nAppends to the container node if one is specified, otherwise\nappends to body.
minimum value of the slider
maximum value of the slider
default value of the slider
step size for each tick of the slider
\nvar slider;\nfunction setup() {\n slider = createSlider(0, 255, 100);\n slider.position(10, 10);\n slider.style('width', '80px');\n}\n\nfunction draw() {\n var val = slider.value();\n background(val);\n}\n
\nvar slider;\nfunction setup() {\n colorMode(HSB);\n slider = createSlider(0, 360, 60, 40);\n slider.position(10, 10);\n slider.style('width', '80px');\n}\n\nfunction draw() {\n var val = slider.value();\n background(val, 100, 100, 1);\n}\n
Creates a <button></button> element in the DOM.\nUse .size() to set the display size of the button.\nUse .mousePressed() to specify behavior on press.\nAppends to the container node if one is specified, otherwise\nappends to body.
label displayed on the button
value of the button
\nvar button;\nfunction setup() {\n createCanvas(100, 100);\n background(0);\n button = createButton('click me');\n button.position(19, 19);\n button.mousePressed(changeBG);\n}\n\nfunction changeBG() {\n var val = random(255);\n background(val);\n}\n
Creates a checkbox <input></input> element in the DOM.\nCalling .checked() on a checkbox returns if it is checked or not
label displayed after checkbox
value of the checkbox; checked is true, unchecked is false.Unchecked if no value given
\nvar checkbox;\n\nfunction setup() {\n checkbox = createCheckbox('label', false);\n checkbox.changed(myCheckedEvent);\n}\n\nfunction myCheckedEvent() {\n if (this.checked()) {\n console.log(\"Checking!\");\n } else {\n console.log(\"Unchecking!\");\n }\n}\n
Creates a dropdown menu <select></select> element in the DOM.
[true if dropdown should support multiple selections]
Creates a radio button <input></input> element in the DOM.\nThe .option() method can be used to set options for the radio after it is\ncreated. The .value() method will return the currently selected option.
the id and name of the created div and input field respectively
\nvar radio;\n\nfunction setup() {\n radio = createRadio();\n radio.option(\"black\");\n radio.option(\"white\");\n radio.option(\"gray\");\n radio.style('width', '60px');\n textAlign(CENTER);\n fill(255, 0, 0);\n}\n\nfunction draw() {\n var val = radio.value();\n background(val);\n text(val, width/2, height/2);\n}\n
\nvar radio;\n\nfunction setup() {\n radio = createRadio();\n radio.option('apple', 1);\n radio.option('bread', 2);\n radio.option('juice', 3);\n radio.style('width', '60px');\n textAlign(CENTER);\n}\n\nfunction draw() {\n background(200);\n var val = radio.value();\n if (val) {\n text('item cost is $'+val, width/2, height/2);\n }\n}\n
Creates an <input></input> element in the DOM for text input.\nUse .size() to set the display length of the box.\nAppends to the container node if one is specified, otherwise\nappends to body.
default value of the input box
\nfunction setup(){\n var inp = createInput('');\n inp.input(myInputEvent);\n}\n\nfunction myInputEvent(){\n console.log('you are typing: ', this.value());\n}\n\n
Creates an <input></input> element in the DOM of type 'file'.\nThis allows users to select local files for use in a sketch.
callback function for when a file loaded
optional to allow multiple files selected
Creates an HTML5 <video> element in the DOM for simple playback\nof audio/video. Shown by default, can be hidden with .hide()\nand drawn into canvas using video(). Appends to the container\nnode if one is specified, otherwise appends to body. The first parameter\ncan be either a single string path to a video file, or an array of string\npaths to different formats of the same video. This is useful for ensuring\nthat your video can play across different browsers, as each supports\ndifferent formats. See this\npage for further information about supported formats.
path to a video file, or array of paths for\n supporting different browsers
callback function to be called upon\n 'canplaythrough' event fire, that is, when the\n browser can play the media, and estimates that\n enough data has been loaded to play the media\n up to its end without having to stop for\n further buffering of content
Creates a hidden HTML5 <audio> element in the DOM for simple audio\nplayback. Appends to the container node if one is specified,\notherwise appends to body. The first parameter\ncan be either a single string path to a audio file, or an array of string\npaths to different formats of the same audio. This is useful for ensuring\nthat your audio can play across different browsers, as each supports\ndifferent formats. See this\npage for further information about supported formats.
path to an audio file, or array of paths for\n supporting different browsers
Creates a new <video> element that contains the audio/video feed\nfrom a webcam. This can be drawn onto the canvas using video().
More specific properties of the feed can be passing in a Constraints object.\nSee the\n W3C\nspec for possible properties. Note that not all of these are supported\nby all browsers.
Security note: A new browser security specification requires that getUserMedia,\nwhich is behind createCapture(), only works when you're running the code locally,\nor on HTTPS. Learn more here\nand here.
type of capture, either VIDEO or\n AUDIO if none specified, default both,\n or a Constraints object
function to be called once\n stream has loaded
\nvar capture;\n\nfunction setup() {\n createCanvas(480, 120);\n capture = createCapture(VIDEO);\n}\n\nfunction draw() {\n image(capture, 0, 0, width, width*capture.height/capture.width);\n filter(INVERT);\n}\n
\nfunction setup() {\n createCanvas(480, 120);\n var constraints = {\n video: {\n mandatory: {\n minWidth: 1280,\n minHeight: 720\n },\n optional: [\n { maxFrameRate: 10 }\n ]\n },\n audio: true\n };\n createCapture(constraints, function(stream) {\n console.log(stream);\n });\n}\n
Creates element with given tag in the DOM with given content.\nAppends to the container node if one is specified, otherwise\nappends to body.
tag for the new element
html content to be inserted into the element
\nvar h2 = createElement('h2','im an h2 p5.element!');\n
Adds specified class to the element.
name of class to add
\n var div = createDiv('div');\n div.addClass('myClass');\n
Removes specified class from the element.
name of class to remove
Attaches the element as a child to the parent specified.\n Accepts either a string ID, DOM node, or p5.Element.\n If no argument is specified, an array of children DOM nodes is returned.
the ID, DOM node, or p5.Element\n to add to the current element
\n var div0 = createDiv('this is the parent');\n var div1 = createDiv('this is the child');\n div0.child(div1); // use p5.Element\n
\n var div0 = createDiv('this is the parent');\n var div1 = createDiv('this is the child');\n div1.id('apples');\n div0.child('apples'); // use id\n
\n var div0 = createDiv('this is the parent');\n var elt = document.getElementById('myChildDiv');\n div0.child(elt); // use element from page\n
Centers a p5 Element either vertically, horizontally,\nor both, relative to its parent or according to\nthe body if the Element has no parent. If no argument is passed\nthe Element is aligned both vertically and horizontally.
passing 'vertical', 'horizontal' aligns element accordingly
\nfunction setup() {\n var div = createDiv('').size(10,10);\n div.style('background-color','orange');\n div.center();\n\n}\n
If an argument is given, sets the inner HTML of the element,\n replacing any existing html. If no arguments are given, returns\n the inner HTML of the element.
the HTML to be placed inside the element
\n var div = createDiv('').size(100,100);\n div.style('background-color','orange');\n div.html('hi');\n
Sets the position of the element relative to (0, 0) of the\n window. Essentially, sets position:absolute and left and top\n properties of style. If no arguments given returns the x and y position\n of the element in an object.
x-position relative to upper left of window
y-position relative to upper left of window
\n function setup() {\n var cnv = createCanvas(100, 100);\n // positions canvas 50px to the right and 100px\n // below upper left corner of the window\n cnv.position(50, 100);\n }\n
Sets the given style (css) property (1st arg) of the element with the\ngiven value (2nd arg). If a single argument is given, .style()\nreturns the value of the given property; however, if the single argument\nis given in css syntax ('text-align:center'), .style() sets the css\nappropriatly. .style() also handles 2d and 3d css transforms. If\nthe 1st arg is 'rotate', 'translate', or 'position', the following arguments\naccept Numbers as values. ('translate', 10, 100, 50);
property to be set
value to assign to property
value to assign to property (rotate/translate)
value to assign to property (translate)
\nvar myDiv = createDiv(\"I like pandas.\");\nmyDiv.style(\"font-size\", \"18px\");\nmyDiv.style(\"color\", \"#ff0000\");\n
\nvar col = color(25,23,200,50);\nvar button = createButton(\"button\");\nbutton.style(\"background-color\", col);\nbutton.position(10, 10);\n
\nvar myDiv = createDiv(\"I like lizards.\");\nmyDiv.style(\"position\", 20, 20);\nmyDiv.style(\"rotate\", 45);\n
\nvar myDiv;\nfunction setup() {\n background(200);\n myDiv = createDiv(\"I like gray.\");\n myDiv.position(20, 20);\n}\n\nfunction draw() {\n myDiv.style(\"font-size\", mouseX+\"px\");\n}\n
Adds a new attribute or changes the value of an existing attribute\n on the specified element. If no value is specified, returns the\n value of the given attribute, or null if attribute is not set.
attribute to set
value to assign to attribute
\n var myDiv = createDiv(\"I like pandas.\");\n myDiv.attribute(\"align\", \"center\");\n
Removes an attribute on the specified element.
attribute to remove
\n var button;\n var checkbox;\nfunction setup() {\n checkbox = createCheckbox('enable', true);\n checkbox.changed(enableButton);\n button = createButton('button');\n button.position(10, 10);\n }\nfunction enableButton() {\n if( this.checked() ) {\n // Re-enable the button\n button.removeAttribute('disabled');\n } else {\n // Disable the button\n button.attribute('disabled','');\n }\n }\n
Either returns the value of the element if no arguments\ngiven, or sets the value of the element.
\n// gets the value\nvar inp;\nfunction setup() {\n inp = createInput('');\n}\n\nfunction mousePressed() {\n print(inp.value());\n}\n
\n// sets the value\nvar inp;\nfunction setup() {\n inp = createInput('myValue');\n}\n\nfunction mousePressed() {\n inp.value(\"myValue\");\n}\n
Shows the current element. Essentially, setting display:block for the style.
\n var div = createDiv('div');\n div.style(\"display\", \"none\");\n div.show(); // turns display to block\n
Hides the current element. Essentially, setting display:none for the style.
\nvar div = createDiv('this is a div');\ndiv.hide();\n
Sets the width and height of the element. AUTO can be used to\n only adjust one dimension. If no arguments given returns the width and height\n of the element in an object.
width of the element
height of the element
\n var div = createDiv('this is a div');\n div.size(100, 100);\n
Removes the element and deregisters all listeners.
\nvar myDiv = createDiv('this is some text');\nmyDiv.remove();\n
Path to the media element source.
Play an HTML5 media element.
Stops an HTML5 media element (sets current time to zero).
Pauses an HTML5 media element.
Set 'loop' to true for an HTML5 media element, and starts playing.
Set 'loop' to false for an HTML5 media element. Element will stop\nwhen it reaches the end.
Set HTML5 media element to autoplay or not.
whether the element should autoplay
Sets volume for this HTML5 media element. If no argument is given,\nreturns the current volume.
volume between 0.0 and 1.0
If no arguments are given, returns the current playback speed of the\nelement. The speed parameter sets the speed where 2.0 will play the\nelement twice as fast, 0.5 will play at half the speed, and -1 will play\nthe element in normal speed in reverse.(Note that not all browsers support\nbackward playback and even if they do, playback might not be smooth.)
speed multiplier for element playback
If no arguments are given, returns the current time of the element.\nIf an argument is given the current time of the element is set to it.
time to jump to (in seconds)
Returns the duration of the HTML5 media element.
Schedule an event to be called when the audio or video\nelement reaches the end. If the element is looping,\nthis will not be called. The element is passed in\nas the argument to the onended callback.
function to call when the\n soundfile has ended. The\n media element will be passed\n in as the argument to the\n callback.
\nfunction setup() {\n audioEl = createAudio('assets/beat.mp3');\n audioEl.showControls(true);\n audioEl.onended(sayDone);\n}\n\nfunction sayDone(elt) {\n alert('done playing ' + elt.src );\n}\n
Send the audio output of this element to a specified audioNode or\np5.sound object. If no element is provided, connects to p5's master\noutput. That connection is established when this method is first called.\nAll connections are removed by the .disconnect() method.
This method is meant to be used with the p5.sound.js addon library.
AudioNode from the Web Audio API,\nor an object from the p5.sound library
Disconnect all Web Audio routing, including to master output.\nThis is useful if you want to re-route the output through\naudio effects, for example.
Show the default MediaElement controls, as determined by the web browser.
Hide the default mediaElement controls.
Schedule events to trigger every time a MediaElement\n(audio/video) reaches a playback cue point.
Accepts a callback function, a time (in seconds) at which to trigger\nthe callback, and an optional parameter for the callback.
Time will be passed as the first parameter to the callback function,\nand param will be the second parameter.
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.
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.
An object to be passed as the\n second parameter to the\n callback function.
\nfunction setup() {\n background(255,255,255);\n\n audioEl = createAudio('assets/beat.mp3');\n audioEl.showControls();\n\n // schedule three calls to changeBackground\n audioEl.addCue(0.5, changeBackground, color(255,0,0) );\n audioEl.addCue(1.0, changeBackground, color(0,255,0) );\n audioEl.addCue(2.5, changeBackground, color(0,0,255) );\n audioEl.addCue(3.0, changeBackground, color(0,255,255) );\n audioEl.addCue(4.2, changeBackground, color(255,255,0) );\n audioEl.addCue(5.0, changeBackground, color(255,255,0) );\n}\n\nfunction changeBackground(val) {\n background(val);\n}\n
Remove a callback based on its ID. The ID is returned by the\naddCue method.
ID of the cue, as returned by addCue
Remove all of the callbacks that had originally been scheduled\nvia the addCue method.
Underlying File object. All normal File methods can be called on this.
File type (image, text, etc.)
File subtype (usually the file extension jpg, png, xml, etc.)
File name
File size
URL string containing image data.
p5.sound developed by Jason Sigal for the Processing Foundation, Google Summer of Code 2014. The MIT License (MIT).
http://github.com/therewasaguy/p5.sound
Some of the many audio libraries & resources that inspire p5.sound:
Wilm Thoben's Sound library for Processing https://github.com/processing/processing/tree/master/java/libraries/sound
Web Audio API: http://w3.org/TR/webaudio/
Returns the Audio Context for this sketch. Useful for users\nwho would like to dig deeper into the Web Audio API\n.
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
Master contains AudioContext and the master sound output.
Returns a number representing the master amplitude (volume) for sound \nin this sketch.
Scale the output of all sound in this sketch
rampTime
How 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.
If no value is provided, returns a Web Audio API Gain Node
Volume (amplitude) between 0.0\n and 1.0 or modulating signal/oscillator
Fade for t seconds
Schedule this event to happen at\n t seconds in the future
p5.soundOut is the p5.sound master output. 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.
.limiter
.input
.output
a silent connection to the DesinationNode\nwhich will ensure that anything connected to it\nwill not be garbage collected
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.
Returns the closest MIDI note value for\na given frequency.
A freqeuncy, for example, the "A"\n above Middle C is 440Hz
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.
The number of a MIDI note
\nvar notes = [60, 64, 67, 72];\nvar i = 0;\n\nfunction setup() {\n osc = new p5.Oscillator('Triangle');\n osc.start();\n frameRate(1);\n}\n\nfunction draw() {\n var freq = midiToFreq(notes[i]);\n osc.freq(freq);\n i++;\n if (i >= notes.length){\n i = 0;\n }\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.
i.e. 'mp3', 'wav', 'ogg'
\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('../sounds/beatbox.mp3');\n}\n\nfunction setup() {\n mySound.play();\n}\n
Used by Osc and Env to chain signal math
Helper function to generate an error\nwith a custom stack trace that points to the sketch\nand removes other parts of the stack trace.
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.
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.
Name of a function to call if there is\n an error loading the file.
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.
\nfunction preload() {\n mySound = loadSound('assets/doorbell.mp3');\n}\n\nfunction setup() {\n mySound.setVolume(0.1);\n mySound.play();\n}\n
This is a helper function that the p5.SoundFile calls to load\nitself. Accepts a callback (the name of another function)\nas an optional parameter.
Name of a function to call if there is an error
Returns true if the sound file finished loading successfully.
Play the p5.SoundFile
(optional) schedule playback to start (in seconds from now).
(optional) playback rate
(optional) amplitude (volume)\n of playback
(optional) cue start time in seconds
(optional) duration of playback in seconds
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. Sustain is the default mode.
restart
sustain
'restart' or 'sustain'
\nfunction setup(){\n mySound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\nfunction mouseClicked() {\n mySound.playMode('sustain');\n mySound.play();\n}\nfunction keyPressed() {\n mySound.playMode('restart');\n mySound.play();\n}\n \n
Pauses a file that is currently playing. If the file is not\nplaying, then nothing will happen.
After 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().
(optional) schedule event to occur\n seconds from now
\nvar soundFile;\n\nfunction preload() {\n soundFormats('ogg', 'mp3');\n soundFile = loadSound('assets/Damscray_-_Dancing_Tiger_02.mp3');\n}\nfunction setup() {\n background(0, 255, 0);\n soundFile.setVolume(0.1);\n soundFile.loop();\n}\nfunction keyTyped() {\n if (key == 'p') {\n soundFile.pause();\n background(255, 0, 0);\n }\n}\n\nfunction keyReleased() {\n if (key == 'p') {\n soundFile.play();\n background(0, 255, 0);\n }\n
Loop the p5.SoundFile. Accepts optional parameters to set the\nplayback rate, playback volume, loopStart, loopEnd.
(optional) playback volume
startTime in seconds
(optional) loop duration in seconds
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.
set looping to true or false
Returns 'true' if a p5.SoundFile is currently looping and playing, 'false' if not.
Returns true if a p5.SoundFile is playing, false if not (i.e.\npaused or stopped).
Returns true if a p5.SoundFile is paused, false if not (i.e.\nplaying or stopped).
Stop soundfile playback.
(optional) schedule event to occur\n in seconds from now
Stop playback on all of this soundfile's sources.
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 Env class.
Alternately, you can pass in a signal source such as an\noscillator to modulate the amplitude with an audio signal.
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).
Set the stereo panner
schedule this event to happen\n seconds from now
\n\n var ball = {};\n var soundFile;\n\n function setup() {\n soundFormats('ogg', 'mp3');\n soundFile = loadSound('assets/beatbox.mp3');\n }\n \n function draw() {\n background(0);\n ball.x = constrain(mouseX, 0, width);\n ellipse(ball.x, height/2, 20, 20)\n }\n \n function mousePressed(){\n // map the ball's x location to a panning degree \n // between -1.0 (left) and 1.0 (right)\n var panning = map(ball.x, 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)
Set the playback rate of a sound file. Will change the speed and the pitch.\nValues less than zero will reverse the audio buffer.
Set the playback rate. 1.0 is normal,\n .5 is half-speed, 2.0 is twice as fast.\n Must be greater than zero.
\nvar song;\n\nfunction preload() {\n song = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n song.loop();\n}\n\nfunction draw() {\n background(200);\n \n // Set the rate to a range between 0.1 and 4\n // Changing the rate also alters the pitch\n var speed = map(mouseY, 0.1, height, 0, 2);\n speed = constrain(speed, 0.01, 4);\n song.rate(speed);\n \n // Draw a circle to show what is going on\n stroke(0);\n fill(51, 100);\n ellipse(mouseX, 100, 48, 48);\n}\n\n
Returns the duration of a sound file in seconds.
Return the current position of the p5.SoundFile playhead, in seconds.\nNote that if you change the playbackRate while the p5.SoundFile is\nplaying, the results may not be accurate.
Move the playhead of the song to a position, in seconds. Start\nand Stop time. If none are given, will reset the file to play\nentire duration from start to finish.
cueTime of the soundFile in seconds.
duration in seconds.
Return the number of channels in a sound file.\nFor example, Mono = 1, Stereo = 2.
Return the sample rate of the sound file.
Return the number of samples in a sound file.\nEqual to sampleRate * duration.
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.
Inspired by Wavesurfer.js.
length is the size of the returned array.\n Larger length results in more precision.\n Defaults to 5*width of the browser window.
Reverses the p5.SoundFile's buffer source.\nPlayback must be handled separately (see example).
\nvar drum;\n\nfunction preload() {\n drum = loadSound('assets/drum.mp3');\n}\n\nfunction setup() {\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.
function to call when the\n soundfile has ended.
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 master output. Most p5sound objects connect to the master\noutput when they are created.
Audio object that accepts an input
Disconnects the output of this p5sound object.
Reset the source for this SoundFile to a\nnew path (URL).
path to audio file
Callback
Replace the current Audio Buffer with a new Buffer.
Array of Float32 Array(s). 2 Float32 Arrays\n will create a stereo source. 1 will create\n a mono source.
processPeaks returns an array of timestamps where it thinks there is a beat.
This is an asynchronous function that processes the soundfile in an offline audio context,\nand sends the results to your callback function.
The process involves running the soundfile through a lowpass filter, and finding all of the\npeaks above the initial threshold. If the total number of peaks are below the minimum number of peaks,\nit decreases the threshold and re-runs the analysis until either minPeaks or minThreshold are reached.
a function to call once this data is returned
initial threshold defaults to 0.9
minimum threshold defaults to 0.22
minimum number of peaks defaults to 200
\nfunction setup() {\n background(0);\n noStroke();\n fill(255);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n \n mySound = loadSound('assets/beat.mp3');\n\n // schedule calls to changeText\n mySound.addCue(0.50, changeText, \"hello\" );\n mySound.addCue(1.00, changeText, \"p5\" );\n mySound.addCue(1.50, changeText, \"what\" );\n mySound.addCue(2.00, changeText, \"do\" );\n mySound.addCue(2.50, changeText, \"you\" );\n mySound.addCue(3.00, changeText, \"want\" );\n mySound.addCue(4.00, changeText, \"to\" );\n mySound.addCue(5.00, changeText, \"make\" );\n mySound.addCue(6.00, changeText, \"?\" );\n}\n\nfunction changeText(val) {\n background(0);\n text(val, width/2, height/2);\n}\n\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n if (mySound.isPlaying() ) {\n mySound.stop();\n } else {\n mySound.play();\n }\n }\n}\n
Connects to the p5sound instance (master output) by default.\nOptionally, you can pass in a specific source (i.e. a soundfile).
set the sound source\n (optional, defaults to\n master output)
a range between 0.0 and 1.0\n to smooth amplitude readings
\nfunction preload(){\n sound1 = loadSound('assets/beat.mp3');\n sound2 = loadSound('assets/drum.mp3');\n}\nfunction setup(){\n amplitude = new p5.Amplitude();\n sound1.play();\n sound2.play();\n amplitude.setInput(sound2);\n}\nfunction draw() {\n background(0);\n fill(255);\n var level = amplitude.getLevel();\n var size = map(level, 0, 1, 0, 200);\n ellipse(width/2, height/2, size, size);\n}\nfunction mouseClicked(){\n sound1.stop();\n sound2.stop();\n}\n
Returns a single Amplitude reading at the moment it is called.\nFor continuous readings, run in the draw loop.
Optionally return only channel 0 (left) or 1 (right)
\nfunction preload(){\n sound = loadSound('assets/beat.mp3');\n}\nfunction setup() { \n amplitude = new p5.Amplitude();\n sound.play();\n}\nfunction draw() {\n background(0);\n fill(255);\n var level = amplitude.getLevel();\n var size = map(level, 0, 1, 0, 200);\n ellipse(width/2, height/2, size, size);\n}\nfunction mouseClicked(){\n sound.stop();\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.
set normalize to true (1) or false (0)
Smooth Amplitude analysis by averaging with the last analysis \nframe. Off by default.
smoothing from 0.0 <= 1
Set the input source for the FFT analysis. If no source is\nprovided, FFT will analyze all sound in the sketch.
p5.sound object (or web audio API source node)
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.
Must be a power of two between\n 16 and 1024. Defaults to 1024.
If any value is provided, will return results\n in a Float32 Array which is more precise\n than a regular array.
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().
If "dB," returns decibel\n float measurements between\n -140 and 0 (max).\n Otherwise returns integers from 0-255.
\nvar osc;\nvar fft;\n\nfunction setup(){\n createCanvas(100,100);\n osc = new p5.Oscillator();\n osc.amp(0);\n osc.start();\n fft = new p5.FFT();\n}\n\nfunction draw(){\n background(0);\n\n var freq = map(mouseX, 0, 800, 20, 15000);\n freq = constrain(freq, 1, 20000);\n osc.freq(freq);\n\n var spectrum = fft.analyze(); \n noStroke();\n fill(0,255,0); // spectrum is green\n for (var i = 0; i< spectrum.length; i++){\n var x = map(i, 0, spectrum.length, 0, width);\n var h = -height + map(spectrum[i], 0, 255, height, 0);\n rect(x, height, width / spectrum.length, h );\n }\n\n stroke(255);\n text('Freq: ' + round(freq)+'Hz', 10, 10); \n\n isMouseOverCanvas();\n}\n\n// only play sound when mouse is over canvas\nfunction isMouseOverCanvas() {\n var mX = mouseX, mY = mouseY;\n if (mX > 0 && mX < width && mY < height && mY > 0) {\n osc.amp(0.5, 0.2);\n } else {\n osc.amp(0, 0.2);\n }\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 determine the value at a specific frequency or\nrange of frequencies.
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.
If a second frequency is given,\n will return average amount of\n energy that exists between the\n two frequencies.
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\n\nfunction setup(){\ncnv = createCanvas(800,400);\nsound = new p5.AudioIn();\nsound.start();\nfft = new p5.FFT();\nsound.connect(fft);\n}\n\n\nfunction draw(){\n\nvar centroidplot = 0.0;\nvar spectralCentroid = 0;\n\n\nbackground(0);\nstroke(0,255,0);\nvar spectrum = fft.analyze(); \nfill(0,255,0); // spectrum is green\n\n//draw the spectrum\n\nfor (var i = 0; i< spectrum.length; i++){\n var x = map(log(i), 0, log(spectrum.length), 0, width);\n var h = map(spectrum[i], 0, 255, 0, height);\n var rectangle_width = (log(i+1)-log(i))*(width/log(spectrum.length));\n rect(x, height, rectangle_width, -h )\n}\n\nvar nyquist = 22050;\n\n// get the centroid\nspectralCentroid = fft.getCentroid();\n\n// the mean_freq_index calculation is for the display.\nvar mean_freq_index = spectralCentroid/(nyquist/spectrum.length);\n\ncentroidplot = map(log(mean_freq_index), 0, log(spectrum.length), 0, width);\n\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\ntextSize(40);\ntext(\"centroid: \"+round(spectralCentroid)+\" Hz\", 10, 40);\n}\n
Smooth FFT analysis by averaging with the last analysis frame.
0.0 < smoothing < 1.0.\n Defaults to 0.8.
Fade to value, for smooth transitions
Value to set this signal
Length of fade, in seconds from now
Connect a p5.sound object or Web Audio node to this\np5.Signal so that its amplitude values can be scaled.
Add a constant value to this audio signal,\nand return the resulting audio signal. Does\nnot change the value of the original signal,\ninstead it returns a new p5.SignalAdd.
Multiply this signal by a constant value,\nand return the resulting audio signal. Does\nnot change the value of the original signal,\ninstead it returns a new p5.SignalMult.
to multiply
Scale this signal value to a given range,\nand return the result as an audio signal. Does\nnot change the value of the original signal,\ninstead it returns a new p5.SignalScale.
input range minumum
input range maximum
Start an oscillator. Accepts an optional parameter to\ndetermine how long (in seconds from now) until the\noscillator starts.
startTime in seconds from now.
frequency in Hz.
Stop an oscillator. Accepts an optional parameter\nto determine how long (in seconds from now) until the\noscillator stops.
Time, in seconds from now.
Set the amplitude between 0 and 1.0. Or, pass in an object\nsuch as an oscillator to modulate amplitude with an audio signal.
between 0 and 1.0\n or a modulating signal/oscillator
create a fade that lasts rampTime
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.
Frequency in Hz\n or modulating signal/oscillator
Ramp time (in seconds)
Schedule this event to happen\n at x seconds from now
\nvar osc = new p5.Oscillator(300);\nosc.start();\nosc.freq(40, 10);\n
Set type to 'sine', 'triangle', 'sawtooth' or 'square'.
'sine', 'triangle', 'sawtooth' or 'square'.
Connect to a p5.sound / Web Audio object.
A p5.sound or Web Audio object
Disconnect all outputs
Pan between Left (-1) and Right (1)
Number between -1 and 1
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.
float between 0.0 and 1.0
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.
Constant number to add
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.
Constant number to multiply
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.
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.
new p5.SinOsc()
new p5.Oscillator('sine')\n
setType('sine')
Set the frequency
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.
new p5.TriOsc()
new p5.Oscillator('triangle')\n
setType('triangle')
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.
new p5.SawOsc()
new p5.Oscillator('sawtooth')\n
setType('sawtooth')
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.
new p5.SqrOsc()
new p5.Oscillator('square')\n
setType('square')
Time until envelope reaches attackLevel
Level once attack is complete.
Time until envelope reaches decayLevel.
Level after decay. The envelope will sustain here until it is released.
Duration of the release portion of the envelope.
Level at the end of the release.
Reset the envelope with a series of time/value pairs.
Time (in seconds) before level\n reaches attackLevel
Typically an amplitude between\n 0.0 and 1.0
Time
Amplitude (In a standard ADSR envelope,\n decayLevel = sustainLevel)
Release Time (in seconds)
Amplitude
Set values like a traditional\n\nADSR envelope\n.
Time (in seconds before envelope\n reaches Attack Level
Time (in seconds) before envelope\n reaches Decay/Sustain Level
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)
Set max (attackLevel) and min (releaseLevel) of envelope.
attack level (defaults to 1)
release level (defaults to 0)
Assign a parameter to be controlled by this envelope.\nIf a p5.Sound object is given, then the p5.Env will control its\noutput gain. If multiple inputs are provided, the env will\ncontrol all of them.
A p5.sound object or\n Web Audio Param.
Set whether the envelope ramp is linear (default) or exponential.\nExponential ramps can be useful because we perceive amplitude\nand frequency logarithmically.
true is exponential, false is linear
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 Env will control its output volume.\nEnvelopes can also be used to control any \nWeb Audio Audio Param.
time from now (in seconds) at which to play
time to sustain before releasing the envelope
\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.2;\nvar susPercent = 0.2;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Env();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv(){\n // trigger env on triOsc, 0 seconds from now\n // After decay, sustain for 0.2 seconds before release\n env.play(triOsc, 0, 0.2);\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.
p5.sound Object or Web Audio Param
time from now (in seconds)
\n\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.3;\nvar susPercent = 0.4;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Env();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(envAttack);\n}\n\nfunction envAttack(){\n console.log('trigger attack');\n env.triggerAttack();\n\n background(0,255,0);\n text('attack!', width/2, height/2);\n}\n\nfunction mouseReleased() {\n env.triggerRelease();\n\n background(200);\n text('click to play', width/2, height/2);\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.
time to trigger the release
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.
setADSR(attackTime, decayTime)
When to trigger the ramp
Target value
Second target value (optional)
\nvar env, osc, amp, cnv;\n\nvar attackTime = 0.001;\nvar decayTime = 0.2;\nvar attackLevel = 1;\nvar decayLevel = 0;\n\nfunction setup() {\n cnv = createCanvas(100, 100);\n fill(0,255,0);\n noStroke();\n\n env = new p5.Env();\n env.setADSR(attackTime, decayTime);\n\n osc = new p5.Oscillator();\n osc.amp(env);\n osc.start();\n\n amp = new p5.Amplitude();\n\n cnv.mousePressed(triggerRamp);\n}\n\nfunction triggerRamp() {\n env.ramp(osc, 0, attackLevel, decayLevel);\n}\n\nfunction draw() {\n background(20,20,20);\n text('click me', 10, 20);\n var h = map(amp.getLevel(), 0, 0.4, 0, height);;\n\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.
Multiply the p5.Env's output amplitude\nby a fixed value. Calling this method\nagain will override the initial mult() with new values.
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.
Set the width of a Pulse object (an oscillator that implements\nPulse Width Modulation).
Set type of noise to 'white', 'pink' or 'brown'.\nWhite is the default.
'white', 'pink' or 'brown'
Start the noise
Stop the noise.
Pan the noise.
Number between -1 (left)\n and 1 (right)
Set the amplitude of the noise between 0 and 1.0. Or,\nmodulate amplitude with an audio signal such as an oscillator.
amplitude between 0 and 1.0\n or modulating signal/oscillator
Send output to a p5.sound or web audio object
Disconnect all output.
Client must allow browser to access their microphone / audioin source.\nDefault: false. Will become true when the client enables acces.
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.
Name of a function to call on\n success.
Name of a function to call if\n there was an error. For example,\n some browsers do not support\n getUserMedia.
Turn the AudioIn off. If the AudioIn is stopped, it cannot getLevel().
Connect to an audio unit. If no parameter is provided, will\nconnect to the master output (i.e. your speakers).
An object that accepts audio input,\n such as an FFT
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.
Add input sources to the list of available sources.
Set amplitude (volume) of a mic input between 0 and 1.0.
between 0 and 1.0
ramp time (optional)
Chrome only. Returns a list of available input sources \nand allows the user to set the media source. Firefox allows \nthe user to choose from input sources in the permissions dialogue\ninstead of enumerating available sources and selecting one.\nNote: in order to have descriptive media names your page must be \nserved over a secure (HTTPS) connection and the page should \nrequest user media before enumerating devices. Otherwise device \nID will be a long device ID number and does not specify device \ntype. For example see \nhttps://simpl.info/getusermedia/sources/index.html vs.\nhttp://simpl.info/getusermedia/sources/index.html
a callback to handle the sources \n when they have been enumerated
\n var audiograb;\n \n function setup(){\n //new audioIn\n audioGrab = new p5.AudioIn();\n \n audioGrab.getSources(function(sourceList) {\n //print out the array of available sources\n console.log(sourceList);\n //set the source to the first item in the inputSources array\n audioGrab.setSource(0);\n });\n }\n
Set the input source. Accepts a number representing a\nposition in the array returned by listSources().\nThis is only available in browsers that support \nMediaStreamTrack.getSources(). Instead, some browsers\ngive users the option to set their own media source.
position of input source in the array
The p5.Filter is built with a\n\nWeb Audio BiquadFilter Node.
Filter an audio signal according to a set\nof filter parameters.
An object that outputs audio
Frequency in Hz, from 10 to 22050
Resonance/Width of the filter frequency\n from 0.001 to 1000
Set the frequency and the resonance of the filter.
Resonance (Q) from 0.001 to 1000
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).
Filter Frequency
Controls either width of a bandpass frequency,\nor the resonance of a low/highpass cutoff frequency.
Resonance/Width of filter freq\n from 0.001 to 1000
Set the type of a p5.Filter. Possible types include: \n"lowpass" (default), "highpass", "bandpass", \n"lowshelf", "highshelf", "peaking", "notch",\n"allpass".
Set the output level of the filter.
amplitude between 0 and 1.0
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.
new p5.LowPass()
setType('lowpass')
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.
new p5.HighPass()
setType('highpass')
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.
new p5.BandPass()
setType('bandpass')
The p5.Delay is built with two\n\nWeb Audio Delay Nodes, one for each stereo channel.
Add delay to an audio signal according to a set\nof delay parameters.
Time (in seconds) of the delay/echo.\n Some browsers limit delayTime to\n 1 second.
sends the delay back through itself\n in a loop that decreases in volume\n each time.
Cutoff frequency. Only frequencies\n below the lowPass will be part of the\n delay.
Set the delay (echo) time, in seconds. Usually this value will be\na floating point number between 0.0 and 1.0.
Time (in seconds) of the delay
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.
0.0 to 1.0, or an object such as an\n Oscillator that can be used to\n modulate this param
Set a lowpass filter frequency for the delay. A lowpass filter\nwill cut off any frequencies higher than the filter frequency.
A lowpass filter will cut off any \n frequencies higher than the filter frequency.
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.
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.
'pingPong' (1) or 'default' (0)
Set the output level of the delay effect.
Connect a source to the reverb, and assign reverb parameters.
p5.sound / Web Audio object with a sound\n output.
Duration of the reverb, in seconds.\n Min: 0, Max: 10. Defaults to 3.
Percentage of decay with each echo.\n Min: 0, Max: 100. Defaults to 2.
Play the reverb backwards or forwards.
Set the reverb settings. Similar to .process(), but without\nassigning a new input.
Inspired by Simple Reverb by Jordan Santell\nhttps://github.com/web-audio-components/simple-reverb/blob/master/index.js
Utility function for building an impulse response\nbased on the module parameters.
Internally, the p5.Convolver uses the a\n\nWeb Audio Convolver Node.
Create a p5.Convolver. Accepts a path to a soundfile \nthat will be used to generate an impulse response.
function to call if loading is successful.\n The object will be passed in as the argument\n to the callback function.
function to call if loading is not successful.\n A custom error will be passed in as the argument\n to the callback function.
Private method to load a buffer as an Impulse Response,\nassign it to the convolverNode, and add to the Array of .impulses.
\nvar cVerb, sound;\nfunction preload() {\n soundFormats('ogg', 'mp3');\n \n cVerb = createConvolver('assets/concrete-tunnel.mp3');\n\n sound = loadSound('assets/beat.mp3');\n}\n\nfunction setup() {\n // disconnect from master output...\n sound.disconnect();\n \n // ...and process with (i.e. connect to) cVerb\n // so that we only hear the convolution\n cVerb.process(sound);\n \n sound.play();\n}\n
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.
toggleImpulse(id)
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.
.impulses
.toggleImpulse(id)
function (optional)
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.
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.
.addImpulse()
.impulses\n
.audioBuffer
.name
Identify the impulse by its original filename\n (String), or by its position in the\n .impulses Array (Number).
Set the global tempo, in beats per minute, for all\np5.Parts. This method will impact all active p5.Parts.
Beats Per Minute
Seconds from now
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.
Set the tempo of this part, in Beats Per Minute.
Returns the Beats Per Minute of this currently part.
Start playback of this part. It will play\nthrough all of its phrases at a speed\ndetermined by setBPM.
seconds from now
Loop playback of this part. It will begin\nlooping through all of its phrases at a speed\ndetermined by setBPM.
Tell the part to stop looping.
Stop the part and cue it to step 0.
Pause the part. Playback will resume\nfrom the current step.
Add a p5.Phrase to this Part.
reference to a p5.Phrase
Remove a phrase from this part, based on the name it was\ngiven when it was created.
Get a phrase from this part, based on the name it was\ngiven when it was created. Now you can modify its array.
Fire a callback function at every step.
The name of the callback\n you want to fire\n on every beat/tatum.
Start playback of the score.
Stop playback of the score.
Pause playback of the score.
Loop playback of the score.
Stop looping playback of the score. If it\nis currently playing, this will go into effect\nafter the current round of playback completes.
Set the tempo for all parts in the score
callback invoked when the recording is over
Connect a specific device to the p5.SoundRecorder.\nIf no parameter is given, p5.SoundRecorer will record\nall audible p5.sound from your sketch.
p5.sound object or a web audio unit\n that outputs sound
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.
p5.SoundFile
Time (in seconds)
The name of a function that will be\n called once the recording completes
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.
internal method called on audio process
Save a p5.SoundFile as a .wav audio file.
p5.SoundFile that you wish to save
name of the resulting .wav file.
isDetected is set to true when a peak is detected.
The update method is run in the draw loop.
Accepts an FFT object. You must call .analyze()\non the FFT object prior to updating the peakDetect\nbecause it relies on a completed FFT analysis.
A p5.FFT object
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.
Name of a function that will\n be called when a peak is\n detected.
Optional value to pass\n into the function when\n a peak is detected.
\nvar cnv, soundFile, fft, peakDetect;\nvar ellipseWidth = 0;\n\nfunction setup() {\n cnv = createCanvas(100,100);\n textAlign(CENTER);\n\n soundFile = loadSound('assets/beat.mp3');\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 source to the gain node.
Set the output level of the gain node.
A rough \"spec\" for CSV can be found\nhere.