From e0a7646eb55eb76d2c252669f0dd52475273a88c Mon Sep 17 00:00:00 2001
From: Bernardo Fontes The web is much more than just canvas and p5.dom makes it easy to interact
+ * with other HTML5 objects, including text, hyperlink, image, input, video,
+ * audio, and webcam. There is a set of creation methods, DOM manipulation methods, and
+ * an extended p5.Element that supports a range of HTML elements. See the
+ *
+ * beyond 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
+ * blue are part of the p5.dom library. You will need to include an extra file
+ * in order to access the blue functions. See the
+ * using a library
+ * section for information on how to include this library. p5.dom comes with
+ * p5 complete or you can download the single file
+ *
+ * here. See tutorial: beyond the canvas
+ * for more info on how to use this library. Creates a new HTML5 <video> element that contains the audio/video
+ * feed from a webcam. The element is separate from the canvas and is
+ * displayed by default. The element can be hidden using .hide(). The feed
+ * can be drawn onto the canvas using image(). The loadedmetadata property can
+ * be used to detect when the element has fully loaded (see second example). More specific properties of the feed can be passing in a Constraints object.
+ * See the
+ * W3C
+ * spec for possible properties. Note that not all of these are supported
+ * by all browsers. Security note: A new browser security specification requires that getUserMedia,
+ * which is behind createCapture(), only works when you're running the code locally,
+ * or on HTTPS. Learn more here
+ * and here. Returns the Audio Context for this sketch. Useful for users
+ * who would like to dig deeper into the Web Audio API
+ * . Some browsers require users to startAudioContext
+ * with a user gesture, such as touchStarted in the example below. It is a good practice to give users control over starting audio playback.
+ * This practice is enforced by Google Chrome's autoplay policy as of r70
+ * (info), iOS Safari, and other browsers.
+ *
+ * userStartAudio() starts the Audio Context on a user gesture. It utilizes
+ * the StartAudioContext library by
+ * Yotam Mann (MIT Licence, 2016). Read more at https://github.com/tambien/StartAudioContext.
+ * Starting the audio context on a user gesture can be as simple as Scale the output of all sound in this sketch How This Works: When you load the p5.sound module, it
+ * creates a single instance of p5sound. All sound objects in this
+ * module output to p5sound before reaching your computer's output.
+ * So if you change the amplitude of p5sound, it impacts all of the
+ * sound in this module. If no value is provided, returns a Web Audio API Gain Node SoundFile object with a path to a file. The p5.SoundFile may not be available immediately because
+ * it loads the file information asynchronously. To do something with the sound as soon as it loads
+ * pass the name of a function as the second parameter. Only one file path is required. However, audio file formats
+ * (i.e. mp3, ogg, wav and m4a/aac) are not supported by all
+ * web browsers. If you want to ensure compatability, instead of a single
+ * file path, you may include an Array of filepaths, and the browser will
+ * choose a format that works. FFT (Fast Fourier Transform) is an analysis algorithm that
+ * isolates individual
+ *
+ * audio frequencies within a waveform. Once instantiated, a p5.FFT object can return an array based on
+ * two types of analyses: FFT analyzes a very short snapshot of sound called a sample
+ * buffer. It returns an array of amplitude measurements, referred
+ * to as
+ * function setup() {
+ * createCanvas(100, 100);
+ * //translates canvas 50px down
+ * select('canvas').position(100, 100);
+ * }
+ *
+ * // these are all valid calls to select()
+ * var a = select('#moo');
+ * var b = select('#blah', '#myContainer');
+ * var c, e;
+ * if (b) {
+ * c = select('#foo', b);
+ * }
+ * var d = document.getElementById('beep');
+ * if (d) {
+ * e = select('p', d);
+ * }
+ * [a, b, c, d, e]; // unused
+ *
+ * function setup() {
+ * createButton('btn');
+ * createButton('2nd btn');
+ * createButton('3rd btn');
+ * var buttons = selectAll('button');
+ *
+ * for (var i = 0; i < buttons.length; i++) {
+ * buttons[i].size(100, 100);
+ * }
+ * }
+ *
+ * // these are all valid calls to selectAll()
+ * var a = selectAll('.moo');
+ * a = selectAll('div');
+ * a = selectAll('button', '#myContainer');
+ *
+ * var d = select('#container');
+ * a = selectAll('p', d);
+ *
+ * var f = document.getElementById('beep');
+ * a = select('.blah', f);
+ *
+ * a; // unused
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * createDiv('this is some text');
+ * createP('this is a paragraph');
+ * }
+ * function mousePressed() {
+ * removeElements(); // this will remove the div and p, not canvas
+ * }
+ *
+ * var sel;
+ *
+ * function setup() {
+ * textAlign(CENTER);
+ * background(200);
+ * sel = createSelect();
+ * sel.position(10, 10);
+ * sel.option('pear');
+ * sel.option('kiwi');
+ * sel.option('grape');
+ * sel.changed(mySelectEvent);
+ * }
+ *
+ * function mySelectEvent() {
+ * var item = sel.value();
+ * background(200);
+ * text("it's a " + item + '!', 50, 50);
+ * }
+ *
+ * var checkbox;
+ * var cnv;
+ *
+ * function setup() {
+ * checkbox = createCheckbox(' fill');
+ * checkbox.changed(changeFill);
+ * cnv = createCanvas(100, 100);
+ * cnv.position(0, 30);
+ * noFill();
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * ellipse(50, 50, 50, 50);
+ * }
+ *
+ * function changeFill() {
+ * if (checkbox.checked()) {
+ * fill(0);
+ * } else {
+ * noFill();
+ * }
+ * }
+ *
+ * // Open your console to see the output
+ * function setup() {
+ * var inp = createInput('');
+ * inp.input(myInputEvent);
+ * }
+ *
+ * function myInputEvent() {
+ * console.log('you are typing: ', this.value());
+ * }
+ *
+ * createDiv('this is some text');
+ *
+ * createP('this is some text');
+ *
+ * createSpan('this is some text');
+ *
+ * createImg('http://p5js.org/img/asterisk-01.png');
+ *
+ * createA('http://p5js.org/', 'this is a link');
+ *
+ * var slider;
+ * function setup() {
+ * slider = createSlider(0, 255, 100);
+ * slider.position(10, 10);
+ * slider.style('width', '80px');
+ * }
+ *
+ * function draw() {
+ * var val = slider.value();
+ * background(val);
+ * }
+ *
+ * var slider;
+ * function setup() {
+ * colorMode(HSB);
+ * slider = createSlider(0, 360, 60, 40);
+ * slider.position(10, 10);
+ * slider.style('width', '80px');
+ * }
+ *
+ * function draw() {
+ * var val = slider.value();
+ * background(val, 100, 100, 1);
+ * }
+ *
+ * var button;
+ * function setup() {
+ * createCanvas(100, 100);
+ * background(0);
+ * button = createButton('click me');
+ * button.position(19, 19);
+ * button.mousePressed(changeBG);
+ * }
+ *
+ * function changeBG() {
+ * var val = random(255);
+ * background(val);
+ * }
+ *
+ * var checkbox;
+ *
+ * function setup() {
+ * checkbox = createCheckbox('label', false);
+ * checkbox.changed(myCheckedEvent);
+ * }
+ *
+ * function myCheckedEvent() {
+ * if (this.checked()) {
+ * console.log('Checking!');
+ * } else {
+ * console.log('Unchecking!');
+ * }
+ * }
+ *
+ * var sel;
+ *
+ * function setup() {
+ * textAlign(CENTER);
+ * background(200);
+ * sel = createSelect();
+ * sel.position(10, 10);
+ * sel.option('pear');
+ * sel.option('kiwi');
+ * sel.option('grape');
+ * sel.changed(mySelectEvent);
+ * }
+ *
+ * function mySelectEvent() {
+ * var item = sel.value();
+ * background(200);
+ * text('It is a ' + item + '!', 50, 50);
+ * }
+ *
+ * var radio;
+ *
+ * function setup() {
+ * radio = createRadio();
+ * radio.option('black');
+ * radio.option('white');
+ * radio.option('gray');
+ * radio.style('width', '60px');
+ * textAlign(CENTER);
+ * fill(255, 0, 0);
+ * }
+ *
+ * function draw() {
+ * var val = radio.value();
+ * background(val);
+ * text(val, width / 2, height / 2);
+ * }
+ *
+ * var radio;
+ *
+ * function setup() {
+ * radio = createRadio();
+ * radio.option('apple', 1);
+ * radio.option('bread', 2);
+ * radio.option('juice', 3);
+ * radio.style('width', '60px');
+ * textAlign(CENTER);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * var val = radio.value();
+ * if (val) {
+ * text('item cost is $' + val, width / 2, height / 2);
+ * }
+ * }
+ *
+ * var inp1, inp2;
+ * function setup() {
+ * createCanvas(100, 100);
+ * background('grey');
+ * inp1 = createColorPicker('#ff0000');
+ * inp2 = createColorPicker(color('yellow'));
+ * inp1.input(setShade1);
+ * inp2.input(setShade2);
+ * setMidShade();
+ * }
+ *
+ * function setMidShade() {
+ * // Finding a shade between the two
+ * var commonShade = lerpColor(inp1.color(), inp2.color(), 0.5);
+ * fill(commonShade);
+ * rect(20, 20, 60, 60);
+ * }
+ *
+ * function setShade1() {
+ * setMidShade();
+ * console.log('You are choosing shade 1 to be : ', this.value());
+ * }
+ * function setShade2() {
+ * setMidShade();
+ * console.log('You are choosing shade 2 to be : ', this.value());
+ * }
+ *
+ *
+ * function setup() {
+ * var inp = createInput('');
+ * inp.input(myInputEvent);
+ * }
+ *
+ * function myInputEvent() {
+ * console.log('you are typing: ', this.value());
+ * }
+ *
+ * let input;
+ * let img;
+ *
+ * function setup() {
+ * input = createFileInput(handleFile);
+ * input.position(0, 0);
+ * }
+ *
+ * function draw() {
+ * background(255);
+ * if (img) {
+ * image(img, 0, 0, width, height);
+ * }
+ * }
+ *
+ * function handleFile(file) {
+ * print(file);
+ * if (file.type === 'image') {
+ * img = createImg(file.data);
+ * img.hide();
+ * } else {
+ * img = null;
+ * }
+ * }
+ *
+ * var vid;
+ * function setup() {
+ * noCanvas();
+ *
+ * vid = createVideo(
+ * ['assets/small.mp4', 'assets/small.ogv', 'assets/small.webm'],
+ * vidLoad
+ * );
+ *
+ * vid.size(100, 100);
+ * }
+ *
+ * // This function is called when the video loads
+ * function vidLoad() {
+ * vid.loop();
+ * vid.volume(0);
+ * }
+ *
+ * var ele;
+ * function setup() {
+ * ele = createAudio('assets/beat.mp3');
+ *
+ * // here we set the element to autoplay
+ * // The element will play as soon
+ * // as it is able to do so.
+ * ele.autoplay(true);
+ * }
+ *
+ * var capture;
+ *
+ * function setup() {
+ * createCanvas(480, 480);
+ * capture = createCapture(VIDEO);
+ * capture.hide();
+ * }
+ *
+ * function draw() {
+ * image(capture, 0, 0, width, width * capture.height / capture.width);
+ * filter(INVERT);
+ * }
+ *
+ * function setup() {
+ * createCanvas(480, 120);
+ * var constraints = {
+ * video: {
+ * mandatory: {
+ * minWidth: 1280,
+ * minHeight: 720
+ * },
+ * optional: [{ maxFrameRate: 10 }]
+ * },
+ * audio: true
+ * };
+ * createCapture(constraints, function(stream) {
+ * console.log(stream);
+ * });
+ * }
+ *
+ */
+ p5.prototype.getAudioContext = function () {
+ return audiocontext;
+ };
+ /**
+ *
+ * createElement('h2', 'im an h2 p5.element!');
+ *
+ * var div = createDiv('div');
+ * div.addClass('myClass');
+ *
+ * // In this example, a class is set when the div is created
+ * // and removed when mouse is pressed. This could link up
+ * // with a CSS style rule to toggle style properties.
+ *
+ * var div;
+ *
+ * function setup() {
+ * div = createDiv('div');
+ * div.addClass('myClass');
+ * }
+ *
+ * function mousePressed() {
+ * div.removeClass('myClass');
+ * }
+ *
+ * var div;
+ *
+ * function setup() {
+ * div = createDiv('div');
+ * div.addClass('show');
+ * }
+ *
+ * function mousePressed() {
+ * if (div.hasClass('show')) {
+ * div.addClass('show');
+ * } else {
+ * div.removeClass('show');
+ * }
+ * }
+ *
+ * var div;
+ *
+ * function setup() {
+ * div = createDiv('div');
+ * div.addClass('show');
+ * }
+ *
+ * function mousePressed() {
+ * div.toggleClass('show');
+ * }
+ *
+ * var div0 = createDiv('this is the parent');
+ * var div1 = createDiv('this is the child');
+ * div0.child(div1); // use p5.Element
+ *
+ * var div0 = createDiv('this is the parent');
+ * var div1 = createDiv('this is the child');
+ * div1.id('apples');
+ * div0.child('apples'); // use id
+ *
+ * // this example assumes there is a div already on the page
+ * // with id "myChildDiv"
+ * var div0 = createDiv('this is the parent');
+ * var elt = document.getElementById('myChildDiv');
+ * div0.child(elt); // use element from page
+ *
+ * function setup() {
+ * var div = createDiv('').size(10, 10);
+ * div.style('background-color', 'orange');
+ * div.center();
+ * }
+ *
+ * var div = createDiv('').size(100, 100);
+ * div.html('hi');
+ *
+ * var div = createDiv('Hello ').size(100, 100);
+ * div.html('World', true);
+ *
+ * function setup() {
+ * var cnv = createCanvas(100, 100);
+ * // positions canvas 50px to the right and 100px
+ * // below upper left corner of the window
+ * cnv.position(50, 100);
+ * }
+ *
+ * var myDiv = createDiv('I like pandas.');
+ * myDiv.style('font-size', '18px');
+ * myDiv.style('color', '#ff0000');
+ *
+ * var col = color(25, 23, 200, 50);
+ * var button = createButton('button');
+ * button.style('background-color', col);
+ * button.position(10, 10);
+ *
+ * var myDiv;
+ * function setup() {
+ * background(200);
+ * myDiv = createDiv('I like gray.');
+ * myDiv.position(20, 20);
+ * }
+ *
+ * function draw() {
+ * myDiv.style('font-size', mouseX + 'px');
+ * }
+ *
+ * var myDiv = createDiv('I like pandas.');
+ * myDiv.attribute('align', 'center');
+ *
+ * var button;
+ * var checkbox;
+ *
+ * function setup() {
+ * checkbox = createCheckbox('enable', true);
+ * checkbox.changed(enableButton);
+ * button = createButton('button');
+ * button.position(10, 10);
+ * }
+ *
+ * function enableButton() {
+ * if (this.checked()) {
+ * // Re-enable the button
+ * button.removeAttribute('disabled');
+ * } else {
+ * // Disable the button
+ * button.attribute('disabled', '');
+ * }
+ * }
+ *
+ * // gets the value
+ * var inp;
+ * function setup() {
+ * inp = createInput('');
+ * }
+ *
+ * function mousePressed() {
+ * print(inp.value());
+ * }
+ *
+ * // sets the value
+ * var inp;
+ * function setup() {
+ * inp = createInput('myValue');
+ * }
+ *
+ * function mousePressed() {
+ * inp.value('myValue');
+ * }
+ *
+ * var div = createDiv('div');
+ * div.style('display', 'none');
+ * div.show(); // turns display to block
+ *
+ * var div = createDiv('this is a div');
+ * div.hide();
+ *
+ * let div = createDiv('this is a div');
+ * div.size(100, 100);
+ * let img = createImg('assets/laDefense.jpg', () => {
+ * img.size(10, AUTO);
+ * });
+ *
+ * var myDiv = createDiv('this is some text');
+ * myDiv.remove();
+ *
+ * function setup() {
+ * var c = createCanvas(100, 100);
+ * background(200);
+ * textAlign(CENTER);
+ * text('drop file', width / 2, height / 2);
+ * c.drop(gotFile);
+ * }
+ *
+ * function gotFile(file) {
+ * background(200);
+ * text('received file:', width / 2, height / 2);
+ * text(file.name, width / 2, height / 2 + 50);
+ * }
+ *
+ * var img;
+ *
+ * function setup() {
+ * var c = createCanvas(100, 100);
+ * background(200);
+ * textAlign(CENTER);
+ * text('drop image', width / 2, height / 2);
+ * c.drop(gotFile);
+ * }
+ *
+ * function draw() {
+ * if (img) {
+ * image(img, 0, 0, width, height);
+ * }
+ * }
+ *
+ * function gotFile(file) {
+ * img = createImg(file.data).hide();
+ * }
+ *
+ * var ele;
+ *
+ * function setup() {
+ * background(250);
+ *
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ *
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio().
+ * ele = createAudio('assets/beat.mp3');
+ *
+ * //We'll set up our example so that
+ * //when you click on the text,
+ * //an alert box displays the MediaElement's
+ * //src field.
+ * textAlign(CENTER);
+ * text('Click Me!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * //Show our p5.MediaElement's src field
+ * alert(ele.src);
+ * }
+ * }
+ *
+ * var ele;
+ *
+ * function setup() {
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ *
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio().
+ * ele = createAudio('assets/beat.mp3');
+ *
+ * background(250);
+ * textAlign(CENTER);
+ * text('Click to Play!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * //Here we call the play() function on
+ * //the p5.MediaElement we created above.
+ * //This will start the audio sample.
+ * ele.play();
+ *
+ * background(200);
+ * text('You clicked Play!', width / 2, height / 2);
+ * }
+ * }
+ *
+ * //This example both starts
+ * //and stops a sound sample
+ * //when the user clicks the canvas
+ *
+ * //We will store the p5.MediaElement
+ * //object in here
+ * var ele;
+ *
+ * //while our audio is playing,
+ * //this will be set to true
+ * var sampleIsPlaying = false;
+ *
+ * function setup() {
+ * //Here we create a p5.MediaElement object
+ * //using the createAudio() function.
+ * ele = createAudio('assets/beat.mp3');
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to play!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * background(200);
+ *
+ * if (sampleIsPlaying) {
+ * //if the sample is currently playing
+ * //calling the stop() function on
+ * //our p5.MediaElement will stop
+ * //it and reset its current
+ * //time to 0 (i.e. it will start
+ * //at the beginning the next time
+ * //you play it)
+ * ele.stop();
+ *
+ * sampleIsPlaying = false;
+ * text('Click to play!', width / 2, height / 2);
+ * } else {
+ * //loop our sound element until we
+ * //call ele.stop() on it.
+ * ele.loop();
+ *
+ * sampleIsPlaying = true;
+ * text('Click to stop!', width / 2, height / 2);
+ * }
+ * }
+ * }
+ *
+ * //This example both starts
+ * //and pauses a sound sample
+ * //when the user clicks the canvas
+ *
+ * //We will store the p5.MediaElement
+ * //object in here
+ * var ele;
+ *
+ * //while our audio is playing,
+ * //this will be set to true
+ * var sampleIsPlaying = false;
+ *
+ * function setup() {
+ * //Here we create a p5.MediaElement object
+ * //using the createAudio() function.
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to play!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * background(200);
+ *
+ * if (sampleIsPlaying) {
+ * //Calling pause() on our
+ * //p5.MediaElement will stop it
+ * //playing, but when we call the
+ * //loop() or play() functions
+ * //the sample will start from
+ * //where we paused it.
+ * ele.pause();
+ *
+ * sampleIsPlaying = false;
+ * text('Click to resume!', width / 2, height / 2);
+ * } else {
+ * //loop our sound element until we
+ * //call ele.pause() on it.
+ * ele.loop();
+ *
+ * sampleIsPlaying = true;
+ * text('Click to pause!', width / 2, height / 2);
+ * }
+ * }
+ * }
+ *
+ * //Clicking the canvas will loop
+ * //the audio sample until the user
+ * //clicks again to stop it
+ *
+ * //We will store the p5.MediaElement
+ * //object in here
+ * var ele;
+ *
+ * //while our audio is playing,
+ * //this will be set to true
+ * var sampleIsLooping = false;
+ *
+ * function setup() {
+ * //Here we create a p5.MediaElement object
+ * //using the createAudio() function.
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to loop!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * background(200);
+ *
+ * if (!sampleIsLooping) {
+ * //loop our sound element until we
+ * //call ele.stop() on it.
+ * ele.loop();
+ *
+ * sampleIsLooping = true;
+ * text('Click to stop!', width / 2, height / 2);
+ * } else {
+ * ele.stop();
+ *
+ * sampleIsLooping = false;
+ * text('Click to loop!', width / 2, height / 2);
+ * }
+ * }
+ * }
+ *
+ * //This example both starts
+ * //and stops loop of sound sample
+ * //when the user clicks the canvas
+ *
+ * //We will store the p5.MediaElement
+ * //object in here
+ * var ele;
+ * //while our audio is playing,
+ * //this will be set to true
+ * var sampleIsPlaying = false;
+ *
+ * function setup() {
+ * //Here we create a p5.MediaElement object
+ * //using the createAudio() function.
+ * ele = createAudio('assets/beat.mp3');
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to play!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * background(200);
+ *
+ * if (sampleIsPlaying) {
+ * ele.noLoop();
+ * text('No more Loops!', width / 2, height / 2);
+ * } else {
+ * ele.loop();
+ * sampleIsPlaying = true;
+ * text('Click to stop looping!', width / 2, height / 2);
+ * }
+ * }
+ * }
+ *
+ * var ele;
+ * function setup() {
+ * // p5.MediaElement objects are usually created
+ * // by calling the createAudio(), createVideo(),
+ * // and createCapture() functions.
+ * // In this example we create
+ * // a new p5.MediaElement via createAudio().
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * background(250);
+ * textAlign(CENTER);
+ * text('Click to Play!', width / 2, height / 2);
+ * }
+ * function mouseClicked() {
+ * // Here we call the volume() function
+ * // on the sound element to set its volume
+ * // Volume must be between 0.0 and 1.0
+ * ele.volume(0.2);
+ * ele.play();
+ * background(200);
+ * text('You clicked Play!', width / 2, height / 2);
+ * }
+ *
+ * var audio;
+ * var counter = 0;
+ *
+ * function loaded() {
+ * audio.play();
+ * }
+ *
+ * function setup() {
+ * audio = createAudio('assets/lucky_dragons.mp3', loaded);
+ * textAlign(CENTER);
+ * }
+ *
+ * function draw() {
+ * if (counter === 0) {
+ * background(0, 255, 0);
+ * text('volume(0.9)', width / 2, height / 2);
+ * } else if (counter === 1) {
+ * background(255, 255, 0);
+ * text('volume(0.5)', width / 2, height / 2);
+ * } else if (counter === 2) {
+ * background(255, 0, 0);
+ * text('volume(0.1)', width / 2, height / 2);
+ * }
+ * }
+ *
+ * function mousePressed() {
+ * counter++;
+ * if (counter === 0) {
+ * audio.volume(0.9);
+ * } else if (counter === 1) {
+ * audio.volume(0.5);
+ * } else if (counter === 2) {
+ * audio.volume(0.1);
+ * } else {
+ * counter = 0;
+ * audio.volume(0.9);
+ * }
+ * }
+ *
+ *
+ * //Clicking the canvas will loop
+ * //the audio sample until the user
+ * //clicks again to stop it
+ *
+ * //We will store the p5.MediaElement
+ * //object in here
+ * var ele;
+ * var button;
+ *
+ * function setup() {
+ * createCanvas(710, 400);
+ * //Here we create a p5.MediaElement object
+ * //using the createAudio() function.
+ * ele = createAudio('assets/beat.mp3');
+ * ele.loop();
+ * background(200);
+ *
+ * button = createButton('2x speed');
+ * button.position(100, 68);
+ * button.mousePressed(twice_speed);
+ *
+ * button = createButton('half speed');
+ * button.position(200, 68);
+ * button.mousePressed(half_speed);
+ *
+ * button = createButton('reverse play');
+ * button.position(300, 68);
+ * button.mousePressed(reverse_speed);
+ *
+ * button = createButton('STOP');
+ * button.position(400, 68);
+ * button.mousePressed(stop_song);
+ *
+ * button = createButton('PLAY!');
+ * button.position(500, 68);
+ * button.mousePressed(play_speed);
+ * }
+ *
+ * function twice_speed() {
+ * ele.speed(2);
+ * }
+ *
+ * function half_speed() {
+ * ele.speed(0.5);
+ * }
+ *
+ * function reverse_speed() {
+ * ele.speed(-1);
+ * }
+ *
+ * function stop_song() {
+ * ele.stop();
+ * }
+ *
+ * function play_speed() {
+ * ele.play();
+ * }
+ *
+ * var ele;
+ * var beginning = true;
+ * function setup() {
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ *
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio().
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * background(250);
+ * textAlign(CENTER);
+ * text('start at beginning', width / 2, height / 2);
+ * }
+ *
+ * // this function fires with click anywhere
+ * function mousePressed() {
+ * if (beginning === true) {
+ * // here we start the sound at the beginning
+ * // time(0) is not necessary here
+ * // as this produces the same result as
+ * // play()
+ * ele.play().time(0);
+ * background(200);
+ * text('jump 2 sec in', width / 2, height / 2);
+ * beginning = false;
+ * } else {
+ * // here we jump 2 seconds into the sound
+ * ele.play().time(2);
+ * background(250);
+ * text('start at beginning', width / 2, height / 2);
+ * beginning = true;
+ * }
+ * }
+ *
+ * var ele;
+ * function setup() {
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio().
+ * ele = createAudio('assets/doorbell.mp3');
+ * background(250);
+ * textAlign(CENTER);
+ * text('Click to know the duration!', 10, 25, 70, 80);
+ * }
+ * function mouseClicked() {
+ * ele.play();
+ * background(200);
+ * //ele.duration dislpays the duration
+ * text(ele.duration() + ' seconds', width / 2, height / 2);
+ * }
+ *
+ * function setup() {
+ * var audioEl = createAudio('assets/beat.mp3');
+ * audioEl.showControls();
+ * audioEl.onended(sayDone);
+ * }
+ *
+ * function sayDone(elt) {
+ * alert('done playing ' + elt.src);
+ * }
+ *
+ * var ele;
+ * function setup() {
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio()
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to Show Controls!', 10, 25, 70, 80);
+ * }
+ * function mousePressed() {
+ * ele.showControls();
+ * background(200);
+ * text('Controls Shown', width / 2, height / 2);
+ * }
+ *
+ * var ele;
+ * function setup() {
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio()
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * ele.showControls();
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to hide Controls!', 10, 25, 70, 80);
+ * }
+ * function mousePressed() {
+ * ele.hideControls();
+ * background(200);
+ * text('Controls hidden', width / 2, height / 2);
+ * }
+ *
+ * //
+ * //
+ * function setup() {
+ * noCanvas();
+ *
+ * var audioEl = createAudio('assets/beat.mp3');
+ * audioEl.showControls();
+ *
+ * // schedule three calls to changeBackground
+ * audioEl.addCue(0.5, changeBackground, color(255, 0, 0));
+ * audioEl.addCue(1.0, changeBackground, color(0, 255, 0));
+ * audioEl.addCue(2.5, changeBackground, color(0, 0, 255));
+ * audioEl.addCue(3.0, changeBackground, color(0, 255, 255));
+ * audioEl.addCue(4.2, changeBackground, color(255, 255, 0));
+ * audioEl.addCue(5.0, changeBackground, color(255, 255, 0));
+ * }
+ *
+ * function changeBackground(val) {
+ * background(val);
+ * }
+ *
+ * var audioEl, id1, id2;
+ * function setup() {
+ * background(255, 255, 255);
+ * audioEl = createAudio('assets/beat.mp3');
+ * audioEl.showControls();
+ * // schedule five calls to changeBackground
+ * id1 = audioEl.addCue(0.5, changeBackground, color(255, 0, 0));
+ * audioEl.addCue(1.0, changeBackground, color(0, 255, 0));
+ * audioEl.addCue(2.5, changeBackground, color(0, 0, 255));
+ * audioEl.addCue(3.0, changeBackground, color(0, 255, 255));
+ * id2 = audioEl.addCue(4.2, changeBackground, color(255, 255, 0));
+ * text('Click to remove first and last Cue!', 10, 25, 70, 80);
+ * }
+ * function mousePressed() {
+ * audioEl.removeCue(id1);
+ * audioEl.removeCue(id2);
+ * }
+ * function changeBackground(val) {
+ * background(val);
+ * }
+ *
+ * var audioEl;
+ * function setup() {
+ * background(255, 255, 255);
+ * audioEl = createAudio('assets/beat.mp3');
+ * //Show the default MediaElement controls, as determined by the web browser
+ * audioEl.showControls();
+ * // schedule calls to changeBackground
+ * background(200);
+ * text('Click to change Cue!', 10, 25, 70, 80);
+ * audioEl.addCue(0.5, changeBackground, color(255, 0, 0));
+ * audioEl.addCue(1.0, changeBackground, color(0, 255, 0));
+ * audioEl.addCue(2.5, changeBackground, color(0, 0, 255));
+ * audioEl.addCue(3.0, changeBackground, color(0, 255, 255));
+ * audioEl.addCue(4.2, changeBackground, color(255, 255, 0));
+ * }
+ * function mousePressed() {
+ * // here we clear the scheduled callbacks
+ * audioEl.clearCues();
+ * // then we add some more callbacks
+ * audioEl.addCue(1, changeBackground, color(2, 2, 2));
+ * audioEl.addCue(3, changeBackground, color(255, 255, 0));
+ * }
+ * function changeBackground(val) {
+ * background(val);
+ * }
+ *
+ * p5.SoundFile: Load and play sound files.
+ * p5.Amplitude: Get the current volume of a sound.
+ * p5.AudioIn: Get sound from an input source, typically
+ * a computer microphone.
+ * p5.FFT: Analyze the frequency of sound. Returns
+ * results from the frequency spectrum or time domain (waveform).
+ * p5.Oscillator: Generate Sine,
+ * Triangle, Square and Sawtooth waveforms. Base class of
+ * p5.Noise and p5.Pulse.
+ *
+ * p5.Envelope: An Envelope is a series
+ * of fades over time. Often used to control an object's
+ * output gain level as an "ADSR Envelope" (Attack, Decay,
+ * Sustain, Release). Can also modulate other parameters.
+ * p5.Delay: A delay effect with
+ * parameters for feedback, delayTime, and lowpass filter.
+ * p5.Filter: Filter the frequency range of a
+ * sound.
+ *
+ * p5.Reverb: Add reverb to a sound by specifying
+ * duration and decay.
+ * p5.Convolver: Extends
+ * p5.Reverb to simulate the sound of real
+ * physical spaces through convolution.
+ * p5.SoundRecorder: Record sound for playback
+ * / save the .wav file.
+ * p5.Phrase, p5.Part and
+ * p5.Score: Compose musical sequences.
+ *
+ * p5.sound is on GitHub.
+ * Download the latest version
+ * here.
+ *
+ * @module p5.sound
+ * @submodule p5.sound
+ * @for p5.sound
+ * @main
+ */
+
+/**
+ * p5.sound
+ * https://p5js.org/reference/#/libraries/p5.sound
+ *
+ * From the Processing Foundation and contributors
+ * https://github.com/processing/p5.js-sound/graphs/contributors
+ *
+ * MIT License (MIT)
+ * https://github.com/processing/p5.js-sound/blob/master/LICENSE
+ *
+ * Some of the many audio libraries & resources that inspire p5.sound:
+ * - TONE.js (c) Yotam Mann. Licensed under The MIT License (MIT). https://github.com/TONEnoTONE/Tone.js
+ * - buzz.js (c) Jay Salvat. Licensed under The MIT License (MIT). http://buzz.jaysalvat.com/
+ * - Boris Smus Web Audio API book, 2013. Licensed under the Apache License http://www.apache.org/licenses/LICENSE-2.0
+ * - wavesurfer.js https://github.com/katspaugh/wavesurfer.js
+ * - Web Audio Components by Jordan Santell https://github.com/web-audio-components
+ * - 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/
+ */
+
+(function (root, factory) {
+ if (typeof define === 'function' && define.amd)
+ define('p5.sound', ['p5'], function (p5) { (factory(p5));});
+ else if (typeof exports === 'object')
+ factory(require('../p5'));
+ else
+ factory(root['p5']);
+}(this, function (p5) {
+
+var shims;
+'use strict'; /**
+ * This module has shims
+ */
+shims = function () {
+ /* AudioContext Monkeypatch
+ Copyright 2013 Chris Wilson
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+ http://www.apache.org/licenses/LICENSE-2.0
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ */
+ (function () {
+ function fixSetTarget(param) {
+ if (!param)
+ // if NYI, just return
+ return;
+ if (!param.setTargetAtTime)
+ param.setTargetAtTime = param.setTargetValueAtTime;
+ }
+ if (window.hasOwnProperty('webkitAudioContext') && !window.hasOwnProperty('AudioContext')) {
+ window.AudioContext = window.webkitAudioContext;
+ if (typeof AudioContext.prototype.createGain !== 'function')
+ AudioContext.prototype.createGain = AudioContext.prototype.createGainNode;
+ if (typeof AudioContext.prototype.createDelay !== 'function')
+ AudioContext.prototype.createDelay = AudioContext.prototype.createDelayNode;
+ if (typeof AudioContext.prototype.createScriptProcessor !== 'function')
+ AudioContext.prototype.createScriptProcessor = AudioContext.prototype.createJavaScriptNode;
+ if (typeof AudioContext.prototype.createPeriodicWave !== 'function')
+ AudioContext.prototype.createPeriodicWave = AudioContext.prototype.createWaveTable;
+ AudioContext.prototype.internal_createGain = AudioContext.prototype.createGain;
+ AudioContext.prototype.createGain = function () {
+ var node = this.internal_createGain();
+ fixSetTarget(node.gain);
+ return node;
+ };
+ AudioContext.prototype.internal_createDelay = AudioContext.prototype.createDelay;
+ AudioContext.prototype.createDelay = function (maxDelayTime) {
+ var node = maxDelayTime ? this.internal_createDelay(maxDelayTime) : this.internal_createDelay();
+ fixSetTarget(node.delayTime);
+ return node;
+ };
+ AudioContext.prototype.internal_createBufferSource = AudioContext.prototype.createBufferSource;
+ AudioContext.prototype.createBufferSource = function () {
+ var node = this.internal_createBufferSource();
+ if (!node.start) {
+ node.start = function (when, offset, duration) {
+ if (offset || duration)
+ this.noteGrainOn(when || 0, offset, duration);
+ else
+ this.noteOn(when || 0);
+ };
+ } else {
+ node.internal_start = node.start;
+ node.start = function (when, offset, duration) {
+ if (typeof duration !== 'undefined')
+ node.internal_start(when || 0, offset, duration);
+ else
+ node.internal_start(when || 0, offset || 0);
+ };
+ }
+ if (!node.stop) {
+ node.stop = function (when) {
+ this.noteOff(when || 0);
+ };
+ } else {
+ node.internal_stop = node.stop;
+ node.stop = function (when) {
+ node.internal_stop(when || 0);
+ };
+ }
+ fixSetTarget(node.playbackRate);
+ return node;
+ };
+ AudioContext.prototype.internal_createDynamicsCompressor = AudioContext.prototype.createDynamicsCompressor;
+ AudioContext.prototype.createDynamicsCompressor = function () {
+ var node = this.internal_createDynamicsCompressor();
+ fixSetTarget(node.threshold);
+ fixSetTarget(node.knee);
+ fixSetTarget(node.ratio);
+ fixSetTarget(node.reduction);
+ fixSetTarget(node.attack);
+ fixSetTarget(node.release);
+ return node;
+ };
+ AudioContext.prototype.internal_createBiquadFilter = AudioContext.prototype.createBiquadFilter;
+ AudioContext.prototype.createBiquadFilter = function () {
+ var node = this.internal_createBiquadFilter();
+ fixSetTarget(node.frequency);
+ fixSetTarget(node.detune);
+ fixSetTarget(node.Q);
+ fixSetTarget(node.gain);
+ return node;
+ };
+ if (typeof AudioContext.prototype.createOscillator !== 'function') {
+ AudioContext.prototype.internal_createOscillator = AudioContext.prototype.createOscillator;
+ AudioContext.prototype.createOscillator = function () {
+ var node = this.internal_createOscillator();
+ if (!node.start) {
+ node.start = function (when) {
+ this.noteOn(when || 0);
+ };
+ } else {
+ node.internal_start = node.start;
+ node.start = function (when) {
+ node.internal_start(when || 0);
+ };
+ }
+ if (!node.stop) {
+ node.stop = function (when) {
+ this.noteOff(when || 0);
+ };
+ } else {
+ node.internal_stop = node.stop;
+ node.stop = function (when) {
+ node.internal_stop(when || 0);
+ };
+ }
+ if (!node.setPeriodicWave)
+ node.setPeriodicWave = node.setWaveTable;
+ fixSetTarget(node.frequency);
+ fixSetTarget(node.detune);
+ return node;
+ };
+ }
+ }
+ if (window.hasOwnProperty('webkitOfflineAudioContext') && !window.hasOwnProperty('OfflineAudioContext')) {
+ window.OfflineAudioContext = window.webkitOfflineAudioContext;
+ }
+ }(window));
+ // <-- end MonkeyPatch.
+ // Polyfill for AudioIn, also handled by p5.dom createCapture
+ navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
+ /**
+ * Determine which filetypes are supported (inspired by buzz.js)
+ * The audio element (el) will only be used to test browser support for various audio formats
+ */
+ var el = document.createElement('audio');
+ p5.prototype.isSupported = function () {
+ return !!el.canPlayType;
+ };
+ var isOGGSupported = function () {
+ return !!el.canPlayType && el.canPlayType('audio/ogg; codecs="vorbis"');
+ };
+ var isMP3Supported = function () {
+ return !!el.canPlayType && el.canPlayType('audio/mpeg;');
+ };
+ var isWAVSupported = function () {
+ return !!el.canPlayType && el.canPlayType('audio/wav; codecs="1"');
+ };
+ var isAACSupported = function () {
+ return !!el.canPlayType && (el.canPlayType('audio/x-m4a;') || el.canPlayType('audio/aac;'));
+ };
+ var isAIFSupported = function () {
+ return !!el.canPlayType && el.canPlayType('audio/x-aiff;');
+ };
+ p5.prototype.isFileSupported = function (extension) {
+ switch (extension.toLowerCase()) {
+ case 'mp3':
+ return isMP3Supported();
+ case 'wav':
+ return isWAVSupported();
+ case 'ogg':
+ return isOGGSupported();
+ case 'aac':
+ case 'm4a':
+ case 'mp4':
+ return isAACSupported();
+ case 'aif':
+ case 'aiff':
+ return isAIFSupported();
+ default:
+ return false;
+ }
+ };
+}();
+var StartAudioContext;
+(function (root, factory) {
+ if (true) {
+ StartAudioContext = function () {
+ return factory();
+ }();
+ } else if (typeof module === 'object' && module.exports) {
+ module.exports = factory();
+ } else {
+ root.StartAudioContext = factory();
+ }
+}(this, function () {
+ var TapListener = function (element, context) {
+ this._dragged = false;
+ this._element = element;
+ this._bindedMove = this._moved.bind(this);
+ this._bindedEnd = this._ended.bind(this, context);
+ element.addEventListener('touchstart', this._bindedEnd);
+ element.addEventListener('touchmove', this._bindedMove);
+ element.addEventListener('touchend', this._bindedEnd);
+ element.addEventListener('mouseup', this._bindedEnd);
+ };
+ TapListener.prototype._moved = function (e) {
+ this._dragged = true;
+ };
+ TapListener.prototype._ended = function (context) {
+ if (!this._dragged) {
+ startContext(context);
+ }
+ this._dragged = false;
+ };
+ TapListener.prototype.dispose = function () {
+ this._element.removeEventListener('touchstart', this._bindedEnd);
+ this._element.removeEventListener('touchmove', this._bindedMove);
+ this._element.removeEventListener('touchend', this._bindedEnd);
+ this._element.removeEventListener('mouseup', this._bindedEnd);
+ this._bindedMove = null;
+ this._bindedEnd = null;
+ this._element = null;
+ };
+ function startContext(context) {
+ var buffer = context.createBuffer(1, 1, context.sampleRate);
+ var source = context.createBufferSource();
+ source.buffer = buffer;
+ source.connect(context.destination);
+ source.start(0);
+ if (context.resume) {
+ context.resume();
+ }
+ }
+ function isStarted(context) {
+ return context.state === 'running';
+ }
+ function onStarted(context, callback) {
+ function checkLoop() {
+ if (isStarted(context)) {
+ callback();
+ } else {
+ requestAnimationFrame(checkLoop);
+ if (context.resume) {
+ context.resume();
+ }
+ }
+ }
+ if (isStarted(context)) {
+ callback();
+ } else {
+ checkLoop();
+ }
+ }
+ function bindTapListener(element, tapListeners, context) {
+ if (Array.isArray(element) || NodeList && element instanceof NodeList) {
+ for (var i = 0; i < element.length; i++) {
+ bindTapListener(element[i], tapListeners, context);
+ }
+ } else if (typeof element === 'string') {
+ bindTapListener(document.querySelectorAll(element), tapListeners, context);
+ } else if (element.jquery && typeof element.toArray === 'function') {
+ bindTapListener(element.toArray(), tapListeners, context);
+ } else if (Element && element instanceof Element) {
+ var tap = new TapListener(element, context);
+ tapListeners.push(tap);
+ }
+ }
+ function StartAudioContext(context, elements, callback) {
+ var promise = new Promise(function (success) {
+ onStarted(context, success);
+ });
+ var tapListeners = [];
+ if (!elements) {
+ elements = document.body;
+ }
+ bindTapListener(elements, tapListeners, context);
+ promise.then(function () {
+ for (var i = 0; i < tapListeners.length; i++) {
+ tapListeners[i].dispose();
+ }
+ tapListeners = null;
+ if (callback) {
+ callback();
+ }
+ });
+ return promise;
+ }
+ return StartAudioContext;
+}));
+/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/
+var Tone_core_Tone;
+Tone_core_Tone = function () {
+ 'use strict';
+ var Tone = function (inputs, outputs) {
+ if (this.isUndef(inputs) || inputs === 1) {
+ this.input = this.context.createGain();
+ } else if (inputs > 1) {
+ this.input = new Array(inputs);
+ }
+ if (this.isUndef(outputs) || outputs === 1) {
+ this.output = this.context.createGain();
+ } else if (outputs > 1) {
+ this.output = new Array(inputs);
+ }
+ };
+ Tone.prototype.set = function (params, value, rampTime) {
+ if (this.isObject(params)) {
+ rampTime = value;
+ } else if (this.isString(params)) {
+ var tmpObj = {};
+ tmpObj[params] = value;
+ params = tmpObj;
+ }
+ paramLoop:
+ for (var attr in params) {
+ value = params[attr];
+ var parent = this;
+ if (attr.indexOf('.') !== -1) {
+ var attrSplit = attr.split('.');
+ for (var i = 0; i < attrSplit.length - 1; i++) {
+ parent = parent[attrSplit[i]];
+ if (parent instanceof Tone) {
+ attrSplit.splice(0, i + 1);
+ var innerParam = attrSplit.join('.');
+ parent.set(innerParam, value);
+ continue paramLoop;
+ }
+ }
+ attr = attrSplit[attrSplit.length - 1];
+ }
+ var param = parent[attr];
+ if (this.isUndef(param)) {
+ continue;
+ }
+ if (Tone.Signal && param instanceof Tone.Signal || Tone.Param && param instanceof Tone.Param) {
+ if (param.value !== value) {
+ if (this.isUndef(rampTime)) {
+ param.value = value;
+ } else {
+ param.rampTo(value, rampTime);
+ }
+ }
+ } else if (param instanceof AudioParam) {
+ if (param.value !== value) {
+ param.value = value;
+ }
+ } else if (param instanceof Tone) {
+ param.set(value);
+ } else if (param !== value) {
+ parent[attr] = value;
+ }
+ }
+ return this;
+ };
+ Tone.prototype.get = function (params) {
+ if (this.isUndef(params)) {
+ params = this._collectDefaults(this.constructor);
+ } else if (this.isString(params)) {
+ params = [params];
+ }
+ var ret = {};
+ for (var i = 0; i < params.length; i++) {
+ var attr = params[i];
+ var parent = this;
+ var subRet = ret;
+ if (attr.indexOf('.') !== -1) {
+ var attrSplit = attr.split('.');
+ for (var j = 0; j < attrSplit.length - 1; j++) {
+ var subAttr = attrSplit[j];
+ subRet[subAttr] = subRet[subAttr] || {};
+ subRet = subRet[subAttr];
+ parent = parent[subAttr];
+ }
+ attr = attrSplit[attrSplit.length - 1];
+ }
+ var param = parent[attr];
+ if (this.isObject(params[attr])) {
+ subRet[attr] = param.get();
+ } else if (Tone.Signal && param instanceof Tone.Signal) {
+ subRet[attr] = param.value;
+ } else if (Tone.Param && param instanceof Tone.Param) {
+ subRet[attr] = param.value;
+ } else if (param instanceof AudioParam) {
+ subRet[attr] = param.value;
+ } else if (param instanceof Tone) {
+ subRet[attr] = param.get();
+ } else if (!this.isFunction(param) && !this.isUndef(param)) {
+ subRet[attr] = param;
+ }
+ }
+ return ret;
+ };
+ Tone.prototype._collectDefaults = function (constr) {
+ var ret = [];
+ if (!this.isUndef(constr.defaults)) {
+ ret = Object.keys(constr.defaults);
+ }
+ if (!this.isUndef(constr._super)) {
+ var superDefs = this._collectDefaults(constr._super);
+ for (var i = 0; i < superDefs.length; i++) {
+ if (ret.indexOf(superDefs[i]) === -1) {
+ ret.push(superDefs[i]);
+ }
+ }
+ }
+ return ret;
+ };
+ Tone.prototype.toString = function () {
+ for (var className in Tone) {
+ var isLetter = className[0].match(/^[A-Z]$/);
+ var sameConstructor = Tone[className] === this.constructor;
+ if (this.isFunction(Tone[className]) && isLetter && sameConstructor) {
+ return className;
+ }
+ }
+ return 'Tone';
+ };
+ Object.defineProperty(Tone.prototype, 'numberOfInputs', {
+ get: function () {
+ if (this.input) {
+ if (this.isArray(this.input)) {
+ return this.input.length;
+ } else {
+ return 1;
+ }
+ } else {
+ return 0;
+ }
+ }
+ });
+ Object.defineProperty(Tone.prototype, 'numberOfOutputs', {
+ get: function () {
+ if (this.output) {
+ if (this.isArray(this.output)) {
+ return this.output.length;
+ } else {
+ return 1;
+ }
+ } else {
+ return 0;
+ }
+ }
+ });
+ Tone.prototype.dispose = function () {
+ if (!this.isUndef(this.input)) {
+ if (this.input instanceof AudioNode) {
+ this.input.disconnect();
+ }
+ this.input = null;
+ }
+ if (!this.isUndef(this.output)) {
+ if (this.output instanceof AudioNode) {
+ this.output.disconnect();
+ }
+ this.output = null;
+ }
+ return this;
+ };
+ Tone.prototype.connect = function (unit, outputNum, inputNum) {
+ if (Array.isArray(this.output)) {
+ outputNum = this.defaultArg(outputNum, 0);
+ this.output[outputNum].connect(unit, 0, inputNum);
+ } else {
+ this.output.connect(unit, outputNum, inputNum);
+ }
+ return this;
+ };
+ Tone.prototype.disconnect = function (destination, outputNum, inputNum) {
+ if (this.isArray(this.output)) {
+ if (this.isNumber(destination)) {
+ this.output[destination].disconnect();
+ } else {
+ outputNum = this.defaultArg(outputNum, 0);
+ this.output[outputNum].disconnect(destination, 0, inputNum);
+ }
+ } else {
+ this.output.disconnect.apply(this.output, arguments);
+ }
+ };
+ Tone.prototype.connectSeries = function () {
+ if (arguments.length > 1) {
+ var currentUnit = arguments[0];
+ for (var i = 1; i < arguments.length; i++) {
+ var toUnit = arguments[i];
+ currentUnit.connect(toUnit);
+ currentUnit = toUnit;
+ }
+ }
+ return this;
+ };
+ Tone.prototype.chain = function () {
+ if (arguments.length > 0) {
+ var currentUnit = this;
+ for (var i = 0; i < arguments.length; i++) {
+ var toUnit = arguments[i];
+ currentUnit.connect(toUnit);
+ currentUnit = toUnit;
+ }
+ }
+ return this;
+ };
+ Tone.prototype.fan = function () {
+ if (arguments.length > 0) {
+ for (var i = 0; i < arguments.length; i++) {
+ this.connect(arguments[i]);
+ }
+ }
+ return this;
+ };
+ AudioNode.prototype.chain = Tone.prototype.chain;
+ AudioNode.prototype.fan = Tone.prototype.fan;
+ Tone.prototype.defaultArg = function (given, fallback) {
+ if (this.isObject(given) && this.isObject(fallback)) {
+ var ret = {};
+ for (var givenProp in given) {
+ ret[givenProp] = this.defaultArg(fallback[givenProp], given[givenProp]);
+ }
+ for (var fallbackProp in fallback) {
+ ret[fallbackProp] = this.defaultArg(given[fallbackProp], fallback[fallbackProp]);
+ }
+ return ret;
+ } else {
+ return this.isUndef(given) ? fallback : given;
+ }
+ };
+ Tone.prototype.optionsObject = function (values, keys, defaults) {
+ var options = {};
+ if (values.length === 1 && this.isObject(values[0])) {
+ options = values[0];
+ } else {
+ for (var i = 0; i < keys.length; i++) {
+ options[keys[i]] = values[i];
+ }
+ }
+ if (!this.isUndef(defaults)) {
+ return this.defaultArg(options, defaults);
+ } else {
+ return options;
+ }
+ };
+ Tone.prototype.isUndef = function (val) {
+ return typeof val === 'undefined';
+ };
+ Tone.prototype.isFunction = function (val) {
+ return typeof val === 'function';
+ };
+ Tone.prototype.isNumber = function (arg) {
+ return typeof arg === 'number';
+ };
+ Tone.prototype.isObject = function (arg) {
+ return Object.prototype.toString.call(arg) === '[object Object]' && arg.constructor === Object;
+ };
+ Tone.prototype.isBoolean = function (arg) {
+ return typeof arg === 'boolean';
+ };
+ Tone.prototype.isArray = function (arg) {
+ return Array.isArray(arg);
+ };
+ Tone.prototype.isString = function (arg) {
+ return typeof arg === 'string';
+ };
+ Tone.noOp = function () {
+ };
+ Tone.prototype._readOnly = function (property) {
+ if (Array.isArray(property)) {
+ for (var i = 0; i < property.length; i++) {
+ this._readOnly(property[i]);
+ }
+ } else {
+ Object.defineProperty(this, property, {
+ writable: false,
+ enumerable: true
+ });
+ }
+ };
+ Tone.prototype._writable = function (property) {
+ if (Array.isArray(property)) {
+ for (var i = 0; i < property.length; i++) {
+ this._writable(property[i]);
+ }
+ } else {
+ Object.defineProperty(this, property, { writable: true });
+ }
+ };
+ Tone.State = {
+ Started: 'started',
+ Stopped: 'stopped',
+ Paused: 'paused'
+ };
+ Tone.prototype.equalPowerScale = function (percent) {
+ var piFactor = 0.5 * Math.PI;
+ return Math.sin(percent * piFactor);
+ };
+ Tone.prototype.dbToGain = function (db) {
+ return Math.pow(2, db / 6);
+ };
+ Tone.prototype.gainToDb = function (gain) {
+ return 20 * (Math.log(gain) / Math.LN10);
+ };
+ Tone.prototype.intervalToFrequencyRatio = function (interval) {
+ return Math.pow(2, interval / 12);
+ };
+ Tone.prototype.now = function () {
+ return Tone.context.now();
+ };
+ Tone.now = function () {
+ return Tone.context.now();
+ };
+ Tone.extend = function (child, parent) {
+ if (Tone.prototype.isUndef(parent)) {
+ parent = Tone;
+ }
+ function TempConstructor() {
+ }
+ TempConstructor.prototype = parent.prototype;
+ child.prototype = new TempConstructor();
+ child.prototype.constructor = child;
+ child._super = parent;
+ };
+ var audioContext;
+ Object.defineProperty(Tone, 'context', {
+ get: function () {
+ return audioContext;
+ },
+ set: function (context) {
+ if (Tone.Context && context instanceof Tone.Context) {
+ audioContext = context;
+ } else {
+ audioContext = new Tone.Context(context);
+ }
+ if (Tone.Context) {
+ Tone.Context.emit('init', audioContext);
+ }
+ }
+ });
+ Object.defineProperty(Tone.prototype, 'context', {
+ get: function () {
+ return Tone.context;
+ }
+ });
+ Tone.setContext = function (ctx) {
+ Tone.context = ctx;
+ };
+ Object.defineProperty(Tone.prototype, 'blockTime', {
+ get: function () {
+ return 128 / this.context.sampleRate;
+ }
+ });
+ Object.defineProperty(Tone.prototype, 'sampleTime', {
+ get: function () {
+ return 1 / this.context.sampleRate;
+ }
+ });
+ Object.defineProperty(Tone, 'supported', {
+ get: function () {
+ var hasAudioContext = window.hasOwnProperty('AudioContext') || window.hasOwnProperty('webkitAudioContext');
+ var hasPromises = window.hasOwnProperty('Promise');
+ var hasWorkers = window.hasOwnProperty('Worker');
+ return hasAudioContext && hasPromises && hasWorkers;
+ }
+ });
+ Tone.version = 'r10';
+ if (!window.TONE_SILENCE_VERSION_LOGGING) {
+ }
+ return Tone;
+}();
+/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/
+var Tone_core_Emitter;
+Tone_core_Emitter = function (Tone) {
+ 'use strict';
+ Tone.Emitter = function () {
+ this._events = {};
+ };
+ Tone.extend(Tone.Emitter);
+ Tone.Emitter.prototype.on = function (event, callback) {
+ var events = event.split(/\W+/);
+ for (var i = 0; i < events.length; i++) {
+ var eventName = events[i];
+ if (!this._events.hasOwnProperty(eventName)) {
+ this._events[eventName] = [];
+ }
+ this._events[eventName].push(callback);
+ }
+ return this;
+ };
+ Tone.Emitter.prototype.off = function (event, callback) {
+ var events = event.split(/\W+/);
+ for (var ev = 0; ev < events.length; ev++) {
+ event = events[ev];
+ if (this._events.hasOwnProperty(event)) {
+ if (Tone.prototype.isUndef(callback)) {
+ this._events[event] = [];
+ } else {
+ var eventList = this._events[event];
+ for (var i = 0; i < eventList.length; i++) {
+ if (eventList[i] === callback) {
+ eventList.splice(i, 1);
+ }
+ }
+ }
+ }
+ }
+ return this;
+ };
+ Tone.Emitter.prototype.emit = function (event) {
+ if (this._events) {
+ var args = Array.apply(null, arguments).slice(1);
+ if (this._events.hasOwnProperty(event)) {
+ var eventList = this._events[event];
+ for (var i = 0, len = eventList.length; i < len; i++) {
+ eventList[i].apply(this, args);
+ }
+ }
+ }
+ return this;
+ };
+ Tone.Emitter.mixin = function (object) {
+ var functions = [
+ 'on',
+ 'off',
+ 'emit'
+ ];
+ object._events = {};
+ for (var i = 0; i < functions.length; i++) {
+ var func = functions[i];
+ var emitterFunc = Tone.Emitter.prototype[func];
+ object[func] = emitterFunc;
+ }
+ };
+ Tone.Emitter.prototype.dispose = function () {
+ Tone.prototype.dispose.call(this);
+ this._events = null;
+ return this;
+ };
+ return Tone.Emitter;
+}(Tone_core_Tone);
+/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/
+var Tone_core_Context;
+Tone_core_Context = function (Tone) {
+ if (!window.hasOwnProperty('AudioContext') && window.hasOwnProperty('webkitAudioContext')) {
+ window.AudioContext = window.webkitAudioContext;
+ }
+ Tone.Context = function (context) {
+ Tone.Emitter.call(this);
+ if (!context) {
+ context = new window.AudioContext();
+ }
+ this._context = context;
+ for (var prop in this._context) {
+ this._defineProperty(this._context, prop);
+ }
+ this._latencyHint = 'interactive';
+ this._lookAhead = 0.1;
+ this._updateInterval = this._lookAhead / 3;
+ this._computedUpdateInterval = 0;
+ this._worker = this._createWorker();
+ this._constants = {};
+ };
+ Tone.extend(Tone.Context, Tone.Emitter);
+ Tone.Emitter.mixin(Tone.Context);
+ Tone.Context.prototype._defineProperty = function (context, prop) {
+ if (this.isUndef(this[prop])) {
+ Object.defineProperty(this, prop, {
+ get: function () {
+ if (typeof context[prop] === 'function') {
+ return context[prop].bind(context);
+ } else {
+ return context[prop];
+ }
+ },
+ set: function (val) {
+ context[prop] = val;
+ }
+ });
+ }
+ };
+ Tone.Context.prototype.now = function () {
+ return this._context.currentTime;
+ };
+ Tone.Context.prototype._createWorker = function () {
+ window.URL = window.URL || window.webkitURL;
+ var blob = new Blob(['var timeoutTime = ' + (this._updateInterval * 1000).toFixed(1) + ';' + 'self.onmessage = function(msg){' + '\ttimeoutTime = parseInt(msg.data);' + '};' + 'function tick(){' + '\tsetTimeout(tick, timeoutTime);' + '\tself.postMessage(\'tick\');' + '}' + 'tick();']);
+ var blobUrl = URL.createObjectURL(blob);
+ var worker = new Worker(blobUrl);
+ worker.addEventListener('message', function () {
+ this.emit('tick');
+ }.bind(this));
+ worker.addEventListener('message', function () {
+ var now = this.now();
+ if (this.isNumber(this._lastUpdate)) {
+ var diff = now - this._lastUpdate;
+ this._computedUpdateInterval = Math.max(diff, this._computedUpdateInterval * 0.97);
+ }
+ this._lastUpdate = now;
+ }.bind(this));
+ return worker;
+ };
+ Tone.Context.prototype.getConstant = function (val) {
+ if (this._constants[val]) {
+ return this._constants[val];
+ } else {
+ var buffer = this._context.createBuffer(1, 128, this._context.sampleRate);
+ var arr = buffer.getChannelData(0);
+ for (var i = 0; i < arr.length; i++) {
+ arr[i] = val;
+ }
+ var constant = this._context.createBufferSource();
+ constant.channelCount = 1;
+ constant.channelCountMode = 'explicit';
+ constant.buffer = buffer;
+ constant.loop = true;
+ constant.start(0);
+ this._constants[val] = constant;
+ return constant;
+ }
+ };
+ Object.defineProperty(Tone.Context.prototype, 'lag', {
+ get: function () {
+ var diff = this._computedUpdateInterval - this._updateInterval;
+ diff = Math.max(diff, 0);
+ return diff;
+ }
+ });
+ Object.defineProperty(Tone.Context.prototype, 'lookAhead', {
+ get: function () {
+ return this._lookAhead;
+ },
+ set: function (lA) {
+ this._lookAhead = lA;
+ }
+ });
+ Object.defineProperty(Tone.Context.prototype, 'updateInterval', {
+ get: function () {
+ return this._updateInterval;
+ },
+ set: function (interval) {
+ this._updateInterval = Math.max(interval, Tone.prototype.blockTime);
+ this._worker.postMessage(Math.max(interval * 1000, 1));
+ }
+ });
+ Object.defineProperty(Tone.Context.prototype, 'latencyHint', {
+ get: function () {
+ return this._latencyHint;
+ },
+ set: function (hint) {
+ var lookAhead = hint;
+ this._latencyHint = hint;
+ if (this.isString(hint)) {
+ switch (hint) {
+ case 'interactive':
+ lookAhead = 0.1;
+ this._context.latencyHint = hint;
+ break;
+ case 'playback':
+ lookAhead = 0.8;
+ this._context.latencyHint = hint;
+ break;
+ case 'balanced':
+ lookAhead = 0.25;
+ this._context.latencyHint = hint;
+ break;
+ case 'fastest':
+ lookAhead = 0.01;
+ break;
+ }
+ }
+ this.lookAhead = lookAhead;
+ this.updateInterval = lookAhead / 3;
+ }
+ });
+ function shimConnect() {
+ var nativeConnect = AudioNode.prototype.connect;
+ var nativeDisconnect = AudioNode.prototype.disconnect;
+ function toneConnect(B, outNum, inNum) {
+ if (B.input) {
+ if (Array.isArray(B.input)) {
+ if (Tone.prototype.isUndef(inNum)) {
+ inNum = 0;
+ }
+ this.connect(B.input[inNum]);
+ } else {
+ this.connect(B.input, outNum, inNum);
+ }
+ } else {
+ try {
+ if (B instanceof AudioNode) {
+ nativeConnect.call(this, B, outNum, inNum);
+ } else {
+ nativeConnect.call(this, B, outNum);
+ }
+ } catch (e) {
+ throw new Error('error connecting to node: ' + B + '\n' + e);
+ }
+ }
+ }
+ function toneDisconnect(B, outNum, inNum) {
+ if (B && B.input && Array.isArray(B.input)) {
+ if (Tone.prototype.isUndef(inNum)) {
+ inNum = 0;
+ }
+ this.disconnect(B.input[inNum], outNum, inNum);
+ } else if (B && B.input) {
+ this.disconnect(B.input, outNum, inNum);
+ } else {
+ try {
+ nativeDisconnect.apply(this, arguments);
+ } catch (e) {
+ throw new Error('error disconnecting node: ' + B + '\n' + e);
+ }
+ }
+ }
+ if (AudioNode.prototype.connect !== toneConnect) {
+ AudioNode.prototype.connect = toneConnect;
+ AudioNode.prototype.disconnect = toneDisconnect;
+ }
+ }
+ if (Tone.supported) {
+ shimConnect();
+ Tone.context = new Tone.Context();
+ } else {
+ console.warn('This browser does not support Tone.js');
+ }
+ return Tone.Context;
+}(Tone_core_Tone);
+var audiocontext;
+'use strict';
+audiocontext = function (StartAudioContext, Context, Tone) {
+ // Create the Audio Context
+ const audiocontext = new window.AudioContext();
+ Tone.context.dispose();
+ Tone.setContext(audiocontext);
+ /**
+ *
+ * function draw() {
+ * background(255);
+ * textAlign(CENTER);
+ *
+ * if (getAudioContext().state !== 'running') {
+ * text('click to start audio', width/2, height/2);
+ * } else {
+ * text('audio is enabled', width/2, height/2);
+ * }
+ * }
+ *
+ * function touchStarted() {
+ * if (getAudioContext().state !== 'running') {
+ * getAudioContext().resume();
+ * }
+ * var synth = new p5.MonoSynth();
+ * synth.play('A4', 0.5, 0, 0.2);
+ * }
+ *
+ *
userStartAudio()
.
+ * Optional parameters let you decide on a specific element that will start the audio context,
+ * and/or call a function once the audio context is started.
+ * function setup() {
+ * var myDiv = createDiv('click to start audio');
+ * myDiv.position(0, 0);
+ *
+ * var mySynth = new p5.MonoSynth();
+ *
+ * // This won't play until the context has started
+ * mySynth.play('A6');
+ *
+ * // Start the audio context on a click/touch event
+ * userStartAudio().then(function() {
+ * myDiv.remove();
+ * });
+ * }
+ *
rampTime
parameter. For more
+ * complex fades, see the Envelope class.
+ *
+ * Alternately, you can pass in a signal source such as an
+ * oscillator to modulate the amplitude with an audio signal.
+ *
+ * .limiter
),
+ * and Gain Nodes for .input
and .output
.
+ *
+ * @property {Object} soundOut
+ */
+ p5.prototype.soundOut = p5.soundOut = p5sound;
+ /**
+ * a silent connection to the DesinationNode
+ * which will ensure that anything connected to it
+ * will not be garbage collected
+ *
+ * @private
+ */
+ p5.soundOut._silentNode = p5sound.audiocontext.createGain();
+ p5.soundOut._silentNode.gain.value = 0;
+ p5.soundOut._silentNode.connect(p5sound.audiocontext.destination);
+ return p5sound;
+}(audiocontext);
+var helpers;
+'use strict';
+helpers = function () {
+ var p5sound = master;
+ /**
+ * @for p5
+ */
+ /**
+ * Returns a number representing the sample rate, in samples per second,
+ * of all sound objects in this audio context. It is determined by the
+ * sampling rate of your operating system's sound card, and it is not
+ * currently possile to change.
+ * It is often 44100, or twice the range of human hearing.
+ *
+ * @method sampleRate
+ * @return {Number} samplerate samples per second
+ */
+ p5.prototype.sampleRate = function () {
+ return p5sound.audiocontext.sampleRate;
+ };
+ /**
+ * Returns the closest MIDI note value for
+ * a given frequency.
+ *
+ * @method freqToMidi
+ * @param {Number} frequency A freqeuncy, for example, the "A"
+ * above Middle C is 440Hz
+ * @return {Number} MIDI note value
+ */
+ p5.prototype.freqToMidi = function (f) {
+ var mathlog2 = Math.log(f / 440) / Math.log(2);
+ var m = Math.round(12 * mathlog2) + 69;
+ return m;
+ };
+ /**
+ * Returns the frequency value of a MIDI note value.
+ * General MIDI treats notes as integers where middle C
+ * is 60, C# is 61, D is 62 etc. Useful for generating
+ * musical frequencies with oscillators.
+ *
+ * @method midiToFreq
+ * @param {Number} midiNote The number of a MIDI note
+ * @return {Number} Frequency value of the given MIDI note
+ * @example
+ *
+ * var notes = [60, 64, 67, 72];
+ * var i = 0;
+ *
+ * function setup() {
+ * osc = new p5.Oscillator('Triangle');
+ * osc.start();
+ * frameRate(1);
+ * }
+ *
+ * function draw() {
+ * var freq = midiToFreq(notes[i]);
+ * osc.freq(freq);
+ * i++;
+ * if (i >= notes.length){
+ * i = 0;
+ * }
+ * }
+ *
+ * function preload() {
+ * // set the global sound formats
+ * soundFormats('mp3', 'ogg');
+ *
+ * // load either beatbox.mp3, or .ogg, depending on browser
+ * mySound = loadSound('assets/beatbox.mp3');
+ * }
+ *
+ * function setup() {
+ * mySound.play();
+ * }
+ *
+ *
+ * function preload() {
+ * soundFormats('mp3', 'ogg');
+ * mySound = loadSound('assets/doorbell.mp3');
+ * }
+ *
+ * function setup() {
+ * mySound.setVolume(0.1);
+ * mySound.play();
+ * }
+ *
+ *
+ * function preload() {
+ * mySound = loadSound('assets/doorbell.mp3');
+ * }
+ *
+ * function setup() {
+ * mySound.setVolume(0.1);
+ * mySound.play();
+ * }
+ *
restart
and
+ * sustain
. Play Mode determines what happens to a
+ * p5.SoundFile if it is triggered while in the middle of playback.
+ * In sustain mode, playback will continue simultaneous to the
+ * new playback. In restart mode, play() will stop playback
+ * and start over. With untilDone, a sound will play only if it's
+ * not already playing. Sustain is the default mode.
+ *
+ * @method playMode
+ * @param {String} str 'restart' or 'sustain' or 'untilDone'
+ * @example
+ *
+ * var mySound;
+ * function preload(){
+ * mySound = loadSound('assets/Damscray_DancingTiger.mp3');
+ * }
+ * function mouseClicked() {
+ * mySound.playMode('sustain');
+ * mySound.play();
+ * }
+ * function keyPressed() {
+ * mySound.playMode('restart');
+ * mySound.play();
+ * }
+ *
+ *
+ * var soundFile;
+ *
+ * function preload() {
+ * soundFormats('ogg', 'mp3');
+ * soundFile = loadSound('assets/Damscray_-_Dancing_Tiger_02.mp3');
+ * }
+ * function setup() {
+ * background(0, 255, 0);
+ * soundFile.setVolume(0.1);
+ * soundFile.loop();
+ * }
+ * function keyTyped() {
+ * if (key == 'p') {
+ * soundFile.pause();
+ * background(255, 0, 0);
+ * }
+ * }
+ *
+ * function keyReleased() {
+ * if (key == 'p') {
+ * soundFile.play();
+ * background(0, 255, 0);
+ * }
+ * }
+ *
+ * rampTime
parameter. For more
+ * complex fades, see the Envelope class.
+ *
+ * Alternately, you can pass in a signal source such as an
+ * oscillator to modulate the amplitude with an audio signal.
+ *
+ * @method setVolume
+ * @param {Number|Object} volume Volume (amplitude) between 0.0
+ * and 1.0 or modulating signal/oscillator
+ * @param {Number} [rampTime] Fade for t seconds
+ * @param {Number} [timeFromNow] Schedule this event to happen at
+ * t seconds in the future
+ */
+ p5.SoundFile.prototype.setVolume = function (vol, _rampTime, _tFromNow) {
+ if (typeof vol === 'number') {
+ var rampTime = _rampTime || 0;
+ var tFromNow = _tFromNow || 0;
+ var now = p5sound.audiocontext.currentTime;
+ var currentVol = this.output.gain.value;
+ this.output.gain.cancelScheduledValues(now + tFromNow);
+ this.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow);
+ this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime);
+ } else if (vol) {
+ vol.connect(this.output.gain);
+ } else {
+ // return the Gain Node
+ return this.output.gain;
+ }
+ };
+ // same as setVolume, to match Processing Sound
+ p5.SoundFile.prototype.amp = p5.SoundFile.prototype.setVolume;
+ // these are the same thing
+ p5.SoundFile.prototype.fade = p5.SoundFile.prototype.setVolume;
+ p5.SoundFile.prototype.getVolume = function () {
+ return this.output.gain.value;
+ };
+ /**
+ * Set the stereo panning of a p5.sound object to
+ * a floating point number between -1.0 (left) and 1.0 (right).
+ * Default is 0.0 (center).
+ *
+ * @method pan
+ * @param {Number} [panValue] Set the stereo panner
+ * @param {Number} [timeFromNow] schedule this event to happen
+ * seconds from now
+ * @example
+ *
+ *
+ * var ball = {};
+ * var soundFile;
+ *
+ * function preload() {
+ * soundFormats('ogg', 'mp3');
+ * soundFile = loadSound('assets/beatbox.mp3');
+ * }
+ *
+ * function draw() {
+ * background(0);
+ * ball.x = constrain(mouseX, 0, width);
+ * ellipse(ball.x, height/2, 20, 20)
+ * }
+ *
+ * function mousePressed(){
+ * // map the ball's x location to a panning degree
+ * // between -1.0 (left) and 1.0 (right)
+ * var panning = map(ball.x, 0., width,-1.0, 1.0);
+ * soundFile.pan(panning);
+ * soundFile.play();
+ * }
+ *
+ * var song;
+ *
+ * function preload() {
+ * song = loadSound('assets/Damscray_DancingTiger.mp3');
+ * }
+ *
+ * function setup() {
+ * song.loop();
+ * }
+ *
+ * function draw() {
+ * background(200);
+ *
+ * // Set the rate to a range between 0.1 and 4
+ * // Changing the rate also alters the pitch
+ * var speed = map(mouseY, 0.1, height, 0, 2);
+ * speed = constrain(speed, 0.01, 4);
+ * song.rate(speed);
+ *
+ * // Draw a circle to show what is going on
+ * stroke(0);
+ * fill(51, 100);
+ * ellipse(mouseX, 100, 48, 48);
+ * }
+ *
+ *
+ *
+ * var drum;
+ *
+ * function preload() {
+ * drum = loadSound('assets/drum.mp3');
+ * }
+ *
+ * function setup() {
+ * drum.reverseBuffer();
+ * drum.play();
+ * }
+ *
+ *
+ *
+ * var mySound;
+ * function preload() {
+ * mySound = loadSound('assets/beat.mp3');
+ * }
+ *
+ * function setup() {
+ * background(0);
+ * noStroke();
+ * fill(255);
+ * textAlign(CENTER);
+ * text('click to play', width/2, height/2);
+ *
+ * // schedule calls to changeText
+ * mySound.addCue(0.50, changeText, "hello" );
+ * mySound.addCue(1.00, changeText, "p5" );
+ * mySound.addCue(1.50, changeText, "what" );
+ * mySound.addCue(2.00, changeText, "do" );
+ * mySound.addCue(2.50, changeText, "you" );
+ * mySound.addCue(3.00, changeText, "want" );
+ * mySound.addCue(4.00, changeText, "to" );
+ * mySound.addCue(5.00, changeText, "make" );
+ * mySound.addCue(6.00, changeText, "?" );
+ * }
+ *
+ * function changeText(val) {
+ * background(0);
+ * text(val, width/2, height/2);
+ * }
+ *
+ * function mouseClicked() {
+ * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {
+ * if (mySound.isPlaying() ) {
+ * mySound.stop();
+ * } else {
+ * mySound.play();
+ * }
+ * }
+ * }
+ *
+ * var inp, button, mySound;
+ * var fileName = 'cool';
+ * function preload() {
+ * mySound = loadSound('assets/doorbell.mp3');
+ * }
+ * function setup() {
+ * btn = createButton('click to save file');
+ * btn.position(0, 0);
+ * btn.mouseClicked(handleMouseClick);
+ * }
+ *
+ * function handleMouseClick() {
+ * mySound.save(fileName);
+ * }
+ *
+ *
+ * function preload() {
+ * mySound = loadSound('assets/doorbell.mp3');
+ * }
+ *
+ * function setup() {
+ * noCanvas();
+ * var soundBlob = mySound.getBlob();
+ *
+ * // Now we can send the blob to a server...
+ * var serverUrl = 'https://jsonplaceholder.typicode.com/posts';
+ * var httpRequestOptions = {
+ * method: 'POST',
+ * body: new FormData().append('soundBlob', soundBlob),
+ * headers: new Headers({
+ * 'Content-Type': 'multipart/form-data'
+ * })
+ * };
+ * httpDo(serverUrl, httpRequestOptions);
+ *
+ * // We can also create an `ObjectURL` pointing to the Blob
+ * var blobUrl = URL.createObjectURL(soundBlob);
+ *
+ * // The `
+ * var sound, amplitude, cnv;
+ *
+ * function preload(){
+ * sound = loadSound('assets/beat.mp3');
+ * }
+ * function setup() {
+ * cnv = createCanvas(100,100);
+ * amplitude = new p5.Amplitude();
+ *
+ * // start / stop the sound when canvas is clicked
+ * cnv.mouseClicked(function() {
+ * if (sound.isPlaying() ){
+ * sound.stop();
+ * } else {
+ * sound.play();
+ * }
+ * });
+ * }
+ * function draw() {
+ * background(0);
+ * fill(255);
+ * var level = amplitude.getLevel();
+ * var size = map(level, 0, 1, 0, 200);
+ * ellipse(width/2, height/2, size, size);
+ * }
+ *
+ *
+ * function preload(){
+ * sound1 = loadSound('assets/beat.mp3');
+ * sound2 = loadSound('assets/drum.mp3');
+ * }
+ * function setup(){
+ * amplitude = new p5.Amplitude();
+ * sound1.play();
+ * sound2.play();
+ * amplitude.setInput(sound2);
+ * }
+ * function draw() {
+ * background(0);
+ * fill(255);
+ * var level = amplitude.getLevel();
+ * var size = map(level, 0, 1, 0, 200);
+ * ellipse(width/2, height/2, size, size);
+ * }
+ * function mouseClicked(){
+ * sound1.stop();
+ * sound2.stop();
+ * }
+ *
+ * function preload(){
+ * sound = loadSound('assets/beat.mp3');
+ * }
+ * function setup() {
+ * amplitude = new p5.Amplitude();
+ * sound.play();
+ * }
+ * function draw() {
+ * background(0);
+ * fill(255);
+ * var level = amplitude.getLevel();
+ * var size = map(level, 0, 1, 0, 200);
+ * ellipse(width/2, height/2, size, size);
+ * }
+ * function mouseClicked(){
+ * sound.stop();
+ * }
+ *
• FFT.waveform()
computes
+ * amplitude values along the time domain. The array indices correspond
+ * to samples across a brief moment in time. Each value represents
+ * amplitude of the waveform at that sample of time.
+ * • FFT.analyze()
computes amplitude values along the
+ * frequency domain. The array indices correspond to frequencies (i.e.
+ * pitches), from the lowest to the highest that humans can hear. Each
+ * value represents amplitude at that slice of the frequency spectrum.
+ * Use with getEnergy()
to measure amplitude at specific
+ * frequencies, or within a range of frequencies. bins
. The array is 1024 bins long by default.
+ * You can change the bin array length, but it must be a power of 2
+ * between 16 and 1024 in order for the FFT algorithm to function
+ * correctly. The actual size of the FFT buffer is twice the
+ * number of bins, so given a standard sample rate, the buffer is
+ * 2048/44100 seconds long.
+ * function preload(){
+ * sound = loadSound('assets/Damscray_DancingTiger.mp3');
+ * }
+ *
+ * function setup(){
+ * var cnv = createCanvas(100,100);
+ * cnv.mouseClicked(togglePlay);
+ * fft = new p5.FFT();
+ * sound.amp(0.2);
+ * }
+ *
+ * function draw(){
+ * background(0);
+ *
+ * var spectrum = fft.analyze();
+ * noStroke();
+ * fill(0,255,0); // spectrum is green
+ * for (var i = 0; i< spectrum.length; i++){
+ * var x = map(i, 0, spectrum.length, 0, width);
+ * var h = -height + map(spectrum[i], 0, 255, height, 0);
+ * rect(x, height, width / spectrum.length, h )
+ * }
+ *
+ * var waveform = fft.waveform();
+ * noFill();
+ * beginShape();
+ * stroke(255,0,0); // waveform is red
+ * strokeWeight(1);
+ * for (var i = 0; i< waveform.length; i++){
+ * var x = map(i, 0, waveform.length, 0, width);
+ * var y = map( waveform[i], -1, 1, 0, height);
+ * vertex(x,y);
+ * }
+ * endShape();
+ *
+ * text('click to play/pause', 4, 10);
+ * }
+ *
+ * // fade sound if mouse is over canvas
+ * function togglePlay() {
+ * if (sound.isPlaying()) {
+ * sound.pause();
+ * } else {
+ * sound.loop();
+ * }
+ * }
+ *
getEnergy()
.
+ *
+ * @method analyze
+ * @param {Number} [bins] Must be a power of two between
+ * 16 and 1024. Defaults to 1024.
+ * @param {Number} [scale] If "dB," returns decibel
+ * float measurements between
+ * -140 and 0 (max).
+ * Otherwise returns integers from 0-255.
+ * @return {Array} spectrum Array of energy (amplitude/volume)
+ * values across the frequency spectrum.
+ * Lowest energy (silence) = 0, highest
+ * possible is 255.
+ * @example
+ *
+ * var osc;
+ * var fft;
+ *
+ * function setup(){
+ * createCanvas(100,100);
+ * osc = new p5.Oscillator();
+ * osc.amp(0);
+ * osc.start();
+ * fft = new p5.FFT();
+ * }
+ *
+ * function draw(){
+ * background(0);
+ *
+ * var freq = map(mouseX, 0, 800, 20, 15000);
+ * freq = constrain(freq, 1, 20000);
+ * osc.freq(freq);
+ *
+ * var spectrum = fft.analyze();
+ * noStroke();
+ * fill(0,255,0); // spectrum is green
+ * for (var i = 0; i< spectrum.length; i++){
+ * var x = map(i, 0, spectrum.length, 0, width);
+ * var h = -height + map(spectrum[i], 0, 255, height, 0);
+ * rect(x, height, width / spectrum.length, h );
+ * }
+ *
+ * stroke(255);
+ * text('Freq: ' + round(freq)+'Hz', 10, 10);
+ *
+ * isMouseOverCanvas();
+ * }
+ *
+ * // only play sound when mouse is over canvas
+ * function isMouseOverCanvas() {
+ * var mX = mouseX, mY = mouseY;
+ * if (mX > 0 && mX < width && mY < height && mY > 0) {
+ * osc.amp(0.5, 0.2);
+ * } else {
+ * osc.amp(0, 0.2);
+ * }
+ * }
+ *
+ *
+ *
+ *function setup(){
+ * cnv = createCanvas(100,100);
+ * sound = new p5.AudioIn();
+ * sound.start();
+ * fft = new p5.FFT();
+ * sound.connect(fft);
+ *}
+ *
+ *
+ *function draw(){
+ *
+ * var centroidplot = 0.0;
+ * var spectralCentroid = 0;
+ *
+ *
+ * background(0);
+ * stroke(0,255,0);
+ * var spectrum = fft.analyze();
+ * fill(0,255,0); // spectrum is green
+ *
+ * //draw the spectrum
+ * for (var i = 0; i< spectrum.length; i++){
+ * var x = map(log(i), 0, log(spectrum.length), 0, width);
+ * var h = map(spectrum[i], 0, 255, 0, height);
+ * var rectangle_width = (log(i+1)-log(i))*(width/log(spectrum.length));
+ * rect(x, height, rectangle_width, -h )
+ * }
+
+ * var nyquist = 22050;
+ *
+ * // get the centroid
+ * spectralCentroid = fft.getCentroid();
+ *
+ * // the mean_freq_index calculation is for the display.
+ * var mean_freq_index = spectralCentroid/(nyquist/spectrum.length);
+ *
+ * centroidplot = map(log(mean_freq_index), 0, log(spectrum.length), 0, width);
+ *
+ *
+ * stroke(255,0,0); // the line showing where the centroid is will be red
+ *
+ * rect(centroidplot, 0, width / spectrum.length, height)
+ * noStroke();
+ * fill(255,255,255); // text is white
+ * text("centroid: ", 10, 20);
+ * text(round(spectralCentroid)+" Hz", 10, 40);
+ *}
+ *
p5.Signal is a constant audio-rate signal used by p5.Oscillator + * and p5.Envelope for modulation math.
+ * + *This is necessary because Web Audio is processed on a seprate clock. + * For example, the p5 draw loop runs about 60 times per second. But + * the audio clock must process samples 44100 times per second. If we + * want to add a value to each of those samples, we can't do it in the + * draw 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 + * a Tone.Signal from the Tone.js library by Yotam Mann. + * If you want to work directly with audio signals for modular + * synthesis, check out + * tone.js.
+ * + * @class p5.Signal + * @constructor + * @return {Tone.Signal} A Signal object from the Tone.js library + * @example + *
+ * function setup() {
+ * carrier = new p5.Oscillator('sine');
+ * carrier.amp(1); // set amplitude
+ * carrier.freq(220); // set frequency
+ * carrier.start(); // start oscillating
+ *
+ * modulator = new p5.Oscillator('sawtooth');
+ * modulator.disconnect();
+ * modulator.amp(1);
+ * modulator.freq(4);
+ * modulator.start();
+ *
+ * // Modulator's default amplitude range is -1 to 1.
+ * // Multiply it by -200, so the range is -200 to 200
+ * // then add 220 so the range is 20 to 420
+ * carrier.freq( modulator.mult(-200).add(220) );
+ * }
+ *
Creates a signal that oscillates between -1.0 and 1.0. + * By default, the oscillation takes the form of a sinusoidal + * shape ('sine'). Additional types include 'triangle', + * 'sawtooth' and 'square'. The frequency defaults to + * 440 oscillations per second (440Hz, equal to the pitch of an + * 'A' note).
+ * + *Set the type of oscillation with setType(), or by instantiating a + * specific oscillator: p5.SinOsc, p5.TriOsc, p5.SqrOsc, or p5.SawOsc. + *
+ * + * @class p5.Oscillator + * @constructor + * @param {Number} [freq] frequency defaults to 440Hz + * @param {String} [type] type of oscillator. Options: + * 'sine' (default), 'triangle', + * 'sawtooth', 'square' + * @example + *
+ * var osc;
+ * var playing = false;
+ *
+ * function setup() {
+ * backgroundColor = color(255,0,255);
+ * textAlign(CENTER);
+ *
+ * osc = new p5.Oscillator();
+ * osc.setType('sine');
+ * osc.freq(240);
+ * osc.amp(0);
+ * osc.start();
+ * }
+ *
+ * function draw() {
+ * background(backgroundColor)
+ * text('click to play', width/2, height/2);
+ * }
+ *
+ * function mouseClicked() {
+ * if (mouseX > 0 && mouseX < width && mouseY < height && mouseY > 0) {
+ * if (!playing) {
+ * // ramp amplitude to 0.5 over 0.05 seconds
+ * osc.amp(0.5, 0.05);
+ * playing = true;
+ * backgroundColor = color(0,255,255);
+ * } else {
+ * // ramp amplitude to 0 over 0.5 seconds
+ * osc.amp(0, 0.5);
+ * playing = false;
+ * backgroundColor = color(255,0,255);
+ * }
+ * }
+ * }
+ *
+ * var osc = new p5.Oscillator(300);
+ * osc.start();
+ * osc.freq(40, 10);
+ *
new p5.SinOsc()
.
+ * This creates a Sine Wave Oscillator and is
+ * equivalent to new p5.Oscillator('sine')
+ *
or creating a p5.Oscillator and then calling
+ * its method setType('sine')
.
+ * See p5.Oscillator for methods.
+ *
+ * @class p5.SinOsc
+ * @constructor
+ * @extends p5.Oscillator
+ * @param {Number} [freq] Set the frequency
+ */
+ p5.SinOsc = function (freq) {
+ p5.Oscillator.call(this, freq, 'sine');
+ };
+ p5.SinOsc.prototype = Object.create(p5.Oscillator.prototype);
+ /**
+ * Constructor: new p5.TriOsc()
.
+ * This creates a Triangle Wave Oscillator and is
+ * equivalent to new p5.Oscillator('triangle')
+ *
or creating a p5.Oscillator and then calling
+ * its method setType('triangle')
.
+ * See p5.Oscillator for methods.
+ *
+ * @class p5.TriOsc
+ * @constructor
+ * @extends p5.Oscillator
+ * @param {Number} [freq] Set the frequency
+ */
+ p5.TriOsc = function (freq) {
+ p5.Oscillator.call(this, freq, 'triangle');
+ };
+ p5.TriOsc.prototype = Object.create(p5.Oscillator.prototype);
+ /**
+ * Constructor: new p5.SawOsc()
.
+ * This creates a SawTooth Wave Oscillator and is
+ * equivalent to new p5.Oscillator('sawtooth')
+ *
or creating a p5.Oscillator and then calling
+ * its method setType('sawtooth')
.
+ * See p5.Oscillator for methods.
+ *
+ * @class p5.SawOsc
+ * @constructor
+ * @extends p5.Oscillator
+ * @param {Number} [freq] Set the frequency
+ */
+ p5.SawOsc = function (freq) {
+ p5.Oscillator.call(this, freq, 'sawtooth');
+ };
+ p5.SawOsc.prototype = Object.create(p5.Oscillator.prototype);
+ /**
+ * Constructor: new p5.SqrOsc()
.
+ * This creates a Square Wave Oscillator and is
+ * equivalent to new p5.Oscillator('square')
+ *
or creating a p5.Oscillator and then calling
+ * its method setType('square')
.
+ * See p5.Oscillator for methods.
+ *
+ * @class p5.SqrOsc
+ * @constructor
+ * @extends p5.Oscillator
+ * @param {Number} [freq] Set the frequency
+ */
+ p5.SqrOsc = function (freq) {
+ p5.Oscillator.call(this, freq, 'square');
+ };
+ p5.SqrOsc.prototype = Object.create(p5.Oscillator.prototype);
+}(master, Tone_signal_Add, Tone_signal_Multiply, Tone_signal_Scale);
+/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/
+var Tone_core_Timeline;
+Tone_core_Timeline = function (Tone) {
+ 'use strict';
+ Tone.Timeline = function () {
+ var options = this.optionsObject(arguments, ['memory'], Tone.Timeline.defaults);
+ this._timeline = [];
+ this._toRemove = [];
+ this._iterating = false;
+ this.memory = options.memory;
+ };
+ Tone.extend(Tone.Timeline);
+ Tone.Timeline.defaults = { 'memory': Infinity };
+ Object.defineProperty(Tone.Timeline.prototype, 'length', {
+ get: function () {
+ return this._timeline.length;
+ }
+ });
+ Tone.Timeline.prototype.add = function (event) {
+ if (this.isUndef(event.time)) {
+ throw new Error('Tone.Timeline: events must have a time attribute');
+ }
+ if (this._timeline.length) {
+ var index = this._search(event.time);
+ this._timeline.splice(index + 1, 0, event);
+ } else {
+ this._timeline.push(event);
+ }
+ if (this.length > this.memory) {
+ var diff = this.length - this.memory;
+ this._timeline.splice(0, diff);
+ }
+ return this;
+ };
+ Tone.Timeline.prototype.remove = function (event) {
+ if (this._iterating) {
+ this._toRemove.push(event);
+ } else {
+ var index = this._timeline.indexOf(event);
+ if (index !== -1) {
+ this._timeline.splice(index, 1);
+ }
+ }
+ return this;
+ };
+ Tone.Timeline.prototype.get = function (time) {
+ var index = this._search(time);
+ if (index !== -1) {
+ return this._timeline[index];
+ } else {
+ return null;
+ }
+ };
+ Tone.Timeline.prototype.peek = function () {
+ return this._timeline[0];
+ };
+ Tone.Timeline.prototype.shift = function () {
+ return this._timeline.shift();
+ };
+ Tone.Timeline.prototype.getAfter = function (time) {
+ var index = this._search(time);
+ if (index + 1 < this._timeline.length) {
+ return this._timeline[index + 1];
+ } else {
+ return null;
+ }
+ };
+ Tone.Timeline.prototype.getBefore = function (time) {
+ var len = this._timeline.length;
+ if (len > 0 && this._timeline[len - 1].time < time) {
+ return this._timeline[len - 1];
+ }
+ var index = this._search(time);
+ if (index - 1 >= 0) {
+ return this._timeline[index - 1];
+ } else {
+ return null;
+ }
+ };
+ Tone.Timeline.prototype.cancel = function (after) {
+ if (this._timeline.length > 1) {
+ var index = this._search(after);
+ if (index >= 0) {
+ if (this._timeline[index].time === after) {
+ for (var i = index; i >= 0; i--) {
+ if (this._timeline[i].time === after) {
+ index = i;
+ } else {
+ break;
+ }
+ }
+ this._timeline = this._timeline.slice(0, index);
+ } else {
+ this._timeline = this._timeline.slice(0, index + 1);
+ }
+ } else {
+ this._timeline = [];
+ }
+ } else if (this._timeline.length === 1) {
+ if (this._timeline[0].time >= after) {
+ this._timeline = [];
+ }
+ }
+ return this;
+ };
+ Tone.Timeline.prototype.cancelBefore = function (time) {
+ if (this._timeline.length) {
+ var index = this._search(time);
+ if (index >= 0) {
+ this._timeline = this._timeline.slice(index + 1);
+ }
+ }
+ return this;
+ };
+ Tone.Timeline.prototype._search = function (time) {
+ var beginning = 0;
+ var len = this._timeline.length;
+ var end = len;
+ if (len > 0 && this._timeline[len - 1].time <= time) {
+ return len - 1;
+ }
+ while (beginning < end) {
+ var midPoint = Math.floor(beginning + (end - beginning) / 2);
+ var event = this._timeline[midPoint];
+ var nextEvent = this._timeline[midPoint + 1];
+ if (event.time === time) {
+ for (var i = midPoint; i < this._timeline.length; i++) {
+ var testEvent = this._timeline[i];
+ if (testEvent.time === time) {
+ midPoint = i;
+ }
+ }
+ return midPoint;
+ } else if (event.time < time && nextEvent.time > time) {
+ return midPoint;
+ } else if (event.time > time) {
+ end = midPoint;
+ } else if (event.time < time) {
+ beginning = midPoint + 1;
+ }
+ }
+ return -1;
+ };
+ Tone.Timeline.prototype._iterate = function (callback, lowerBound, upperBound) {
+ this._iterating = true;
+ lowerBound = this.defaultArg(lowerBound, 0);
+ upperBound = this.defaultArg(upperBound, this._timeline.length - 1);
+ for (var i = lowerBound; i <= upperBound; i++) {
+ callback(this._timeline[i]);
+ }
+ this._iterating = false;
+ if (this._toRemove.length > 0) {
+ for (var j = 0; j < this._toRemove.length; j++) {
+ var index = this._timeline.indexOf(this._toRemove[j]);
+ if (index !== -1) {
+ this._timeline.splice(index, 1);
+ }
+ }
+ this._toRemove = [];
+ }
+ };
+ Tone.Timeline.prototype.forEach = function (callback) {
+ this._iterate(callback);
+ return this;
+ };
+ Tone.Timeline.prototype.forEachBefore = function (time, callback) {
+ var upperBound = this._search(time);
+ if (upperBound !== -1) {
+ this._iterate(callback, 0, upperBound);
+ }
+ return this;
+ };
+ Tone.Timeline.prototype.forEachAfter = function (time, callback) {
+ var lowerBound = this._search(time);
+ this._iterate(callback, lowerBound + 1);
+ return this;
+ };
+ Tone.Timeline.prototype.forEachFrom = function (time, callback) {
+ var lowerBound = this._search(time);
+ while (lowerBound >= 0 && this._timeline[lowerBound].time >= time) {
+ lowerBound--;
+ }
+ this._iterate(callback, lowerBound + 1);
+ return this;
+ };
+ Tone.Timeline.prototype.forEachAtTime = function (time, callback) {
+ var upperBound = this._search(time);
+ if (upperBound !== -1) {
+ this._iterate(function (event) {
+ if (event.time === time) {
+ callback(event);
+ }
+ }, 0, upperBound);
+ }
+ return this;
+ };
+ Tone.Timeline.prototype.dispose = function () {
+ Tone.prototype.dispose.call(this);
+ this._timeline = null;
+ this._toRemove = null;
+ };
+ return Tone.Timeline;
+}(Tone_core_Tone);
+/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/
+var Tone_signal_TimelineSignal;
+Tone_signal_TimelineSignal = function (Tone) {
+ 'use strict';
+ Tone.TimelineSignal = function () {
+ var options = this.optionsObject(arguments, [
+ 'value',
+ 'units'
+ ], Tone.Signal.defaults);
+ this._events = new Tone.Timeline(10);
+ Tone.Signal.apply(this, options);
+ options.param = this._param;
+ Tone.Param.call(this, options);
+ this._initial = this._fromUnits(this._param.value);
+ };
+ Tone.extend(Tone.TimelineSignal, Tone.Param);
+ Tone.TimelineSignal.Type = {
+ Linear: 'linear',
+ Exponential: 'exponential',
+ Target: 'target',
+ Curve: 'curve',
+ Set: 'set'
+ };
+ Object.defineProperty(Tone.TimelineSignal.prototype, 'value', {
+ get: function () {
+ var now = this.now();
+ var val = this.getValueAtTime(now);
+ return this._toUnits(val);
+ },
+ set: function (value) {
+ var convertedVal = this._fromUnits(value);
+ this._initial = convertedVal;
+ this.cancelScheduledValues();
+ this._param.value = convertedVal;
+ }
+ });
+ Tone.TimelineSignal.prototype.setValueAtTime = function (value, startTime) {
+ value = this._fromUnits(value);
+ startTime = this.toSeconds(startTime);
+ this._events.add({
+ 'type': Tone.TimelineSignal.Type.Set,
+ 'value': value,
+ 'time': startTime
+ });
+ this._param.setValueAtTime(value, startTime);
+ return this;
+ };
+ Tone.TimelineSignal.prototype.linearRampToValueAtTime = function (value, endTime) {
+ value = this._fromUnits(value);
+ endTime = this.toSeconds(endTime);
+ this._events.add({
+ 'type': Tone.TimelineSignal.Type.Linear,
+ 'value': value,
+ 'time': endTime
+ });
+ this._param.linearRampToValueAtTime(value, endTime);
+ return this;
+ };
+ Tone.TimelineSignal.prototype.exponentialRampToValueAtTime = function (value, endTime) {
+ endTime = this.toSeconds(endTime);
+ var beforeEvent = this._searchBefore(endTime);
+ if (beforeEvent && beforeEvent.value === 0) {
+ this.setValueAtTime(this._minOutput, beforeEvent.time);
+ }
+ value = this._fromUnits(value);
+ var setValue = Math.max(value, this._minOutput);
+ this._events.add({
+ 'type': Tone.TimelineSignal.Type.Exponential,
+ 'value': setValue,
+ 'time': endTime
+ });
+ if (value < this._minOutput) {
+ this._param.exponentialRampToValueAtTime(this._minOutput, endTime - this.sampleTime);
+ this.setValueAtTime(0, endTime);
+ } else {
+ this._param.exponentialRampToValueAtTime(value, endTime);
+ }
+ return this;
+ };
+ Tone.TimelineSignal.prototype.setTargetAtTime = function (value, startTime, timeConstant) {
+ value = this._fromUnits(value);
+ value = Math.max(this._minOutput, value);
+ timeConstant = Math.max(this._minOutput, timeConstant);
+ startTime = this.toSeconds(startTime);
+ this._events.add({
+ 'type': Tone.TimelineSignal.Type.Target,
+ 'value': value,
+ 'time': startTime,
+ 'constant': timeConstant
+ });
+ this._param.setTargetAtTime(value, startTime, timeConstant);
+ return this;
+ };
+ Tone.TimelineSignal.prototype.setValueCurveAtTime = function (values, startTime, duration, scaling) {
+ scaling = this.defaultArg(scaling, 1);
+ var floats = new Array(values.length);
+ for (var i = 0; i < floats.length; i++) {
+ floats[i] = this._fromUnits(values[i]) * scaling;
+ }
+ startTime = this.toSeconds(startTime);
+ duration = this.toSeconds(duration);
+ this._events.add({
+ 'type': Tone.TimelineSignal.Type.Curve,
+ 'value': floats,
+ 'time': startTime,
+ 'duration': duration
+ });
+ this._param.setValueAtTime(floats[0], startTime);
+ for (var j = 1; j < floats.length; j++) {
+ var segmentTime = startTime + j / (floats.length - 1) * duration;
+ this._param.linearRampToValueAtTime(floats[j], segmentTime);
+ }
+ return this;
+ };
+ Tone.TimelineSignal.prototype.cancelScheduledValues = function (after) {
+ after = this.toSeconds(after);
+ this._events.cancel(after);
+ this._param.cancelScheduledValues(after);
+ return this;
+ };
+ Tone.TimelineSignal.prototype.setRampPoint = function (time) {
+ time = this.toSeconds(time);
+ var val = this._toUnits(this.getValueAtTime(time));
+ var before = this._searchBefore(time);
+ if (before && before.time === time) {
+ this.cancelScheduledValues(time + this.sampleTime);
+ } else if (before && before.type === Tone.TimelineSignal.Type.Curve && before.time + before.duration > time) {
+ this.cancelScheduledValues(time);
+ this.linearRampToValueAtTime(val, time);
+ } else {
+ var after = this._searchAfter(time);
+ if (after) {
+ this.cancelScheduledValues(time);
+ if (after.type === Tone.TimelineSignal.Type.Linear) {
+ this.linearRampToValueAtTime(val, time);
+ } else if (after.type === Tone.TimelineSignal.Type.Exponential) {
+ this.exponentialRampToValueAtTime(val, time);
+ }
+ }
+ this.setValueAtTime(val, time);
+ }
+ return this;
+ };
+ Tone.TimelineSignal.prototype.linearRampToValueBetween = function (value, start, finish) {
+ this.setRampPoint(start);
+ this.linearRampToValueAtTime(value, finish);
+ return this;
+ };
+ Tone.TimelineSignal.prototype.exponentialRampToValueBetween = function (value, start, finish) {
+ this.setRampPoint(start);
+ this.exponentialRampToValueAtTime(value, finish);
+ return this;
+ };
+ Tone.TimelineSignal.prototype._searchBefore = function (time) {
+ return this._events.get(time);
+ };
+ Tone.TimelineSignal.prototype._searchAfter = function (time) {
+ return this._events.getAfter(time);
+ };
+ Tone.TimelineSignal.prototype.getValueAtTime = function (time) {
+ time = this.toSeconds(time);
+ var after = this._searchAfter(time);
+ var before = this._searchBefore(time);
+ var value = this._initial;
+ if (before === null) {
+ value = this._initial;
+ } else if (before.type === Tone.TimelineSignal.Type.Target) {
+ var previous = this._events.getBefore(before.time);
+ var previouVal;
+ if (previous === null) {
+ previouVal = this._initial;
+ } else {
+ previouVal = previous.value;
+ }
+ value = this._exponentialApproach(before.time, previouVal, before.value, before.constant, time);
+ } else if (before.type === Tone.TimelineSignal.Type.Curve) {
+ value = this._curveInterpolate(before.time, before.value, before.duration, time);
+ } else if (after === null) {
+ value = before.value;
+ } else if (after.type === Tone.TimelineSignal.Type.Linear) {
+ value = this._linearInterpolate(before.time, before.value, after.time, after.value, time);
+ } else if (after.type === Tone.TimelineSignal.Type.Exponential) {
+ value = this._exponentialInterpolate(before.time, before.value, after.time, after.value, time);
+ } else {
+ value = before.value;
+ }
+ return value;
+ };
+ Tone.TimelineSignal.prototype.connect = Tone.SignalBase.prototype.connect;
+ Tone.TimelineSignal.prototype._exponentialApproach = function (t0, v0, v1, timeConstant, t) {
+ return v1 + (v0 - v1) * Math.exp(-(t - t0) / timeConstant);
+ };
+ Tone.TimelineSignal.prototype._linearInterpolate = function (t0, v0, t1, v1, t) {
+ return v0 + (v1 - v0) * ((t - t0) / (t1 - t0));
+ };
+ Tone.TimelineSignal.prototype._exponentialInterpolate = function (t0, v0, t1, v1, t) {
+ v0 = Math.max(this._minOutput, v0);
+ return v0 * Math.pow(v1 / v0, (t - t0) / (t1 - t0));
+ };
+ Tone.TimelineSignal.prototype._curveInterpolate = function (start, curve, duration, time) {
+ var len = curve.length;
+ if (time >= start + duration) {
+ return curve[len - 1];
+ } else if (time <= start) {
+ return curve[0];
+ } else {
+ var progress = (time - start) / duration;
+ var lowerIndex = Math.floor((len - 1) * progress);
+ var upperIndex = Math.ceil((len - 1) * progress);
+ var lowerVal = curve[lowerIndex];
+ var upperVal = curve[upperIndex];
+ if (upperIndex === lowerIndex) {
+ return lowerVal;
+ } else {
+ return this._linearInterpolate(lowerIndex, lowerVal, upperIndex, upperVal, progress * (len - 1));
+ }
+ }
+ };
+ Tone.TimelineSignal.prototype.dispose = function () {
+ Tone.Signal.prototype.dispose.call(this);
+ Tone.Param.prototype.dispose.call(this);
+ this._events.dispose();
+ this._events = null;
+ };
+ return Tone.TimelineSignal;
+}(Tone_core_Tone, Tone_signal_Signal);
+var envelope;
+'use strict';
+envelope = function () {
+ var p5sound = master;
+ var Add = Tone_signal_Add;
+ var Mult = Tone_signal_Multiply;
+ var Scale = Tone_signal_Scale;
+ var TimelineSignal = Tone_signal_TimelineSignal;
+ /**
+ * Envelopes are pre-defined amplitude distribution over time.
+ * Typically, envelopes are used to control the output volume
+ * of an object, a series of fades referred to as Attack, Decay,
+ * Sustain and Release (
+ * ADSR
+ * ). Envelopes can also control other Web Audio Parameters—for example, a p5.Envelope can
+ * control an Oscillator's frequency like this: osc.freq(env)
.
Use setRange
to change the attack/release level.
+ * Use setADSR
to change attackTime, decayTime, sustainPercent and releaseTime.
Use the play
method to play the entire envelope,
+ * the ramp
method for a pingable trigger,
+ * or triggerAttack
/
+ * triggerRelease
to trigger noteOn/noteOff.
+ * var attackLevel = 1.0;
+ * var releaseLevel = 0;
+ *
+ * var attackTime = 0.001;
+ * var decayTime = 0.2;
+ * var susPercent = 0.2;
+ * var releaseTime = 0.5;
+ *
+ * var env, triOsc;
+ *
+ * function setup() {
+ * var cnv = createCanvas(100, 100);
+ *
+ * textAlign(CENTER);
+ * text('click to play', width/2, height/2);
+ *
+ * env = new p5.Envelope();
+ * env.setADSR(attackTime, decayTime, susPercent, releaseTime);
+ * env.setRange(attackLevel, releaseLevel);
+ *
+ * triOsc = new p5.Oscillator('triangle');
+ * triOsc.amp(env);
+ * triOsc.start();
+ * triOsc.freq(220);
+ *
+ * cnv.mousePressed(playEnv);
+ * }
+ *
+ * function playEnv() {
+ * env.play();
+ * }
+ *
+ * var t1 = 0.1; // attack time in seconds
+ * var l1 = 0.7; // attack level 0.0 to 1.0
+ * var t2 = 0.3; // decay time in seconds
+ * var l2 = 0.1; // decay level 0.0 to 1.0
+ * var t3 = 0.2; // sustain time in seconds
+ * var l3 = 0.5; // sustain level 0.0 to 1.0
+ * // release level defaults to zero
+ *
+ * var env;
+ * var triOsc;
+ *
+ * function setup() {
+ * background(0);
+ * noStroke();
+ * fill(255);
+ * textAlign(CENTER);
+ * text('click to play', width/2, height/2);
+ *
+ * env = new p5.Envelope(t1, l1, t2, l2, t3, l3);
+ * triOsc = new p5.Oscillator('triangle');
+ * triOsc.amp(env); // give the env control of the triOsc's amp
+ * triOsc.start();
+ * }
+ *
+ * // mouseClick triggers envelope if over canvas
+ * function mouseClicked() {
+ * // is mouse over canvas?
+ * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {
+ * env.play(triOsc);
+ * }
+ * }
+ *
setRange
),
+ * then decayLevel would increase proportionally, to become 0.5.
+ * @param {Number} [releaseTime] Time in seconds from now (defaults to 0)
+ * @example
+ *
+ * var attackLevel = 1.0;
+ * var releaseLevel = 0;
+ *
+ * var attackTime = 0.001;
+ * var decayTime = 0.2;
+ * var susPercent = 0.2;
+ * var releaseTime = 0.5;
+ *
+ * var env, triOsc;
+ *
+ * function setup() {
+ * var cnv = createCanvas(100, 100);
+ *
+ * textAlign(CENTER);
+ * text('click to play', width/2, height/2);
+ *
+ * env = new p5.Envelope();
+ * env.setADSR(attackTime, decayTime, susPercent, releaseTime);
+ * env.setRange(attackLevel, releaseLevel);
+ *
+ * triOsc = new p5.Oscillator('triangle');
+ * triOsc.amp(env);
+ * triOsc.start();
+ * triOsc.freq(220);
+ *
+ * cnv.mousePressed(playEnv);
+ * }
+ *
+ * function playEnv() {
+ * env.play();
+ * }
+ *
+ * var attackLevel = 1.0;
+ * var releaseLevel = 0;
+ *
+ * var attackTime = 0.001;
+ * var decayTime = 0.2;
+ * var susPercent = 0.2;
+ * var releaseTime = 0.5;
+ *
+ * var env, triOsc;
+ *
+ * function setup() {
+ * var cnv = createCanvas(100, 100);
+ *
+ * textAlign(CENTER);
+ * text('click to play', width/2, height/2);
+ *
+ * env = new p5.Envelope();
+ * env.setADSR(attackTime, decayTime, susPercent, releaseTime);
+ * env.setRange(attackLevel, releaseLevel);
+ *
+ * triOsc = new p5.Oscillator('triangle');
+ * triOsc.amp(env);
+ * triOsc.start();
+ * triOsc.freq(220);
+ *
+ * cnv.mousePressed(playEnv);
+ * }
+ *
+ * function playEnv() {
+ * env.play();
+ * }
+ *
+ * var attackLevel = 1.0;
+ * var releaseLevel = 0;
+ *
+ * var attackTime = 0.001;
+ * var decayTime = 0.2;
+ * var susPercent = 0.2;
+ * var releaseTime = 0.5;
+ *
+ * var env, triOsc;
+ *
+ * function setup() {
+ * var cnv = createCanvas(100, 100);
+ *
+ * textAlign(CENTER);
+ * text('click to play', width/2, height/2);
+ *
+ * env = new p5.Envelope();
+ * env.setADSR(attackTime, decayTime, susPercent, releaseTime);
+ * env.setRange(attackLevel, releaseLevel);
+ *
+ * triOsc = new p5.Oscillator('triangle');
+ * triOsc.amp(env);
+ * triOsc.start();
+ * triOsc.freq(220);
+ *
+ * cnv.mousePressed(playEnv);
+ * }
+ *
+ * function playEnv() {
+ * // trigger env on triOsc, 0 seconds from now
+ * // After decay, sustain for 0.2 seconds before release
+ * env.play(triOsc, 0, 0.2);
+ * }
+ *
+ *
+ * var attackLevel = 1.0;
+ * var releaseLevel = 0;
+ *
+ * var attackTime = 0.001;
+ * var decayTime = 0.3;
+ * var susPercent = 0.4;
+ * var releaseTime = 0.5;
+ *
+ * var env, triOsc;
+ *
+ * function setup() {
+ * var cnv = createCanvas(100, 100);
+ * background(200);
+ * textAlign(CENTER);
+ * text('click to play', width/2, height/2);
+ *
+ * env = new p5.Envelope();
+ * env.setADSR(attackTime, decayTime, susPercent, releaseTime);
+ * env.setRange(attackLevel, releaseLevel);
+ *
+ * triOsc = new p5.Oscillator('triangle');
+ * triOsc.amp(env);
+ * triOsc.start();
+ * triOsc.freq(220);
+ *
+ * cnv.mousePressed(envAttack);
+ * }
+ *
+ * function envAttack() {
+ * console.log('trigger attack');
+ * env.triggerAttack();
+ *
+ * background(0,255,0);
+ * text('attack!', width/2, height/2);
+ * }
+ *
+ * function mouseReleased() {
+ * env.triggerRelease();
+ *
+ * background(200);
+ * text('click to play', width/2, height/2);
+ * }
+ *
+ *
+ * var attackLevel = 1.0;
+ * var releaseLevel = 0;
+ *
+ * var attackTime = 0.001;
+ * var decayTime = 0.3;
+ * var susPercent = 0.4;
+ * var releaseTime = 0.5;
+ *
+ * var env, triOsc;
+ *
+ * function setup() {
+ * var cnv = createCanvas(100, 100);
+ * background(200);
+ * textAlign(CENTER);
+ * text('click to play', width/2, height/2);
+ *
+ * env = new p5.Envelope();
+ * env.setADSR(attackTime, decayTime, susPercent, releaseTime);
+ * env.setRange(attackLevel, releaseLevel);
+ *
+ * triOsc = new p5.Oscillator('triangle');
+ * triOsc.amp(env);
+ * triOsc.start();
+ * triOsc.freq(220);
+ *
+ * cnv.mousePressed(envAttack);
+ * }
+ *
+ * function envAttack() {
+ * console.log('trigger attack');
+ * env.triggerAttack();
+ *
+ * background(0,255,0);
+ * text('attack!', width/2, height/2);
+ * }
+ *
+ * function mouseReleased() {
+ * env.triggerRelease();
+ *
+ * background(200);
+ * text('click to play', width/2, height/2);
+ * }
+ *
setADSR(attackTime, decayTime)
+ * as
+ * time constants for simple exponential ramps.
+ * If the value is higher than current value, it uses attackTime,
+ * while a decrease uses decayTime.
+ *
+ * @method ramp
+ * @param {Object} unit p5.sound Object or Web Audio Param
+ * @param {Number} secondsFromNow When to trigger the ramp
+ * @param {Number} v Target value
+ * @param {Number} [v2] Second target value (optional)
+ * @example
+ *
+ * var env, osc, amp, cnv;
+ *
+ * var attackTime = 0.001;
+ * var decayTime = 0.2;
+ * var attackLevel = 1;
+ * var decayLevel = 0;
+ *
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * fill(0,255,0);
+ * noStroke();
+ *
+ * env = new p5.Envelope();
+ * env.setADSR(attackTime, decayTime);
+ *
+ * osc = new p5.Oscillator();
+ * osc.amp(env);
+ * osc.start();
+ *
+ * amp = new p5.Amplitude();
+ *
+ * cnv.mousePressed(triggerRamp);
+ * }
+ *
+ * function triggerRamp() {
+ * env.ramp(osc, 0, attackLevel, decayLevel);
+ * }
+ *
+ * function draw() {
+ * background(20,20,20);
+ * text('click me', 10, 20);
+ * var h = map(amp.getLevel(), 0, 0.4, 0, height);;
+ *
+ * rect(0, height, width, -h);
+ * }
+ *
p5.Oscillator
for a full list of methods.
+ *
+ * @class p5.Pulse
+ * @extends p5.Oscillator
+ * @constructor
+ * @param {Number} [freq] Frequency in oscillations per second (Hz)
+ * @param {Number} [w] Width between the pulses (0 to 1.0,
+ * defaults to 0)
+ * @example
+ *
+ * var pulse;
+ * function setup() {
+ * background(0);
+ *
+ * // Create and start the pulse wave oscillator
+ * pulse = new p5.Pulse();
+ * pulse.amp(0.5);
+ * pulse.freq(220);
+ * pulse.start();
+ * }
+ *
+ * function draw() {
+ * var w = map(mouseX, 0, width, 0, 1);
+ * w = constrain(w, 0, 1);
+ * pulse.width(w)
+ * }
+ *
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 + * is on, its volume can be measured with getLevel or by connecting an + * FFT object.
+ * + *If you want to hear the AudioIn, use the .connect() method. + * AudioIn does not connect to p5.sound output by default to prevent + * feedback.
+ * + *Note: This uses the getUserMedia/ + * Stream API, which is not supported by certain browsers. Access in Chrome browser + * is limited to localhost and https, but access over http may be limited.
+ * + * @class p5.AudioIn + * @constructor + * @param {Function} [errorCallback] A function to call if there is an error + * accessing the AudioIn. For example, + * Safari and iOS devices do not + * currently allow microphone access. + * @example + *
+ * var mic;
+ * function setup(){
+ * mic = new p5.AudioIn()
+ * mic.start();
+ * }
+ * function draw(){
+ * background(0);
+ * micLevel = mic.getLevel();
+ * ellipse(width/2, constrain(height-micLevel*height*5, 0, height), 10, 10);
+ * }
+ *
+ * var audiograb;
+ *
+ * function setup(){
+ * //new audioIn
+ * audioGrab = new p5.AudioIn();
+ *
+ * audioGrab.getSources(function(deviceList) {
+ * //print out the array of available sources
+ * console.log(deviceList);
+ * //set the source to the first item in the deviceList array
+ * audioGrab.setSource(0);
+ * });
+ * }
+ *
A p5.Filter uses a Web Audio Biquad Filter to filter + * the frequency response of an input source. Subclasses + * include:
+ * *p5.LowPass
:
+ * Allows frequencies below the cutoff frequency to pass through,
+ * and attenuates frequencies above the cutoff.p5.HighPass
:
+ * The opposite of a lowpass filter. p5.BandPass
:
+ * Allows a range of frequencies to pass through and attenuates
+ * the frequencies below and above this frequency range..res()
method controls either width of the
+ * bandpass, or resonance of the low/highpass cutoff frequency.
+ *
+ * This class extends p5.Effect.
+ * Methods amp(), chain(),
+ * drywet(), connect(), and
+ * disconnect() are available.
+ *
+ * @class p5.Filter
+ * @extends p5.Effect
+ * @constructor
+ * @param {String} [type] 'lowpass' (default), 'highpass', 'bandpass'
+ * @example
+ *
+ * var fft, noise, filter;
+ *
+ * function setup() {
+ * fill(255, 40, 255);
+ *
+ * filter = new p5.BandPass();
+ *
+ * noise = new p5.Noise();
+ * // disconnect unfiltered noise,
+ * // and connect to filter
+ * noise.disconnect();
+ * noise.connect(filter);
+ * noise.start();
+ *
+ * fft = new p5.FFT();
+ * }
+ *
+ * function draw() {
+ * background(30);
+ *
+ * // set the BandPass frequency based on mouseX
+ * var freq = map(mouseX, 0, width, 20, 10000);
+ * filter.freq(freq);
+ * // give the filter a narrow band (lower res = wider bandpass)
+ * filter.res(50);
+ *
+ * // draw filtered spectrum
+ * var spectrum = fft.analyze();
+ * noStroke();
+ * for (var i = 0; i < spectrum.length; i++) {
+ * var x = map(i, 0, spectrum.length, 0, width);
+ * var h = -height + map(spectrum[i], 0, 255, height, 0);
+ * rect(x, height, width/spectrum.length, h);
+ * }
+ *
+ * isMouseOverCanvas();
+ * }
+ *
+ * function isMouseOverCanvas() {
+ * var mX = mouseX, mY = mouseY;
+ * if (mX > 0 && mX < width && mY < height && mY > 0) {
+ * noise.amp(0.5, 0.2);
+ * } else {
+ * noise.amp(0, 0.2);
+ * }
+ * }
+ *
new p5.LowPass()
Filter.
+ * This is the same as creating a p5.Filter and then calling
+ * its method setType('lowpass')
.
+ * See p5.Filter for methods.
+ *
+ * @class p5.LowPass
+ * @constructor
+ * @extends p5.Filter
+ */
+ p5.LowPass = function () {
+ p5.Filter.call(this, 'lowpass');
+ };
+ p5.LowPass.prototype = Object.create(p5.Filter.prototype);
+ /**
+ * Constructor: new p5.HighPass()
Filter.
+ * This is the same as creating a p5.Filter and then calling
+ * its method setType('highpass')
.
+ * See p5.Filter for methods.
+ *
+ * @class p5.HighPass
+ * @constructor
+ * @extends p5.Filter
+ */
+ p5.HighPass = function () {
+ p5.Filter.call(this, 'highpass');
+ };
+ p5.HighPass.prototype = Object.create(p5.Filter.prototype);
+ /**
+ * Constructor: new p5.BandPass()
Filter.
+ * This is the same as creating a p5.Filter and then calling
+ * its method setType('bandpass')
.
+ * See p5.Filter for methods.
+ *
+ * @class p5.BandPass
+ * @constructor
+ * @extends p5.Filter
+ */
+ p5.BandPass = function () {
+ p5.Filter.call(this, 'bandpass');
+ };
+ p5.BandPass.prototype = Object.create(p5.Filter.prototype);
+ return p5.Filter;
+}(master, effect);
+var src_eqFilter;
+'use strict';
+src_eqFilter = function () {
+ var Filter = filter;
+ var p5sound = master;
+ /**
+ * EQFilter extends p5.Filter with constraints
+ * necessary for the p5.EQ
+ *
+ * @private
+ */
+ var EQFilter = function (freq, res) {
+ Filter.call(this, 'peaking');
+ this.disconnect();
+ this.set(freq, res);
+ this.biquad.gain.value = 0;
+ delete this.input;
+ delete this.output;
+ delete this._drywet;
+ delete this.wet;
+ };
+ EQFilter.prototype = Object.create(Filter.prototype);
+ EQFilter.prototype.amp = function () {
+ console.warn('`amp()` is not available for p5.EQ bands. Use `.gain()`');
+ };
+ EQFilter.prototype.drywet = function () {
+ console.warn('`drywet()` is not available for p5.EQ bands.');
+ };
+ EQFilter.prototype.connect = function (unit) {
+ var u = unit || p5.soundOut.input;
+ if (this.biquad) {
+ this.biquad.connect(u.input ? u.input : u);
+ } else {
+ this.output.connect(u.input ? u.input : u);
+ }
+ };
+ EQFilter.prototype.disconnect = function () {
+ if (this.biquad) {
+ this.biquad.disconnect();
+ }
+ };
+ EQFilter.prototype.dispose = function () {
+ // remove reference form soundArray
+ var index = p5sound.soundArray.indexOf(this);
+ p5sound.soundArray.splice(index, 1);
+ this.disconnect();
+ delete this.biquad;
+ };
+ return EQFilter;
+}(filter, master);
+var eq;
+'use strict';
+eq = function () {
+ var Effect = effect;
+ var EQFilter = src_eqFilter;
+ /**
+ * p5.EQ is an audio effect that performs the function of a multiband
+ * audio equalizer. Equalization is used to adjust the balance of
+ * frequency compoenents of an audio signal. This process is commonly used
+ * in sound production and recording to change the waveform before it reaches
+ * a sound output device. EQ can also be used as an audio effect to create
+ * interesting distortions by filtering out parts of the spectrum. p5.EQ is
+ * built using a chain of Web Audio Biquad Filter Nodes and can be
+ * instantiated with 3 or 8 bands. Bands can be added or removed from
+ * the EQ by directly modifying p5.EQ.bands (the array that stores filters).
+ *
+ * This class extends p5.Effect.
+ * Methods amp(), chain(),
+ * drywet(), connect(), and
+ * disconnect() are available.
+ *
+ * @class p5.EQ
+ * @constructor
+ * @extends p5.Effect
+ * @param {Number} [_eqsize] Constructor will accept 3 or 8, defaults to 3
+ * @return {Object} p5.EQ object
+ *
+ * @example
+ *
+ * var eq;
+ * var band_names;
+ * var band_index;
+ *
+ * var soundFile, play;
+ *
+ * function preload() {
+ * soundFormats('mp3', 'ogg');
+ * soundFile = loadSound('assets/beat');
+ * }
+ *
+ * function setup() {
+ * eq = new p5.EQ(3);
+ * soundFile.disconnect();
+ * eq.process(soundFile);
+ *
+ * band_names = ['lows','mids','highs'];
+ * band_index = 0;
+ * play = false;
+ * textAlign(CENTER);
+ * }
+ *
+ * function draw() {
+ * background(30);
+ * noStroke();
+ * fill(255);
+ * text('click to kill',50,25);
+ *
+ * fill(255, 40, 255);
+ * textSize(26);
+ * text(band_names[band_index],50,55);
+ *
+ * fill(255);
+ * textSize(9);
+ * text('space = play/pause',50,80);
+ * }
+ *
+ * //If mouse is over canvas, cycle to the next band and kill the frequency
+ * function mouseClicked() {
+ * for (var i = 0; i < eq.bands.length; i++) {
+ * eq.bands[i].gain(0);
+ * }
+ * eq.bands[band_index].gain(-40);
+ * if (mouseX > 0 && mouseX < width && mouseY < height && mouseY > 0) {
+ * band_index === 2 ? band_index = 0 : band_index++;
+ * }
+ * }
+ *
+ * //use space bar to trigger play / pause
+ * function keyPressed() {
+ * if (key===' ') {
+ * play = !play
+ * play ? soundFile.loop() : soundFile.pause();
+ * }
+ * }
+ *
p5.soundOut.audiocontext.listener
+ *
+ *
+ * @class p5.Panner3D
+ * @constructor
+ */
+ p5.Panner3D = function () {
+ Effect.call(this);
+ /**
+ *
+ * Web Audio Spatial Panner Node
+ *
+ * Properties include
+ * - panningModel: "equal power" or "HRTF"
+ * - distanceModel: "linear", "inverse", or "exponential"
+ *
+ * @property {AudioNode} panner
+ *
+ */
+ this.panner = this.ac.createPanner();
+ this.panner.panningModel = 'HRTF';
+ this.panner.distanceModel = 'linear';
+ this.panner.connect(this.output);
+ this.input.connect(this.panner);
+ };
+ p5.Panner3D.prototype = Object.create(Effect.prototype);
+ /**
+ * Connect an audio sorce
+ *
+ * @method process
+ * @param {Object} src Input source
+ */
+ p5.Panner3D.prototype.process = function (src) {
+ src.connect(this.input);
+ };
+ /**
+ * Set the X,Y,Z position of the Panner
+ * @method set
+ * @param {Number} xVal
+ * @param {Number} yVal
+ * @param {Number} zVal
+ * @param {Number} time
+ * @return {Array} Updated x, y, z values as an array
+ */
+ p5.Panner3D.prototype.set = function (xVal, yVal, zVal, time) {
+ this.positionX(xVal, time);
+ this.positionY(yVal, time);
+ this.positionZ(zVal, time);
+ return [
+ this.panner.positionX.value,
+ this.panner.positionY.value,
+ this.panner.positionZ.value
+ ];
+ };
+ /**
+ * Getter and setter methods for position coordinates
+ * @method positionX
+ * @return {Number} updated coordinate value
+ */
+ /**
+ * Getter and setter methods for position coordinates
+ * @method positionY
+ * @return {Number} updated coordinate value
+ */
+ /**
+ * Getter and setter methods for position coordinates
+ * @method positionZ
+ * @return {Number} updated coordinate value
+ */
+ p5.Panner3D.prototype.positionX = function (xVal, time) {
+ var t = time || 0;
+ if (typeof xVal === 'number') {
+ this.panner.positionX.value = xVal;
+ this.panner.positionX.cancelScheduledValues(this.ac.currentTime + 0.01 + t);
+ this.panner.positionX.linearRampToValueAtTime(xVal, this.ac.currentTime + 0.02 + t);
+ } else if (xVal) {
+ xVal.connect(this.panner.positionX);
+ }
+ return this.panner.positionX.value;
+ };
+ p5.Panner3D.prototype.positionY = function (yVal, time) {
+ var t = time || 0;
+ if (typeof yVal === 'number') {
+ this.panner.positionY.value = yVal;
+ this.panner.positionY.cancelScheduledValues(this.ac.currentTime + 0.01 + t);
+ this.panner.positionY.linearRampToValueAtTime(yVal, this.ac.currentTime + 0.02 + t);
+ } else if (yVal) {
+ yVal.connect(this.panner.positionY);
+ }
+ return this.panner.positionY.value;
+ };
+ p5.Panner3D.prototype.positionZ = function (zVal, time) {
+ var t = time || 0;
+ if (typeof zVal === 'number') {
+ this.panner.positionZ.value = zVal;
+ this.panner.positionZ.cancelScheduledValues(this.ac.currentTime + 0.01 + t);
+ this.panner.positionZ.linearRampToValueAtTime(zVal, this.ac.currentTime + 0.02 + t);
+ } else if (zVal) {
+ zVal.connect(this.panner.positionZ);
+ }
+ return this.panner.positionZ.value;
+ };
+ /**
+ * Set the X,Y,Z position of the Panner
+ * @method orient
+ * @param {Number} xVal
+ * @param {Number} yVal
+ * @param {Number} zVal
+ * @param {Number} time
+ * @return {Array} Updated x, y, z values as an array
+ */
+ p5.Panner3D.prototype.orient = function (xVal, yVal, zVal, time) {
+ this.orientX(xVal, time);
+ this.orientY(yVal, time);
+ this.orientZ(zVal, time);
+ return [
+ this.panner.orientationX.value,
+ this.panner.orientationY.value,
+ this.panner.orientationZ.value
+ ];
+ };
+ /**
+ * Getter and setter methods for orient coordinates
+ * @method orientX
+ * @return {Number} updated coordinate value
+ */
+ /**
+ * Getter and setter methods for orient coordinates
+ * @method orientY
+ * @return {Number} updated coordinate value
+ */
+ /**
+ * Getter and setter methods for orient coordinates
+ * @method orientZ
+ * @return {Number} updated coordinate value
+ */
+ p5.Panner3D.prototype.orientX = function (xVal, time) {
+ var t = time || 0;
+ if (typeof xVal === 'number') {
+ this.panner.orientationX.value = xVal;
+ this.panner.orientationX.cancelScheduledValues(this.ac.currentTime + 0.01 + t);
+ this.panner.orientationX.linearRampToValueAtTime(xVal, this.ac.currentTime + 0.02 + t);
+ } else if (xVal) {
+ xVal.connect(this.panner.orientationX);
+ }
+ return this.panner.orientationX.value;
+ };
+ p5.Panner3D.prototype.orientY = function (yVal, time) {
+ var t = time || 0;
+ if (typeof yVal === 'number') {
+ this.panner.orientationY.value = yVal;
+ this.panner.orientationY.cancelScheduledValues(this.ac.currentTime + 0.01 + t);
+ this.panner.orientationY.linearRampToValueAtTime(yVal, this.ac.currentTime + 0.02 + t);
+ } else if (yVal) {
+ yVal.connect(this.panner.orientationY);
+ }
+ return this.panner.orientationY.value;
+ };
+ p5.Panner3D.prototype.orientZ = function (zVal, time) {
+ var t = time || 0;
+ if (typeof zVal === 'number') {
+ this.panner.orientationZ.value = zVal;
+ this.panner.orientationZ.cancelScheduledValues(this.ac.currentTime + 0.01 + t);
+ this.panner.orientationZ.linearRampToValueAtTime(zVal, this.ac.currentTime + 0.02 + t);
+ } else if (zVal) {
+ zVal.connect(this.panner.orientationZ);
+ }
+ return this.panner.orientationZ.value;
+ };
+ /**
+ * Set the rolloff factor and max distance
+ * @method setFalloff
+ * @param {Number} [maxDistance]
+ * @param {Number} [rolloffFactor]
+ */
+ p5.Panner3D.prototype.setFalloff = function (maxDistance, rolloffFactor) {
+ this.maxDist(maxDistance);
+ this.rolloff(rolloffFactor);
+ };
+ /**
+ * Maxium distance between the source and the listener
+ * @method maxDist
+ * @param {Number} maxDistance
+ * @return {Number} updated value
+ */
+ p5.Panner3D.prototype.maxDist = function (maxDistance) {
+ if (typeof maxDistance === 'number') {
+ this.panner.maxDistance = maxDistance;
+ }
+ return this.panner.maxDistance;
+ };
+ /**
+ * How quickly the volume is reduced as the source moves away from the listener
+ * @method rollof
+ * @param {Number} rolloffFactor
+ * @return {Number} updated value
+ */
+ p5.Panner3D.prototype.rolloff = function (rolloffFactor) {
+ if (typeof rolloffFactor === 'number') {
+ this.panner.rolloffFactor = rolloffFactor;
+ }
+ return this.panner.rolloffFactor;
+ };
+ p5.Panner3D.dispose = function () {
+ Effect.prototype.dispose.apply(this);
+ if (this.panner) {
+ this.panner.disconnect();
+ delete this.panner;
+ }
+ };
+ return p5.Panner3D;
+}(master, effect);
+var listener3d;
+'use strict';
+listener3d = function () {
+ var p5sound = master;
+ var Effect = effect;
+ // /**
+ // * listener is a class that can construct both a Spatial Panner
+ // * and a Spatial Listener. The panner is based on the
+ // * Web Audio Spatial Panner Node
+ // * https://www.w3.org/TR/webaudio/#the-listenernode-interface
+ // * This panner is a spatial processing node that allows audio to be positioned
+ // * and oriented in 3D space.
+ // *
+ // * The Listener modifies the properties of the Audio Context Listener.
+ // * Both objects types use the same methods. The default is a spatial panner.
+ // *
+ // * p5.Panner3D
- Constructs a Spatial Pannerp5.Listener3D
- Constructs a Spatial Listener
+ * var noise, env, delay;
+ *
+ * function setup() {
+ * background(0);
+ * noStroke();
+ * fill(255);
+ * textAlign(CENTER);
+ * text('click to play', width/2, height/2);
+ *
+ * noise = new p5.Noise('brown');
+ * noise.amp(0);
+ * noise.start();
+ *
+ * delay = new p5.Delay();
+ *
+ * // delay.process() accepts 4 parameters:
+ * // source, delayTime, feedback, filter frequency
+ * // play with these numbers!!
+ * delay.process(noise, .12, .7, 2300);
+ *
+ * // play the noise with an envelope,
+ * // a series of fades ( time / value pairs )
+ * env = new p5.Envelope(.01, 0.2, .2, .1);
+ * }
+ *
+ * // mouseClick triggers envelope
+ * function mouseClicked() {
+ * // is mouse over canvas?
+ * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {
+ * env.play(noise);
+ * }
+ * }
+ *
+ * var soundFile, reverb;
+ * function preload() {
+ * soundFile = loadSound('assets/Damscray_DancingTiger.mp3');
+ * }
+ *
+ * function setup() {
+ * reverb = new p5.Reverb();
+ * soundFile.disconnect(); // so we'll only hear reverb...
+ *
+ * // connect soundFile to reverb, process w/
+ * // 3 second reverbTime, decayRate of 2%
+ * reverb.process(soundFile, 3, 2);
+ * soundFile.play();
+ * }
+ *
p5.Convolver extends p5.Reverb. It can emulate the sound of real + * physical spaces through a process called + * convolution.
+ * + *Convolution multiplies any audio input by an "impulse response" + * to simulate the dispersion of sound over time. The impulse response is + * generated from an audio file that you provide. One way to + * generate an impulse response is to pop a balloon in a reverberant space + * and record the echo. Convolution can also be used to experiment with + * sound.
+ * + *Use the method createConvolution(path)
to instantiate a
+ * p5.Convolver with a path to your impulse response audio file.
+ * var cVerb, sound;
+ * function preload() {
+ * // We have both MP3 and OGG versions of all sound assets
+ * soundFormats('ogg', 'mp3');
+ *
+ * // Try replacing 'bx-spring' with other soundfiles like
+ * // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox'
+ * cVerb = createConvolver('assets/bx-spring.mp3');
+ *
+ * // Try replacing 'Damscray_DancingTiger' with
+ * // 'beat', 'doorbell', lucky_dragons_-_power_melody'
+ * sound = loadSound('assets/Damscray_DancingTiger.mp3');
+ * }
+ *
+ * function setup() {
+ * // disconnect from master output...
+ * sound.disconnect();
+ *
+ * // ...and process with cVerb
+ * // so that we only hear the convolution
+ * cVerb.process(sound);
+ *
+ * sound.play();
+ * }
+ *
+ * var cVerb, sound;
+ * function preload() {
+ * // We have both MP3 and OGG versions of all sound assets
+ * soundFormats('ogg', 'mp3');
+ *
+ * // Try replacing 'bx-spring' with other soundfiles like
+ * // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox'
+ * cVerb = createConvolver('assets/bx-spring.mp3');
+ *
+ * // Try replacing 'Damscray_DancingTiger' with
+ * // 'beat', 'doorbell', lucky_dragons_-_power_melody'
+ * sound = loadSound('assets/Damscray_DancingTiger.mp3');
+ * }
+ *
+ * function setup() {
+ * // disconnect from master output...
+ * sound.disconnect();
+ *
+ * // ...and process with cVerb
+ * // so that we only hear the convolution
+ * cVerb.process(sound);
+ *
+ * sound.play();
+ * }
+ *
+ * var cVerb, sound;
+ * function preload() {
+ * soundFormats('ogg', 'mp3');
+ *
+ * cVerb = createConvolver('assets/concrete-tunnel.mp3');
+ *
+ * sound = loadSound('assets/beat.mp3');
+ * }
+ *
+ * function setup() {
+ * // disconnect from master output...
+ * sound.disconnect();
+ *
+ * // ...and process with (i.e. connect to) cVerb
+ * // so that we only hear the convolution
+ * cVerb.process(sound);
+ *
+ * sound.play();
+ * }
+ *
toggleImpulse(id)
method.
+ *
+ * @property {Array} impulses
+ */
+ p5.Convolver.prototype.impulses = [];
+ /**
+ * Load and assign a new Impulse Response to the p5.Convolver.
+ * The impulse is added to the .impulses
array. Previous
+ * impulses can be accessed with the .toggleImpulse(id)
+ * method.
+ *
+ * @method addImpulse
+ * @param {String} path path to a sound file
+ * @param {Function} callback function (optional)
+ * @param {Function} errorCallback function (optional)
+ */
+ p5.Convolver.prototype.addImpulse = function (path, callback, errorCallback) {
+ // if loading locally without a server
+ if (window.location.origin.indexOf('file://') > -1 && window.cordova === 'undefined') {
+ alert('This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS');
+ }
+ this._loadBuffer(path, callback, errorCallback);
+ };
+ /**
+ * Similar to .addImpulse, except that the .impulses
+ * Array is reset to save memory. A new .impulses
+ * array is created with this impulse as the only item.
+ *
+ * @method resetImpulse
+ * @param {String} path path to a sound file
+ * @param {Function} callback function (optional)
+ * @param {Function} errorCallback function (optional)
+ */
+ p5.Convolver.prototype.resetImpulse = function (path, callback, errorCallback) {
+ // if loading locally without a server
+ if (window.location.origin.indexOf('file://') > -1 && window.cordova === 'undefined') {
+ alert('This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS');
+ }
+ this.impulses = [];
+ this._loadBuffer(path, callback, errorCallback);
+ };
+ /**
+ * If you have used .addImpulse()
to add multiple impulses
+ * to a p5.Convolver, then you can use this method to toggle between
+ * the items in the .impulses
Array. Accepts a parameter
+ * to identify which impulse you wish to use, identified either by its
+ * original filename (String) or by its position in the .impulses
+ *
Array (Number)..audioBuffer
(type:
+ * Web Audio
+ * AudioBuffer) and a .name
, a String that corresponds
+ * with the original filename.
+ *
+ * @method toggleImpulse
+ * @param {String|Number} id Identify the impulse by its original filename
+ * (String), or by its position in the
+ * .impulses
Array (Number).
+ */
+ p5.Convolver.prototype.toggleImpulse = function (id) {
+ if (typeof id === 'number' && id < this.impulses.length) {
+ this._setBuffer(this.impulses[id].audioBuffer);
+ }
+ if (typeof id === 'string') {
+ for (var i = 0; i < this.impulses.length; i++) {
+ if (this.impulses[i].name === id) {
+ this._setBuffer(this.impulses[i].audioBuffer);
+ break;
+ }
+ }
+ }
+ };
+ p5.Convolver.prototype.dispose = function () {
+ p5.Reverb.prototype.dispose.apply(this);
+ // remove all the Impulse Response buffers
+ for (var i in this.impulses) {
+ if (this.impulses[i]) {
+ this.impulses[i] = null;
+ }
+ }
+ };
+}(errorHandler, effect);
+/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/
+var Tone_core_TimelineState;
+Tone_core_TimelineState = function (Tone) {
+ 'use strict';
+ Tone.TimelineState = function (initial) {
+ Tone.Timeline.call(this);
+ this._initial = initial;
+ };
+ Tone.extend(Tone.TimelineState, Tone.Timeline);
+ Tone.TimelineState.prototype.getValueAtTime = function (time) {
+ var event = this.get(time);
+ if (event !== null) {
+ return event.state;
+ } else {
+ return this._initial;
+ }
+ };
+ Tone.TimelineState.prototype.setStateAtTime = function (state, time) {
+ this.add({
+ 'state': state,
+ 'time': time
+ });
+ };
+ return Tone.TimelineState;
+}(Tone_core_Tone, Tone_core_Timeline);
+/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/
+var Tone_core_Clock;
+Tone_core_Clock = function (Tone) {
+ 'use strict';
+ Tone.Clock = function () {
+ Tone.Emitter.call(this);
+ var options = this.optionsObject(arguments, [
+ 'callback',
+ 'frequency'
+ ], Tone.Clock.defaults);
+ this.callback = options.callback;
+ this._nextTick = 0;
+ this._lastState = Tone.State.Stopped;
+ this.frequency = new Tone.TimelineSignal(options.frequency, Tone.Type.Frequency);
+ this._readOnly('frequency');
+ this.ticks = 0;
+ this._state = new Tone.TimelineState(Tone.State.Stopped);
+ this._boundLoop = this._loop.bind(this);
+ this.context.on('tick', this._boundLoop);
+ };
+ Tone.extend(Tone.Clock, Tone.Emitter);
+ Tone.Clock.defaults = {
+ 'callback': Tone.noOp,
+ 'frequency': 1,
+ 'lookAhead': 'auto'
+ };
+ Object.defineProperty(Tone.Clock.prototype, 'state', {
+ get: function () {
+ return this._state.getValueAtTime(this.now());
+ }
+ });
+ Tone.Clock.prototype.start = function (time, offset) {
+ time = this.toSeconds(time);
+ if (this._state.getValueAtTime(time) !== Tone.State.Started) {
+ this._state.add({
+ 'state': Tone.State.Started,
+ 'time': time,
+ 'offset': offset
+ });
+ }
+ return this;
+ };
+ Tone.Clock.prototype.stop = function (time) {
+ time = this.toSeconds(time);
+ this._state.cancel(time);
+ this._state.setStateAtTime(Tone.State.Stopped, time);
+ return this;
+ };
+ Tone.Clock.prototype.pause = function (time) {
+ time = this.toSeconds(time);
+ if (this._state.getValueAtTime(time) === Tone.State.Started) {
+ this._state.setStateAtTime(Tone.State.Paused, time);
+ }
+ return this;
+ };
+ Tone.Clock.prototype._loop = function () {
+ var now = this.now();
+ var lookAhead = this.context.lookAhead;
+ var updateInterval = this.context.updateInterval;
+ var lagCompensation = this.context.lag * 2;
+ var loopInterval = now + lookAhead + updateInterval + lagCompensation;
+ while (loopInterval > this._nextTick && this._state) {
+ var currentState = this._state.getValueAtTime(this._nextTick);
+ if (currentState !== this._lastState) {
+ this._lastState = currentState;
+ var event = this._state.get(this._nextTick);
+ if (currentState === Tone.State.Started) {
+ this._nextTick = event.time;
+ if (!this.isUndef(event.offset)) {
+ this.ticks = event.offset;
+ }
+ this.emit('start', event.time, this.ticks);
+ } else if (currentState === Tone.State.Stopped) {
+ this.ticks = 0;
+ this.emit('stop', event.time);
+ } else if (currentState === Tone.State.Paused) {
+ this.emit('pause', event.time);
+ }
+ }
+ var tickTime = this._nextTick;
+ if (this.frequency) {
+ this._nextTick += 1 / this.frequency.getValueAtTime(this._nextTick);
+ if (currentState === Tone.State.Started) {
+ this.callback(tickTime);
+ this.ticks++;
+ }
+ }
+ }
+ };
+ Tone.Clock.prototype.getStateAtTime = function (time) {
+ time = this.toSeconds(time);
+ return this._state.getValueAtTime(time);
+ };
+ Tone.Clock.prototype.dispose = function () {
+ Tone.Emitter.prototype.dispose.call(this);
+ this.context.off('tick', this._boundLoop);
+ this._writable('frequency');
+ this.frequency.dispose();
+ this.frequency = null;
+ this._boundLoop = null;
+ this._nextTick = Infinity;
+ this.callback = null;
+ this._state.dispose();
+ this._state = null;
+ };
+ return Tone.Clock;
+}(Tone_core_Tone, Tone_signal_TimelineSignal, Tone_core_TimelineState, Tone_core_Emitter);
+var metro;
+'use strict';
+metro = function () {
+ var p5sound = master;
+ // requires the Tone.js library's Clock (MIT license, Yotam Mann)
+ // https://github.com/TONEnoTONE/Tone.js/
+ var Clock = Tone_core_Clock;
+ p5.Metro = function () {
+ this.clock = new Clock({ 'callback': this.ontick.bind(this) });
+ this.syncedParts = [];
+ this.bpm = 120;
+ // gets overridden by p5.Part
+ this._init();
+ this.prevTick = 0;
+ this.tatumTime = 0;
+ this.tickCallback = function () {
+ };
+ };
+ p5.Metro.prototype.ontick = function (tickTime) {
+ var elapsedTime = tickTime - this.prevTick;
+ var secondsFromNow = tickTime - p5sound.audiocontext.currentTime;
+ if (elapsedTime - this.tatumTime <= -0.02) {
+ return;
+ } else {
+ // console.log('ok', this.syncedParts[0].phrases[0].name);
+ this.prevTick = tickTime;
+ // for all of the active things on the metro:
+ var self = this;
+ this.syncedParts.forEach(function (thisPart) {
+ if (!thisPart.isPlaying)
+ return;
+ thisPart.incrementStep(secondsFromNow);
+ // each synced source keeps track of its own beat number
+ thisPart.phrases.forEach(function (thisPhrase) {
+ var phraseArray = thisPhrase.sequence;
+ var bNum = self.metroTicks % phraseArray.length;
+ if (phraseArray[bNum] !== 0 && (self.metroTicks < phraseArray.length || !thisPhrase.looping)) {
+ thisPhrase.callback(secondsFromNow, phraseArray[bNum]);
+ }
+ });
+ });
+ this.metroTicks += 1;
+ this.tickCallback(secondsFromNow);
+ }
+ };
+ p5.Metro.prototype.setBPM = function (bpm, rampTime) {
+ var beatTime = 60 / (bpm * this.tatums);
+ var now = p5sound.audiocontext.currentTime;
+ this.tatumTime = beatTime;
+ var rampTime = rampTime || 0;
+ this.clock.frequency.setValueAtTime(this.clock.frequency.value, now);
+ this.clock.frequency.linearRampToValueAtTime(bpm, now + rampTime);
+ this.bpm = bpm;
+ };
+ p5.Metro.prototype.getBPM = function () {
+ return this.clock.getRate() / this.tatums * 60;
+ };
+ p5.Metro.prototype._init = function () {
+ this.metroTicks = 0;
+ };
+ // clear existing synced parts, add only this one
+ p5.Metro.prototype.resetSync = function (part) {
+ this.syncedParts = [part];
+ };
+ // push a new synced part to the array
+ p5.Metro.prototype.pushSync = function (part) {
+ this.syncedParts.push(part);
+ };
+ p5.Metro.prototype.start = function (timeFromNow) {
+ var t = timeFromNow || 0;
+ var now = p5sound.audiocontext.currentTime;
+ this.clock.start(now + t);
+ this.setBPM(this.bpm);
+ };
+ p5.Metro.prototype.stop = function (timeFromNow) {
+ var t = timeFromNow || 0;
+ var now = p5sound.audiocontext.currentTime;
+ this.clock.stop(now + t);
+ };
+ p5.Metro.prototype.beatLength = function (tatums) {
+ this.tatums = 1 / tatums / 4;
+ };
+}(master, Tone_core_Clock);
+var looper;
+'use strict';
+looper = function () {
+ var p5sound = master;
+ var BPM = 120;
+ /**
+ * Set the global tempo, in beats per minute, for all
+ * p5.Parts. This method will impact all active p5.Parts.
+ *
+ * @method setBPM
+ * @param {Number} BPM Beats Per Minute
+ * @param {Number} rampTime Seconds from now
+ */
+ p5.prototype.setBPM = function (bpm, rampTime) {
+ BPM = bpm;
+ for (var i in p5sound.parts) {
+ if (p5sound.parts[i]) {
+ p5sound.parts[i].setBPM(bpm, rampTime);
+ }
+ }
+ };
+ /**
+ * A phrase is a pattern of musical events over time, i.e. + * a series of notes and rests.
+ * + *Phrases must be added to a p5.Part for playback, and + * each part can play multiple phrases at the same time. + * For example, one Phrase might be a kick drum, another + * could be a snare, and another could be the bassline.
+ * + *The first parameter is a name so that the phrase can be
+ * modified or deleted later. The callback is a a function that
+ * this phrase will call at every step—for example it might be
+ * called playNote(value){}
. The array determines
+ * which value is passed into the callback at each step of the
+ * phrase. It can be numbers, an object with multiple numbers,
+ * or a zero (0) indicates a rest so the callback won't be called).
+ * var mySound, myPhrase, myPart;
+ * var pattern = [1,0,0,2,0,2,0,0];
+ * var msg = 'click to play';
+ *
+ * function preload() {
+ * mySound = loadSound('assets/beatbox.mp3');
+ * }
+ *
+ * function setup() {
+ * noStroke();
+ * fill(255);
+ * textAlign(CENTER);
+ * masterVolume(0.1);
+ *
+ * myPhrase = new p5.Phrase('bbox', makeSound, pattern);
+ * myPart = new p5.Part();
+ * myPart.addPhrase(myPhrase);
+ * myPart.setBPM(60);
+ * }
+ *
+ * function draw() {
+ * background(0);
+ * text(msg, width/2, height/2);
+ * }
+ *
+ * function makeSound(time, playbackRate) {
+ * mySound.rate(playbackRate);
+ * mySound.play(time);
+ * }
+ *
+ * function mouseClicked() {
+ * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {
+ * myPart.start();
+ * msg = 'playing pattern';
+ * }
+ * }
+ *
+ *
A p5.Part plays back one or more p5.Phrases. Instantiate a part + * with steps and tatums. By default, each step represents a 1/16th note.
+ * + *See p5.Phrase for more about musical timing.
+ * + * @class p5.Part + * @constructor + * @param {Number} [steps] Steps in the part + * @param {Number} [tatums] Divisions of a beat, e.g. use 1/4, or 0.25 for a quater note (default is 1/16, a sixteenth note) + * @example + *
+ * var box, drum, myPart;
+ * var boxPat = [1,0,0,2,0,2,0,0];
+ * var drumPat = [0,1,1,0,2,0,1,0];
+ * var msg = 'click to play';
+ *
+ * function preload() {
+ * box = loadSound('assets/beatbox.mp3');
+ * drum = loadSound('assets/drum.mp3');
+ * }
+ *
+ * function setup() {
+ * noStroke();
+ * fill(255);
+ * textAlign(CENTER);
+ * masterVolume(0.1);
+ *
+ * var boxPhrase = new p5.Phrase('box', playBox, boxPat);
+ * var drumPhrase = new p5.Phrase('drum', playDrum, drumPat);
+ * myPart = new p5.Part();
+ * myPart.addPhrase(boxPhrase);
+ * myPart.addPhrase(drumPhrase);
+ * myPart.setBPM(60);
+ * masterVolume(0.1);
+ * }
+ *
+ * function draw() {
+ * background(0);
+ * text(msg, width/2, height/2);
+ * }
+ *
+ * function playBox(time, playbackRate) {
+ * box.rate(playbackRate);
+ * box.play(time);
+ * }
+ *
+ * function playDrum(time, playbackRate) {
+ * drum.rate(playbackRate);
+ * drum.play(time);
+ * }
+ *
+ * function mouseClicked() {
+ * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {
+ * myPart.start();
+ * msg = 'playing part';
+ * }
+ * }
+ *
new p5.Score(a, a, b, a, c)
+ *
+ * @class p5.Score
+ * @constructor
+ * @param {p5.Part} [...parts] One or multiple parts, to be played in sequence.
+ */
+ p5.Score = function () {
+ // for all of the arguments
+ this.parts = [];
+ this.currentPart = 0;
+ var thisScore = this;
+ for (var i in arguments) {
+ if (arguments[i] && this.parts[i]) {
+ this.parts[i] = arguments[i];
+ this.parts[i].nextPart = this.parts[i + 1];
+ this.parts[i].onended = function () {
+ thisScore.resetPart(i);
+ playNextPart(thisScore);
+ };
+ }
+ }
+ this.looping = false;
+ };
+ p5.Score.prototype.onended = function () {
+ if (this.looping) {
+ // this.resetParts();
+ this.parts[0].start();
+ } else {
+ this.parts[this.parts.length - 1].onended = function () {
+ this.stop();
+ this.resetParts();
+ };
+ }
+ this.currentPart = 0;
+ };
+ /**
+ * Start playback of the score.
+ *
+ * @method start
+ */
+ p5.Score.prototype.start = function () {
+ this.parts[this.currentPart].start();
+ this.scoreStep = 0;
+ };
+ /**
+ * Stop playback of the score.
+ *
+ * @method stop
+ */
+ p5.Score.prototype.stop = function () {
+ this.parts[this.currentPart].stop();
+ this.currentPart = 0;
+ this.scoreStep = 0;
+ };
+ /**
+ * Pause playback of the score.
+ *
+ * @method pause
+ */
+ p5.Score.prototype.pause = function () {
+ this.parts[this.currentPart].stop();
+ };
+ /**
+ * Loop playback of the score.
+ *
+ * @method loop
+ */
+ p5.Score.prototype.loop = function () {
+ this.looping = true;
+ this.start();
+ };
+ /**
+ * Stop looping playback of the score. If it
+ * is currently playing, this will go into effect
+ * after the current round of playback completes.
+ *
+ * @method noLoop
+ */
+ p5.Score.prototype.noLoop = function () {
+ this.looping = false;
+ };
+ p5.Score.prototype.resetParts = function () {
+ var self = this;
+ this.parts.forEach(function (part) {
+ self.resetParts[part];
+ });
+ };
+ p5.Score.prototype.resetPart = function (i) {
+ this.parts[i].stop();
+ this.parts[i].partStep = 0;
+ for (var p in this.parts[i].phrases) {
+ if (this.parts[i]) {
+ this.parts[i].phrases[p].phraseStep = 0;
+ }
+ }
+ };
+ /**
+ * Set the tempo for all parts in the score
+ *
+ * @method setBPM
+ * @param {Number} BPM Beats Per Minute
+ * @param {Number} rampTime Seconds from now
+ */
+ p5.Score.prototype.setBPM = function (bpm, rampTime) {
+ for (var i in this.parts) {
+ if (this.parts[i]) {
+ this.parts[i].setBPM(bpm, rampTime);
+ }
+ }
+ };
+ function playNextPart(aScore) {
+ aScore.currentPart++;
+ if (aScore.currentPart >= aScore.parts.length) {
+ aScore.scoreStep = 0;
+ aScore.onended();
+ } else {
+ aScore.scoreStep = 0;
+ aScore.parts[aScore.currentPart - 1].stop();
+ aScore.parts[aScore.currentPart].start();
+ }
+ }
+}(master);
+var soundloop;
+'use strict';
+soundloop = function () {
+ var p5sound = master;
+ var Clock = Tone_core_Clock;
+ /**
+ * SoundLoop
+ *
+ * @class p5.SoundLoop
+ * @constructor
+ *
+ * @param {Function} callback this function will be called on each iteration of theloop
+ * @param {Number|String} [interval] amount of time or beats for each iteration of the loop
+ * defaults to 1
+ *
+ * @example
+ *
+ * var click;
+ * var looper1;
+ *
+ * function preload() {
+ * click = loadSound('assets/drum.mp3');
+ * }
+ *
+ * function setup() {
+ * //the looper's callback is passed the timeFromNow
+ * //this value should be used as a reference point from
+ * //which to schedule sounds
+ * looper1 = new p5.SoundLoop(function(timeFromNow){
+ * click.play(timeFromNow);
+ * background(255 * (looper1.iterations % 2));
+ * }, 2);
+ *
+ * //stop after 10 iteratios;
+ * looper1.maxIterations = 10;
+ * //start the loop
+ * looper1.start();
+ * }
+ *
Record sounds for playback and/or to save as a .wav file. + * The p5.SoundRecorder records all sound output from your sketch, + * or can be assigned a specific source with setInput().
+ *The record() method accepts a p5.SoundFile as a parameter. + * When playback is stopped (either after the given amount of time, + * or with the stop() method), the p5.SoundRecorder will send its + * recording to that p5.SoundFile for playback.
+ * + * @class p5.SoundRecorder + * @constructor + * @example + *
+ * var mic, recorder, soundFile;
+ * var state = 0;
+ *
+ * function setup() {
+ * background(200);
+ * // create an audio in
+ * mic = new p5.AudioIn();
+ *
+ * // prompts user to enable their browser mic
+ * mic.start();
+ *
+ * // create a sound recorder
+ * recorder = new p5.SoundRecorder();
+ *
+ * // connect the mic to the recorder
+ * recorder.setInput(mic);
+ *
+ * // this sound file will be used to
+ * // playback & save the recording
+ * soundFile = new p5.SoundFile();
+ *
+ * text('keyPress to record', 20, 20);
+ * }
+ *
+ * function keyPressed() {
+ * // make sure user enabled the mic
+ * if (state === 0 && mic.enabled) {
+ *
+ * // record to our p5.SoundFile
+ * recorder.record(soundFile);
+ *
+ * background(255,0,0);
+ * text('Recording!', 20, 20);
+ * state++;
+ * }
+ * else if (state === 1) {
+ * background(0,255,0);
+ *
+ * // stop recorder and
+ * // send result to soundFile
+ * recorder.stop();
+ *
+ * text('Stopped', 20, 20);
+ * state++;
+ * }
+ *
+ * else if (state === 2) {
+ * soundFile.play(); // play the result!
+ * save(soundFile, 'mySound.wav');
+ * state++;
+ * }
+ * }
+ *
PeakDetect works in conjunction with p5.FFT to + * look for onsets in some or all of the frequency spectrum. + *
+ *
+ * To use p5.PeakDetect, call update
in the draw loop
+ * and pass in a p5.FFT object.
+ *
+ * You can listen for a specific part of the frequency spectrum by
+ * setting the range between freq1
and freq2
.
+ *
threshold
is the threshold for detecting a peak,
+ * scaled between 0 and 1. It is logarithmic, so 0.1 is half as loud
+ * as 1.0.
+ * The update method is meant to be run in the draw loop, and
+ * frames determines how many loops must pass before
+ * another peak can be detected.
+ * For example, if the frameRate() = 60, you could detect the beat of a
+ * 120 beat-per-minute song with this equation:
+ * framesPerPeak = 60 / (estimatedBPM / 60 );
+ *
+ * Based on example contribtued by @b2renger, and a simple beat detection + * explanation by Felix Turner. + *
+ * + * @class p5.PeakDetect + * @constructor + * @param {Number} [freq1] lowFrequency - defaults to 20Hz + * @param {Number} [freq2] highFrequency - defaults to 20000 Hz + * @param {Number} [threshold] Threshold for detecting a beat between 0 and 1 + * scaled logarithmically where 0.1 is 1/2 the loudness + * of 1.0. Defaults to 0.35. + * @param {Number} [framesPerPeak] Defaults to 20. + * @example + *
+ *
+ * var cnv, soundFile, fft, peakDetect;
+ * var ellipseWidth = 10;
+ *
+ * function preload() {
+ * soundFile = loadSound('assets/beat.mp3');
+ * }
+ *
+ * function setup() {
+ * background(0);
+ * noStroke();
+ * fill(255);
+ * textAlign(CENTER);
+ *
+ * // p5.PeakDetect requires a p5.FFT
+ * fft = new p5.FFT();
+ * peakDetect = new p5.PeakDetect();
+ * }
+ *
+ * function draw() {
+ * background(0);
+ * text('click to play/pause', width/2, height/2);
+ *
+ * // peakDetect accepts an fft post-analysis
+ * fft.analyze();
+ * peakDetect.update(fft);
+ *
+ * if ( peakDetect.isDetected ) {
+ * ellipseWidth = 50;
+ * } else {
+ * ellipseWidth *= 0.95;
+ * }
+ *
+ * ellipse(width/2, height/2, ellipseWidth, ellipseWidth);
+ * }
+ *
+ * // toggle play/stop when canvas is clicked
+ * function mouseClicked() {
+ * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {
+ * if (soundFile.isPlaying() ) {
+ * soundFile.stop();
+ * } else {
+ * soundFile.play();
+ * }
+ * }
+ * }
+ *
+ * var cnv, soundFile, fft, peakDetect;
+ * var ellipseWidth = 0;
+ *
+ * function preload() {
+ * soundFile = loadSound('assets/beat.mp3');
+ * }
+ *
+ * function setup() {
+ * cnv = createCanvas(100,100);
+ * textAlign(CENTER);
+ *
+ * fft = new p5.FFT();
+ * peakDetect = new p5.PeakDetect();
+ *
+ * setupSound();
+ *
+ * // when a beat is detected, call triggerBeat()
+ * peakDetect.onPeak(triggerBeat);
+ * }
+ *
+ * function draw() {
+ * background(0);
+ * fill(255);
+ * text('click to play', width/2, height/2);
+ *
+ * fft.analyze();
+ * peakDetect.update(fft);
+ *
+ * ellipseWidth *= 0.95;
+ * ellipse(width/2, height/2, ellipseWidth, ellipseWidth);
+ * }
+ *
+ * // this function is called by peakDetect.onPeak
+ * function triggerBeat() {
+ * ellipseWidth = 50;
+ * }
+ *
+ * // mouseclick starts/stops sound
+ * function setupSound() {
+ * cnv.mouseClicked( function() {
+ * if (soundFile.isPlaying() ) {
+ * soundFile.stop();
+ * } else {
+ * soundFile.play();
+ * }
+ * });
+ * }
+ *
+ *
+ * // load two soundfile and crossfade beetween them
+ * var sound1,sound2;
+ * var gain1, gain2, gain3;
+ *
+ * function preload(){
+ * soundFormats('ogg', 'mp3');
+ * sound1 = loadSound('assets/Damscray_-_Dancing_Tiger_01');
+ * sound2 = loadSound('assets/beat.mp3');
+ * }
+ *
+ * function setup() {
+ * createCanvas(400,200);
+ *
+ * // create a 'master' gain to which we will connect both soundfiles
+ * gain3 = new p5.Gain();
+ * gain3.connect();
+ *
+ * // setup first sound for playing
+ * sound1.rate(1);
+ * sound1.loop();
+ * sound1.disconnect(); // diconnect from p5 output
+ *
+ * gain1 = new p5.Gain(); // setup a gain node
+ * gain1.setInput(sound1); // connect the first sound to its input
+ * gain1.connect(gain3); // connect its output to the 'master'
+ *
+ * sound2.rate(1);
+ * sound2.disconnect();
+ * sound2.loop();
+ *
+ * gain2 = new p5.Gain();
+ * gain2.setInput(sound2);
+ * gain2.connect(gain3);
+ *
+ * }
+ *
+ * function draw(){
+ * background(180);
+ *
+ * // calculate the horizontal distance beetween the mouse and the right of the screen
+ * var d = dist(mouseX,0,width,0);
+ *
+ * // map the horizontal position of the mouse to values useable for volume control of sound1
+ * var vol1 = map(mouseX,0,width,0,1);
+ * var vol2 = 1-vol1; // when sound1 is loud, sound2 is quiet and vice versa
+ *
+ * gain1.amp(vol1,0.5,0);
+ * gain2.amp(vol2,0.5,0);
+ *
+ * // map the vertical position of the mouse to values useable for 'master volume control'
+ * var vol3 = map(mouseY,0,height,0,1);
+ * gain3.amp(vol3,0.5,0);
+ * }
+ *
+ * var monoSynth;
+ *
+ * function setup() {
+ * var cnv = createCanvas(100, 100);
+ * cnv.mousePressed(playSynth);
+ *
+ * monoSynth = new p5.MonoSynth();
+ *
+ * textAlign(CENTER);
+ * text('click to play', width/2, height/2);
+ * }
+ *
+ * function playSynth() {
+ * // time from now (in seconds)
+ * var time = 0;
+ * // note duration (in seconds)
+ * var dur = 0.25;
+ * // velocity (volume, from 0 to 1)
+ * var v = 0.2;
+ *
+ * monoSynth.play("G3", v, time, dur);
+ * monoSynth.play("C4", v, time += dur, dur);
+ *
+ * background(random(255), random(255), 255);
+ * text('click to play', width/2, height/2);
+ * }
+ *
+ * var monoSynth;
+ *
+ * function setup() {
+ * var cnv = createCanvas(100, 100);
+ * cnv.mousePressed(playSynth);
+ *
+ * monoSynth = new p5.MonoSynth();
+ *
+ * textAlign(CENTER);
+ * text('click to play', width/2, height/2);
+ * }
+ *
+ * function playSynth() {
+ * // time from now (in seconds)
+ * var time = 0;
+ * // note duration (in seconds)
+ * var dur = 1/6;
+ * // note velocity (volume, from 0 to 1)
+ * var v = random();
+ *
+ * monoSynth.play("Fb3", v, 0, dur);
+ * monoSynth.play("Gb3", v, time += dur, dur);
+ *
+ * background(random(255), random(255), 255);
+ * text('click to play', width/2, height/2);
+ * }
+ *
+ * var monoSynth = new p5.MonoSynth();
+ *
+ * function mousePressed() {
+ * monoSynth.triggerAttack("E3");
+ * }
+ *
+ * function mouseReleased() {
+ * monoSynth.triggerRelease();
+ * }
+ *
+ * var monoSynth = new p5.MonoSynth();
+ *
+ * function mousePressed() {
+ * monoSynth.triggerAttack("E3");
+ * }
+ *
+ * function mouseReleased() {
+ * monoSynth.triggerRelease();
+ * }
+ *
setRange
),
+ * then decayLevel would increase proportionally, to become 0.5.
+ * @param {Number} [releaseTime] Time in seconds from now (defaults to 0)
+ */
+ p5.MonoSynth.prototype.setADSR = function (attack, decay, sustain, release) {
+ this.env.setADSR(attack, decay, sustain, release);
+ };
+ /**
+ * Getters and Setters
+ * @property {Number} attack
+ */
+ /**
+ * @property {Number} decay
+ */
+ /**
+ * @property {Number} sustain
+ */
+ /**
+ * @property {Number} release
+ */
+ Object.defineProperties(p5.MonoSynth.prototype, {
+ 'attack': {
+ get: function () {
+ return this.env.aTime;
+ },
+ set: function (attack) {
+ this.env.setADSR(attack, this.env.dTime, this.env.sPercent, this.env.rTime);
+ }
+ },
+ 'decay': {
+ get: function () {
+ return this.env.dTime;
+ },
+ set: function (decay) {
+ this.env.setADSR(this.env.aTime, decay, this.env.sPercent, this.env.rTime);
+ }
+ },
+ 'sustain': {
+ get: function () {
+ return this.env.sPercent;
+ },
+ set: function (sustain) {
+ this.env.setADSR(this.env.aTime, this.env.dTime, sustain, this.env.rTime);
+ }
+ },
+ 'release': {
+ get: function () {
+ return this.env.rTime;
+ },
+ set: function (release) {
+ this.env.setADSR(this.env.aTime, this.env.dTime, this.env.sPercent, release);
+ }
+ }
+ });
+ /**
+ * MonoSynth amp
+ * @method amp
+ * @param {Number} vol desired volume
+ * @param {Number} [rampTime] Time to reach new volume
+ * @return {Number} new volume value
+ */
+ p5.MonoSynth.prototype.amp = function (vol, rampTime) {
+ var t = rampTime || 0;
+ if (typeof vol !== 'undefined') {
+ this.oscillator.amp(vol, t);
+ }
+ return this.oscillator.amp().value;
+ };
+ /**
+ * Connect to a p5.sound / Web Audio object.
+ *
+ * @method connect
+ * @param {Object} unit A p5.sound or Web Audio object
+ */
+ p5.MonoSynth.prototype.connect = function (unit) {
+ var u = unit || p5sound.input;
+ this.output.connect(u.input ? u.input : u);
+ };
+ /**
+ * Disconnect all outputs
+ *
+ * @method disconnect
+ */
+ p5.MonoSynth.prototype.disconnect = function () {
+ if (this.output) {
+ this.output.disconnect();
+ }
+ };
+ /**
+ * Get rid of the MonoSynth and free up its resources / memory.
+ *
+ * @method dispose
+ */
+ p5.MonoSynth.prototype.dispose = function () {
+ AudioVoice.prototype.dispose.apply(this);
+ if (this.env) {
+ this.env.dispose();
+ }
+ if (this.oscillator) {
+ this.oscillator.dispose();
+ }
+ };
+}(master, audioVoice, helpers);
+var polysynth;
+'use strict';
+polysynth = function () {
+ var p5sound = master;
+ var TimelineSignal = Tone_signal_TimelineSignal;
+ var noteToFreq = helpers.noteToFreq;
+ /**
+ * An AudioVoice is used as a single voice for sound synthesis.
+ * The PolySynth class holds an array of AudioVoice, and deals
+ * with voices allocations, with setting notes to be played, and
+ * parameters to be set.
+ *
+ * @class p5.PolySynth
+ * @constructor
+ *
+ * @param {Number} [synthVoice] A monophonic synth voice inheriting
+ * the AudioVoice class. Defaults to p5.MonoSynth
+ * @param {Number} [maxVoices] Number of voices, defaults to 8;
+ * @example
+ *
+ * var polySynth;
+ *
+ * function setup() {
+ * var cnv = createCanvas(100, 100);
+ * cnv.mousePressed(playSynth);
+ *
+ * polySynth = new p5.PolySynth();
+ *
+ * textAlign(CENTER);
+ * text('click to play', width/2, height/2);
+ * }
+ *
+ * function playSynth() {
+ * // note duration (in seconds)
+ * var dur = 1.5;
+ *
+ * // time from now (in seconds)
+ * var time = 0;
+ *
+ * // velocity (volume, from 0 to 1)
+ * var vel = 0.1;
+ *
+ * // notes can overlap with each other
+ * polySynth.play("G2", vel, 0, dur);
+ * polySynth.play("C3", vel, time += 1/3, dur);
+ * polySynth.play("G3", vel, time += 1/3, dur);
+ *
+ * background(random(255), random(255), 255);
+ * text('click to play', width/2, height/2);
+ * }
+ *
+ * var polySynth;
+ *
+ * function setup() {
+ * var cnv = createCanvas(100, 100);
+ * cnv.mousePressed(playSynth);
+ *
+ * polySynth = new p5.PolySynth();
+ *
+ * textAlign(CENTER);
+ * text('click to play', width/2, height/2);
+ * }
+ *
+ * function playSynth() {
+ * // note duration (in seconds)
+ * var dur = 0.1;
+ *
+ * // time from now (in seconds)
+ * var time = 0;
+ *
+ * // velocity (volume, from 0 to 1)
+ * var vel = 0.1;
+ *
+ * polySynth.play("G2", vel, 0, dur);
+ * polySynth.play("C3", vel, 0, dur);
+ * polySynth.play("G3", vel, 0, dur);
+ *
+ * background(random(255), random(255), 255);
+ * text('click to play', width/2, height/2);
+ * }
+ *
setRange
),
+ * then decayLevel would increase proportionally, to become 0.5.
+ * @param {Number} [releaseTime] Time in seconds from now (defaults to 0)
+ **/
+ p5.PolySynth.prototype.noteADSR = function (note, a, d, s, r, timeFromNow) {
+ var now = p5sound.audiocontext.currentTime;
+ var timeFromNow = timeFromNow || 0;
+ var t = now + timeFromNow;
+ this.audiovoices[this.notes[note].getValueAtTime(t)].setADSR(a, d, s, r);
+ };
+ /**
+ * Set the PolySynths global envelope. This method modifies the envelopes of each
+ * monosynth so that all notes are played with this envelope.
+ *
+ * @method setADSR
+ * @param {Number} [attackTime] Time (in seconds before envelope
+ * reaches Attack Level
+ * @param {Number} [decayTime] Time (in seconds) before envelope
+ * reaches Decay/Sustain Level
+ * @param {Number} [susRatio] Ratio between attackLevel and releaseLevel, on a scale from 0 to 1,
+ * where 1.0 = attackLevel, 0.0 = releaseLevel.
+ * The susRatio determines the decayLevel and the level at which the
+ * sustain portion of the envelope will sustain.
+ * For example, if attackLevel is 0.4, releaseLevel is 0,
+ * and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is
+ * increased to 1.0 (using setRange
),
+ * then decayLevel would increase proportionally, to become 0.5.
+ * @param {Number} [releaseTime] Time in seconds from now (defaults to 0)
+ **/
+ p5.PolySynth.prototype.setADSR = function (a, d, s, r) {
+ this.audiovoices.forEach(function (voice) {
+ voice.setADSR(a, d, s, r);
+ });
+ };
+ /**
+ * Trigger the Attack, and Decay portion of a MonoSynth.
+ * Similar to holding down a key on a piano, but it will
+ * hold the sustain level until you let go.
+ *
+ * @method noteAttack
+ * @param {Number} [note] midi note on which attack should be triggered.
+ * @param {Number} [velocity] velocity of the note to play (ranging from 0 to 1)/
+ * @param {Number} [secondsFromNow] time from now (in seconds)
+ * @example
+ *
+ * var polySynth = new p5.PolySynth();
+ * var pitches = ["G", "D", "G", "C"];
+ * var octaves = [2, 3, 4];
+ *
+ * function mousePressed() {
+ * // play a chord: multiple notes at the same time
+ * for (var i = 0; i < 4; i++) {
+ * var note = random(pitches) + random(octaves);
+ * polySynth.noteAttack(note, 0.1);
+ * }
+ * }
+ *
+ * function mouseReleased() {
+ * // release all voices
+ * polySynth.noteRelease();
+ * }
+ *
+ * var pitches = ["G", "D", "G", "C"];
+ * var octaves = [2, 3, 4];
+ * var polySynth = new p5.PolySynth();
+ *
+ * function mousePressed() {
+ * // play a chord: multiple notes at the same time
+ * for (var i = 0; i < 4; i++) {
+ * var note = random(pitches) + random(octaves);
+ * polySynth.noteAttack(note, 0.1);
+ * }
+ * }
+ *
+ * function mouseReleased() {
+ * // release all voices
+ * polySynth.noteRelease();
+ * }
+ *
This is the p5 instance constructor.
\nA p5 instance holds all the properties and methods related to\na p5 sketch. It expects an incoming sketch closure and it can also\ntake an optional node parameter for attaching the generated p5 canvas\nto a node. The sketch closure takes the newly created p5 instance as\nits sole argument and may optionally set preload(), setup(), and/or\ndraw() properties on it for running a sketch.
\nA p5 sketch can run in "global" or "instance" mode:\n"global" - all properties and methods are attached to the window\n"instance" - all properties and methods are bound to this p5 object
\n" }, "Table": { @@ -1425,7 +1425,7 @@ module.exports={ }, "namespaces": {}, "file": "src/typography/p5.Font.js", - "line": 21 + "line": 15 }, "Font": { "name": "Font", @@ -1440,7 +1440,7 @@ module.exports={ "module": "Typography", "namespace": "", "file": "src/typography/p5.Font.js", - "line": 21, + "line": 15, "description": "This module defines the p5.Font class and functions for\ndrawing text to the display canvas.
\n", "requires": [ "core", @@ -1700,8 +1700,8 @@ module.exports={ "namespaces": {}, "module": "p5.dom", "file": "lib/addons/p5.dom.js", - "line": 3083, - "description": "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.
\nThere is a set of creation methods, DOM manipulation methods, and\nan extended p5.Element that supports a range of HTML elements. See the\n\nbeyond the canvas tutorial for a full overview of how this addon works.
\nMethods 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.
\nSee tutorial: beyond the canvas\nfor more info on how to use this libary.
\n", + "line": 3331, + "description": "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.
\nThere is a set of creation methods, DOM manipulation methods, and\nan extended p5.Element that supports a range of HTML elements. See the\n\nbeyond the canvas tutorial for a full overview of how this addon works.
\nMethods 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.
\nSee tutorial: beyond the canvas\nfor more info on how to use this library.
\n", "tag": "main", "itemtype": "main" }, @@ -1754,8 +1754,8 @@ module.exports={ "namespaces": {}, "module": "p5.sound", "file": "lib/addons/p5.sound.js", - "line": 12501, - "description": "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.
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.Envelope: 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.
A simple Dictionary class for Strings.
\n", "extends": "p5.TypedDict" }, @@ -1961,7 +1961,7 @@ module.exports={ "submodule": "Dictionary", "namespace": "", "file": "src/data/p5.TypedDict.js", - "line": 410, + "line": 422, "description": "A simple Dictionary class for Numbers.
\n", "extends": "p5.TypedDict" }, @@ -1980,7 +1980,7 @@ module.exports={ "line": 23, "description": "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.
\nfunction setup() {\n var img = createImage(100, 100); // same as new p5.Image(100, 100);\n img.loadPixels();\n createCanvas(100, 100);\n background(0);\n\n // helper for writing color to array\n function writeColor(image, x, y, red, green, blue, alpha) {\n var index = (x + y * width) * 4;\n image.pixels[index] = red;\n image.pixels[index + 1] = green;\n image.pixels[index + 2] = blue;\n image.pixels[index + 3] = alpha;\n }\n\n var x, y;\n // fill with random colors\n for (y = 0; y < img.height; y++) {\n for (x = 0; x < img.width; x++) {\n var red = random(255);\n var green = random(255);\n var blue = random(255);\n var alpha = 255;\n writeColor(img, x, y, red, green, blue, alpha);\n }\n }\n\n // draw a red line\n y = 0;\n for (x = 0; x < img.width; x++) {\n writeColor(img, x, y, 255, 0, 0, 255);\n }\n\n // draw a green line\n y = img.height - 1;\n for (x = 0; x < img.width; x++) {\n writeColor(img, x, y, 0, 255, 0, 255);\n }\n\n img.updatePixels();\n image(img, 0, 0);\n}\n
\nfunction setup() {\n let img = createImage(100, 100); // same as new p5.Image(100, 100);\n img.loadPixels();\n createCanvas(100, 100);\n background(0);\n\n // helper for writing color to array\n function writeColor(image, x, y, red, green, blue, alpha) {\n let index = (x + y * width) * 4;\n image.pixels[index] = red;\n image.pixels[index + 1] = green;\n image.pixels[index + 2] = blue;\n image.pixels[index + 3] = alpha;\n }\n\n let x, y;\n // fill with random colors\n for (y = 0; y < img.height; y++) {\n for (x = 0; x < img.width; x++) {\n let red = random(255);\n let green = random(255);\n let blue = random(255);\n let alpha = 255;\n writeColor(img, x, y, red, green, blue, alpha);\n }\n }\n\n // draw a red line\n y = 0;\n for (x = 0; x < img.width; x++) {\n writeColor(img, x, y, 255, 0, 0, 255);\n }\n\n // draw a green line\n y = img.height - 1;\n for (x = 0; x < img.width; x++) {\n writeColor(img, x, y, 0, 255, 0, 255);\n }\n\n img.updatePixels();\n image(img, 0, 0);\n}\n
XML is a representation of an XML object, able to parse XML code. Use\nloadXML() to load external XML files and create XML objects.
\n", "is_constructor": 1, "example": [ - "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\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].getNum('id');\n var coloring = children[i].getString('species');\n var name = children[i].getContent();\n print(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
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let children = xml.getChildren('animal');\n\n for (let i = 0; i < children.length; i++) {\n let id = children[i].getNum('id');\n let coloring = children[i].getString('species');\n let name = children[i].getContent();\n print(id + ', ' + coloring + ', ' + name);\n }\n}\n\n// Sketch prints:\n// 0, Capra hircus, Goat\n// 1, Panthera pardus, Leopard\n// 2, Equus zebra, Zebra\n
\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
\n\nlet v1 = createVector(40, 50);\nlet v2 = createVector(40, 50);\n\nellipse(v1.x, v1.y, 50, 50);\nellipse(v2.x, v2.y, 50, 50);\nv1.add(v2);\nellipse(v1.x, v1.y, 50, 50);\n
\nBase class for font handling
\n", "params": [ { @@ -2180,7 +2180,7 @@ module.exports={ } ], "example": [ - "\n\nvar cam;\nvar delta = 0.01;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n // set initial pan angle\n cam.pan(-0.8);\n}\n\nfunction draw() {\n background(200);\n\n // pan camera according to angle 'delta'\n cam.pan(delta);\n\n // every 160 frames, switch direction\n if (frameCount % 160 === 0) {\n delta *= -1;\n }\n\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n
\n\nlet cam;\nlet delta = 0.01;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n // set initial pan angle\n cam.pan(-0.8);\n}\n\nfunction draw() {\n background(200);\n\n // pan camera according to angle 'delta'\n cam.pan(delta);\n\n // every 160 frames, switch direction\n if (frameCount % 160 === 0) {\n delta *= -1;\n }\n\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n
\nExtends p5.Element to handle audio and video. In addition to the methods\nof p5.Element, it also contains methods for controlling media. It is not\ncalled directly, but p5.MediaElements are created by calling createVideo,\ncreateAudio, and createCapture.
\n", "is_constructor": 1, "params": [ @@ -2286,8 +2286,8 @@ module.exports={ "submodule": "p5.dom", "namespace": "", "file": "lib/addons/p5.dom.js", - "line": 3083, - "description": "Base class for a file\nUsing this for createFileInput
\n", + "line": 3331, + "description": "Base class for a file.\nUsed for Element.drop and createFileInput.
\n", "is_constructor": 1, "params": [ { @@ -2321,7 +2321,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 808, + "line": 1645, "description": "SoundFile object with a path to a file.
\n\nThe p5.SoundFile may not be available immediately because\nit loads the file information asynchronously.
\n\nTo do something with the sound as soon as it loads\npass the name of a function as the second parameter.
\n\nOnly one file path is required. However, audio file formats\n(i.e. mp3, ogg, wav and m4a/aac) are not supported by all\nweb browsers. If you want to ensure compatability, instead of a single\nfile path, you may include an Array of filepaths, and the browser will\nchoose a format that works.
", "is_constructor": 1, "params": [ @@ -2365,7 +2365,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 2234, + "line": 3179, "description": "Amplitude measures volume between 0.0 and 1.0.\nListens to all p5sound by default, or use setInput()\nto listen to a specific sound source. Accepts an optional\nsmoothing value, which defaults to 0.
\n", "is_constructor": 1, "params": [ @@ -2392,7 +2392,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 2513, + "line": 3458, "description": "FFT (Fast Fourier Transform) is an analysis algorithm that\nisolates individual\n\naudio frequencies within a waveform.
\n\nOnce instantiated, a p5.FFT object can return an array based on\ntwo types of analyses:
• FFT.waveform()
computes\namplitude values along the time domain. The array indices correspond\nto samples across a brief moment in time. Each value represents\namplitude of the waveform at that sample of time.
\n• FFT.analyze()
computes amplitude values along the\nfrequency domain. The array indices correspond to frequencies (i.e.\npitches), from the lowest to the highest that humans can hear. Each\nvalue represents amplitude at that slice of the frequency spectrum.\nUse with getEnergy()
to measure amplitude at specific\nfrequencies, or within a range of frequencies.
FFT analyzes a very short snapshot of sound called a sample\nbuffer. It returns an array of amplitude measurements, referred\nto as bins
. The array is 1024 bins long by default.\nYou can change the bin array length, but it must be a power of 2\nbetween 16 and 1024 in order for the FFT algorithm to function\ncorrectly. The actual size of the FFT buffer is twice the\nnumber of bins, so given a standard sample rate, the buffer is\n2048/44100 seconds long.
p5.Signal is a constant audio-rate signal used by p5.Oscillator\nand p5.Envelope for modulation math.
\n\nThis 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.</p.\n\n
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.
", "is_constructor": 1, "return": { @@ -2448,7 +2448,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 5062, + "line": 5369, "description": "Creates a signal that oscillates between -1.0 and 1.0.\nBy default, the oscillation takes the form of a sinusoidal\nshape ('sine'). Additional types include 'triangle',\n'sawtooth' and 'square'. The frequency defaults to\n440 oscillations per second (440Hz, equal to the pitch of an\n'A' note).
\n\nSet the type of oscillation with setType(), or by instantiating a\nspecific oscillator: p5.SinOsc, p5.TriOsc, p5.SqrOsc, or p5.SawOsc.\n
", "is_constructor": 1, "params": [ @@ -2481,7 +2481,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 5503, + "line": 5810, "description": "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.
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.
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.
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.
Envelopes are pre-defined amplitude distribution over time.\nTypically, envelopes are used to control the output volume\nof an object, a series of fades referred to as Attack, Decay,\nSustain and Release (\nADSR\n). Envelopes can also control other Web Audio Parameters—for example, a p5.Envelope can\ncontrol an Oscillator's frequency like this: osc.freq(env)
.
Use setRange
to change the attack/release level.\nUse setADSR
to change attackTime, decayTime, sustainPercent and releaseTime.
Use the play
method to play the entire envelope,\nthe ramp
method for a pingable trigger,\nor triggerAttack
/\ntriggerRelease
to trigger noteOn/noteOff.
\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.Envelope();\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
\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.Envelope();\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.
Noise is a type of oscillator that generates a buffer with random values.
\n", "extends": "p5.Oscillator", "is_constructor": 1, @@ -2658,7 +2658,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 7136, + "line": 7441, "description": "Get audio from an input, i.e. your computer's microphone.
\n\nTurn the mic on/off with the start() and stop() methods. When the mic\nis on, its volume can be measured with getLevel or by connecting an\nFFT object.
\n\nIf you want to hear the AudioIn, use the .connect() method.\nAudioIn does not connect to p5.sound output by default to prevent\nfeedback.
\n\nNote: This uses the getUserMedia/\nStream API, which is not supported by certain browsers. Access in Chrome browser\nis limited to localhost and https, but access over http may be limited.
", "is_constructor": 1, "params": [ @@ -2685,7 +2685,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 8033, + "line": 8357, "description": "Effect is a base class for audio effects in p5.
\nThis module handles the nodes and methods that are \ncommon and useful for current and future effects.
This class is extended by p5.Distortion, \np5.Compressor,\np5.Delay, \np5.Filter, \np5.Reverb.
\n", "is_constructor": 1, "params": [ @@ -2733,7 +2733,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 8175, + "line": 8499, "description": "A p5.Filter uses a Web Audio Biquad Filter to filter\nthe frequency response of an input source. Subclasses\ninclude:
\np5.LowPass
:\nAllows frequencies below the cutoff frequency to pass through,\nand attenuates frequencies above the cutoff.p5.HighPass
:\nThe opposite of a lowpass filter. p5.BandPass
:\nAllows a range of frequencies to pass through and attenuates\nthe frequencies below and above this frequency range.The .res()
method controls either width of the\nbandpass, or resonance of the low/highpass cutoff frequency.
This class extends p5.Effect.
Methods amp(), chain(), \ndrywet(), connect(), and \ndisconnect() are available.
Constructor: new p5.LowPass()
Filter.\nThis is the same as creating a p5.Filter and then calling\nits method setType('lowpass')
.\nSee p5.Filter for methods.
Constructor: new p5.HighPass()
Filter.\nThis is the same as creating a p5.Filter and then calling\nits method setType('highpass')
.\nSee p5.Filter for methods.
Constructor: new p5.BandPass()
Filter.\nThis is the same as creating a p5.Filter and then calling\nits method setType('bandpass')
.\nSee p5.Filter for methods.
p5.EQ is an audio effect that performs the function of a multiband\naudio equalizer. Equalization is used to adjust the balance of\nfrequency compoenents of an audio signal. This process is commonly used\nin sound production and recording to change the waveform before it reaches\na sound output device. EQ can also be used as an audio effect to create\ninteresting distortions by filtering out parts of the spectrum. p5.EQ is\nbuilt using a chain of Web Audio Biquad Filter Nodes and can be\ninstantiated with 3 or 8 bands. Bands can be added or removed from\nthe EQ by directly modifying p5.EQ.bands (the array that stores filters).
\nThis class extends p5.Effect.\nMethods amp(), chain(),\ndrywet(), connect(), and\ndisconnect() are available.
\n", "is_constructor": 1, "extends": "p5.Effect", @@ -2844,7 +2844,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 8698, + "line": 9021, "description": "Panner3D is based on the \nWeb Audio Spatial Panner Node.\nThis panner is a spatial processing node that allows audio to be positioned\nand oriented in 3D space.
\nThe position is relative to an \nAudio Context Listener, which can be accessed\nby p5.soundOut.audiocontext.listener
Delay is an echo effect. It processes an existing sound source,\nand outputs a delayed version of that sound. The p5.Delay can\nproduce different effects depending on the delayTime, feedback,\nfilter, and type. In the example below, a feedback of 0.5 (the\ndefaul value) will produce a looping delay that decreases in\nvolume by 50% each repeat. A filter will cut out the high\nfrequencies so that the delay does not sound as piercing as the\noriginal source.
\nThis class extends p5.Effect.
Methods amp(), chain(), \ndrywet(), connect(), and \ndisconnect() are available.
Reverb adds depth to a sound through a large number of decaying\nechoes. It creates the perception that sound is occurring in a\nphysical space. The p5.Reverb has paramters for Time (how long does the\nreverb last) and decayRate (how much the sound decays with each echo)\nthat can be set with the .set() or .process() methods. The p5.Convolver\nextends p5.Reverb allowing you to recreate the sound of actual physical\nspaces through convolution.
\nThis class extends p5.Effect.\nMethods amp(), chain(),\ndrywet(), connect(), and\ndisconnect() are available.
\n", "extends": "p5.Effect", "is_constructor": 1, @@ -2900,7 +2900,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 9586, + "line": 9920, "description": "p5.Convolver extends p5.Reverb. It can emulate the sound of real\nphysical spaces through a process called \nconvolution.
\n\nConvolution multiplies any audio input by an "impulse response"\nto simulate the dispersion of sound over time. The impulse response is\ngenerated from an audio file that you provide. One way to\ngenerate an impulse response is to pop a balloon in a reverberant space\nand record the echo. Convolution can also be used to experiment with\nsound.
\n\nUse the method createConvolution(path)
to instantiate a\np5.Convolver with a path to your impulse response audio file.
A phrase is a pattern of musical events over time, i.e.\na series of notes and rests.
\n\nPhrases must be added to a p5.Part for playback, and\neach part can play multiple phrases at the same time.\nFor example, one Phrase might be a kick drum, another\ncould be a snare, and another could be the bassline.
\n\nThe first parameter is a name so that the phrase can be\nmodified or deleted later. The callback is a a function that\nthis phrase will call at every step—for example it might be\ncalled playNote(value){}
. The array determines\nwhich value is passed into the callback at each step of the\nphrase. It can be numbers, an object with multiple numbers,\nor a zero (0) indicates a rest so the callback won't be called).
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.
\n\nSee p5.Phrase for more about musical timing.
", + "line": 10561, + "description": "A p5.Part plays back one or more p5.Phrases. Instantiate a part\nwith steps and tatums. By default, each step represents a 1/16th note.
\n\nSee p5.Phrase for more about musical timing.
", "is_constructor": 1, "params": [ { @@ -2987,7 +2987,7 @@ module.exports={ }, { "name": "tatums", - "description": "Divisions of a beat (default is 1/16, a quarter note)
\n", + "description": "Divisions of a beat, e.g. use 1/4, or 0.25 for a quater note (default is 1/16, a sixteenth note)
\n", "type": "Number", "optional": true } @@ -3008,7 +3008,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 10487, + "line": 10814, "description": "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)
SoundLoop
\n", "is_constructor": 1, "params": [ @@ -3065,7 +3065,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 10878, + "line": 11205, "description": "Compressor is an audio effect class that performs dynamics compression\non an audio input source. This is a very commonly used technique in music\nand sound production. Compression creates an overall louder, richer, \nand fuller sound by lowering the volume of louds and raising that of softs.\nCompression can be used to avoid clipping (sound distortion due to \npeaks in volume) and is especially useful when many sounds are played \nat once. Compression can be used on indivudal sound sources in addition\nto the master output.
\nThis class extends p5.Effect.
Methods amp(), chain(), \ndrywet(), connect(), and \ndisconnect() are available.
Record sounds for playback and/or to save as a .wav file.\nThe p5.SoundRecorder records all sound output from your sketch,\nor can be assigned a specific source with setInput().
\nThe record() method accepts a p5.SoundFile as a parameter.\nWhen playback is stopped (either after the given amount of time,\nor with the stop() method), the p5.SoundRecorder will send its\nrecording to that p5.SoundFile for playback.
", "is_constructor": 1, "example": [ @@ -3101,8 +3101,8 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 11378, - "description": "PeakDetect works in conjunction with p5.FFT to\nlook for onsets in some or all of the frequency spectrum.\n
\n\nTo use p5.PeakDetect, call update
in the draw loop\nand pass in a p5.FFT object.\n
\nYou can listen for a specific part of the frequency spectrum by\nsetting the range between freq1
and freq2
.\n
threshold
is the threshold for detecting a peak,\nscaled between 0 and 1. It is logarithmic, so 0.1 is half as loud\nas 1.0.
\nThe update method is meant to be run in the draw loop, and\nframes determines how many loops must pass before\nanother peak can be detected.\nFor example, if the frameRate() = 60, you could detect the beat of a\n120 beat-per-minute song with this equation:\n framesPerPeak = 60 / (estimatedBPM / 60 );
\n
\nBased on example contribtued by @b2renger, and a simple beat detection\nexplanation by a\nhref="http://www.airtightinteractive.com/2013/10/making-audio-reactive-visuals/"\ntarget="_blank"Felix Turner.\n
", + "line": 11655, + "description": "PeakDetect works in conjunction with p5.FFT to\nlook for onsets in some or all of the frequency spectrum.\n
\n\nTo use p5.PeakDetect, call update
in the draw loop\nand pass in a p5.FFT object.\n
\nYou can listen for a specific part of the frequency spectrum by\nsetting the range between freq1
and freq2
.\n
threshold
is the threshold for detecting a peak,\nscaled between 0 and 1. It is logarithmic, so 0.1 is half as loud\nas 1.0.
\nThe update method is meant to be run in the draw loop, and\nframes determines how many loops must pass before\nanother peak can be detected.\nFor example, if the frameRate() = 60, you could detect the beat of a\n120 beat-per-minute song with this equation:\n framesPerPeak = 60 / (estimatedBPM / 60 );
\n
\nBased on example contribtued by @b2renger, and a simple beat detection\nexplanation by Felix Turner.\n
", "is_constructor": 1, "params": [ { @@ -3146,7 +3146,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 11602, + "line": 11879, "description": "A gain node is usefull to set the relative volume of sound.\nIt's typically used to build mixers.
\n", "is_constructor": 1, "example": [ @@ -3165,7 +3165,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 11743, + "line": 12020, "description": "Base class for monophonic synthesizers. Any extensions of this class\nshould follow the API and implement the methods below in order to \nremain compatible with p5.PolySynth();
\n", "is_constructor": 1 }, @@ -3181,7 +3181,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 11796, + "line": 12073, "description": "A MonoSynth is used as a single voice for sound synthesis.\nThis is a class to be used in conjunction with the PolySynth\nclass. Custom synthetisers should be built inheriting from\nthis class.
\n", "is_constructor": 1, "example": [ @@ -3200,7 +3200,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 12096, + "line": 12362, "description": "An AudioVoice is used as a single voice for sound synthesis.\nThe PolySynth class holds an array of AudioVoice, and deals\nwith voices allocations, with setting notes to be played, and\nparameters to be set.
\n", "is_constructor": 1, "params": [ @@ -3233,7 +3233,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 12501, + "line": 12767, "description": "A Distortion effect created with a Waveshaper Node,\nwith an approach adapted from\nKevin Ennis
\nThis class extends p5.Effect.
Methods amp(), chain(), \ndrywet(), connect(), and \ndisconnect() are available.
\nnoStroke();\nvar c = color(0, 126, 255, 102);\nfill(c);\nrect(15, 15, 35, 70);\nvar value = alpha(c); // Sets 'value' to 102\nfill(value);\nrect(50, 15, 35, 70);\n
\n\nnoStroke();\nlet c = color(0, 126, 255, 102);\nfill(c);\nrect(15, 15, 35, 70);\nlet value = alpha(c); // Sets 'value' to 102\nfill(value);\nrect(50, 15, 35, 70);\n
\n\nvar c = 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\nvar blueValue = blue(c); // Get blue in 'c'\nprint(blueValue); // Prints \"220.0\"\nfill(0, 0, blueValue); // Use 'blueValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n
\n\nlet c = 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\nlet blueValue = blue(c); // Get blue in 'c'\nprint(blueValue); // Prints \"220.0\"\nfill(0, 0, blueValue); // Use 'blueValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n
\n\nnoStroke();\ncolorMode(HSB, 255);\nvar c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nvar value = brightness(c); // Sets 'value' to 255\nfill(value);\nrect(50, 20, 35, 60);\n
\n\nnoStroke();\ncolorMode(HSB, 255);\nlet c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nlet value = brightness(c); // Sets 'value' to 255\nfill(value);\nrect(50, 20, 35, 60);\n
\n\nnoStroke();\ncolorMode(HSB, 255);\nlet c = color('hsb(60, 100%, 50%)');\nfill(c);\nrect(15, 20, 35, 60);\nlet value = brightness(c); // A 'value' of 50% is 127.5\nfill(value);\nrect(50, 20, 35, 60);\n
\nCreates colors for storing in variables of the color datatype. The\nparameters are interpreted as RGB or HSB values depending on the\ncurrent colorMode(). The default mode is RGB values from 0 to 255\nand, therefore, the function call color(255, 204, 0) will return a\nbright yellow color.\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.\n
\nIf a single string argument is provided, RGB, RGBA and Hex CSS color\nstrings and all named color strings are supported. In this case, an alpha\nnumber value as a second argument is not supported, the RGBA form should be\nused.
\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
\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.\nc = 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\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\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\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\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\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
\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
\n\nlet 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
\n\nlet 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.\nc = 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\n// Named SVG & CSS colors may be used,\nlet 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\n// as can hex color codes:\nnoStroke(); // Don't draw a stroke around shapes\nlet 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\n// RGB and RGBA color strings are also supported:\n// these all set to the same color (solid blue)\nlet 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\n// HSL color is also supported and can be specified\n// by value\nlet 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\n// HSB color is also supported and can be specified\n// by value\nlet 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
\n\nlet 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
\nExtracts the green value from a color or pixel array.
\n", "itemtype": "method", "name": "green", @@ -3518,7 +3518,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\nvar c = color(20, 75, 200); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nvar greenValue = green(c); // Get green in 'c'\nprint(greenValue); // Print \"75.0\"\nfill(0, greenValue, 0); // Use 'greenValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n
\n\nlet c = color(20, 75, 200); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nlet greenValue = green(c); // Get green in 'c'\nprint(greenValue); // Print \"75.0\"\nfill(0, greenValue, 0); // Use 'greenValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n
\nExtracts the hue value from a color or pixel array.
\nHue exists in both HSB and HSL. This function will return the\nHSB-normalized hue when supplied with an HSB color object (or when supplied\nwith a pixel array while the color mode is HSB), but will default to the\nHSL-normalized hue otherwise. (The values will only be different if the\nmaximum hue setting for each system is different.)
\n", "itemtype": "method", "name": "hue", @@ -3543,7 +3543,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\nnoStroke();\ncolorMode(HSB, 255);\nvar c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nvar value = hue(c); // Sets 'value' to \"0\"\nfill(value);\nrect(50, 20, 35, 60);\n
\n\nnoStroke();\ncolorMode(HSB, 255);\nlet c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nlet value = hue(c); // Sets 'value' to \"0\"\nfill(value);\nrect(50, 20, 35, 60);\n
\nBlends two colors to find a third color somewhere between them. The amt\nparameter is the amount to interpolate between the two values where 0.0\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.
\ncolorMode(RGB);\nstroke(255);\nbackground(51);\nvar from = color(218, 165, 32);\nvar to = color(72, 61, 139);\ncolorMode(RGB); // Try changing to HSB.\nvar interA = lerpColor(from, to, 0.33);\nvar interB = lerpColor(from, to, 0.66);\nfill(from);\nrect(10, 20, 20, 60);\nfill(interA);\nrect(30, 20, 20, 60);\nfill(interB);\nrect(50, 20, 20, 60);\nfill(to);\nrect(70, 20, 20, 60);\n
\n\ncolorMode(RGB);\nstroke(255);\nbackground(51);\nlet from = color(218, 165, 32);\nlet to = color(72, 61, 139);\ncolorMode(RGB); // Try changing to HSB.\nlet interA = lerpColor(from, to, 0.33);\nlet interB = lerpColor(from, to, 0.66);\nfill(from);\nrect(10, 20, 20, 60);\nfill(interA);\nrect(30, 20, 20, 60);\nfill(interB);\nrect(50, 20, 20, 60);\nfill(to);\nrect(70, 20, 20, 60);\n
\nExtracts the HSL lightness value from a color or pixel array.
\n", "itemtype": "method", "name": "lightness", @@ -3603,7 +3603,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\nnoStroke();\ncolorMode(HSL);\nvar c = color(156, 100, 50, 1);\nfill(c);\nrect(15, 20, 35, 60);\nvar value = lightness(c); // Sets 'value' to 50\nfill(value);\nrect(50, 20, 35, 60);\n
\n\nnoStroke();\ncolorMode(HSL);\nlet c = color(156, 100, 50, 1);\nfill(c);\nrect(15, 20, 35, 60);\nlet value = lightness(c); // Sets 'value' to 50\nfill(value);\nrect(50, 20, 35, 60);\n
\nExtracts the red value from a color or pixel array.
\n", "itemtype": "method", "name": "red", @@ -3628,7 +3628,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\nvar c = color(255, 204, 0); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nvar redValue = red(c); // Get red in 'c'\nprint(redValue); // Print \"255.0\"\nfill(redValue, 0, 0); // Use 'redValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n
\n\ncolorMode(RGB, 255);\nvar c = color(127, 255, 0);\ncolorMode(RGB, 1);\nvar myColor = red(c);\nprint(myColor);\n
\n\nlet c = color(255, 204, 0); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nlet redValue = red(c); // Get red in 'c'\nprint(redValue); // Print \"255.0\"\nfill(redValue, 0, 0); // Use 'redValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n
\n\ncolorMode(RGB, 255); // Sets the range for red, green, and blue to 255\nlet c = color(127, 255, 0);\ncolorMode(RGB, 1); // Sets the range for red, green, and blue to 1\nlet myColor = red(c);\nprint(myColor); // 0.4980392156862745\n
\nExtracts the saturation value from a color or pixel array.
\nSaturation is scaled differently in HSB and HSL. This function will return\nthe HSB saturation when supplied with an HSB color object (or when supplied\nwith a pixel array while the color mode is HSB), but will default to the\nHSL saturation otherwise.
\n", "itemtype": "method", "name": "saturation", @@ -3653,7 +3653,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\nnoStroke();\ncolorMode(HSB, 255);\nvar c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nvar value = saturation(c); // Sets 'value' to 126\nfill(value);\nrect(50, 20, 35, 60);\n
\n\nnoStroke();\ncolorMode(HSB, 255);\nlet c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nlet value = saturation(c); // Sets 'value' to 126\nfill(value);\nrect(50, 20, 35, 60);\n
\n\nvar myColor;\nfunction setup() {\n createCanvas(200, 200);\n stroke(255);\n myColor = color(100, 100, 250);\n fill(myColor);\n}\n\nfunction draw() {\n rotate(HALF_PI);\n text(myColor.toString(), 0, -5);\n text(myColor.toString('#rrggbb'), 0, -30);\n text(myColor.toString('rgba%'), 0, -55);\n}\n
\n\nlet myColor;\nfunction setup() {\n createCanvas(200, 200);\n stroke(255);\n myColor = color(100, 100, 250);\n fill(myColor);\n}\n\nfunction draw() {\n rotate(HALF_PI);\n text(myColor.toString(), 0, -5);\n text(myColor.toString('#rrggbb'), 0, -30);\n text(myColor.toString('rgba%'), 0, -55);\n}\n
\n\nvar backgroundColor;\n\nfunction setup() {\n backgroundColor = color(100, 50, 150);\n}\n\nfunction draw() {\n backgroundColor.setRed(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n}\n
\n\nlet backgroundColor;\n\nfunction setup() {\n backgroundColor = color(100, 50, 150);\n}\n\nfunction draw() {\n backgroundColor.setRed(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n}\n
\n\nvar backgroundColor;\n\nfunction setup() {\n backgroundColor = color(100, 50, 150);\n}\n\nfunction draw() {\n backgroundColor.setGreen(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n}\n
\n\nlet backgroundColor;\n\nfunction setup() {\n backgroundColor = color(100, 50, 150);\n}\n\nfunction draw() {\n backgroundColor.setGreen(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n}\n
\n\nvar backgroundColor;\n\nfunction setup() {\n backgroundColor = color(100, 50, 150);\n}\n\nfunction draw() {\n backgroundColor.setBlue(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n}\n
\n\nlet backgroundColor;\n\nfunction setup() {\n backgroundColor = color(100, 50, 150);\n}\n\nfunction draw() {\n backgroundColor.setBlue(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n}\n
\n\nvar squareColor;\n\nfunction setup() {\n ellipseMode(CORNERS);\n strokeWeight(4);\n squareColor = color(100, 50, 150);\n}\n\nfunction draw() {\n background(255);\n\n noFill();\n stroke(0);\n ellipse(10, 10, width - 10, height - 10);\n\n squareColor.setAlpha(128 + 128 * sin(millis() / 1000));\n fill(squareColor);\n noStroke();\n rect(13, 13, width - 26, height - 26);\n}\n
\n\nlet squareColor;\n\nfunction setup() {\n ellipseMode(CORNERS);\n strokeWeight(4);\n squareColor = color(100, 50, 150);\n}\n\nfunction draw() {\n background(255);\n\n noFill();\n stroke(0);\n ellipse(10, 10, width - 10, height - 10);\n\n squareColor.setAlpha(128 + 128 * sin(millis() / 1000));\n fill(squareColor);\n noStroke();\n rect(13, 13, width - 26, height - 26);\n}\n
\nHue is the same in HSB and HSL, but the maximum value may be different.\nThis function will return the HSB-normalized saturation when supplied with\nan HSB color object, but will default to the HSL-normalized saturation\notherwise.
\n", "class": "p5.Color", "module": "Color", @@ -3776,7 +3776,7 @@ module.exports={ }, { "file": "src/color/p5.Color.js", - "line": 441, + "line": 446, "description": "Saturation is scaled differently in HSB and HSL. This function will return\nthe HSB saturation when supplied with an HSB color object, but will default\nto the HSL saturation otherwise.
\n", "class": "p5.Color", "module": "Color", @@ -3784,7 +3784,7 @@ module.exports={ }, { "file": "src/color/p5.Color.js", - "line": 460, + "line": 465, "description": "CSS named colors.
\n", "class": "p5.Color", "module": "Color", @@ -3792,7 +3792,7 @@ module.exports={ }, { "file": "src/color/p5.Color.js", - "line": 613, + "line": 618, "description": "These regular expressions are used to build up the patterns for matching\nviable CSS color strings: fragmenting the regexes in this way increases the\nlegibility and comprehensibility of the code.
\nNote that RGB values of .9 are not parsed by IE, but are supported here for\ncolor string consistency.
\n", "class": "p5.Color", "module": "Color", @@ -3800,7 +3800,7 @@ module.exports={ }, { "file": "src/color/p5.Color.js", - "line": 626, + "line": 631, "description": "Full color string patterns. The capture groups are necessary.
\n", "class": "p5.Color", "module": "Color", @@ -3808,7 +3808,7 @@ module.exports={ }, { "file": "src/color/p5.Color.js", - "line": 989, + "line": 994, "description": "For HSB and HSL, interpret the gray level as a brightness/lightness\nvalue (they are equivalent when chroma is zero). For RGB, normalize the\ngray level according to the blue maximum.
\n", "class": "p5.Color", "module": "Color", @@ -3817,7 +3817,7 @@ module.exports={ { "file": "src/color/setting.js", "line": 15, - "description": "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
\nThe color is either specified in terms of the RGB, HSB, or HSL color\ndepending on the current colorMode. (The default color space is RGB, with\neach value in the range from 0 to 255). The alpha range by default is also 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. In this case, an alpha number\nvalue as a second argument is not supported, the RGBA form should be used.\n
\nA p5.Color object can also be provided to set the background color.\n
\nA p5.Image can also be provided to set the background image.
The background() function sets the color used for the background of the\np5.js canvas. The default background is transparent. 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
\nThe color is either specified in terms of the RGB, HSB, or HSL color\ndepending on the current colorMode. (The default color space is RGB, with\neach value in the range from 0 to 255). The alpha range by default is also 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. In this case, an alpha number\nvalue as a second argument is not supported, the RGBA form should be used.\n
\nA p5.Color object can also be provided to set the background color.\n
\nA p5.Image can also be provided to set the background image.
an array containing the red,green,blue &\n and alpha components of the color
\n", + "description": "an array containing the red, green, blue\n and alpha components of the color
\n", "type": "Number[]" } ], @@ -3933,8 +3933,8 @@ module.exports={ }, { "file": "src/color/setting.js", - "line": 185, - "description": "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", + "line": 181, + "description": "Clears the pixels within a buffer. This function only clears the canvas.\nIt will not clear objects created by createX() methods such as\ncreateVideo() or createDiv().\nUnlike the main graphics context, pixels in additional graphics areas created\nwith createGraphics() can be entirely\nor partially transparent. This function clears everything to make all of\nthe pixels 100% transparent.
\n", "itemtype": "method", "name": "clear", "chainable": 1, @@ -3948,21 +3948,21 @@ module.exports={ }, { "file": "src/color/setting.js", - "line": 223, + "line": 220, "description": "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.
\nnoStroke();\ncolorMode(RGB, 100);\nfor (var i = 0; i < 100; i++) {\n for (var j = 0; j < 100; j++) {\n stroke(i, j, 0);\n point(i, j);\n }\n}\n
\n\nnoStroke();\ncolorMode(HSB, 100);\nfor (var i = 0; i < 100; i++) {\n for (var j = 0; j < 100; j++) {\n stroke(i, j, 100);\n point(i, j);\n }\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
\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
\n\nnoStroke();\ncolorMode(RGB, 100);\nfor (let i = 0; i < 100; i++) {\n for (let j = 0; j < 100; j++) {\n stroke(i, j, 0);\n point(i, j);\n }\n}\n
\n\nnoStroke();\ncolorMode(HSB, 100);\nfor (let i = 0; i < 100; i++) {\n for (let j = 0; j < 100; j++) {\n stroke(i, j, 100);\n point(i, j);\n }\n}\n
\n\ncolorMode(RGB, 255);\nlet c = color(127, 255, 0);\n\ncolorMode(RGB, 1);\nlet myColor = c._getRed();\ntext(myColor, 10, 10, 80, 80);\n
\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
\nrange for the blue or brightness/lighntess\n depending on the current color mode
\n", + "description": "range for the blue or brightness/lightness\n depending on the current color mode
\n", "type": "Number" }, { @@ -4014,7 +4014,7 @@ module.exports={ }, { "file": "src/color/setting.js", - "line": 344, + "line": 341, "description": "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). The alpha range by default is also 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. In this case, an alpha number\nvalue as a second argument is not supported, the RGBA form should be used.\n
\nA p5 Color object can also be provided to set the fill color.
\n// Grayscale integer value\nfill(51);\nrect(20, 20, 60, 60);\n
\n\n// R, G & B integer values\nfill(255, 204, 0);\nrect(20, 20, 60, 60);\n
\n\n// H, S & B integer values\ncolorMode(HSB);\nfill(255, 204, 100);\nrect(20, 20, 60, 60);\n
\n\n// Named SVG/CSS color string\nfill('red');\nrect(20, 20, 60, 60);\n
\n\n// three-digit hexadecimal RGB notation\nfill('#fae');\nrect(20, 20, 60, 60);\n
\n\n// six-digit hexadecimal RGB notation\nfill('#222222');\nrect(20, 20, 60, 60);\n
\n\n// integer RGB notation\nfill('rgb(0,255,0)');\nrect(20, 20, 60, 60);\n
\n\n// integer RGBA notation\nfill('rgba(0,255,0, 0.25)');\nrect(20, 20, 60, 60);\n
\n\n// percentage RGB notation\nfill('rgb(100%,0%,10%)');\nrect(20, 20, 60, 60);\n
\n\n// percentage RGBA notation\nfill('rgba(100%,0%,100%,0.5)');\nrect(20, 20, 60, 60);\n
\n\n// p5 Color object\nfill(color(0, 0, 255));\nrect(20, 20, 60, 60);\n
\nDisables filling geometry. If both noStroke() and noFill() are called,\nnothing will be drawn to the screen.
\n", "itemtype": "method", "name": "noFill", @@ -4123,7 +4123,7 @@ module.exports={ }, { "file": "src/color/setting.js", - "line": 542, + "line": 539, "description": "Disables drawing the stroke (outline). If both noStroke() and noFill()\nare called, nothing will be drawn to the screen.
\n", "itemtype": "method", "name": "noStroke", @@ -4138,7 +4138,7 @@ module.exports={ }, { "file": "src/color/setting.js", - "line": 582, + "line": 579, "description": "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). The alpha range by default is also 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. In this case, an alpha\nnumber value as a second argument is not supported, the RGBA form should be\nused.\n
\nA p5 Color object can also be provided to set the stroke color.
\n// Grayscale integer value\nstrokeWeight(4);\nstroke(51);\nrect(20, 20, 60, 60);\n
\n\n// R, G & B integer values\nstroke(255, 204, 0);\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n
\n\n// H, S & B integer values\ncolorMode(HSB);\nstrokeWeight(4);\nstroke(255, 204, 100);\nrect(20, 20, 60, 60);\n
\n\n// Named SVG/CSS color string\nstroke('red');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n
\n\n// three-digit hexadecimal RGB notation\nstroke('#fae');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n
\n\n// six-digit hexadecimal RGB notation\nstroke('#222222');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n
\n\n// integer RGB notation\nstroke('rgb(0,255,0)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n
\n\n// integer RGBA notation\nstroke('rgba(0,255,0,0.25)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n
\n\n// percentage RGB notation\nstroke('rgb(100%,0%,10%)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n
\n\n// percentage RGBA notation\nstroke('rgba(100%,0%,100%,0.5)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n
\n\n// p5 Color object\nstroke(color(0, 0, 255));\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n
\nDraw an arc to the screen. If called with only x, y, w, h, start, and\nstop, the arc will be drawn and filled as an open pie segment. If a mode parameter is provided, the arc\nwill be filled like an open semi-circle (OPEN) , a closed semi-circle (CHORD), or as a closed pie segment (PIE). 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.
This function does 3 things:
\nBounds the desired start/stop angles for an arc (in radians) so that:
\n0 <= start < TWO_PI ; start <= stop < start + TWO_PI\n
This means that the arc rendering functions don't have to be concerned\nwith what happens if stop is smaller than start, or if the arc 'goes\nround more than once', etc.: they can just start at start and increase\nuntil stop and the correct arc will be drawn.
\nOptionally adjusts the angles within each quadrant to counter the naive\nscaling of the underlying ellipse up from the unit circle. Without\nthis, the angles become arbitrary when width != height: 45 degrees\nmight be drawn at 5 degrees on a 'wide' ellipse, or at 85 degrees on\na 'tall' ellipse.
\nFlags up when start and stop correspond to the same place on the\nunderlying ellipse. This is useful if you want to do something special\nthere (like rendering a whole ellipse instead).
\nDraw an arc to the screen. If called with only x, y, w, h, start, and\nstop, the arc will be drawn and filled as an open pie segment. If a mode parameter is provided, the arc\nwill be filled like an open semi-circle (OPEN) , a closed semi-circle (CHORD), or as a closed pie segment (PIE). The\norigin may be changed with the ellipseMode() function.
\nThe arc is always drawn clockwise from wherever start falls to wherever stop falls on the ellipse.\nAdding or subtracting TWO_PI to either angle does not change where they fall.\nIf both start and stop fall at the same place, a full ellipse will be drawn.
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. If a negative height or width is specified, the absolute value is taken.\nThe origin may be changed with the ellipseMode() function.
\n", "itemtype": "method", "name": "ellipse", @@ -4305,7 +4313,7 @@ module.exports={ "submodule": "2D Primitives", "overloads": [ { - "line": 149, + "line": 210, "params": [ { "name": "x", @@ -4332,7 +4340,7 @@ module.exports={ "chainable": 1 }, { - "line": 174, + "line": 235, "params": [ { "name": "x", @@ -4356,7 +4364,7 @@ module.exports={ }, { "name": "detail", - "description": "number of radial sectors to draw
\n", + "description": "number of radial sectors to draw (for WebGL mode)
\n", "type": "Integer" } ] @@ -4365,7 +4373,39 @@ module.exports={ }, { "file": "src/core/shape/2d_primitives.js", - "line": 208, + "line": 270, + "description": "Draws a circle to the screen. A circle is a simple closed shape.\nIt is the set of all points in a plane that are at a given distance from a given point, the centre.\nThis function is a special case of the ellipse() function, where the width and height of the ellipse are the same.\nHeight and width of the ellipse correspond to the diameter of the circle.\nBy default, the first two parameters set the location of the centre of the circle, the third sets the diameter of the circle.
\n", + "itemtype": "method", + "name": "circle", + "params": [ + { + "name": "x", + "description": "x-coordinate of the centre of the circle.
\n", + "type": "Number" + }, + { + "name": "y", + "description": "y-coordinate of the centre of the circle.
\n", + "type": "Number" + }, + { + "name": "d", + "description": "diameter of the circle.
\n", + "type": "Number" + } + ], + "chainable": 1, + "example": [ + "\n\n// Draw a circle at location (30, 30) with a diameter of 20.\ncircle(30, 30, 20);\n
\nDraws 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.
\n", "itemtype": "method", "name": "line", @@ -4379,7 +4419,7 @@ module.exports={ "submodule": "2D Primitives", "overloads": [ { - "line": 208, + "line": 300, "params": [ { "name": "x1", @@ -4405,7 +4445,7 @@ module.exports={ "chainable": 1 }, { - "line": 244, + "line": 336, "params": [ { "name": "x1", @@ -4444,7 +4484,7 @@ module.exports={ }, { "file": "src/core/shape/2d_primitives.js", - "line": 264, + "line": 356, "description": "Draws a point, a coordinate in space at the dimension of one pixel.\nThe first parameter is the horizontal value for the point, the second\nvalue is the vertical value for the point. The color of the point is\ndetermined by the current stroke.
\n", "itemtype": "method", "name": "point", @@ -4461,7 +4501,7 @@ module.exports={ }, { "name": "z", - "description": "the z-coordinate (for WEBGL mode)
\n", + "description": "the z-coordinate (for WebGL mode)
\n", "type": "Number", "optional": true } @@ -4477,8 +4517,8 @@ module.exports={ }, { "file": "src/core/shape/2d_primitives.js", - "line": 299, - "description": "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.
\n", + "line": 391, + "description": "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.\nz-arguments only work when quad() is used in WEBGL mode.
\n", "itemtype": "method", "name": "quad", "chainable": 1, @@ -4491,7 +4531,7 @@ module.exports={ "submodule": "2D Primitives", "overloads": [ { - "line": 299, + "line": 391, "params": [ { "name": "x1", @@ -4537,7 +4577,7 @@ module.exports={ "chainable": 1 }, { - "line": 327, + "line": 421, "params": [ { "name": "x1", @@ -4606,7 +4646,7 @@ module.exports={ }, { "file": "src/core/shape/2d_primitives.js", - "line": 353, + "line": 458, "description": "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-left, top-right, lower-right and\nlower-left corners, respectively. An omitted corner radius parameter is set\nto the value of the previously specified radius value in the parameter list.
number of segments in the x-direction
\n", + "description": "number of segments in the x-direction (for WebGL mode)
\n", "type": "Integer", "optional": true }, { "name": "detailY", - "description": "number of segments in the y-direction
\n", + "description": "number of segments in the y-direction (for WebGL mode)
\n", "type": "Integer", "optional": true } @@ -4711,7 +4751,63 @@ module.exports={ }, { "file": "src/core/shape/2d_primitives.js", - "line": 436, + "line": 541, + "description": "Draws a square to the screen. A square is a four-sided shape with\nevery angle at ninety degrees, and equal side size.\nThis function is a special case of the rect() function, where the width and height are the same, and the parameter is called "s" for side size.\nBy default, the first two parameters set the location of the upper-left corner, the third sets the side size of the square.\nThe way these parameters are interpreted, however,\nmay be changed with the rectMode() function.\n
\nThe fourth, fifth, sixth and seventh parameters, if specified,\ndetermine corner radius for the top-left, top-right, lower-right and\nlower-left corners, respectively. An omitted corner radius parameter is set\nto the value of the previously specified radius value in the parameter list.
x-coordinate of the square.
\n", + "type": "Number" + }, + { + "name": "y", + "description": "y-coordinate of the square.
\n", + "type": "Number" + }, + { + "name": "s", + "description": "side size of the square.
\n", + "type": "Number" + }, + { + "name": "tl", + "description": "optional radius of top-left corner.
\n", + "type": "Number", + "optional": true + }, + { + "name": "tr", + "description": "optional radius of top-right corner.
\n", + "type": "Number", + "optional": true + }, + { + "name": "br", + "description": "optional radius of bottom-right corner.
\n", + "type": "Number", + "optional": true + }, + { + "name": "bl", + "description": "optional radius of bottom-left corner.
\n", + "type": "Number", + "optional": true + } + ], + "chainable": 1, + "example": [ + "\n\n// Draw a square at location (30, 20) with a side size of 55.\nsquare(30, 20, 55);\n
\n\n// Draw a square with rounded corners, each having a radius of 20.\nsquare(30, 20, 55, 20);\n
\n\n// Draw a square with rounded corners having the following radii:\n// top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5.\nsquare(30, 20, 55, 20, 15, 10, 5);\n
\nA 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.
\n", "itemtype": "method", "name": "triangle", @@ -4795,7 +4891,7 @@ module.exports={ }, { "file": "src/core/shape/attributes.js", - "line": 113, + "line": 116, "description": "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.
Draws all geometry with smooth (anti-aliased) edges. smooth() will also\nimprove image quality of resized images. Note that smooth() is active by\ndefault in 2D mode; noSmooth() can be used to disable smoothing of geometry,\nimages, and fonts. In 3D mode, noSmooth() is enabled\nby default, so it is necessary to call smooth() if you would like\nsmooth (antialiased) edges on your geometry.
\n", "itemtype": "method", "name": "smooth", @@ -4832,7 +4928,7 @@ module.exports={ }, { "file": "src/core/shape/attributes.js", - "line": 213, + "line": 219, "description": "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.
\n", "itemtype": "method", "name": "strokeCap", @@ -4854,7 +4950,7 @@ module.exports={ }, { "file": "src/core/shape/attributes.js", - "line": 250, + "line": 256, "description": "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.
\n", "itemtype": "method", "name": "strokeJoin", @@ -4876,7 +4972,7 @@ module.exports={ }, { "file": "src/core/shape/attributes.js", - "line": 317, + "line": 323, "description": "Sets the width of the stroke used for lines, points, and the border\naround shapes. All widths are set in units of pixels.
\n", "itemtype": "method", "name": "strokeWeight", @@ -5040,7 +5136,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noFill();\n\n bezierDetail(5);\n}\n\nfunction draw() {\n background(200);\n\n // prettier-ignore\n bezier(-40, -40, 0,\n 90, -40, 0,\n -90, 40, 0,\n 40, 40, 0);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noFill();\n\n bezierDetail(5);\n}\n\nfunction draw() {\n background(200);\n\n bezier(-40, -40, 0,\n 90, -40, 0,\n -90, 40, 0,\n 40, 40, 0);\n}\n
\n\nnoFill();\nvar x1 = 85,\n x2 = 10,\n x3 = 90,\n x4 = 15;\nvar y1 = 20,\n y2 = 10,\n y3 = 90,\n y4 = 80;\nbezier(x1, y1, x2, y2, x3, y3, x4, y4);\nfill(255);\nvar steps = 10;\nfor (var i = 0; i <= steps; i++) {\n var t = i / steps;\n var x = bezierPoint(x1, x2, x3, x4, t);\n var y = bezierPoint(y1, y2, y3, y4, t);\n ellipse(x, y, 5, 5);\n}\n
\n\nnoFill();\nlet x1 = 85,\n x2 = 10,\n x3 = 90,\n x4 = 15;\nlet y1 = 20,\n y2 = 10,\n y3 = 90,\n y4 = 80;\nbezier(x1, y1, x2, y2, x3, y3, x4, y4);\nfill(255);\nlet steps = 10;\nfor (let i = 0; i <= steps; i++) {\n let t = i / steps;\n let x = bezierPoint(x1, x2, x3, x4, t);\n let y = bezierPoint(y1, y2, y3, y4, t);\n ellipse(x, y, 5, 5);\n}\n
\n\nnoFill();\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\nvar steps = 6;\nfill(255);\nfor (var i = 0; i <= steps; i++) {\n var t = i / steps;\n // Get the location of the point\n var x = bezierPoint(85, 10, 90, 15, t);\n var y = bezierPoint(20, 10, 90, 80, t);\n // Get the tangent points\n var tx = bezierTangent(85, 10, 90, 15, t);\n var ty = bezierTangent(20, 10, 90, 80, t);\n // Calculate an angle from the tangent points\n var a = atan2(ty, tx);\n a += PI;\n stroke(255, 102, 0);\n line(x, y, cos(a) * 30 + x, sin(a) * 30 + y);\n // The following line of code makes a line\n // inverse of the above line\n //line(x, y, cos(a)*-30 + x, sin(a)*-30 + y);\n stroke(0);\n ellipse(x, y, 5, 5);\n}\n
\n\nnoFill();\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\nstroke(255, 102, 0);\nvar steps = 16;\nfor (var i = 0; i <= steps; i++) {\n var t = i / steps;\n var x = bezierPoint(85, 10, 90, 15, t);\n var y = bezierPoint(20, 10, 90, 80, t);\n var tx = bezierTangent(85, 10, 90, 15, t);\n var ty = bezierTangent(20, 10, 90, 80, t);\n var a = atan2(ty, tx);\n a -= HALF_PI;\n line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);\n}\n
\n\nnoFill();\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\nlet steps = 6;\nfill(255);\nfor (let i = 0; i <= steps; i++) {\n let t = i / steps;\n // Get the location of the point\n let x = bezierPoint(85, 10, 90, 15, t);\n let y = bezierPoint(20, 10, 90, 80, t);\n // Get the tangent points\n let tx = bezierTangent(85, 10, 90, 15, t);\n let ty = bezierTangent(20, 10, 90, 80, t);\n // Calculate an angle from the tangent points\n let a = atan2(ty, tx);\n a += PI;\n stroke(255, 102, 0);\n line(x, y, cos(a) * 30 + x, sin(a) * 30 + y);\n // The following line of code makes a line\n // inverse of the above line\n //line(x, y, cos(a)*-30 + x, sin(a)*-30 + y);\n stroke(0);\n ellipse(x, y, 5, 5);\n}\n
\n\nnoFill();\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\nstroke(255, 102, 0);\nlet steps = 16;\nfor (let i = 0; i <= steps; i++) {\n let t = i / steps;\n let x = bezierPoint(85, 10, 90, 15, t);\n let y = bezierPoint(20, 10, 90, 80, t);\n let tx = bezierTangent(85, 10, 90, 15, t);\n let ty = bezierTangent(20, 10, 90, 80, t);\n let a = atan2(ty, tx);\n a -= HALF_PI;\n line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);\n}\n
\n\nnoFill();\nstroke(255, 102, 0);\ncurve(5, 26, 5, 26, 73, 24, 73, 61);\nstroke(0);\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nstroke(255, 102, 0);\ncurve(73, 24, 73, 61, 15, 65, 15, 65);\n
\n\n// Define the curve points as JavaScript objects\nvar p1 = { x: 5, y: 26 },\n p2 = { x: 73, y: 24 };\nvar p3 = { x: 73, y: 61 },\n p4 = { x: 15, y: 65 };\nnoFill();\nstroke(255, 102, 0);\ncurve(p1.x, p1.y, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);\nstroke(0);\ncurve(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y);\nstroke(255, 102, 0);\ncurve(p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, p4.x, p4.y);\n
\n\nnoFill();\nstroke(255, 102, 0);\ncurve(5, 26, 0, 5, 26, 0, 73, 24, 0, 73, 61, 0);\nstroke(0);\ncurve(5, 26, 0, 73, 24, 0, 73, 61, 0, 15, 65, 0);\nstroke(255, 102, 0);\ncurve(73, 24, 0, 73, 61, 0, 15, 65, 0, 15, 65, 0);\n
\n\nnoFill();\nstroke(255, 102, 0);\ncurve(5, 26, 5, 26, 73, 24, 73, 61);\nstroke(0);\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nstroke(255, 102, 0);\ncurve(73, 24, 73, 61, 15, 65, 15, 65);\n
\n\n// Define the curve points as JavaScript objects\nlet p1 = { x: 5, y: 26 },\n p2 = { x: 73, y: 24 };\nlet p3 = { x: 73, y: 61 },\n p4 = { x: 15, y: 65 };\nnoFill();\nstroke(255, 102, 0);\ncurve(p1.x, p1.y, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);\nstroke(0);\ncurve(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y);\nstroke(255, 102, 0);\ncurve(p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, p4.x, p4.y);\n
\n\nnoFill();\nstroke(255, 102, 0);\ncurve(5, 26, 0, 5, 26, 0, 73, 24, 0, 73, 61, 0);\nstroke(0);\ncurve(5, 26, 0, 73, 24, 0, 73, 61, 0, 15, 65, 0);\nstroke(255, 102, 0);\ncurve(73, 24, 0, 73, 61, 0, 15, 65, 0, 15, 65, 0);\n
\nof the curves
\n", + "description": "resolution of the curves
\n", "type": "Number" } ], @@ -5297,13 +5393,13 @@ module.exports={ "params": [ { "name": "amount", - "description": "of deformation from the original vertices
\n", + "description": "amount of deformation from the original vertices
\n", "type": "Number" } ], "chainable": 1, "example": [ - "\n\n// Move the mouse left and right to see the curve change\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
\n\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 let t = map(mouseX, 0, width, -5, 5);\n curveTightness(t);\n beginShape();\n curveVertex(10, 26);\n curveVertex(10, 26);\n curveVertex(83, 24);\n curveVertex(83, 61);\n curveVertex(25, 65);\n curveVertex(25, 65);\n endShape();\n}\n
\n\nnoFill();\ncurve(5, 26, 5, 26, 73, 24, 73, 61);\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nfill(255);\nellipseMode(CENTER);\nvar steps = 6;\nfor (var i = 0; i <= steps; i++) {\n var t = i / steps;\n var x = curvePoint(5, 5, 73, 73, t);\n var 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
\n\nnoFill();\ncurve(5, 26, 5, 26, 73, 24, 73, 61);\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nfill(255);\nellipseMode(CENTER);\nlet steps = 6;\nfor (let i = 0; i <= steps; i++) {\n let t = i / steps;\n let x = curvePoint(5, 5, 73, 73, t);\n let y = curvePoint(26, 26, 24, 61, t);\n ellipse(x, y, 5, 5);\n x = curvePoint(5, 73, 73, 15, t);\n y = curvePoint(26, 24, 61, 65, t);\n ellipse(x, y, 5, 5);\n}\n
\n\nnoFill();\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nvar steps = 6;\nfor (var i = 0; i <= steps; i++) {\n var t = i / steps;\n var x = curvePoint(5, 73, 73, 15, t);\n var y = curvePoint(26, 24, 61, 65, t);\n //ellipse(x, y, 5, 5);\n var tx = curveTangent(5, 73, 73, 15, t);\n var ty = curveTangent(26, 24, 61, 65, t);\n var a = atan2(ty, tx);\n a -= PI / 2.0;\n line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);\n}\n
\n\nnoFill();\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nlet steps = 6;\nfor (let i = 0; i <= steps; i++) {\n let t = i / steps;\n let x = curvePoint(5, 73, 73, 15, t);\n let y = curvePoint(26, 24, 61, 65, t);\n //ellipse(x, y, 5, 5);\n let tx = curveTangent(5, 73, 73, 15, t);\n let ty = curveTangent(26, 24, 61, 65, t);\n let a = atan2(ty, tx);\n a -= PI / 2.0;\n line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);\n}\n
\n\nnoFill();\nbeginShape();\nvertex(30, 20);\nbezierVertex(80, 0, 80, 75, 30, 75);\nendShape();\n
\n\nbeginShape();\nvertex(30, 20);\nbezierVertex(80, 0, 80, 75, 30, 75);\nbezierVertex(50, 80, 60, 25, 30, 20);\nendShape();\n
\n\nnoFill();\nbeginShape();\nvertex(30, 20);\nbezierVertex(80, 0, 80, 75, 30, 75);\nendShape();\n
\n\nbeginShape();\nvertex(30, 20);\nbezierVertex(80, 0, 80, 75, 30, 75);\nbezierVertex(50, 80, 60, 25, 30, 20);\nendShape();\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n setAttributes('antialias', true);\n}\nfunction draw() {\n orbitControl();\n background(50);\n strokeWeight(4);\n stroke(255);\n point(-25, 30);\n point(25, 30);\n point(25, -30);\n point(-25, -30);\n\n strokeWeight(1);\n noFill();\n\n beginShape();\n vertex(-25, 30);\n bezierVertex(25, 30, 25, -30, -25, -30);\n endShape();\n\n beginShape();\n vertex(-25, 30, 20);\n bezierVertex(25, 30, 20, 25, -30, 20, -25, -30, 20);\n endShape();\n}\n
\nz-coordinate for the first control point (for WebGL mode)
\n", - "type": "Number", - "optional": true + "type": "Number" }, { "name": "x3", @@ -5520,8 +5617,7 @@ module.exports={ { "name": "z3", "description": "z-coordinate for the second control point (for WebGL mode)
\n", - "type": "Number", - "optional": true + "type": "Number" }, { "name": "x4", @@ -5536,8 +5632,7 @@ module.exports={ { "name": "z4", "description": "z-coordinate for the anchor point (for WebGL mode)
\n", - "type": "Number", - "optional": true + "type": "Number" } ], "chainable": 1 @@ -5546,7 +5641,7 @@ module.exports={ }, { "file": "src/core/shape/vertex.js", - "line": 390, + "line": 398, "description": "Specifies vertex coordinates for curves. This function may only\nbe used between beginShape() and endShape() and only when there\nis no MODE parameter specified to beginShape().\nFor WebGL mode curveVertex() can be used in 2D as well as 3D mode.\n2D mode expects 2 parameters, while 3D mode expects 3 parameters.\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.
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.
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).
\n", "itemtype": "method", "name": "endShape", @@ -5639,7 +5734,7 @@ module.exports={ }, { "file": "src/core/shape/vertex.js", - "line": 646, + "line": 654, "description": "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.\nFor WebGL mode quadraticVertex() can be used in 2D as well as 3D mode.\n2D mode expects 4 parameters, while 3D mode expects 6 parameters\n(including z coordinates).\n
\nThis function must be used between beginShape() and endShape()\nand only when there is no MODE or POINTS parameter specified to\nbeginShape().
z-coordinate for the control point (for WebGL mode)
\n", - "type": "Number", - "optional": true + "type": "Number" }, { "name": "x3", @@ -5710,8 +5804,7 @@ module.exports={ { "name": "z3", "description": "z-coordinate for the anchor point (for WebGL mode)
\n", - "type": "Number", - "optional": true + "type": "Number" } ], "chainable": 1 @@ -5720,7 +5813,7 @@ module.exports={ }, { "file": "src/core/shape/vertex.js", - "line": 800, + "line": 813, "description": "All shapes are constructed by connecting a series of vertices. vertex()\nis used to specify the vertex coordinates for points, lines, triangles,\nquads, and polygons. It is used exclusively within the beginShape() and\nendShape() functions.
\n", "itemtype": "method", "name": "vertex", @@ -5734,7 +5827,7 @@ module.exports={ "submodule": "Vertex", "overloads": [ { - "line": 800, + "line": 813, "params": [ { "name": "x", @@ -5750,7 +5843,7 @@ module.exports={ "chainable": 1 }, { - "line": 887, + "line": 900, "params": [ { "name": "x", @@ -6326,6 +6419,7 @@ module.exports={ { "file": "src/core/constants.js", "line": 350, + "description": "AUTO allows us to automatically set the width or height of an element (but not both),\nbased on the current height and width of the element. Only one parameter can\nbe passed to the size function as AUTO, at a time.
\n", "itemtype": "property", "name": "AUTO", "type": "String", @@ -6336,7 +6430,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 373, + "line": 377, "itemtype": "property", "name": "BLEND", "type": "String", @@ -6348,7 +6442,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 379, + "line": 383, "itemtype": "property", "name": "ADD", "type": "String", @@ -6360,7 +6454,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 387, + "line": 391, "itemtype": "property", "name": "DARKEST", "type": "String", @@ -6371,7 +6465,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 392, + "line": 396, "itemtype": "property", "name": "LIGHTEST", "type": "String", @@ -6383,7 +6477,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 398, + "line": 402, "itemtype": "property", "name": "DIFFERENCE", "type": "String", @@ -6394,7 +6488,18 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 403, + "line": 407, + "itemtype": "property", + "name": "SUBTRACT", + "type": "String", + "final": 1, + "class": "p5", + "module": "Constants", + "submodule": "Constants" + }, + { + "file": "src/core/constants.js", + "line": 412, "itemtype": "property", "name": "EXCLUSION", "type": "String", @@ -6405,7 +6510,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 408, + "line": 417, "itemtype": "property", "name": "MULTIPLY", "type": "String", @@ -6416,7 +6521,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 413, + "line": 422, "itemtype": "property", "name": "SCREEN", "type": "String", @@ -6427,7 +6532,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 418, + "line": 427, "itemtype": "property", "name": "REPLACE", "type": "String", @@ -6439,7 +6544,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 424, + "line": 433, "itemtype": "property", "name": "OVERLAY", "type": "String", @@ -6450,7 +6555,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 429, + "line": 438, "itemtype": "property", "name": "HARD_LIGHT", "type": "String", @@ -6461,7 +6566,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 434, + "line": 443, "itemtype": "property", "name": "SOFT_LIGHT", "type": "String", @@ -6472,7 +6577,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 439, + "line": 448, "itemtype": "property", "name": "DODGE", "type": "String", @@ -6484,7 +6589,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 445, + "line": 454, "itemtype": "property", "name": "BURN", "type": "String", @@ -6496,7 +6601,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 453, + "line": 462, "itemtype": "property", "name": "THRESHOLD", "type": "String", @@ -6507,7 +6612,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 458, + "line": 467, "itemtype": "property", "name": "GRAY", "type": "String", @@ -6518,7 +6623,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 463, + "line": 472, "itemtype": "property", "name": "OPAQUE", "type": "String", @@ -6529,7 +6634,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 468, + "line": 477, "itemtype": "property", "name": "INVERT", "type": "String", @@ -6540,7 +6645,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 473, + "line": 482, "itemtype": "property", "name": "POSTERIZE", "type": "String", @@ -6551,7 +6656,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 478, + "line": 487, "itemtype": "property", "name": "DILATE", "type": "String", @@ -6562,7 +6667,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 483, + "line": 492, "itemtype": "property", "name": "ERODE", "type": "String", @@ -6573,7 +6678,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 488, + "line": 497, "itemtype": "property", "name": "BLUR", "type": "String", @@ -6584,7 +6689,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 495, + "line": 504, "itemtype": "property", "name": "NORMAL", "type": "String", @@ -6595,7 +6700,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 500, + "line": 509, "itemtype": "property", "name": "ITALIC", "type": "String", @@ -6606,7 +6711,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 505, + "line": 514, "itemtype": "property", "name": "BOLD", "type": "String", @@ -6617,7 +6722,29 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 536, + "line": 519, + "itemtype": "property", + "name": "BOLDITALIC", + "type": "String", + "final": 1, + "class": "p5", + "module": "Constants", + "submodule": "Constants" + }, + { + "file": "src/core/constants.js", + "line": 544, + "itemtype": "property", + "name": "IMAGE", + "type": "String", + "final": 1, + "class": "p5", + "module": "Constants", + "submodule": "Constants" + }, + { + "file": "src/core/constants.js", + "line": 558, "itemtype": "property", "name": "LANDSCAPE", "type": "String", @@ -6628,7 +6755,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 541, + "line": 563, "itemtype": "property", "name": "PORTRAIT", "type": "String", @@ -6639,7 +6766,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 551, + "line": 573, "itemtype": "property", "name": "GRID", "type": "String", @@ -6650,7 +6777,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 557, + "line": 579, "itemtype": "property", "name": "AXES", "type": "String", @@ -6662,7 +6789,7 @@ module.exports={ { "file": "src/core/environment.js", "line": 22, - "description": "The print() 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", + "description": "The print() 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 (+).
\nNote that calling print() without any arguments invokes the window.print()\nfunction which opens the browser's print dialog. To print a blank line\nto console you can write print('\\n').
\n", "itemtype": "method", "name": "print", "params": [ @@ -6673,7 +6800,7 @@ module.exports={ } ], "example": [ - "\n\nvar x = 10;\nprint('The value of x is ' + x);\n// prints \"The value of x is 10\"\n
\nlet x = 10;\nprint('The value of x is ' + x);\n// prints \"The value of x is 10\"\n
The system variable frameCount contains the 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", "itemtype": "property", "name": "frameCount", @@ -6698,7 +6825,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 76, + "line": 80, "description": "Confirms if the window a p5.js program is in is "focused," meaning that\nthe sketch will accept mouse or keyboard input. This variable is\n"true" if the window is focused and "false" if not.
\n", "itemtype": "property", "name": "focused", @@ -6714,46 +6841,46 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 108, + "line": 112, "description": "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. The values for parameters x and y\nmust be less than the dimensions of the image.
\n", "itemtype": "method", "name": "cursor", "params": [ { "name": "type", - "description": "either ARROW, CROSS, HAND, MOVE, TEXT, or\n WAIT, or path for image
\n", + "description": "Built-In: either ARROW, CROSS, HAND, MOVE, TEXT and WAIT\n Native CSS properties: 'grab', 'progress', 'cell' etc.\n External: path for cursor's images\n (Allowed File extensions: .cur, .gif, .jpg, .jpeg, .png)\n For more information on Native CSS cursors and url visit:\n https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
\n", "type": "String|Constant" }, { "name": "x", - "description": "the horizontal active spot of the cursor
\n", + "description": "the horizontal active spot of the cursor (must be less than 32)
\n", "type": "Number", "optional": true }, { "name": "y", - "description": "the vertical active spot of the cursor
\n", + "description": "the vertical active spot of the cursor (must be less than 32)
\n", "type": "Number", "optional": true } ], "example": [ - "\n\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
\n// Move the mouse across the quadrants\n// to see the cursor change\nfunction draw() {\n line(width / 2, 0, width / 2, height);\n line(0, height / 2, width, height / 2);\n if (mouseX < 50 && mouseY < 50) {\n cursor(CROSS);\n } else if (mouseX > 50 && mouseY < 50) {\n cursor('progress');\n } else if (mouseX > 50 && mouseY > 50) {\n cursor('https://s3.amazonaws.com/mupublicdata/cursor.cur');\n } else {\n cursor('grab');\n }\n}\n
Specifies the number of frames to be displayed every second. For example,\nthe function call frameRate(30) will attempt to refresh 30 times a second.\nIf the processor is not fast enough to maintain the specified rate, the\nframe rate will not be achieved. Setting the frame rate within setup() is\nrecommended. The default frame rate is based on the frame rate of the display\n(here also called "refresh rate"), which is set to 60 frames per second on most\ncomputers. A frame rate of 24 frames per second (usual for movies) or above\nwill be enough for smooth animations\nThis is the same as setFrameRate(val).\n
\nCalling frameRate() with no arguments returns the current framerate. The\ndraw function must run at least once before it will return a value. 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.
\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) {\n // If you go off screen.\n if (fr === 30) {\n clr = color(0, 0, 255);\n fr = 10;\n frameRate(fr); // make frameRate 10 FPS\n } else {\n clr = color(255, 0, 0);\n fr = 30;\n frameRate(fr); // make frameRate 30 FPS\n }\n rectX = 0;\n }\n fill(clr);\n rect(rectX, 40, 20, 20);\n}\n
\nlet rectX = 0;\nlet fr = 30; //starting FPS\nlet clr;\n\nfunction setup() {\n background(200);\n frameRate(fr); // Attempt to refresh at starting FPS\n clr = color(255, 0, 0);\n}\n\nfunction draw() {\n background(200);\n rectX = rectX += 1; // Move Rectangle\n\n if (rectX >= width) {\n // If you go off screen.\n if (fr === 30) {\n clr = color(0, 0, 255);\n fr = 10;\n frameRate(fr); // make frameRate 10 FPS\n } else {\n clr = color(255, 0, 0);\n fr = 30;\n frameRate(fr); // make frameRate 30 FPS\n }\n rectX = 0;\n }\n fill(clr);\n rect(rectX, 40, 20, 20);\n}\n
Hides the cursor from view.
\n", "itemtype": "method", "name": "noCursor", @@ -6797,7 +6924,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 293, + "line": 306, "description": "System variable that stores the width of the screen display according to The\ndefault pixelDensity. This is used to run a\nfull-screen program on any display size. To return actual screen size,\nmultiply this by pixelDensity.
\n", "itemtype": "property", "name": "displayWidth", @@ -6813,7 +6940,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 312, + "line": 325, "description": "System variable that stores the height of the screen display according to The\ndefault pixelDensity. This is used to run a\nfull-screen program on any display size. To return actual screen size,\nmultiply this by pixelDensity.
\n", "itemtype": "property", "name": "displayHeight", @@ -6829,7 +6956,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 331, + "line": 344, "description": "System variable that stores the width of the inner window, it maps to\nwindow.innerWidth.
\n", "itemtype": "property", "name": "windowWidth", @@ -6845,7 +6972,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 347, + "line": 360, "description": "System variable that stores the height of the inner window, it maps to\nwindow.innerHeight.
\n", "itemtype": "property", "name": "windowHeight", @@ -6861,7 +6988,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 363, + "line": 376, "description": "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\nadjustments to accommodate the new window size.
\n", "itemtype": "method", "name": "windowResized", @@ -6875,7 +7002,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 417, + "line": 430, "description": "System variable that stores the width of the drawing canvas. This value\nis set by the first parameter of the createCanvas() function.\nFor example, the function call createCanvas(320, 240) sets the width\nvariable to the value 320. The value of width defaults to 100 if\ncreateCanvas() is not used in a program.
\n", "itemtype": "property", "name": "width", @@ -6887,7 +7014,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 429, + "line": 442, "description": "System variable that stores the height of the drawing canvas. This value\nis set by the second parameter of the createCanvas() function. For\nexample, the function call createCanvas(320, 240) sets the height\nvariable to the value 240. The value of height defaults to 100 if\ncreateCanvas() is not used in a program.
\n", "itemtype": "property", "name": "height", @@ -6899,7 +7026,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 441, + "line": 454, "description": "If argument is given, sets the sketch to fullscreen or not based on the\nvalue of the argument. If no argument is given, returns the current\nfullscreen state. Note that due to browser restrictions this can only\nbe called on user input, for example, on mouse press like the example\nbelow.
\n", "itemtype": "method", "name": "fullscreen", @@ -6916,7 +7043,7 @@ module.exports={ "type": "Boolean" }, "example": [ - "\n\n// Clicking in the box toggles fullscreen on and off.\nfunction setup() {\n background(200);\n}\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n var fs = fullscreen();\n fullscreen(!fs);\n }\n}\n
\n\n// Clicking in the box toggles fullscreen on and off.\nfunction setup() {\n background(200);\n}\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n let fs = fullscreen();\n fullscreen(!fs);\n }\n}\n
\nSets the pixel scaling for high pixel density displays. By default\npixel density is set to match display density, call pixelDensity(1)\nto turn this off. Calling pixelDensity() with no arguments returns\nthe current pixel density of the sketch.
\n", "itemtype": "method", "name": "pixelDensity", @@ -6939,7 +7066,7 @@ module.exports={ "submodule": "Environment", "overloads": [ { - "line": 492, + "line": 505, "params": [ { "name": "val", @@ -6950,7 +7077,7 @@ module.exports={ "chainable": 1 }, { - "line": 527, + "line": 540, "params": [], "return": { "description": "current pixel density of the sketch", @@ -6961,7 +7088,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 547, + "line": 560, "description": "Returns the pixel density of the current display the sketch is running on.
\n", "itemtype": "method", "name": "displayDensity", @@ -6970,7 +7097,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\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
\n\nfunction setup() {\n let density = displayDensity();\n pixelDensity(density);\n createCanvas(100, 100);\n background(200);\n ellipse(width / 2, height / 2, 50, 50);\n}\n
\nGets the current URL.
\n", "itemtype": "method", "name": "getURL", @@ -6988,7 +7115,7 @@ module.exports={ "type": "String" }, "example": [ - "\n\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
\n\nlet url;\nlet x = 100;\n\nfunction setup() {\n fill(0);\n noStroke();\n url = getURL();\n}\n\nfunction draw() {\n background(200);\n text(url, x, height / 2);\n x--;\n}\n
\nGets the current URL path as an array.
\n", "itemtype": "method", "name": "getURLPath", @@ -7006,7 +7133,7 @@ module.exports={ "type": "String[]" }, "example": [ - "\n\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
\nfunction setup() {\n let urlPath = getURLPath();\n for (let i = 0; i < urlPath.length; i++) {\n text(urlPath[i], 10, i * 20 + 20);\n }\n}\n
Gets the current URL params as an Object.
\n", "itemtype": "method", "name": "getURLParams", @@ -7024,7 +7151,7 @@ module.exports={ "type": "Object" }, "example": [ - "\n\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
\n\n// Example: http://p5js.org?year=2014&month=May&day=15\n\nfunction setup() {\n let params = getURLParams();\n text(params.day, 10, 20);\n text(params.month, 10, 40);\n text(params.year, 10, 60);\n}\n
\nValidates parameters\nparam {String} func the name of the function\nparam {Array} args user input arguments
\nexample:\n var a;\n ellipse(10,10,a,5);\nconsole ouput:\n "It looks like ellipse received an empty variable in spot #2."
\nexample:\n ellipse(10,"foo",5,5);\nconsole output:\n "ellipse was expecting a number for parameter #1,\n received "foo" instead."
\n", "class": "p5", "module": "Environment" }, { "file": "src/core/error_helpers.js", - "line": 624, + "line": 645, "description": "Prints out all the colors in the color pallete with white text.\nFor color blindness testing.
\n", "class": "p5", "module": "Environment" @@ -7081,7 +7208,7 @@ module.exports={ "itemtype": "method", "name": "preload", "example": [ - "\n\nvar img;\nvar c;\nfunction preload() {\n // preload() runs once\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n // setup() waits until preload() is done\n img.loadPixels();\n // get color of middle pixel\n c = img.get(img.width / 2, img.height / 2);\n}\n\nfunction draw() {\n background(c);\n image(img, 25, 25, 50, 50);\n}\n
\nlet img;\nlet c;\nfunction preload() {\n // preload() runs once\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n // setup() waits until preload() is done\n img.loadPixels();\n // get color of middle pixel\n c = img.get(img.width / 2, img.height / 2);\n}\n\nfunction draw() {\n background(c);\n image(img, 25, 25, 50, 50);\n}\n
\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
\nlet a = 0;\n\nfunction setup() {\n background(0);\n noStroke();\n fill(102);\n}\n\nfunction draw() {\n rect(a++ % width, 10, 2, 80);\n}\n
\nvar yPos = 0;\nfunction setup() {\n // setup() runs once\n frameRate(30);\n}\nfunction draw() {\n // draw() loops forever, until stopped\n background(204);\n yPos = yPos - 1;\n if (yPos < 0) {\n yPos = height;\n }\n line(0, yPos, width, yPos);\n}\n
\nlet yPos = 0;\nfunction setup() {\n // setup() runs once\n frameRate(30);\n}\nfunction draw() {\n // draw() loops forever, until stopped\n background(204);\n yPos = yPos - 1;\n if (yPos < 0) {\n yPos = height;\n }\n line(0, yPos, width, yPos);\n}\n
Removes the entire p5 sketch. This will remove the canvas and any\nelements created by p5.js. It will also stop the draw loop and unbind\nany properties or methods from the window global scope. It will\nleave a variable p5 in case you wanted to create a new p5 sketch.\nIf you like, you can set p5 = null to erase it. While all functions and\nvariables and objects created by the p5 library will be removed, any\nother global variables created by your code will remain.
\n", "itemtype": "method", "name": "remove", @@ -7130,12 +7257,26 @@ module.exports={ "module": "Structure", "submodule": "Structure" }, + { + "file": "src/core/main.js", + "line": 586, + "description": "Allows for the friendly error system (FES) to be turned off when creating a sketch,\nwhich can give a significant boost to performance when needed.\nSee \ndisabling the friendly error system.
\n", + "itemtype": "property", + "name": "disableFriendlyErrors", + "type": "Boolean", + "example": [ + "\n\np5.disableFriendlyErrors = true;\n\nfunction setup() {\n createCanvas(100, 50);\n}\n
Underlying HTML element. All normal HTML methods can be called on this.
\n", "example": [ - "\n\ncreateCanvas(300, 500);\nbackground(0, 0, 0, 0);\nvar input = createInput();\ninput.position(20, 225);\nvar inputElem = new p5.Element(input.elt);\ninputElem.style('width:450px;');\ninputElem.value('some string');\n
\n\nfunction setup() {\n let c = createCanvas(50, 50);\n c.elt.style.border = '5px solid red';\n}\n\nfunction draw() {\n background(220);\n}\n
\nAttaches the element to the parent specified. A way of setting\n the container for the element. Accepts either a string ID, DOM\n node, or p5.Element. If no arguments given, parent node is returned.\n For more ways to position the canvas, see the\n \n positioning the canvas wiki page.
\n", + "line": 52, + "description": "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.\nAll above examples except for the first one require the inclusion of\n the p5.dom library in your index.html. See the\n using a library\n section for information on how to include this library.
\n", "itemtype": "method", "name": "parent", "chainable": 1, "example": [ - "\n\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
\n // in the html file:\n // <div id=\"myContainer\"></div>\n// in the js file:\n let cnv = createCanvas(100, 100);\n cnv.parent('myContainer');\n
\n let div0 = createDiv('this is the parent');\n let div1 = createDiv('this is the child');\n div1.parent(div0); // use p5.Element\n
\n let div0 = createDiv('this is the parent');\n div0.id('apples');\n let div1 = createDiv('this is the child');\n div1.parent('apples'); // use id\n
\n let elt = document.getElementById('myParentDiv');\n let div1 = createDiv('this is the child');\n div1.parent(elt); // use element from page\n
Sets the ID of the element. If no ID argument is passed in, it instead\n returns the current ID of the element.
\n", + "line": 122, + "description": "Sets the ID of the element. If no ID argument is passed in, it instead\n returns the current ID of the element.\n Note that only one element can have a particular id in a page.\n The .class() function can be used\n to identify multiple elements with the same class name.
\n", "itemtype": "method", "name": "id", "chainable": 1, "example": [ - "\n\n function setup() {\n var cnv = createCanvas(100, 100);\n // Assigns a CSS selector ID to\n // the canvas element.\n cnv.id('mycanvas');\n }\n
\n function setup() {\n let cnv = createCanvas(100, 100);\n // Assigns a CSS selector ID to\n // the canvas element.\n cnv.id('mycanvas');\n }\n
Adds given class to the element. If no class argument is passed in, it\n instead returns a string containing the current class(es) of the element.
\n", "itemtype": "method", "name": "class", "chainable": 1, "example": [ - "\n\n function setup() {\n var cnv = createCanvas(100, 100);\n // Assigns a CSS selector class 'small'\n // to the canvas element.\n cnv.class('small');\n }\n
\n function setup() {\n let cnv = createCanvas(100, 100);\n // Assigns a CSS selector class 'small'\n // to the canvas element.\n cnv.class('small');\n }\n
The .mousePressed() function is called once after every time a\nmouse button is pressed over the element.\nSome mobile browsers may also trigger this event on a touch screen,\nif the user performs a quick tap.\nThis can be used to attach element specific event listeners.
\n", "itemtype": "method", "name": "mousePressed", @@ -7267,7 +7408,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n\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
\nlet cnv;\nlet d;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mousePressed(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any click anywhere\nfunction mousePressed() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
The .doubleClicked() function is called once after every time a\nmouse button is pressed twice over the element. This can be used to\nattach element and action specific event listeners.
\n", "itemtype": "method", "name": "doubleClicked", @@ -7292,7 +7433,7 @@ module.exports={ "type": "p5.Element" }, "example": [ - "\n\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.doubleClicked(changeGray); // attach listener for\n // canvas double click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any double click anywhere\nfunction doubleClicked() {\n d = d + 10;\n}\n\n// this function fires only when cnv is double clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
\nlet cnv;\nlet d;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.doubleClicked(changeGray); // attach listener for\n // canvas double click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any double click anywhere\nfunction doubleClicked() {\n d = d + 10;\n}\n\n// this function fires only when cnv is double clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
The .mouseWheel() 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.\n
\nThe function accepts a callback function as argument which will be executed\nwhen the wheel
event is triggered on the element, the callback function is\npassed one argument event
. The event.deltaY
property returns negative\nvalues if the mouse wheel is rotated up or away from the user and positive\nin the other direction. The event.deltaX
does the same as event.deltaY
\nexcept it reads the horizontal wheel scroll of the mouse wheel.\n
\nOn OS X with "natural" scrolling enabled, the event.deltaY
values are\nreversed.
\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(event) {\n if (event.deltaY > 0) {\n d = d + 10;\n } else {\n d = d - 10;\n }\n}\n
\nlet cnv;\nlet d;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseWheel(changeSize); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with mousewheel movement\n// anywhere on screen\nfunction mouseWheel() {\n g = g + 10;\n}\n\n// this function fires with mousewheel movement\n// over canvas only\nfunction changeSize(event) {\n if (event.deltaY > 0) {\n d = d + 10;\n } else {\n d = d - 10;\n }\n}\n
The .mouseReleased() function is called once after every time a\nmouse button is released over the element.\nSome mobile browsers may also trigger this event on a touch screen,\nif the user performs a quick tap.\nThis can be used to attach element specific event listeners.
\n", "itemtype": "method", "name": "mouseReleased", @@ -7336,7 +7477,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n\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
\nlet cnv;\nlet d;\nlet 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.\nSome mobile browsers may also trigger this event on a touch screen,\nif the user performs a quick tap.\nThis can be used to attach element specific event listeners.
\n", "itemtype": "method", "name": "mouseClicked", @@ -7358,7 +7499,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n\nvar cnv;\nvar d;\nvar g;\n\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseClicked(changeGray); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires after the mouse has been\n// clicked anywhere\nfunction mouseClicked() {\n d = d + 10;\n}\n\n// this function fires after the mouse has been\n// clicked on canvas\nfunction changeGray() {\n g = random(0, 255);\n}\n
\n\nlet cnv;\nlet d;\nlet g;\n\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseClicked(changeGray); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires after the mouse has been\n// clicked anywhere\nfunction mouseClicked() {\n d = d + 10;\n}\n\n// this function fires after the mouse has been\n// clicked on canvas\nfunction changeGray() {\n g = random(0, 255);\n}\n
\nThe .mouseMoved() function is called once every time a\nmouse moves over the element. This can be used to attach an\nelement specific event listener.
\n", "itemtype": "method", "name": "mouseMoved", @@ -7380,7 +7521,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n\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
\nlet cnv;\nlet d = 30;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseMoved(changeSize); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n fill(200);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires when mouse moves anywhere on\n// page\nfunction mouseMoved() {\n g = g + 5;\n if (g > 255) {\n g = 0;\n }\n}\n\n// this function fires when mouse moves over canvas\nfunction changeSize() {\n d = d + 2;\n if (d > 100) {\n d = 0;\n }\n}\n
The .mouseOver() function is called once after every time a\nmouse moves onto the element. This can be used to attach an\nelement specific event listener.
\n", "itemtype": "method", "name": "mouseOver", @@ -7402,7 +7543,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n\nvar cnv;\nvar d;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseOver(changeGray);\n d = 10;\n}\n\nfunction draw() {\n ellipse(width / 2, height / 2, d, d);\n}\n\nfunction changeGray() {\n d = d + 10;\n if (d > 100) {\n d = 0;\n }\n}\n
\nlet cnv;\nlet d;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseOver(changeGray);\n d = 10;\n}\n\nfunction draw() {\n ellipse(width / 2, height / 2, d, d);\n}\n\nfunction changeGray() {\n d = d + 10;\n if (d > 100) {\n d = 0;\n }\n}\n
The .changed() function is called when the value of an\nelement changes.\nThis can be used to attach an element specific event listener.
\n", - "itemtype": "method", - "name": "changed", - "params": [ - { - "name": "fxn", - "description": "function to be fired when the value of\n an element changes.\n if false
is passed instead, the previously\n firing function will no longer fire.
\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.
\n", - "itemtype": "method", - "name": "input", - "params": [ - { - "name": "fxn", - "description": "function to be fired when any user input is\n detected within the element.\n if false
is passed instead, the previously\n firing function will no longer fire.
\n// Open your console to see the output\nfunction setup() {\n 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.
\n", "itemtype": "method", "name": "mouseOut", @@ -7468,7 +7565,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n\nvar cnv;\nvar d;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseOut(changeGray);\n d = 10;\n}\n\nfunction draw() {\n ellipse(width / 2, height / 2, d, d);\n}\n\nfunction changeGray() {\n d = d + 10;\n if (d > 100) {\n d = 0;\n }\n}\n
\nlet cnv;\nlet d;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseOut(changeGray);\n d = 10;\n}\n\nfunction draw() {\n ellipse(width / 2, height / 2, d, d);\n}\n\nfunction changeGray() {\n d = d + 10;\n if (d > 100) {\n d = 0;\n }\n}\n
The .touchStarted() function is called once after every time a touch is\nregistered. This can be used to attach element specific event listeners.
\n", "itemtype": "method", "name": "touchStarted", @@ -7490,7 +7587,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n\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
\nlet cnv;\nlet d;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchStarted(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any touch anywhere\nfunction touchStarted() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
The .touchMoved() function is called once after every time a touch move is\nregistered. This can be used to attach element specific event listeners.
\n", "itemtype": "method", "name": "touchMoved", @@ -7512,7 +7609,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n\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
\nlet cnv;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchMoved(changeGray); // attach listener for\n // canvas click only\n g = 100;\n}\n\nfunction draw() {\n background(g);\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
The .touchEnded() function is called once after every time a touch is\nregistered. This can be used to attach element specific event listeners.
\n", "itemtype": "method", "name": "touchEnded", @@ -7534,7 +7631,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n\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
\nlet cnv;\nlet d;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchEnded(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any touch anywhere\nfunction touchEnded() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
The .dragOver() 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.
\n", "itemtype": "method", "name": "dragOver", @@ -7556,7 +7653,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n\n// To test this sketch, simply drag a\n// file over the canvas\nfunction setup() {\n var c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('Drag file', width / 2, height / 2);\n c.dragOver(dragOverCallback);\n}\n\n// This function will be called whenever\n// a file is dragged over the canvas\nfunction dragOverCallback() {\n background(240);\n text('Dragged over', width / 2, height / 2);\n}\n
\n// To test this sketch, simply drag a\n// file over the canvas\nfunction setup() {\n let c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('Drag file', width / 2, height / 2);\n c.dragOver(dragOverCallback);\n}\n\n// This function will be called whenever\n// a file is dragged over the canvas\nfunction dragOverCallback() {\n background(240);\n text('Dragged over', width / 2, height / 2);\n}\n
The .dragLeave() 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.
\n", "itemtype": "method", "name": "dragLeave", @@ -7578,7 +7675,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n\n// To test this sketch, simply drag a file\n// over and then out of the canvas area\nfunction setup() {\n var c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('Drag file', width / 2, height / 2);\n c.dragLeave(dragLeaveCallback);\n}\n\n// This function will be called whenever\n// a file is dragged out of the canvas\nfunction dragLeaveCallback() {\n background(240);\n text('Dragged off', width / 2, height / 2);\n}\n
\n// To test this sketch, simply drag a file\n// over and then out of the canvas area\nfunction setup() {\n let c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('Drag file', width / 2, height / 2);\n c.dragLeave(dragLeaveCallback);\n}\n\n// This function will be called whenever\n// a file is dragged out of the canvas\nfunction dragLeaveCallback() {\n background(240);\n text('Dragged off', width / 2, height / 2);\n}\n
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.
\n", - "itemtype": "method", - "name": "drop", - "params": [ - { - "name": "callback", - "description": "callback triggered when files are dropped.
\n", - "type": "Function" - }, - { - "name": "fxn", - "description": "callback to receive loaded file.
\n", - "type": "Function", - "optional": true - } - ], - "chainable": 1, - "example": [ - "\n\nfunction setup() {\n var c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('drop file', width / 2, height / 2);\n c.drop(gotFile);\n}\n\nfunction gotFile(file) {\n background(200);\n text('received file:', width / 2, height / 2);\n text(file.name, width / 2, height / 2 + 50);\n}\n
\nvar img;\n\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 draw() {\n if (img) {\n image(img, 0, 0, width, height);\n }\n}\n\nfunction gotFile(file) {\n img = createImg(file.data).hide();\n}\n
Helper fxn for sharing pixel methods
\n", "class": "p5.Element", "module": "DOM", @@ -7624,11 +7693,25 @@ module.exports={ { "file": "src/core/p5.Graphics.js", "line": 65, + "description": "Resets certain values such as those modified by functions in the Transform category\nand in the Lights category that are not automatically reset\nwith graphics buffer objects. Calling this in draw() will copy the behavior\nof the standard canvas.
\n", + "itemtype": "method", + "name": "reset", + "example": [ + "\n\n\nlet pg;\nfunction setup() {\n createCanvas(100, 100);\n background(0);\n pg = createGraphics(50, 100);\n pg.fill(0);\n frameRate(5);\n}\nfunction draw() {\n image(pg, width / 2, 0);\n pg.background(255);\n // p5.Graphics object behave a bit differently in some cases\n // The normal canvas on the left resets the translate\n // with every loop through draw()\n // the graphics object on the right doesn't automatically reset\n // so translate() is additive and it moves down the screen\n rect(0, 0, width / 2, 5);\n pg.rect(0, 0, width / 2, 5);\n translate(0, 5, 0);\n pg.translate(0, 5, 0);\n}\nfunction mouseClicked() {\n // if you click you will see that\n // reset() resets the translate back to the initial state\n // of the Graphics object\n pg.reset();\n}\n
Removes a Graphics object from the page and frees any resources\nassociated with it.
\n", "itemtype": "method", "name": "remove", "example": [ - "\n\nvar bg;\nfunction setup() {\n bg = createCanvas(100, 100);\n bg.background(0);\n image(bg, 0, 0);\n bg.remove();\n}\n
\nvar bg;\nfunction setup() {\n pixelDensity(1);\n createCanvas(100, 100);\n stroke(255);\n fill(0);\n\n // create and draw the background image\n bg = createGraphics(100, 100);\n bg.background(200);\n bg.ellipse(50, 50, 80, 80);\n}\nfunction draw() {\n var t = millis() / 1000;\n // draw the background\n if (bg) {\n image(bg, frameCount % 100, 0);\n image(bg, frameCount % 100 - 100, 0);\n }\n // draw the foreground\n var p = p5.Vector.fromAngle(t, 35).add(50, 50);\n ellipse(p.x, p.y, 30);\n}\nfunction mouseClicked() {\n // remove the background\n if (bg) {\n bg.remove();\n bg = null;\n }\n}\n
\nlet bg;\nfunction setup() {\n bg = createCanvas(100, 100);\n bg.background(0);\n image(bg, 0, 0);\n bg.remove();\n}\n
\nlet bg;\nfunction setup() {\n pixelDensity(1);\n createCanvas(100, 100);\n stroke(255);\n fill(0);\n\n // create and draw the background image\n bg = createGraphics(100, 100);\n bg.background(200);\n bg.ellipse(50, 50, 80, 80);\n}\nfunction draw() {\n let t = millis() / 1000;\n // draw the background\n if (bg) {\n image(bg, frameCount % 100, 0);\n image(bg, frameCount % 100 - 100, 0);\n }\n // draw the foreground\n let p = p5.Vector.fromAngle(t, 35).add(50, 50);\n ellipse(p.x, p.y, 30);\n}\nfunction mouseClicked() {\n // remove the background\n if (bg) {\n bg.remove();\n bg = null;\n }\n}\n
Resize our canvas element.
\n", "class": "p5.Renderer", "module": "Rendering", @@ -7645,7 +7728,7 @@ module.exports={ }, { "file": "src/core/p5.Renderer.js", - "line": 300, + "line": 335, "description": "Helper fxn to check font type (system or otf)
\n", "class": "p5.Renderer", "module": "Rendering", @@ -7653,7 +7736,7 @@ module.exports={ }, { "file": "src/core/p5.Renderer.js", - "line": 353, + "line": 388, "description": "Helper fxn to measure ascent and descent.\nAdapted from http://stackoverflow.com/a/25355178
\n", "class": "p5.Renderer", "module": "Rendering", @@ -7668,8 +7751,8 @@ module.exports={ }, { "file": "src/core/p5.Renderer2D.js", - "line": 414, - "description": "Generate a cubic Bezier representing an arc on the unit circle of total\nangle size
radians, beginning start
radians above the x-axis. Up to\nfour of these curves are combined to make a full arc.
See www.joecridge.me/bezier.pdf for an explanation of the method.
\n", + "line": 405, + "description": "Generate a cubic Bezier representing an arc on the unit circle of total\nangle size
radians, beginning start
radians above the x-axis. Up to\nfour of these curves are combined to make a full arc.
See www.joecridge.me/bezier.pdf for an explanation of the method.
\n", "class": "p5", "module": "Rendering" }, @@ -7784,7 +7867,7 @@ module.exports={ "type": "p5.Graphics" }, "example": [ - "\n\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
\n\nlet 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
\nBlends the pixels in the display window according to the defined mode.\nThere is a choice of the following modes to blend the source pixels (A)\nwith the ones of pixels already in the display window (B):
\nBLEND
- linear interpolation of colours: C =\nA*factor + B. This is the default blending mode.ADD
- sum of A and BDARKEST
- only the darkest colour succeeds: C =\nmin(A*factor, B).LIGHTEST
- only the lightest colour succeeds: C =\nmax(A*factor, B).DIFFERENCE
- subtract colors from underlying image.EXCLUSION
- similar to DIFFERENCE
, but less\nextreme.MULTIPLY
- multiply the colors, result will always be\ndarker.SCREEN
- opposite multiply, uses inverse values of the\ncolors.REPLACE
- the pixels entirely replace the others and\ndon't utilize alpha (transparency) values.OVERLAY
- mix of MULTIPLY
and SCREEN\n
. Multiplies dark values, and screens light values.HARD_LIGHT
- SCREEN
when greater than 50%\ngray, MULTIPLY
when lower.SOFT_LIGHT
- mix of DARKEST
and\nLIGHTEST
. Works like OVERLAY
, but not as harsh.\nDODGE
- lightens light tones and increases contrast,\nignores darks.BURN
- darker areas are applied, increasing contrast,\nignores lights.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):
\nBLEND
- linear interpolation of colours: C =\nA*factor + B. This is the default blending mode.ADD
- sum of A and BDARKEST
- only the darkest colour succeeds: C =\nmin(A*factor, B).LIGHTEST
- only the lightest colour succeeds: C =\nmax(A*factor, B).DIFFERENCE
- subtract colors from underlying image.EXCLUSION
- similar to DIFFERENCE
, but less\nextreme.MULTIPLY
- multiply the colors, result will always be\ndarker.SCREEN
- opposite multiply, uses inverse values of the\ncolors.REPLACE
- the pixels entirely replace the others and\ndon't utilize alpha (transparency) values.OVERLAY
- mix of MULTIPLY
and SCREEN\n
. Multiplies dark values, and screens light values. (2D)HARD_LIGHT
- SCREEN
when greater than 50%\ngray, MULTIPLY
when lower. (2D)SOFT_LIGHT
- mix of DARKEST
and\nLIGHTEST
. Works like OVERLAY
, but not as harsh. (2D)\nDODGE
- lightens light tones and increases contrast,\nignores darks. (2D)BURN
- darker areas are applied, increasing contrast,\nignores lights. (2D)SUBTRACT
- remainder of A and B (3D)blend mode to set for canvas.\n either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY,\n EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD or NORMAL
\n", + "description": "blend mode to set for canvas.\n either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY,\n EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD, or SUBTRACT
\n", "type": "Constant" } ], @@ -7833,7 +7916,7 @@ module.exports={ "itemtype": "method", "name": "noLoop", "example": [ - "\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n noLoop();\n}\n\nfunction draw() {\n line(10, 10, 90, 90);\n}\n
\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
\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n noLoop();\n}\n\nfunction draw() {\n line(10, 10, 90, 90);\n}\n
\nlet x = 0;\nfunction setup() {\n createCanvas(100, 100);\n}\n\nfunction draw() {\n background(204);\n x = x + 0.1;\n if (x > width) {\n x = 0;\n }\n line(x, 0, x, height);\n}\n\nfunction mousePressed() {\n noLoop();\n}\n\nfunction mouseReleased() {\n loop();\n}\n
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().
\n", + "description": "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().
\nAvoid calling loop() from inside setup().
\n", "itemtype": "method", "name": "loop", "example": [ - "\n\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
\nlet x = 0;\nfunction setup() {\n createCanvas(100, 100);\n noLoop();\n}\n\nfunction draw() {\n background(204);\n x = x + 0.1;\n if (x > width) {\n x = 0;\n }\n line(x, 0, x, height);\n}\n\nfunction mousePressed() {\n loop();\n}\n\nfunction mouseReleased() {\n noLoop();\n}\n
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().
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(), textSize(), textLeading().\n
\nIn WEBGL mode additional style settings are stored. These are controlled by the following functions: setCamera(), ambientLight(), directionalLight(),\npointLight(), texture(), specularMaterial(), shininess(), normalMaterial()\nand shader().
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().
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(), textSize(), textLeading().\n
\nIn WEBGL mode additional style settings are stored. These are controlled by the following functions: setCamera(), ambientLight(), directionalLight(),\npointLight(), texture(), specularMaterial(), shininess(), normalMaterial()\nand shader().
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.
\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
\n let 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 let 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
\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n background(200);\n // Equivalent to translate(x, y);\n applyMatrix(1, 0, 0, 1, 40 + step, 50);\n rect(0, 0, 50, 50);\n}\n
\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n background(200);\n translate(50, 50);\n // Equivalent to scale(x, y);\n applyMatrix(1 / step, 0, 0, 1 / step, 0, 0);\n rect(0, 0, 50, 50);\n}\n
\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n var angle = map(step, 0, 20, 0, TWO_PI);\n var cos_a = cos(angle);\n var sin_a = sin(angle);\n background(200);\n translate(50, 50);\n // Equivalent to rotate(angle);\n applyMatrix(cos_a, sin_a, -sin_a, cos_a, 0, 0);\n rect(0, 0, 50, 50);\n}\n
\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n var angle = map(step, 0, 20, -PI / 4, PI / 4);\n background(200);\n translate(50, 50);\n // equivalent to shearX(angle);\n var shear_factor = 1 / tan(PI / 2 - angle);\n applyMatrix(1, 0, shear_factor, 1, 0, 0);\n rect(0, 0, 50, 50);\n}\n
\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n background(200);\n // Equivalent to translate(x, y);\n applyMatrix(1, 0, 0, 1, 40 + step, 50);\n rect(0, 0, 50, 50);\n}\n
\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n background(200);\n translate(50, 50);\n // Equivalent to scale(x, y);\n applyMatrix(1 / step, 0, 0, 1 / step, 0, 0);\n rect(0, 0, 50, 50);\n}\n
\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n var angle = map(step, 0, 20, 0, TWO_PI);\n var cos_a = cos(angle);\n var sin_a = sin(angle);\n background(200);\n translate(50, 50);\n // Equivalent to rotate(angle);\n applyMatrix(cos_a, sin_a, -sin_a, cos_a, 0, 0);\n rect(0, 0, 50, 50);\n}\n
\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n var angle = map(step, 0, 20, -PI / 4, PI / 4);\n background(200);\n translate(50, 50);\n // equivalent to shearX(angle);\n var shear_factor = 1 / tan(PI / 2 - angle);\n applyMatrix(1, 0, shear_factor, 1, 0, 0);\n rect(0, 0, 50, 50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noFill();\n}\n\nfunction draw() {\n background(200);\n rotateY(PI / 6);\n stroke(153);\n box(35);\n var rad = millis() / 1000;\n // Set rotation angles\n var ct = cos(rad);\n var st = sin(rad);\n // Matrix for rotation around the Y axis\n applyMatrix( ct, 0.0, st, 0.0,\n 0.0, 1.0, 0.0, 0.0,\n -st, 0.0, ct, 0.0,\n 0.0, 0.0, 0.0, 1.0);\n stroke(255);\n box(50);\n}\n
\nReplaces the current matrix with the identity matrix.
\n", "itemtype": "method", "name": "resetMatrix", @@ -7968,7 +8051,7 @@ module.exports={ }, { "file": "src/core/transform.js", - "line": 161, + "line": 176, "description": "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().
Rotates around X axis.
\n", "itemtype": "method", "name": "rotateX", @@ -8018,7 +8101,7 @@ module.exports={ }, { "file": "src/core/transform.js", - "line": 231, + "line": 246, "description": "Rotates around Y axis.
\n", "itemtype": "method", "name": "rotateY", @@ -8040,7 +8123,7 @@ module.exports={ }, { "file": "src/core/transform.js", - "line": 261, + "line": 276, "description": "Rotates around Z axis. Webgl mode only.
\n", "itemtype": "method", "name": "rotateZ", @@ -8062,7 +8145,7 @@ module.exports={ }, { "file": "src/core/transform.js", - "line": 291, + "line": 306, "description": "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().
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.
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.
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().
\n function setup() {\n var myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // logs true to console\n var anotherDictionary = createStringDict({ happy: 'coding' });\n print(anotherDictionary.hasKey('happy')); // logs true to console\n }\n
\n function setup() {\n let myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // logs true to console\n let anotherDictionary = createStringDict({ happy: 'coding' });\n print(anotherDictionary.hasKey('happy')); // logs true to console\n }\n
\n function setup() {\n var myDictionary = createNumberDict(100, 42);\n print(myDictionary.hasKey(100)); // logs true to console\n var anotherDictionary = createNumberDict({ 200: 84 });\n print(anotherDictionary.hasKey(200)); // logs true to console\n }\n
\n function setup() {\n let myDictionary = createNumberDict(100, 42);\n print(myDictionary.hasKey(100)); // logs true to console\n let anotherDictionary = createNumberDict({ 200: 84 });\n print(anotherDictionary.hasKey(200)); // logs true to console\n }\n
\nfunction setup() {\n var myDictionary = createNumberDict(1, 10);\n myDictionary.create(2, 20);\n myDictionary.create(3, 30);\n print(myDictionary.size()); // logs 3 to the console\n}\n
\nfunction setup() {\n let myDictionary = createNumberDict(1, 10);\n myDictionary.create(2, 20);\n myDictionary.create(3, 30);\n print(myDictionary.size()); // logs 3 to the console\n}\n
\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // logs true to console\n}\n
\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // logs true to console\n}\n
\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n var myValue = myDictionary.get('p5');\n print(myValue === 'js'); // logs true to console\n}\n
\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n let myValue = myDictionary.get('p5');\n print(myValue === 'js'); // logs true to console\n}\n
\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n myDictionary.set('p5', 'JS');\n myDictionary.print(); // logs \"key: p5 - value: JS\" to console\n}\n
\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.set('p5', 'JS');\n myDictionary.print(); // logs \"key: p5 - value: JS\" to console\n}\n
\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n}\n
\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n}\n
\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // prints 'true'\n myDictionary.clear();\n print(myDictionary.hasKey('p5')); // prints 'false'\n}\n
\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // prints 'true'\n myDictionary.clear();\n print(myDictionary.hasKey('p5')); // prints 'false'\n}\n
\n\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n myDictionary.remove('p5');\n myDictionary.print();\n // above logs \"key: happy value: coding\" to console\n}\n
\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n myDictionary.remove('p5');\n myDictionary.print();\n // above logs \"key: happy value: coding\" to console\n}\n
\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n}\n
\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n}\n
\n\ncreateButton('save')\n .position(10, 10)\n .mousePressed(function() {\n createStringDict({\n john: 1940,\n paul: 1942,\n george: 1943,\n ringo: 1940\n }).saveTable('beatles');\n });\n
\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n}\n\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n createStringDict({\n john: 1940,\n paul: 1942,\n george: 1943,\n ringo: 1940\n }).saveTable('beatles');\n }\n}\n
\nConverts the Dictionary into a JSON file for local download.
\n", "itemtype": "method", "name": "saveJSON", "example": [ - "\n\ncreateButton('save')\n .position(10, 10)\n .mousePressed(function() {\n createStringDict({\n john: 1940,\n paul: 1942,\n george: 1943,\n ringo: 1940\n }).saveJSON('beatles');\n });\n
\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n}\n\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n createStringDict({\n john: 1940,\n paul: 1942,\n george: 1943,\n ringo: 1940\n }).saveJSON('beatles');\n }\n}\n
\nprivate helper function to ensure that the user passed in valid\nvalues for the Dictionary type
\n", "class": "p5.TypedDict", "module": "Data", @@ -8529,7 +8612,7 @@ module.exports={ }, { "file": "src/data/p5.TypedDict.js", - "line": 425, + "line": 437, "description": "private helper function to ensure that the user passed in valid\nvalues for the Dictionary type
\n", "class": "p5.NumberDict", "module": "Data", @@ -8537,7 +8620,7 @@ module.exports={ }, { "file": "src/data/p5.TypedDict.js", - "line": 434, + "line": 446, "description": "Add the given number to the value currently stored at the given key.\nThe sum then replaces the value previously stored in the Dictionary.
\n", "itemtype": "method", "name": "add", @@ -8554,7 +8637,7 @@ module.exports={ } ], "example": [ - "\n\nfunction setup() {\n var myDictionary = createNumberDict(2, 5);\n myDictionary.add(2, 2);\n print(myDictionary.get(2)); // logs 7 to console.\n}\n
\nfunction setup() {\n let myDictionary = createNumberDict(2, 5);\n myDictionary.add(2, 2);\n print(myDictionary.get(2)); // logs 7 to console.\n}\n
Subtract the given number from the value currently stored at the given key.\nThe difference then replaces the value previously stored in the Dictionary.
\n", "itemtype": "method", "name": "sub", @@ -8579,7 +8662,7 @@ module.exports={ } ], "example": [ - "\n\nfunction setup() {\n var myDictionary = createNumberDict(2, 5);\n myDictionary.sub(2, 2);\n print(myDictionary.get(2)); // logs 3 to console.\n}\n
\nfunction setup() {\n let myDictionary = createNumberDict(2, 5);\n myDictionary.sub(2, 2);\n print(myDictionary.get(2)); // logs 3 to console.\n}\n
Multiply the given number with the value currently stored at the given key.\nThe product then replaces the value previously stored in the Dictionary.
\n", "itemtype": "method", "name": "mult", @@ -8604,7 +8687,7 @@ module.exports={ } ], "example": [ - "\n\nfunction setup() {\n var myDictionary = createNumberDict(2, 4);\n myDictionary.mult(2, 2);\n print(myDictionary.get(2)); // logs 8 to console.\n}\n
\nfunction setup() {\n let myDictionary = createNumberDict(2, 4);\n myDictionary.mult(2, 2);\n print(myDictionary.get(2)); // logs 8 to console.\n}\n
Divide the given number with the value currently stored at the given key.\nThe quotient then replaces the value previously stored in the Dictionary.
\n", "itemtype": "method", "name": "div", @@ -8629,7 +8712,7 @@ module.exports={ } ], "example": [ - "\n\nfunction setup() {\n var myDictionary = createNumberDict(2, 8);\n myDictionary.div(2, 2);\n print(myDictionary.get(2)); // logs 4 to console.\n}\n
\nfunction setup() {\n let myDictionary = createNumberDict(2, 8);\n myDictionary.div(2, 2);\n print(myDictionary.get(2)); // logs 4 to console.\n}\n
private helper function for finding lowest or highest value\nthe argument 'flip' is used to flip the comparison arrow\nfrom 'less than' to 'greater than'
\n", "class": "p5.NumberDict", "module": "Data", @@ -8645,7 +8728,7 @@ module.exports={ }, { "file": "src/data/p5.TypedDict.js", - "line": 567, + "line": 579, "description": "Return the lowest number currently stored in the Dictionary.
\n", "itemtype": "method", "name": "minValue", @@ -8654,7 +8737,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\nfunction setup() {\n var myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });\n var lowestValue = myDictionary.minValue(); // value is -10\n print(lowestValue);\n}\n
\nfunction setup() {\n let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });\n let lowestValue = myDictionary.minValue(); // value is -10\n print(lowestValue);\n}\n
Return the highest number currently stored in the Dictionary.
\n", "itemtype": "method", "name": "maxValue", @@ -8671,7 +8754,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\nfunction setup() {\n var myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });\n var highestValue = myDictionary.maxValue(); // value is 3\n print(highestValue);\n}\n
\nfunction setup() {\n let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });\n let highestValue = myDictionary.maxValue(); // value is 3\n print(highestValue);\n}\n
private helper function for finding lowest or highest key\nthe argument 'flip' is used to flip the comparison arrow\nfrom 'less than' to 'greater than'
\n", "class": "p5.NumberDict", "module": "Data", @@ -8687,7 +8770,7 @@ module.exports={ }, { "file": "src/data/p5.TypedDict.js", - "line": 632, + "line": 644, "description": "Return the lowest key currently used in the Dictionary.
\n", "itemtype": "method", "name": "minKey", @@ -8696,7 +8779,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\nfunction setup() {\n var myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });\n var lowestKey = myDictionary.minKey(); // value is 1.2\n print(lowestKey);\n}\n
\nfunction setup() {\n let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });\n let lowestKey = myDictionary.minKey(); // value is 1.2\n print(lowestKey);\n}\n
Return the highest key currently used in the Dictionary.
\n", "itemtype": "method", "name": "maxKey", @@ -8713,7 +8796,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\nfunction setup() {\n var myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });\n var highestKey = myDictionary.maxKey(); // value is 4\n print(highestKey);\n}\n
\nfunction setup() {\n let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });\n let highestKey = myDictionary.maxKey(); // value is 4\n print(highestKey);\n}\n
\n// Move a touchscreen device to register\n// acceleration changes.\nfunction draw() {\n background(220, 50);\n fill('magenta');\n ellipse(width / 2, height / 2, accelerationX);\n}\n
\nThe system variable accelerationY always contains the acceleration of the\ndevice along the y axis. Value is represented as meters per second squared.
\n", "itemtype": "property", "name": "accelerationY", "type": "Number", "readonly": "", + "example": [ + "\n\n// Move a touchscreen device to register\n// acceleration changes.\nfunction draw() {\n background(220, 50);\n fill('magenta');\n ellipse(width / 2, height / 2, accelerationY);\n}\n
\nThe system variable accelerationZ always contains the acceleration of the\ndevice along the z axis. Value is represented as meters per second squared.
\n", "itemtype": "property", "name": "accelerationZ", "type": "Number", "readonly": "", + "example": [ + "\n\n// Move a touchscreen device to register\n// acceleration changes.\nfunction draw() {\n background(220, 50);\n fill('magenta');\n ellipse(width / 2, height / 2, accelerationZ);\n}\n
\nThe system variable pAccelerationX always contains the acceleration of the\ndevice along the x axis in the frame previous to the current frame. Value\nis represented as meters per second squared.
\n", "itemtype": "property", "name": "pAccelerationX", @@ -8781,7 +8876,7 @@ module.exports={ }, { "file": "src/events/acceleration.js", - "line": 60, + "line": 104, "description": "The system variable pAccelerationY always contains the acceleration of the\ndevice along the y axis in the frame previous to the current frame. Value\nis represented as meters per second squared.
\n", "itemtype": "property", "name": "pAccelerationY", @@ -8793,7 +8888,7 @@ module.exports={ }, { "file": "src/events/acceleration.js", - "line": 70, + "line": 114, "description": "The system variable pAccelerationZ always contains the acceleration of the\ndevice along the z axis in the frame previous to the current frame. Value\nis represented as meters per second squared.
\n", "itemtype": "property", "name": "pAccelerationZ", @@ -8805,15 +8900,15 @@ module.exports={ }, { "file": "src/events/acceleration.js", - "line": 91, + "line": 135, "description": "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
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n //rotateZ(radians(rotationZ));\n rotateX(radians(rotationX));\n //rotateY(radians(rotationY));\n box(200, 200, 200);\n}\n
\nThe 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
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n //rotateZ(radians(rotationZ));\n //rotateX(radians(rotationX));\n rotateY(radians(rotationY));\n box(200, 200, 200);\n}\n
\nThe 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
\nThe 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 necessary 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\nprint(rotateDirection);\n
\n\n// A simple if statement looking at whether\n// rotationX - pRotationX < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nlet rotateDirection = 'clockwise';\n\n// Simple range conversion to make things simpler.\n// This is not absolutely necessary but the logic\n// will be different in that case.\n\nlet rX = rotationX + 180;\nlet pRX = pRotationX + 180;\n\nif ((rX - pRX > 0 && rX - pRX < 270) || rX - pRX < -270) {\n rotateDirection = 'clockwise';\n} else if (rX - pRX < 0 || rX - pRX > 270) {\n rotateDirection = 'counter-clockwise';\n}\n\nprint(rotateDirection);\n
\nThe 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 necessary 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}\nprint(rotateDirection);\n
\n\n// A simple if statement looking at whether\n// rotationY - pRotationY < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nlet rotateDirection = 'clockwise';\n\n// Simple range conversion to make things simpler.\n// This is not absolutely necessary but the logic\n// will be different in that case.\n\nlet rY = rotationY + 180;\nlet pRY = pRotationY + 180;\n\nif ((rY - pRY > 0 && rY - pRY < 270) || rY - pRY < -270) {\n rotateDirection = 'clockwise';\n} else if (rY - pRY < 0 || rY - pRY > 270) {\n rotateDirection = 'counter-clockwise';\n}\nprint(rotateDirection);\n
\nThe 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 (\n (rotationZ - pRotationZ > 0 && rotationZ - pRotationZ < 270) ||\n rotationZ - pRotationZ < -270\n) {\n rotateDirection = 'clockwise';\n} else if (rotationZ - pRotationZ < 0 || rotationZ - pRotationZ > 270) {\n rotateDirection = 'counter-clockwise';\n}\nprint(rotateDirection);\n
\n\n// A simple if statement looking at whether\n// rotationZ - pRotationZ < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nlet rotateDirection = 'clockwise';\n\nif (\n (rotationZ - pRotationZ > 0 && rotationZ - pRotationZ < 270) ||\n rotationZ - pRotationZ < -270\n) {\n rotateDirection = 'clockwise';\n} else if (rotationZ - pRotationZ < 0 || rotationZ - pRotationZ > 270) {\n rotateDirection = 'counter-clockwise';\n}\nprint(rotateDirection);\n
\nWhen a device is rotated, the axis that triggers the deviceTurned()\nmethod is stored in the turnAxis variable. The turnAxis variable is only defined within\nthe scope of deviceTurned().
\n", "itemtype": "property", "name": "turnAxis", "type": "String", "readonly": "", + "example": [ + "\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees in the\n// X-axis to change the value.\n\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
\nThe setMoveThreshold() function is used to set the movement threshold for\nthe deviceMoved() function. The default threshold is set to 0.5.
\n", "itemtype": "method", "name": "setMoveThreshold", @@ -8924,7 +9024,7 @@ module.exports={ } ], "example": [ - "\n\n// Run this example on a mobile device\n// You will need to move the device incrementally further\n// the closer the square's color gets to white in order to change the value.\n\nvar value = 0;\nvar threshold = 0.5;\nfunction setup() {\n setMoveThreshold(threshold);\n}\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceMoved() {\n value = value + 5;\n threshold = threshold + 0.1;\n if (value > 255) {\n value = 0;\n threshold = 30;\n }\n setMoveThreshold(threshold);\n}\n
\n\n// Run this example on a mobile device\n// You will need to move the device incrementally further\n// the closer the square's color gets to white in order to change the value.\n\nlet value = 0;\nlet threshold = 0.5;\nfunction setup() {\n setMoveThreshold(threshold);\n}\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceMoved() {\n value = value + 5;\n threshold = threshold + 0.1;\n if (value > 255) {\n value = 0;\n threshold = 30;\n }\n setMoveThreshold(threshold);\n}\n
\nThe setShakeThreshold() function is used to set the movement threshold for\nthe deviceShaken() function. The default threshold is set to 30.
\n", "itemtype": "method", "name": "setShakeThreshold", @@ -8945,7 +9045,7 @@ module.exports={ } ], "example": [ - "\n\n// Run this example on a mobile device\n// You will need to shake the device more firmly\n// the closer the box's fill gets to white in order to change the value.\n\nvar value = 0;\nvar threshold = 30;\nfunction setup() {\n setShakeThreshold(threshold);\n}\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceMoved() {\n value = value + 5;\n threshold = threshold + 5;\n if (value > 255) {\n value = 0;\n threshold = 30;\n }\n setShakeThreshold(threshold);\n}\n
\n\n// Run this example on a mobile device\n// You will need to shake the device more firmly\n// the closer the box's fill gets to white in order to change the value.\n\nlet value = 0;\nlet threshold = 30;\nfunction setup() {\n setShakeThreshold(threshold);\n}\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceMoved() {\n value = value + 5;\n threshold = threshold + 5;\n if (value > 255) {\n value = 0;\n threshold = 30;\n }\n setShakeThreshold(threshold);\n}\n
\nThe deviceMoved() function is called when the device is moved by more than\nthe threshold value along X, Y or Z axis. The default threshold is set to\n0.5.
\n", + "line": 506, + "description": "The deviceMoved() function is called when the device is moved by more than\nthe threshold value along X, Y or Z axis. The default threshold is set to 0.5.\nThe threshold value can be changed using setMoveThreshold().
\n", "itemtype": "method", "name": "deviceMoved", "example": [ - "\n\n// Run this example on a mobile device\n// Move the device around\n// to change the value.\n\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
\n\n// Run this example on a mobile device\n// Move the device around\n// to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n
\nThe deviceTurned() function is called when the device rotates by\nmore than 90 degrees continuously.\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\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
\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees\n// to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceTurned() {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n}\n
\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees in the\n// X-axis to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceTurned() {\n if (turnAxis === 'X') {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n }\n}\n
\nThe deviceShaken() function is called when the device total acceleration\nchanges of accelerationX and accelerationY values is more than\nthe threshold value. The default threshold is set to 30.
\n", + "line": 597, + "description": "The deviceShaken() function is called when the device total acceleration\nchanges of accelerationX and accelerationY values is more than\nthe threshold value. The default threshold is set to 30.\nThe threshold value can be changed using setShakeThreshold().
\n", "itemtype": "method", "name": "deviceShaken", "example": [ - "\n\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
\n\n// Run this example on a mobile device\n// Shake the device to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceShaken() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n
\nThe boolean system variable keyIsPressed is true if any key is pressed\nand false if no keys are pressed.
\n", "itemtype": "property", "name": "keyIsPressed", @@ -9012,7 +9112,7 @@ module.exports={ }, { "file": "src/events/keyboard.js", - "line": 45, + "line": 39, "description": "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", "itemtype": "property", "name": "key", @@ -9028,28 +9128,28 @@ module.exports={ }, { "file": "src/events/keyboard.js", - "line": 74, + "line": 68, "description": "The variable keyCode is used to detect special keys such as BACKSPACE,\nDELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL, OPTION, ALT, UP_ARROW,\nDOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.\nYou can also check for custom keys by looking up the keyCode of any key\non a site like this: keycode.info.
\n", "itemtype": "property", "name": "keyCode", "type": "Integer", "readonly": "", "example": [ - "\n\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
\nlet 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
\nfunction draw() {}\nfunction keyPressed() {\n background('yellow');\n text(`${key} ${keyCode}`, 10, 40);\n print(key, ' ', keyCode);\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.
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, the key that was pressed is stored in the key variable. However, it\ndoes not distinguish between uppercase and lowercase. For this reason, it\nis recommended to use keyTyped() to read the key variable, in which the\ncase of the variable will be distinguished.\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
\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
\n\nfunction keyPressed() {\n // Do something\n return false; // prevent any default behaviour\n}\n
\n\nlet 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
\n\nlet 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
\n\nfunction keyPressed() {\n // Do something\n return false; // prevent any default behaviour\n}\n
\nThe keyReleased() function is called once every time a key is released.\nSee key and keyCode for more information.
\nBrowsers may have different default\nbehaviors attached to various key events. To prevent any default\nbehavior for this event, add "return false" to the end of the 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
\n\nlet 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
\nThe 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
\n\nlet 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
\nThe onblur function is called when the user is no longer focused\non the p5 element. Because the keyup events will not fire if the user is\nnot focused on the element we must assume all keys currently down have\nbeen released.
\n", "class": "p5", "module": "Events", @@ -9094,7 +9194,7 @@ module.exports={ }, { "file": "src/events/keyboard.js", - "line": 310, + "line": 312, "description": "The keyIsDown() function checks if the key is currently down, i.e. pressed.\nIt can be used if you have an object that moves, and you want several keys\nto be able to affect its behaviour simultaneously, such as moving a\nsprite diagonally. You can put in any number representing the keyCode of\nthe key, or use any of the variable keyCode names listed\nhere.
\n", "itemtype": "method", "name": "keyIsDown", @@ -9110,7 +9210,7 @@ module.exports={ "type": "Boolean" }, "example": [ - "\n\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\n if (keyIsDown(RIGHT_ARROW)) {\n x += 5;\n }\n\n if (keyIsDown(UP_ARROW)) {\n y -= 5;\n }\n\n if (keyIsDown(DOWN_ARROW)) {\n y += 5;\n }\n\n clear();\n fill(255, 0, 0);\n ellipse(x, y, 50, 50);\n}\n
\nvar diameter = 50;\n\nfunction setup() {\n createCanvas(512, 512);\n}\n\nfunction draw() {\n // 107 and 187 are keyCodes for \"+\"\n if (keyIsDown(107) || keyIsDown(187)) {\n diameter += 1;\n }\n\n // 109 and 189 are keyCodes for \"-\"\n if (keyIsDown(109) || keyIsDown(189)) {\n diameter -= 1;\n }\n\n clear();\n fill(255, 0, 0);\n ellipse(50, 50, diameter, diameter);\n}\n
\nlet x = 100;\nlet y = 100;\n\nfunction setup() {\n createCanvas(512, 512);\n fill(255, 0, 0);\n}\n\nfunction draw() {\n if (keyIsDown(LEFT_ARROW)) {\n x -= 5;\n }\n\n if (keyIsDown(RIGHT_ARROW)) {\n x += 5;\n }\n\n if (keyIsDown(UP_ARROW)) {\n y -= 5;\n }\n\n if (keyIsDown(DOWN_ARROW)) {\n y += 5;\n }\n\n clear();\n ellipse(x, y, 50, 50);\n}\n
\nlet diameter = 50;\n\nfunction setup() {\n createCanvas(512, 512);\n}\n\nfunction draw() {\n // 107 and 187 are keyCodes for \"+\"\n if (keyIsDown(107) || keyIsDown(187)) {\n diameter += 1;\n }\n\n // 109 and 189 are keyCodes for \"-\"\n if (keyIsDown(109) || keyIsDown(189)) {\n diameter -= 1;\n }\n\n clear();\n fill(255, 0, 0);\n ellipse(50, 50, diameter, diameter);\n}\n
\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n //draw a square only if the mouse is not moving\n if (mouseY === pmouseY && mouseX === pmouseX) {\n rect(20, 20, 60, 60);\n }\n\n print(pmouseY + ' -> ' + mouseY);\n}\n
\n\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 //rela tive 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\nlet myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n const body = document.getElementsByTagName('body')[0];\n myCanvas.parent(body);\n}\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n //move the canvas to the horizontal mouse position\n //relative to the window\n myCanvas.position(winMouseX + 1, windowHeight / 2);\n\n //the y of the square is relative to the canvas\n rect(20, mouseY, 60, 60);\n}\n
\nThe system variable winMouseY always contains the current vertical\nposition of the mouse, relative to (0, 0) of the window.
\n", "itemtype": "property", "name": "winMouseY", "type": "Number", "readonly": "", "example": [ - "\n\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 //rel ative 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\nlet myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n const body = document.getElementsByTagName('body')[0];\n myCanvas.parent(body);\n}\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n //move the canvas to the vertical mouse position\n //relative to the window\n myCanvas.position(windowWidth / 2, winMouseY + 1);\n\n //the x of the square is relative to the canvas\n rect(mouseX, 20, 60, 60);\n}\n
\nThe system variable pwinMouseX always contains the horizontal position\nof the mouse in the frame previous to the current frame, relative to\n(0, 0) of the window. Note: pwinMouseX will be reset to the current winMouseX\nvalue at the start of each touch event.
\n", "itemtype": "property", "name": "pwinMouseX", "type": "Number", "readonly": "", "example": [ - "\n\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\nlet myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n noStroke();\n fill(237, 34, 93);\n}\n\nfunction draw() {\n clear();\n //the difference between previous and\n //current x position is the horizontal mouse speed\n let speed = abs(winMouseX - pwinMouseX);\n //change the size of the circle\n //according to the horizontal speed\n ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);\n //move the canvas to the mouse position\n myCanvas.position(winMouseX + 1, winMouseY + 1);\n}\n
\nThe system variable pwinMouseY always contains the vertical position of\nthe mouse in the frame previous to the current frame, relative to (0, 0)\nof the window. Note: pwinMouseY will be reset to the current winMouseY\nvalue at the start of each touch event.
\n", "itemtype": "property", "name": "pwinMouseY", "type": "Number", "readonly": "", "example": [ - "\n\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\nlet myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n noStroke();\n fill(237, 34, 93);\n}\n\nfunction draw() {\n clear();\n //the difference between previous and\n //current y position is the vertical mouse speed\n let speed = abs(winMouseY - pwinMouseY);\n //change the size of the circle\n //according to the vertical speed\n ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);\n //move the canvas to the mouse position\n myCanvas.position(winMouseX + 1, winMouseY + 1);\n}\n
\nProcessing automatically tracks if the mouse button is pressed and which\nbutton is pressed. The value of the system variable mouseButton is either\nLEFT, RIGHT, or CENTER depending on which button was pressed last.\nWarning: different browsers may track mouseButton differently.
\n", "itemtype": "property", "name": "mouseButton", @@ -9256,14 +9356,14 @@ module.exports={ "example": [ "\n\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 }\n if (mouseButton === RIGHT) {\n rect(25, 25, 50, 50);\n }\n if (mouseButton === CENTER) {\n triangle(23, 75, 50, 20, 78, 75);\n }\n }\n\n print(mouseButton);\n}\n
\nThe boolean system variable mouseIsPressed is true if the mouse is pressed\nand false if not.
\n", "itemtype": "property", "name": "mouseIsPressed", @@ -9272,19 +9372,27 @@ module.exports={ "example": [ "\n\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\n print(mouseIsPressed);\n}\n
\nThe mouseMoved() function is called every time the mouse moves and a mouse\nbutton is not pressed.
\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.
optional MouseEvent callback argument.
\n", + "type": "Object", + "optional": true + } + ], "example": [ - "\n\n// Move the mouse across the page\n// to change its value\n\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
\n\nfunction mouseMoved() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// Move the mouse across the page\n// to change its value\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n
\n\nfunction mouseMoved() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// returns a MouseEvent object\n// as a callback argument\nfunction mouseMoved(event) {\n console.log(event);\n}\n
\nThe mouseDragged() function is called once every time the mouse moves and\na mouse button is pressed. If no mouseDragged() function is defined, the\ntouchMoved() function will be called instead if it is defined.
\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.
optional MouseEvent callback argument.
\n", + "type": "Object", + "optional": true + } + ], "example": [ - "\n\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
\n\nfunction mouseDragged() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// Drag the mouse across the page\n// to change its value\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseDragged() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n
\n\nfunction mouseDragged() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// returns a MouseEvent object\n// as a callback argument\nfunction mouseDragged(event) {\n console.log(event);\n}\n
\nThe mousePressed() function is called once after every time a mouse button\nis pressed. The mouseButton variable (see the related reference entry)\ncan be used to determine which button has been pressed. If no\nmousePressed() function is defined, the touchStarted() function will be\ncalled instead if it is defined.
\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.
optional MouseEvent callback argument.
\n", + "type": "Object", + "optional": true + } + ], "example": [ - "\n\n// Click within the image to change\n// the value of the rectangle\n\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
\n\nfunction mousePressed() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// Click within the image to change\n// the value of the rectangle\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mousePressed() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\n\nfunction mousePressed() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// returns a MouseEvent object\n// as a callback argument\nfunction mousePressed(event) {\n console.log(event);\n}\n
\nThe mouseReleased() function is called every time a mouse button is\nreleased. If no mouseReleased() function is defined, the touchEnded()\nfunction will be called instead if it is defined.
\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.
optional MouseEvent callback argument.
\n", + "type": "Object", + "optional": true + } + ], "example": [ - "\n\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been clicked\n\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
\n\nfunction mouseReleased() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been clicked\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseReleased() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\n\nfunction mouseReleased() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// returns a MouseEvent object\n// as a callback argument\nfunction mouseReleased(event) {\n console.log(event);\n}\n
\nThe mouseClicked() function is called once after a mouse button has been\npressed and then released.
\nBrowsers handle clicks differently, so this function is only guaranteed to be\nrun when the left mouse button is clicked. To handle other mouse buttons\nbeing pressed or released, see mousePressed() or mouseReleased().
\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.
optional MouseEvent callback argument.
\n", + "type": "Object", + "optional": true + } + ], "example": [ - "\n\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been clicked\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\n\nfunction mouseClicked() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\n\nfunction mouseClicked() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been clicked\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\n\nfunction mouseClicked() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\n\nfunction mouseClicked() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// returns a MouseEvent object\n// as a callback argument\nfunction mouseClicked(event) {\n console.log(event);\n}\n
\nThe doubleClicked() function is executed every time a event\nlistener has detected a dblclick event which is a part of the\nDOM L3 specification. The doubleClicked event is fired when a\npointing device button (usually a mouse's primary button)\nis clicked twice on a single element. For more info on the\ndblclick event refer to mozilla's documentation here:\nhttps://developer.mozilla.org/en-US/docs/Web/Events/dblclick
\n", "itemtype": "method", "name": "doubleClicked", + "params": [ + { + "name": "event", + "description": "optional MouseEvent callback argument.
\n", + "type": "Object", + "optional": true + } + ], "example": [ - "\n\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been double clicked\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\n\nfunction doubleClicked() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\n\nfunction doubleClicked() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been double clicked\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\n\nfunction doubleClicked() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\n\nfunction doubleClicked() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// returns a MouseEvent object\n// as a callback argument\nfunction doubleClicked(event) {\n console.log(event);\n}\n
\nThe function mouseWheel() is executed every time a vertical mouse wheel\nevent is detected either triggered by an actual mouse wheel or by a\ntouchpad.
\nThe event.delta property returns the amount the mouse wheel\nhave scrolled. The values can be positive or negative depending on the\nscroll direction (on 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.
optional WheelEvent callback argument.
\n", + "type": "Object", + "optional": true + } + ], "example": [ - "\n\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 print(event.delta);\n //move the square according to the vertical scroll amount\n pos += event.delta;\n //uncomment to block page scrolling\n //return false;\n}\n
\n\nlet 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 print(event.delta);\n //move the square according to the vertical scroll amount\n pos += event.delta;\n //uncomment to block page scrolling\n //return false;\n}\n
\n\n// On a touchscreen device, touch\n// the canvas using one or more fingers\n// at the same time\nfunction draw() {\n clear();\n var display = touches.length + ' touches';\n text(display, 5, 10);\n}\n
\n\n// On a touchscreen device, touch\n// the canvas using one or more fingers\n// at the same time\nfunction draw() {\n clear();\n let display = touches.length + ' touches';\n text(display, 5, 10);\n}\n
\nThe touchStarted() function is called once after every time a touch is\nregistered. If no touchStarted() function is defined, the mousePressed()\nfunction will be called instead if it is defined.
\nBrowsers may have different default behaviors attached to various touch\nevents. To prevent any default behavior for this event, add "return false"\nto the end of the method.
optional TouchEvent callback argument.
\n", + "type": "Object", + "optional": true + } + ], "example": [ - "\n\n// Touch within the image to change\n// the value of the rectangle\n\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
\n\nfunction touchStarted() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// Touch within the image to change\n// the value of the rectangle\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchStarted() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\n\nfunction touchStarted() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// returns a TouchEvent object\n// as a callback argument\nfunction touchStarted(event) {\n console.log(event);\n}\n
\nThe touchMoved() function is called every time a touch move is registered.\nIf no touchMoved() function is defined, the mouseDragged() function will\nbe called instead if it is defined.
\nBrowsers may have different default behaviors attached to various touch\nevents. To prevent any default behavior for this event, add "return false"\nto the end of the method.
optional TouchEvent callback argument.
\n", + "type": "Object", + "optional": true + } + ], "example": [ - "\n\n// Move your finger across the page\n// to change its value\n\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
\n\nfunction touchMoved() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// Move your finger across the page\n// to change its value\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n
\n\nfunction touchMoved() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// returns a TouchEvent object\n// as a callback argument\nfunction touchMoved(event) {\n console.log(event);\n}\n
\nThe touchEnded() function is called every time a touch ends. If no\ntouchEnded() function is defined, the mouseReleased() function will be\ncalled instead if it is defined.
\nBrowsers may have different default behaviors attached to various touch\nevents. To prevent any default behavior for this event, add "return false"\nto the end of the method.
optional TouchEvent callback argument.
\n", + "type": "Object", + "optional": true + } + ], "example": [ - "\n\n// Release touch within the image to\n// change the value of the rectangle\n\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
\n\nfunction touchEnded() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// Release touch within the image to\n// change the value of the rectangle\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchEnded() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\n\nfunction touchEnded() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n
\n\n// returns a TouchEvent object\n// as a callback argument\nfunction touchEnded(event) {\n console.log(event);\n}\n
\n\nvar img = createImage(66, 66);\nimg.loadPixels();\nfor (var i = 0; i < img.width; i++) {\n for (var j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\n
\n\nvar img = createImage(66, 66);\nimg.loadPixels();\nfor (var i = 0; i < img.width; i++) {\n for (var j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102, (i % img.width) * 2));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\nimage(img, 34, 34);\n
\n\nvar pink = color(255, 102, 204);\nvar img = createImage(66, 66);\nimg.loadPixels();\nvar d = pixelDensity();\nvar halfImage = 4 * (img.width * d) * (img.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
\n\nlet img = createImage(66, 66);\nimg.loadPixels();\nfor (let i = 0; i < img.width; i++) {\n for (let j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\n
\n\nlet img = createImage(66, 66);\nimg.loadPixels();\nfor (let i = 0; i < img.width; i++) {\n for (let j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102, (i % img.width) * 2));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\nimage(img, 34, 34);\n
\n\nlet pink = color(255, 102, 204);\nlet img = createImage(66, 66);\nimg.loadPixels();\nlet d = pixelDensity();\nlet halfImage = 4 * (img.width * d) * (img.height / 2 * d);\nfor (let i = 0; i < halfImage; i += 4) {\n img.pixels[i] = red(pink);\n img.pixels[i + 1] = green(pink);\n img.pixels[i + 2] = blue(pink);\n img.pixels[i + 3] = alpha(pink);\n}\nimg.updatePixels();\nimage(img, 17, 17);\n
\n\n function 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\n function setup() {\n var c = createCanvas(100, 100);\n background(255, 0, 0);\n saveCanvas('myCanvas', 'jpg');\n\n // all of the following are valid\n saveCanvas(c, 'myCanvas', 'jpg');\n saveCanvas(c, 'myCanvas.jpg');\n saveCanvas(c, 'myCanvas');\n saveCanvas(c);\n saveCanvas('myCanvas', 'png');\n saveCanvas('myCanvas');\n saveCanvas();\n }\n
\n function setup() {\n let c = createCanvas(100, 100);\n background(255, 0, 0);\n saveCanvas(c, 'myCanvas', 'jpg');\n }\n
\n // note that this example has the same result as above\n // if no canvas is specified, defaults to main canvas\n function setup() {\n let c = createCanvas(100, 100);\n background(255, 0, 0);\n saveCanvas('myCanvas', 'jpg');\n\n // all of the following are valid\n saveCanvas(c, 'myCanvas', 'jpg');\n saveCanvas(c, 'myCanvas.jpg');\n saveCanvas(c, 'myCanvas');\n saveCanvas(c);\n saveCanvas('myCanvas', 'png');\n saveCanvas('myCanvas');\n saveCanvas();\n }\n
\n function draw() {\n background(mouseX);\n }\n\n function mousePressed() {\n saveFrames('out', 'png', 1, 25, function(data) {\n print(data);\n });\n }\n
\n function draw() {\n background(mouseX);\n }\n\n function mousePressed() {\n saveFrames('out', 'png', 1, 25, data => {\n print(data);\n });\n }\n
\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n}\n
\n\nfunction setup() {\n // here we use a callback to display the image after loading\n loadImage('assets/laDefense.jpg', function(img) {\n image(img, 0, 0);\n });\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n}\n
\n\nfunction setup() {\n // here we use a callback to display the image after loading\n loadImage('assets/laDefense.jpg', img => {\n image(img, 0, 0);\n });\n}\n
\nDraw an image to the p5.js canvas.
\nThis function can be used with different numbers of parameters. The\nsimplest use requires only three parameters: img, x, and y—where (x, y) is\nthe position of the image. Two more parameters can optionally be added to\nspecify the width and height of the image.
\nThis function can also be used with all eight Number parameters. To\ndifferentiate between all these parameters, p5.js uses the language of\n"destination rectangle" (which corresponds to "dx", "dy", etc.) and "source\nimage" (which corresponds to "sx", "sy", etc.) below. Specifying the\n"source image" dimensions can be useful when you want to display a\nsubsection of the source image instead of the whole thing. Here's a diagram\nto explain further:\n
\n", "itemtype": "method", "name": "image", "example": [ - "\n\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n // Top-left corner of the img is at (0, 0)\n // Width and height are the img's original width and height\n image(img, 0, 0);\n}\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n background(50);\n // Top-left corner of the img is at (10, 10)\n // Width and height are 50 x 50\n image(img, 10, 10, 50, 50);\n}\n
\n\nfunction setup() {\n // Here, we use a callback to display the image after loading\n loadImage('assets/laDefense.jpg', function(img) {\n image(img, 0, 0);\n });\n}\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/gradient.png');\n}\nfunction setup() {\n // 1. Background image\n // Top-left corner of the img is at (0, 0)\n // Width and height are the img's original width and height, 100 x 100\n image(img, 0, 0);\n // 2. Top right image\n // Top-left corner of destination rectangle is at (50, 0)\n // Destination rectangle width and height are 40 x 20\n // The next parameters are relative to the source image:\n // - Starting at position (50, 50) on the source image, capture a 50 x 50\n // subsection\n // - Draw this subsection to fill the dimensions of the destination rectangle\n image(img, 50, 0, 40, 20, 50, 50, 50, 50);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n // Top-left corner of the img is at (0, 0)\n // Width and height are the img's original width and height\n image(img, 0, 0);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n background(50);\n // Top-left corner of the img is at (10, 10)\n // Width and height are 50 x 50\n image(img, 10, 10, 50, 50);\n}\n
\n\nfunction setup() {\n // Here, we use a callback to display the image after loading\n loadImage('assets/laDefense.jpg', img => {\n image(img, 0, 0);\n });\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/gradient.png');\n}\nfunction setup() {\n // 1. Background image\n // Top-left corner of the img is at (0, 0)\n // Width and height are the img's original width and height, 100 x 100\n image(img, 0, 0);\n // 2. Top right image\n // Top-left corner of destination rectangle is at (50, 0)\n // Destination rectangle width and height are 40 x 20\n // The next parameters are relative to the source image:\n // - Starting at position (50, 50) on the source image, capture a 50 x 50\n // subsection\n // - Draw this subsection to fill the dimensions of the destination rectangle\n image(img, 50, 0, 40, 20, 50, 50, 50, 50);\n}\n
\nSets 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.
\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
\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
\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
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n tint(0, 153, 204); // Tint blue\n image(img, 50, 0);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n tint(0, 153, 204, 126); // Tint blue and set transparency\n image(img, 50, 0);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n tint(255, 126); // Apply transparency without changing color\n image(img, 50, 0);\n}\n
\nRemoves the current fill value for displaying images and reverts to\ndisplaying images with their original hues.
\n", "itemtype": "method", "name": "noTint", "example": [ - "\n\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
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n tint(0, 153, 204); // Tint blue\n image(img, 0, 0);\n noTint(); // Disable tint\n image(img, 50, 0);\n}\n
\nSet image mode. Modifies the location from which images are drawn by\nchanging the way in which parameters given to image() are interpreted.\nThe default mode is imageMode(CORNER), which interprets the second and\nthird parameters of image() as the upper-left corner of the image. If\ntwo additional parameters are specified, they are used to set the image's\nwidth and height.\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.
\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
\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
\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
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n imageMode(CORNER);\n image(img, 10, 10, 50, 50);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n imageMode(CORNERS);\n image(img, 10, 10, 90, 40);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n imageMode(CENTER);\n image(img, 50, 50, 80, 80);\n}\n
\n\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
\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n image(img, 0, 0);\n for (let i = 0; i < img.width; i++) {\n let c = img.get(i, img.height / 2);\n stroke(c);\n line(i, height / 2, i, height);\n }\n}\n
\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
\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n image(img, 0, 0);\n for (let i = 0; i < img.height; i++) {\n let c = img.get(img.width / 2, i);\n stroke(c);\n line(0, i, width / 2, i);\n }\n}\n
Array containing the values for all the pixels in the display window.\nThese values are numbers. This array is the size (include an appropriate\nfactor for pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. Retina and other\nhigh 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.
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):
\nlet d = pixelDensity();\nfor (let i = 0; i < d; i++) {\n for (let j = 0; j < d; j++) {\n // loop over\n index = 4 * ((y * d + j) * width * d + (x * d + i));\n pixels[index] = r;\n pixels[index+1] = g;\n pixels[index+2] = b;\n pixels[index+3] = a;\n }\n}\n
\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.
\nvar img = createImage(66, 66);\nimg.loadPixels();\nfor (var i = 0; i < img.width; i++) {\n for (var j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\n
\n\nvar pink = color(255, 102, 204);\nvar img = 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
\n\nlet img = createImage(66, 66);\nimg.loadPixels();\nfor (let i = 0; i < img.width; i++) {\n for (let j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\n
\n\nlet pink = color(255, 102, 204);\nlet img = createImage(66, 66);\nimg.loadPixels();\nfor (let i = 0; i < 4 * (width * height / 2); i += 4) {\n img.pixels[i] = red(pink);\n img.pixels[i + 1] = green(pink);\n img.pixels[i + 2] = blue(pink);\n img.pixels[i + 3] = alpha(pink);\n}\nimg.updatePixels();\nimage(img, 17, 17);\n
\nHelper fxn for sharing pixel methods
\n", "class": "p5.Image", "module": "Image", @@ -9900,12 +10080,12 @@ module.exports={ }, { "file": "src/image/p5.Image.js", - "line": 231, + "line": 232, "description": "Loads the pixels data for this image into the [pixels] attribute.
\n", "itemtype": "method", "name": "loadPixels", "example": [ - "\n\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
\nlet myImage;\nlet halfImage;\n\nfunction preload() {\n myImage = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n myImage.loadPixels();\n halfImage = 4 * myImage.width * myImage.height / 2;\n for (let i = 0; i < halfImage; i++) {\n myImage.pixels[i + halfImage] = myImage.pixels[i];\n }\n myImage.updatePixels();\n}\n\nfunction draw() {\n image(myImage, 0, 0, width, height);\n}\n
Updates the backing canvas for this image with the contents of\nthe [pixels] array.
\n", "itemtype": "method", "name": "updatePixels", "example": [ - "\n\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
\nlet myImage;\nlet halfImage;\n\nfunction preload() {\n myImage = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n myImage.loadPixels();\n halfImage = 4 * myImage.width * myImage.height / 2;\n for (let i = 0; i < halfImage; i++) {\n myImage.pixels[i + halfImage] = myImage.pixels[i];\n }\n myImage.updatePixels();\n}\n\nfunction draw() {\n image(myImage, 0, 0, width, height);\n}\n
Get a region of pixels from an image.
\nIf 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.
\nReturns undefined if the region is outside the bounds of the image
\n", + "line": 316, + "description": "Get a region of pixels from an image.
\nIf no params are passed, the whole image is returned.\nIf x and y are the only params passed a single pixel is extracted.\nIf all params are passed a rectangle region is extracted and a p5.Image\nis returned.
\n", "itemtype": "method", "name": "get", - "params": [ - { - "name": "x", - "description": "x-coordinate of the pixel
\n", - "type": "Number", - "optional": true - }, - { - "name": "y", - "description": "y-coordinate of the pixel
\n", - "type": "Number", - "optional": true - }, - { - "name": "w", - "description": "width
\n", - "type": "Number", - "optional": true - }, - { - "name": "h", - "description": "height
\n", - "type": "Number", - "optional": true - } - ], "return": { - "description": "color of pixel at x,y in array format\n [R, G, B, A] or p5.Image", - "type": "Number[]|Color|p5.Image" + "description": "the rectangle p5.Image", + "type": "p5.Image" }, "example": [ - "\n\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
\nlet myImage;\nlet c;\n\nfunction preload() {\n myImage = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n background(myImage);\n noStroke();\n c = myImage.get(60, 90);\n fill(c);\n rect(25, 25, 50, 50);\n}\n\n//get() returns color here\n
x-coordinate of the pixel
\n", + "type": "Number" + }, + { + "name": "y", + "description": "y-coordinate of the pixel
\n", + "type": "Number" + }, + { + "name": "w", + "description": "width
\n", + "type": "Number" + }, + { + "name": "h", + "description": "height
\n", + "type": "Number" + } + ], + "return": { + "description": "the rectangle p5.Image", + "type": "p5.Image" + } + }, + { + "line": 354, + "params": [], + "return": { + "description": "the whole p5.Image", + "type": "p5.Image" + } + }, + { + "line": 358, + "params": [ + { + "name": "x", + "description": "", + "type": "Number" + }, + { + "name": "y", + "description": "", + "type": "Number" + } + ], + "return": { + "description": "color of pixel at x,y in array format [R, G, B, A]", + "type": "Number[]" + } + } + ] }, { "file": "src/image/p5.Image.js", - "line": 360, + "line": 371, "description": "Set the color of a single pixel or write an image into\nthis p5.Image.
\nNote that for a large number of pixels this will\nbe slower than directly manipulating the pixels array\nand then calling updatePixels().
\n", "itemtype": "method", "name": "set", @@ -10025,7 +10237,7 @@ module.exports={ } ], "example": [ - "\n\nvar img = createImage(66, 66);\nimg.loadPixels();\nfor (var i = 0; i < img.width; i++) {\n for (var j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102, (i % img.width) * 2));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\nimage(img, 34, 34);\n
\n\nlet img = createImage(66, 66);\nimg.loadPixels();\nfor (let i = 0; i < img.width; i++) {\n for (let j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102, (i % img.width) * 2));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\nimage(img, 34, 34);\n
\nResize the image to a new width and height. To make the image scale\nproportionally, use 0 as the value for the wide or high parameter.\nFor instance, to make the width of an image 150 pixels, and change\nthe height using the same proportion, use resize(150, 0).
\n", "itemtype": "method", "name": "resize", @@ -10051,7 +10263,7 @@ module.exports={ } ], "example": [ - "\n\nvar img;\n\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction draw() {\n image(img, 0, 0);\n}\n\nfunction mousePressed() {\n img.resize(50, 100);\n}\n
\nlet img;\n\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction draw() {\n image(img, 0, 0);\n}\n\nfunction mousePressed() {\n img.resize(50, 100);\n}\n
Copies a region of pixels from one image to another. If no\nsrcImage is specified this is used as the source. If the source\nand destination regions aren't the same size, it will\nautomatically resize source pixels to fit the specified\ntarget region.
\n", "itemtype": "method", "name": "copy", "example": [ - "\n\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
\nlet photo;\nlet bricks;\nlet x;\nlet y;\n\nfunction preload() {\n photo = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n x = bricks.width / 2;\n y = bricks.height / 2;\n photo.copy(bricks, 0, 0, x, y, 0, 0, x, y);\n image(photo, 0, 0);\n}\n
Masks part of an image from displaying by loading another\nimage and using it's alpha channel as an alpha channel for\nthis image.
\n", "itemtype": "method", "name": "mask", @@ -10183,7 +10395,7 @@ module.exports={ } ], "example": [ - "\n\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
\nlet photo, maskImage;\nfunction preload() {\n photo = loadImage('assets/rockies.jpg');\n maskImage = loadImage('assets/mask2.png');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n photo.mask(maskImage);\n image(photo, 0, 0);\n}\n
Applies an image filter to a p5.Image
\n", "itemtype": "method", "name": "filter", @@ -10210,7 +10422,7 @@ module.exports={ } ], "example": [ - "\n\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
\nlet photo1;\nlet photo2;\n\nfunction preload() {\n photo1 = loadImage('assets/rockies.jpg');\n photo2 = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n photo2.filter(GRAY);\n image(photo1, 0, 0);\n image(photo2, width / 2, 0);\n}\n
Copies a region of pixels from one image to another, using a specified\nblend mode to do the operation.
\n", "itemtype": "method", "name": "blend", "example": [ - "\n\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
\nlet mountains;\nlet bricks;\n\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n
\nlet mountains;\nlet bricks;\n\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n
\nlet mountains;\nlet bricks;\n\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n
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.
\n", "itemtype": "method", "name": "save", @@ -10357,7 +10569,7 @@ module.exports={ } ], "example": [ - "\n\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
\nlet photo;\n\nfunction preload() {\n photo = loadImage('assets/rockies.jpg');\n}\n\nfunction draw() {\n image(photo, 0, 0);\n}\n\nfunction keyTyped() {\n if (key === 's') {\n photo.save('photo', 'png');\n }\n}\n
Uint8ClampedArray\ncontaining the values for all the pixels in the display window.\nThese values are numbers. This array is the size (include an appropriate\nfactor for pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. Retina and other\nhigh density displays will have more pixels[] (by a factor of\npixelDensity^2).\nFor example, if the image is 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):
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
\nWhile the above method is complex, it is flexible enough to work with\nany pixelDensity. Note that set() will automatically take care of\nsetting all the appropriate values in pixels[] for a given (x, y) at\nany pixelDensity, but the performance may not be as fast when lots of\nmodifications are made to the pixel array.\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.
Uint8ClampedArray\ncontaining the values for all the pixels in the display window.\nThese values are numbers. This array is the size (include an appropriate\nfactor for pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. Retina and other\nhigh density displays will have more pixels[] (by a factor of\npixelDensity^2).\nFor example, if the image is 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):
let d = pixelDensity();\nfor (let i = 0; i < d; i++) {\n for (let j = 0; j < d; j++) {\n // loop over\n index = 4 * ((y * d + j) * width * d + (x * d + i));\n pixels[index] = r;\n pixels[index+1] = g;\n pixels[index+2] = b;\n pixels[index+3] = a;\n }\n}\n
\nWhile the above method is complex, it is flexible enough to work with\nany pixelDensity. Note that set() will automatically take care of\nsetting all the appropriate values in pixels[] for a given (x, y) at\nany pixelDensity, but the performance may not be as fast when lots of\nmodifications are made to the pixel array.\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.
\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
\n\nlet pink = color(255, 102, 204);\nloadPixels();\nlet d = pixelDensity();\nlet halfImage = 4 * (width * d) * (height / 2 * d);\nfor (let i = 0; i < halfImage; i += 4) {\n pixels[i] = red(pink);\n pixels[i + 1] = green(pink);\n pixels[i + 2] = blue(pink);\n pixels[i + 3] = alpha(pink);\n}\nupdatePixels();\n
\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, 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
\nlet img0;\nlet img1;\n\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n}\n
\nlet img0;\nlet img1;\n\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n}\n
\nlet img0;\nlet img1;\n\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n}\n
\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
\nlet img;\n\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n background(img);\n copy(img, 7, 22, 10, 10, 35, 25, 50, 50);\n stroke(255);\n noFill();\n // Rectangle shows area being copied\n rect(7, 22, 10, 10);\n}\n
\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(THRESHOLD);\n}\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
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(OPAQUE);\n}\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
\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
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(DILATE);\n}\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
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(ERODE);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(THRESHOLD);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(GRAY);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(OPAQUE);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(INVERT);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(POSTERIZE, 3);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(DILATE);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(BLUR, 3);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(ERODE);\n}\n
\nReturns an array of [R,G,B,A] values for any pixel or grabs a section of\nan image. If no parameters are specified, the entire image is returned.\nUse the x and y parameters to get the value of one pixel. Get a section of\nthe display window by specifying additional w and h parameters. When\ngetting an image, the x and y parameters define the coordinates for the\nupper-left corner of the image, regardless of the current imageMode().\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 x, y, d; // set these to the coordinates\nvar off = (y width + x) d * 4;\nvar components = [\n pixels[off],\n pixels[off + 1],\n pixels[off + 2],\n pixels[off + 3]\n];\nprint(components);\n
\n
\nSee the reference for pixels[] for more information.
If you want to extract an array of colors or a subimage from an p5.Image object,\ntake a look at p5.Image.get()
\n", + "description": "Get a region of pixels, or a single pixel, from the canvas.
\nReturns an array of [R,G,B,A] values for any pixel or grabs a section of\nan image. If no parameters are specified, the entire image is returned.\nUse the x and y parameters to get the value of one pixel. Get a section of\nthe display window by specifying additional w and h parameters. When\ngetting an image, the x and y parameters define the coordinates for the\nupper-left corner of the image, regardless of the current imageMode().\n
\nTo get the color components 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
let x, y, d; // set these to the coordinates\nlet off = (y * width + x) * d * 4;\nlet components = [\n pixels[off],\n pixels[off + 1],\n pixels[off + 2],\n pixels[off + 3]\n];\nprint(components);\n
\nSee the reference for pixels[] for more information.
\nIf you want to extract an array of colors or a subimage from an p5.Image object,\ntake a look at p5.Image.get()
\n", "itemtype": "method", "name": "get", - "params": [ - { - "name": "x", - "description": "x-coordinate of the pixel
\n", - "type": "Number", - "optional": true - }, - { - "name": "y", - "description": "y-coordinate of the pixel
\n", - "type": "Number", - "optional": true - }, - { - "name": "w", - "description": "width
\n", - "type": "Number", - "optional": true - }, - { - "name": "h", - "description": "height
\n", - "type": "Number", - "optional": true - } - ], "return": { - "description": "values of pixel at x,y in array format\n [R, G, B, A] or p5.Image", - "type": "Number[]|p5.Image" + "description": "the rectangle p5.Image", + "type": "p5.Image" }, "example": [ - "\n\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
\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
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n let c = get();\n image(c, width / 2, 0);\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n let c = get(50, 90);\n fill(c);\n noStroke();\n rect(25, 25, 50, 50);\n}\n
\nx-coordinate of the pixel
\n", + "type": "Number" + }, + { + "name": "y", + "description": "y-coordinate of the pixel
\n", + "type": "Number" + }, + { + "name": "w", + "description": "width
\n", + "type": "Number" + }, + { + "name": "h", + "description": "height
\n", + "type": "Number" + } + ], + "return": { + "description": "the rectangle p5.Image", + "type": "p5.Image" + } + }, + { + "line": 491, + "params": [], + "return": { + "description": "the whole p5.Image", + "type": "p5.Image" + } + }, + { + "line": 495, + "params": [ + { + "name": "x", + "description": "", + "type": "Number" + }, + { + "name": "y", + "description": "", + "type": "Number" + } + ], + "return": { + "description": "color of pixel at x,y in array format [R, G, B, A]", + "type": "Number[]" + } + } + ] }, { "file": "src/image/pixels.js", - "line": 494, + "line": 506, "description": "Loads the pixel data for the display window into the pixels[] array. This\nfunction must always be called before reading from or writing to pixels[].\nNote that only changes made with set() or direct manipulation of pixels[]\nwill occur.
\n", "itemtype": "method", "name": "loadPixels", "example": [ - "\n\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) * (img.height * d / 2);\n loadPixels();\n for (var i = 0; i < halfImage; i++) {\n pixels[i + halfImage] = pixels[i];\n }\n updatePixels();\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n image(img, 0, 0, width, height);\n let d = pixelDensity();\n let halfImage = 4 * (width * d) * (height * d / 2);\n loadPixels();\n for (let i = 0; i < halfImage; i++) {\n pixels[i + halfImage] = pixels[i];\n }\n updatePixels();\n}\n
\nChanges the color of any pixel, or writes an image directly to the\ndisplay window.
\nThe x and y parameters specify the pixel to change and the c parameter\nspecifies the color value. This can be a p5.Color object, or [R, G, B, A]\npixel array. It can also be a single grayscale value.\nWhen setting an image, the x and y parameters define the coordinates for\nthe upper-left corner of the image, regardless of the current imageMode().\n
\n\nAfter using set(), you must call updatePixels() for your changes to appear.\nThis should be called once all pixels have been set, and must be called before\ncalling .get() or drawing the image.\n
\nSetting the color of a single pixel with set(x, y) is easy, but not as\nfast as putting the data directly into pixels[]. Setting the pixels[]\nvalues directly may be complicated when working with a retina display,\nbut will perform better when lots of pixels need to be set directly on\nevery loop.
\nSee the reference for pixels[] for more information.
", "itemtype": "method", "name": "set", @@ -10720,7 +10964,7 @@ module.exports={ } ], "example": [ - "\n\nvar black = color(0);\nset(30, 20, black);\nset(85, 20, black);\nset(85, 75, black);\nset(30, 75, black);\nupdatePixels();\n
\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
\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
\n\nlet black = color(0);\nset(30, 20, black);\nset(85, 20, black);\nset(85, 75, black);\nset(30, 75, black);\nupdatePixels();\n
\n\nfor (let i = 30; i < width - 15; i++) {\n for (let j = 20; j < height - 25; j++) {\n let c = color(204 - j, 153 - i, 0);\n set(i, j, c);\n }\n}\nupdatePixels();\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n set(0, 0, img);\n updatePixels();\n line(0, 0, width, height);\n line(0, height, width, 0);\n}\n
\nUpdates the display window with the data in the pixels[] array.\nUse in conjunction with loadPixels(). If you're only reading pixels from\nthe array, there's no need to call updatePixels() — updating is only\nnecessary to apply changes. updatePixels() should be called anytime the\npixels array is manipulated or set() is called, and only changes made with\nset() or direct changes to pixels[] will occur.
\n", "itemtype": "method", "name": "updatePixels", @@ -10760,7 +11004,7 @@ module.exports={ } ], "example": [ - "\n\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) * (img.height * d / 2);\n loadPixels();\n for (var i = 0; i < halfImage; i++) {\n pixels[i + halfImage] = pixels[i];\n }\n updatePixels();\n}\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n image(img, 0, 0, width, height);\n let d = pixelDensity();\n let halfImage = 4 * (width * d) * (height * d / 2);\n loadPixels();\n for (let i = 0; i < halfImage; i++) {\n pixels[i + halfImage] = pixels[i];\n }\n updatePixels();\n}\n
\nCalling loadJSON() inside preload() guarantees to complete the\noperation before setup() and draw() are called.
\n\n\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\nvar earthquakes;\nfunction preload() {\n // Get the most recent earthquake in the database\n var url =\n 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +\n 'summary/all_day.geojson';\n earthquakes = loadJSON(url);\n}\n\nfunction setup() {\n noLoop();\n}\n\nfunction draw() {\n background(200);\n // Get the magnitude and name of the earthquake out of the loaded JSON\n var earthquakeMag = earthquakes.features[0].properties.mag;\n var earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n}\n
Outside of preload(), you may supply a callback function to handle the\nobject:
\n\nfunction setup() {\n noLoop();\n var url =\n 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +\n 'summary/all_day.geojson';\n loadJSON(url, drawEarthquake);\n}\n\nfunction draw() {\n background(200);\n}\n\nfunction drawEarthquake(earthquakes) {\n // Get the magnitude and name of the earthquake out of the loaded JSON\n var earthquakeMag = earthquakes.features[0].properties.mag;\n var earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n}\n
Calling loadJSON() inside preload() guarantees to complete the\noperation before setup() and draw() are called.
\n\n\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\nlet earthquakes;\nfunction preload() {\n // Get the most recent earthquake in the database\n let url =\n 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +\n 'summary/all_day.geojson';\n earthquakes = loadJSON(url);\n}\n\nfunction setup() {\n noLoop();\n}\n\nfunction draw() {\n background(200);\n // Get the magnitude and name of the earthquake out of the loaded JSON\n let earthquakeMag = earthquakes.features[0].properties.mag;\n let earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n}\n
Outside of preload(), you may supply a callback function to handle the\nobject:
\n\nfunction setup() {\n noLoop();\n let url =\n 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +\n 'summary/all_day.geojson';\n loadJSON(url, drawEarthquake);\n}\n\nfunction draw() {\n background(200);\n}\n\nfunction drawEarthquake(earthquakes) {\n // Get the magnitude and name of the earthquake out of the loaded JSON\n let earthquakeMag = earthquakes.features[0].properties.mag;\n let earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n}\n
Calling loadStrings() inside preload() guarantees to complete the\noperation before setup() and draw() are called.
\n\n\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
Outside of preload(), you may supply a callback function to handle the\nobject:
\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
Calling loadStrings() inside preload() guarantees to complete the\noperation before setup() and draw() are called.
\n\n\nlet result;\nfunction preload() {\n result = loadStrings('assets/test.txt');\n}\n\nfunction setup() {\n background(200);\n let ind = floor(random(result.length));\n text(result[ind], 10, 10, 80, 80);\n}\n
Outside of preload(), you may supply a callback function to handle the\nobject:
\n\n\nfunction setup() {\n loadStrings('assets/test.txt', pickString);\n}\n\nfunction pickString(result) {\n background(200);\n let ind = floor(random(result.length));\n text(result[ind], 10, 10, 80, 80);\n}\n
\n// Given the following CSV file called \"mammals.csv\"\n// located in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\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 print(table.getRowCount() + ' total rows in table');\n print(table.getColumnCount() + ' total columns in table');\n\n print(table.getColumn('name'));\n //[\"Goat\", \"Leopard\", \"Zebra\"]\n\n //cycle through the table\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++) {\n print(table.getString(r, c));\n }\n}\n
\n\n// Given the following CSV file called \"mammals.csv\"\n// located in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n //the file can be remote\n //table = loadTable(\"http://p5js.org/reference/assets/mammals.csv\",\n // \"csv\", \"header\");\n}\n\nfunction setup() {\n //count the columns\n print(table.getRowCount() + ' total rows in table');\n print(table.getColumnCount() + ' total columns in table');\n\n print(table.getColumn('name'));\n //[\"Goat\", \"Leopard\", \"Zebra\"]\n\n //cycle through the table\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++) {\n print(table.getString(r, c));\n }\n}\n
\nReads the contents of a file and creates an XML object with its values.\nIf the name of the file is used as the parameter, as in the above example,\nthe file must be located in the sketch directory/folder.
\nAlternatively, the file maybe be loaded from anywhere on the local\ncomputer using an absolute path (something that starts with / on Unix and\nLinux, or a drive letter on Windows), or the filename parameter can be a\nURL for a file found on a network.
\nThis method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed. Calling loadXML() inside preload()\nguarantees to complete the operation before setup() and draw() are called.
\nOutside of preload(), you may supply a callback function to handle the\nobject.
\nThis method is suitable for fetching files up to size of 64MB.
\n", "itemtype": "method", "name": "loadXML", @@ -11025,7 +11269,7 @@ module.exports={ "type": "Object" }, "example": [ - "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\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].getNum('id');\n var coloring = children[i].getString('species');\n var name = children[i].getContent();\n print(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
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let children = xml.getChildren('animal');\n\n for (let i = 0; i < children.length; i++) {\n let id = children[i].getNum('id');\n let coloring = children[i].getString('species');\n let name = children[i].getContent();\n print(id + ', ' + coloring + ', ' + name);\n }\n}\n\n// Sketch prints:\n// 0, Capra hircus, Goat\n// 1, Panthera pardus, Leopard\n// 2, Equus zebra, Zebra\n
This method is suitable for fetching files up to size of 64MB.
\n", "itemtype": "method", "name": "loadBytes", @@ -11062,7 +11306,7 @@ module.exports={ "type": "Object" }, "example": [ - "\n\nvar data;\n\nfunction preload() {\n data = loadBytes('assets/mammals.xml');\n}\n\nfunction setup() {\n for (var i = 0; i < 5; i++) {\n console.log(data.bytes[i].toString(16));\n }\n}\n
\nlet data;\n\nfunction preload() {\n data = loadBytes('assets/mammals.xml');\n}\n\nfunction setup() {\n for (let i = 0; i < 5; i++) {\n console.log(data.bytes[i].toString(16));\n }\n}\n
Method for executing an HTTP GET request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text. This is equivalent to\ncalling httpDo(path, 'GET')
. The 'binary' datatype will return\na Blob object, and the 'arrayBuffer' datatype will return an ArrayBuffer\nwhich can be used to initialize typed arrays (such as Uint8Array).
\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\nvar earthquakes;\nfunction preload() {\n // Get the most recent earthquake in the database\n var url =\n 'https://earthquake.usgs.gov/fdsnws/event/1/query?' +\n 'format=geojson&limit=1&orderby=time';\n httpGet(url, 'jsonp', false, function(response) {\n // when the HTTP request completes, populate the variable that holds the\n // earthquake data used in the visualization.\n earthquakes = response;\n });\n}\n\nfunction draw() {\n if (!earthquakes) {\n // Wait until the earthquake data has loaded before drawing.\n return;\n }\n background(200);\n // Get the magnitude and name of the earthquake out of the loaded JSON\n var earthquakeMag = earthquakes.features[0].properties.mag;\n var earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n noLoop();\n}\n
\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\nlet earthquakes;\nfunction preload() {\n // Get the most recent earthquake in the database\n let url =\n 'https://earthquake.usgs.gov/fdsnws/event/1/query?' +\n 'format=geojson&limit=1&orderby=time';\n httpGet(url, 'jsonp', false, function(response) {\n // when the HTTP request completes, populate the variable that holds the\n // earthquake data used in the visualization.\n earthquakes = response;\n });\n}\n\nfunction draw() {\n if (!earthquakes) {\n // Wait until the earthquake data has loaded before drawing.\n return;\n }\n background(200);\n // Get the magnitude and name of the earthquake out of the loaded JSON\n let earthquakeMag = earthquakes.features[0].properties.mag;\n let earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n noLoop();\n}\n
Method for executing an HTTP POST request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text. This is equivalent to\ncalling httpDo(path, 'POST')
.
\n// Examples use jsonplaceholder.typicode.com for a Mock Data API\n\nvar url = 'https://jsonplaceholder.typicode.com/posts';\nvar postData = { userId: 1, title: 'p5 Clicked!', body: 'p5.js is way cool.' };\n\nfunction setup() {\n createCanvas(800, 800);\n}\n\nfunction mousePressed() {\n // Pick new random color values\n var r = random(255);\n var g = random(255);\n var b = random(255);\n\n httpPost(url, 'json', postData, function(result) {\n strokeWeight(2);\n stroke(r, g, b);\n fill(r, g, b, 127);\n ellipse(mouseX, mouseY, 200, 200);\n text(result.body, mouseX, mouseY);\n });\n}\n
\n\nvar url = 'https://invalidURL'; // A bad URL that will cause errors\nvar postData = { title: 'p5 Clicked!', body: 'p5.js is way cool.' };\n\nfunction setup() {\n createCanvas(800, 800);\n}\n\nfunction mousePressed() {\n // Pick new random color values\n var r = random(255);\n var g = random(255);\n var b = random(255);\n\n httpPost(\n url,\n 'json',\n postData,\n function(result) {\n // ... won't be called\n },\n function(error) {\n strokeWeight(2);\n stroke(r, g, b);\n fill(r, g, b, 127);\n text(error.toString(), mouseX, mouseY);\n }\n );\n}\n
\n// Examples use jsonplaceholder.typicode.com for a Mock Data API\n\nlet url = 'https://jsonplaceholder.typicode.com/posts';\nlet postData = { userId: 1, title: 'p5 Clicked!', body: 'p5.js is way cool.' };\n\nfunction setup() {\n createCanvas(800, 800);\n}\n\nfunction mousePressed() {\n // Pick new random color values\n let r = random(255);\n let g = random(255);\n let b = random(255);\n\n httpPost(url, 'json', postData, function(result) {\n strokeWeight(2);\n stroke(r, g, b);\n fill(r, g, b, 127);\n ellipse(mouseX, mouseY, 200, 200);\n text(result.body, mouseX, mouseY);\n });\n}\n
\n\nlet url = 'https://invalidURL'; // A bad URL that will cause errors\nlet postData = { title: 'p5 Clicked!', body: 'p5.js is way cool.' };\n\nfunction setup() {\n createCanvas(800, 800);\n}\n\nfunction mousePressed() {\n // Pick new random color values\n let r = random(255);\n let g = random(255);\n let b = random(255);\n\n httpPost(\n url,\n 'json',\n postData,\n function(result) {\n // ... won't be called\n },\n function(error) {\n strokeWeight(2);\n stroke(r, g, b);\n fill(r, g, b, 127);\n text(error.toString(), mouseX, mouseY);\n }\n );\n}\n
Method for executing an HTTP request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text.
\nFor more advanced use, you may also pass in the path as the first argument\nand a object as the second argument, the signature follows the one specified\nin the Fetch API specification.\nThis method is suitable for fetching files up to size of 64MB when "GET" is used.
\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\n\n// displays an animation of all USGS earthquakes\nvar earthquakes;\nvar eqFeatureIndex = 0;\n\nfunction preload() {\n var url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson';\n httpDo(\n url,\n {\n method: 'GET',\n // Other Request options, like special headers for apis\n headers: { authorization: 'Bearer secretKey' }\n },\n function(res) {\n earthquakes = res;\n }\n );\n}\n\nfunction draw() {\n // wait until the data is loaded\n if (!earthquakes || !earthquakes.features[eqFeatureIndex]) {\n return;\n }\n clear();\n\n var feature = earthquakes.features[eqFeatureIndex];\n var mag = feature.properties.mag;\n var rad = mag / 11 * ((width + height) / 2);\n fill(255, 0, 0, 100);\n ellipse(width / 2 + random(-2, 2), height / 2 + random(-2, 2), rad, rad);\n\n if (eqFeatureIndex >= earthquakes.features.length) {\n eqFeatureIndex = 0;\n } else {\n eqFeatureIndex += 1;\n }\n}\n
\n\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\n\n// displays an animation of all USGS earthquakes\nlet earthquakes;\nlet eqFeatureIndex = 0;\n\nfunction preload() {\n let url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson';\n httpDo(\n url,\n {\n method: 'GET',\n // Other Request options, like special headers for apis\n headers: { authorization: 'Bearer secretKey' }\n },\n function(res) {\n earthquakes = res;\n }\n );\n}\n\nfunction draw() {\n // wait until the data is loaded\n if (!earthquakes || !earthquakes.features[eqFeatureIndex]) {\n return;\n }\n clear();\n\n let feature = earthquakes.features[eqFeatureIndex];\n let mag = feature.properties.mag;\n let rad = mag / 11 * ((width + height) / 2);\n fill(255, 0, 0, 100);\n ellipse(width / 2 + random(-2, 2), height / 2 + random(-2, 2), rad, rad);\n\n if (eqFeatureIndex >= earthquakes.features.length) {\n eqFeatureIndex = 0;\n } else {\n eqFeatureIndex += 1;\n }\n}\n
\n\ncreateButton('save')\n .position(10, 10)\n .mousePressed(function() {\n var writer = createWriter('squares.txt');\n for (var i = 0; i < 10; i++) {\n writer.print(i * i);\n }\n writer.close();\n writer.clear();\n });\n
\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n}\n\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n var writer = createWriter('squares.txt');\n for (let i = 0; i < 10; i++) {\n writer.print(i * i);\n }\n writer.close();\n writer.clear();\n }\n}\n
\nWrites data to the PrintWriter stream
\n", "itemtype": "method", "name": "write", @@ -11432,7 +11676,7 @@ module.exports={ } ], "example": [ - "\n\n// creates a file called 'newFile.txt'\nvar writer = createWriter('newFile.txt');\n// write 'Hello world!'' to the file\nwriter.write(['Hello world!']);\n// close the PrintWriter and save the file\nwriter.close();\n
\n\n// creates a file called 'newFile2.txt'\nvar writer = createWriter('newFile2.txt');\n// write 'apples,bananas,123' to the file\nwriter.write(['apples', 'bananas', 123]);\n// close the PrintWriter and save the file\nwriter.close();\n
\n\n// creates a file called 'newFile3.txt'\nvar writer = createWriter('newFile3.txt');\n// write 'My name is: Teddy' to the file\nwriter.write('My name is:');\nwriter.write(' Teddy');\n// close the PrintWriter and save the file\nwriter.close();\n
\n\n// creates a file called 'newFile.txt'\nlet writer = createWriter('newFile.txt');\n// write 'Hello world!'' to the file\nwriter.write(['Hello world!']);\n// close the PrintWriter and save the file\nwriter.close();\n
\n\n// creates a file called 'newFile2.txt'\nlet writer = createWriter('newFile2.txt');\n// write 'apples,bananas,123' to the file\nwriter.write(['apples', 'bananas', 123]);\n// close the PrintWriter and save the file\nwriter.close();\n
\n\n// creates a file called 'newFile3.txt'\nlet writer = createWriter('newFile3.txt');\n// write 'My name is: Teddy' to the file\nwriter.write('My name is:');\nwriter.write(' Teddy');\n// close the PrintWriter and save the file\nwriter.close();\n
\nWrites data to the PrintWriter stream, and adds a new line at the end
\n", "itemtype": "method", "name": "print", @@ -11452,7 +11696,7 @@ module.exports={ } ], "example": [ - "\n\n// creates a file called 'newFile.txt'\nvar writer = createWriter('newFile.txt');\n// creates a file containing\n// My name is:\n// Teddy\nwriter.print('My name is:');\nwriter.print('Teddy');\n// close the PrintWriter and save the file\nwriter.close();\n
\n\nvar writer;\n\nfunction setup() {\n createCanvas(400, 400);\n // create a PrintWriter\n writer = createWriter('newFile.txt');\n}\n\nfunction draw() {\n // print all mouseX and mouseY coordinates to the stream\n writer.print([mouseX, mouseY]);\n}\n\nfunction mouseClicked() {\n // close the PrintWriter and save the file\n writer.close();\n}\n
\n\n// creates a file called 'newFile.txt'\nlet writer = createWriter('newFile.txt');\n// creates a file containing\n// My name is:\n// Teddy\nwriter.print('My name is:');\nwriter.print('Teddy');\n// close the PrintWriter and save the file\nwriter.close();\n
\n\nlet writer;\n\nfunction setup() {\n createCanvas(400, 400);\n // create a PrintWriter\n writer = createWriter('newFile.txt');\n}\n\nfunction draw() {\n // print all mouseX and mouseY coordinates to the stream\n writer.print([mouseX, mouseY]);\n}\n\nfunction mouseClicked() {\n // close the PrintWriter and save the file\n writer.close();\n}\n
\nClears the data already written to the PrintWriter object
\n", "itemtype": "method", "name": "clear", "example": [ - "\n\n// create writer object\nvar writer = createWriter('newFile.txt');\nwriter.write(['clear me']);\n// clear writer object here\nwriter.clear();\n// close writer\nwriter.close();\n
\n// create writer object\nlet writer = createWriter('newFile.txt');\nwriter.write(['clear me']);\n// clear writer object here\nwriter.clear();\n// close writer\nwriter.close();\n
Closes the PrintWriter
\n", "itemtype": "method", "name": "close", "example": [ - "\n\n// create a file called 'newFile.txt'\nvar writer = createWriter('newFile.txt');\n// close the PrintWriter and save the file\nwriter.close();\n
\n\n// create a file called 'newFile2.txt'\nvar writer = createWriter('newFile2.txt');\n// write some data to the file\nwriter.write([100, 101, 102]);\n// close the PrintWriter and save the file\nwriter.close();\n
\n\n// create a file called 'newFile.txt'\nlet writer = createWriter('newFile.txt');\n// close the PrintWriter and save the file\nwriter.close();\n
\n\n// create a file called 'newFile2.txt'\nlet writer = createWriter('newFile2.txt');\n// write some data to the file\nwriter.write([100, 101, 102]);\n// close the PrintWriter and save the file\nwriter.close();\n
\nSave 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.
\nThe default behavior is to save the canvas as an image. You can\noptionally specify a filename.\nFor example:
\n\n save();\n save('myCanvas.jpg'); // save a specific canvas with a filename\n
\n\nAlternately, 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\n\n // Saves canvas as an image\n save('myCanvas.jpg');\n\n // Saves pImage as a png image\n var img = createImage(10, 10);\n save(img, 'my.png');\n\n // Saves canvas as an image\n var cnv = createCanvas(100, 100);\n save(cnv, 'myCanvas.jpg');\n\n // Saves p5.Renderer object as an image\n var gb = createGraphics(100, 100);\n save(gb, 'myGraphics.jpg');\n\n var myTable = new p5.Table();\n\n // Saves table as html file\n save(myTable, 'myTable.html');\n\n // Comma Separated Values\n save(myTable, 'myTable.csv');\n\n // Tab Separated Values\n save(myTable, 'myTable.tsv');\n\n var myJSON = { a: 1, b: true };\n\n // Saves pretty JSON\n save(myJSON, 'my.json');\n\n // Optimizes JSON filesize\n save(myJSON, 'my.json', true);\n\n // Saves array of strings to a text file with line breaks after each item\n var arrayOfStrings = ['a', 'b'];\n save(arrayOfStrings, 'my.txt');\n
",
+ "line": 1391,
+ "description": "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.
\nThe default behavior is to save the canvas as an image. You can\noptionally specify a filename.\nFor example:
\n\n save();\n save('myCanvas.jpg'); // save a specific canvas with a filename\n
\n\nAlternately, 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 parameters. For example:
\n\n\n // Saves canvas as an image\n save('myCanvas.jpg');\n\n // Saves pImage as a png image\n let img = createImage(10, 10);\n save(img, 'my.png');\n\n // Saves canvas as an image\n let cnv = createCanvas(100, 100);\n save(cnv, 'myCanvas.jpg');\n\n // Saves p5.Renderer object as an image\n let gb = createGraphics(100, 100);\n save(gb, 'myGraphics.jpg');\n\n let myTable = new p5.Table();\n\n // Saves table as html file\n save(myTable, 'myTable.html');\n\n // Comma Separated Values\n save(myTable, 'myTable.csv');\n\n // Tab Separated Values\n save(myTable, 'myTable.tsv');\n\n let myJSON = { a: 1, b: true };\n\n // Saves pretty JSON\n save(myJSON, 'my.json');\n\n // Optimizes JSON filesize\n save(myJSON, 'my.json', true);\n\n // Saves array of strings to a text file with line breaks after each item\n let arrayOfStrings = ['a', 'b'];\n save(arrayOfStrings, 'my.txt');\n
",
"itemtype": "method",
"name": "save",
"params": [
@@ -11516,7 +11760,7 @@ module.exports={
},
{
"file": "src/io/files.js",
- "line": 1530,
+ "line": 1519,
"description": "Writes the contents of an Array or a JSON object to a .json file.\nThe file saving process and location of the saved file will\nvary between web browsers.
\n", "itemtype": "method", "name": "saveJSON", @@ -11539,7 +11783,7 @@ module.exports={ } ], "example": [ - "\n\n var json = {}; // new JSON Object\n\n json.id = 0;\n json.species = 'Panthera leo';\n json.name = 'Lion';\n\n createButton('save')\n .position(10, 10)\n .mousePressed(function() {\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
\n let json = {}; // new JSON Object\n\n json.id = 0;\n json.species = 'Panthera leo';\n json.name = 'Lion';\n\n function setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n }\n\n function mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n saveJSON(json, 'lion.json');\n }\n }\n\n // saves the following to a file called \"lion.json\":\n // {\n // \"id\": 0,\n // \"species\": \"Panthera leo\",\n // \"name\": \"Lion\"\n // }\n
Writes an array of Strings to a text file, one line per String.\nThe file saving process and location of the saved file will\nvary between web browsers.
\n", "itemtype": "method", "name": "saveStrings", @@ -11571,7 +11815,7 @@ module.exports={ } ], "example": [ - "\n\n var words = 'apple bear cat dog';\n\n // .split() outputs an Array\n var list = split(words, ' ');\n\n createButton('save')\n .position(10, 10)\n .mousePressed(function() {\n saveStrings(list, 'nouns.txt');\n });\n\n // Saves the following to a file called 'nouns.txt':\n //\n // apple\n // bear\n // cat\n // dog\n
\n let words = 'apple bear cat dog';\n\n // .split() outputs an Array\n let list = split(words, ' ');\n\n function setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n }\n\n function mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n saveStrings(list, 'nouns.txt');\n }\n }\n\n // Saves the following to a file called 'nouns.txt':\n //\n // apple\n // bear\n // cat\n // dog\n
Writes the contents of a Table object to a file. Defaults to a\ntext file with comma-separated-values ('csv') but can also\nuse tab separation ('tsv'), or generate an HTML table ('html').\nThe file saving process and location of the saved file will\nvary between web browsers.
\n", "itemtype": "method", "name": "saveTable", @@ -11603,7 +11847,7 @@ module.exports={ } ], "example": [ - "\n\n var table;\n\n function setup() {\n table = new p5.Table();\n\n table.addColumn('id');\n table.addColumn('species');\n table.addColumn('name');\n\n 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
\n let table;\n\n function setup() {\n table = new p5.Table();\n\n table.addColumn('id');\n table.addColumn('species');\n table.addColumn('name');\n\n let newRow = table.addRow();\n newRow.setNum('id', table.getRowCount() - 1);\n newRow.setString('species', 'Panthera leo');\n newRow.setString('name', 'Lion');\n\n // To save, un-comment next line then click 'run'\n // saveTable(table, 'new.csv');\n }\n\n // Saves the following to a file called 'new.csv':\n // id,species,name\n // 0,Panthera leo,Lion\n
\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n 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 print(table.getString(r, c));\n }\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //add a row\n let newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Canis Lupus');\n newRow.setString('name', 'Wolf');\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n }\n
\n \n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\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 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 print(table.getString(r, c));\n}\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //remove the first row\n table.removeRow(0);\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n}\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\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 print(row.getString(c));\n }\n}\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n let row = table.getRow(1);\n //print it column by column\n //note: a row is an object, not an array\n for (let c = 0; c < table.getColumnCount(); c++) {\n print(row.getString(c));\n }\n}\n
\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n 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\n //print the results\n for (r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n }\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n\n //warning: rows is an array of objects\n for (let r = 0; r < rows.length; r++) {\n rows[r].set('name', 'Unicorn');\n }\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n }\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n 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 print(row.getString('species'));\n }\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //find the animal named zebra\n let row = table.findRow('Zebra', 'name');\n //find the corresponding species\n print(row.getString('species'));\n }\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n 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 print(rows.length + ' Goats found');\n }\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //add another goat\n let newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Scape Goat');\n newRow.setString('name', 'Goat');\n\n //find the rows containing animals named Goat\n let rows = table.findRows('Goat', 'name');\n print(rows.length + ' Goats found');\n }\n
\n \n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\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 //Search using specified regex on a given column, return TableRow object\n var mammal = table.matchRow(new RegExp('ant'), 1);\n print(mammal.getString(1));\n //Output \"Panthera pardus\"\n}\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //Search using specified regex on a given column, return TableRow object\n let mammal = table.matchRow(new RegExp('ant'), 1);\n print(mammal.getString(1));\n //Output \"Panthera pardus\"\n}\n
\n\nvar table;\n\nfunction setup() {\n table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n var newRow = table.addRow();\n newRow.setString('name', 'Lion');\n newRow.setString('type', 'Mammal');\n\n newRow = table.addRow();\n newRow.setString('name', 'Snake');\n newRow.setString('type', 'Reptile');\n\n newRow = table.addRow();\n newRow.setString('name', 'Mosquito');\n newRow.setString('type', 'Insect');\n\n newRow = table.addRow();\n newRow.setString('name', 'Lizard');\n newRow.setString('type', 'Reptile');\n\n var rows = table.matchRows('R.*', 'type');\n for (var i = 0; i < rows.length; i++) {\n print(rows[i].getString('name') + ': ' + rows[i].getString('type'));\n }\n}\n// Sketch prints:\n// Snake: Reptile\n// Lizard: Reptile\n
\n\nlet table;\n\nfunction setup() {\n table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n let newRow = table.addRow();\n newRow.setString('name', 'Lion');\n newRow.setString('type', 'Mammal');\n\n newRow = table.addRow();\n newRow.setString('name', 'Snake');\n newRow.setString('type', 'Reptile');\n\n newRow = table.addRow();\n newRow.setString('name', 'Mosquito');\n newRow.setString('type', 'Insect');\n\n newRow = table.addRow();\n newRow.setString('name', 'Lizard');\n newRow.setString('type', 'Reptile');\n\n let rows = table.matchRows('R.*', 'type');\n for (let i = 0; i < rows.length; i++) {\n print(rows[i].getString('name') + ': ' + rows[i].getString('type'));\n }\n}\n// Sketch prints:\n// Snake: Reptile\n// Lizard: Reptile\n
\n\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 print(table.getColumn('species'));\n //outputs [\"Capra hircus\", \"Panthera pardus\", \"Equus zebra\"]\n }\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //getColumn returns an array that can be printed directly\n print(table.getColumn('species'));\n //outputs [\"Capra hircus\", \"Panthera pardus\", \"Equus zebra\"]\n }\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n 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 print(table.getRowCount() + ' total rows in table');\n print(table.getColumnCount() + ' total columns in table');\n }\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.clearRows();\n print(table.getRowCount() + ' total rows in table');\n print(table.getColumnCount() + ' total columns in table');\n }\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n 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 print(table.getString(r, c));\n }\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.addColumn('carnivore');\n table.set(0, 'carnivore', 'no');\n table.set(1, 'carnivore', 'yes');\n table.set(2, 'carnivore', 'no');\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n }\n
\n \n // given the cvs file \"blobs.csv\" in /assets directory\n // ID, Name, Flavor, Shape, Color\n // Blob1, Blobby, Sweet, Blob, Pink\n // Blob2, Saddy, Savory, Blob, Blue\n\n var table;\n\n function preload() {\n table = loadTable('assets/blobs.csv');\n }\n\n function setup() {\n createCanvas(200, 100);\n textAlign(CENTER);\n background(255);\n }\n\n function draw() {\n var numOfColumn = table.getColumnCount();\n text('There are ' + numOfColumn + ' columns in the table.', 100, 50);\n }\n
\n \n // given the cvs file \"blobs.csv\" in /assets directory\n // ID, Name, Flavor, Shape, Color\n // Blob1, Blobby, Sweet, Blob, Pink\n // Blob2, Saddy, Savory, Blob, Blue\n\n let table;\n\n function preload() {\n table = loadTable('assets/blobs.csv');\n }\n\n function setup() {\n createCanvas(200, 100);\n textAlign(CENTER);\n background(255);\n }\n\n function draw() {\n let numOfColumn = table.getColumnCount();\n text('There are ' + numOfColumn + ' columns in the table.', 100, 50);\n }\n
\n \n // given the cvs file \"blobs.csv\" in /assets directory\n //\n // ID, Name, Flavor, Shape, Color\n // Blob1, Blobby, Sweet, Blob, Pink\n // Blob2, Saddy, Savory, Blob, Blue\n\n var table;\n\n function preload() {\n table = loadTable('assets/blobs.csv');\n }\n\n function setup() {\n createCanvas(200, 100);\n textAlign(CENTER);\n background(255);\n }\n\n function draw() {\n text('There are ' + table.getRowCount() + ' rows in the table.', 100, 50);\n }\n
\n \n // given the cvs file \"blobs.csv\" in /assets directory\n //\n // ID, Name, Flavor, Shape, Color\n // Blob1, Blobby, Sweet, Blob, Pink\n // Blob2, Saddy, Savory, Blob, Blue\n\n let table;\n\n function preload() {\n table = loadTable('assets/blobs.csv');\n }\n\n function setup() {\n createCanvas(200, 100);\n textAlign(CENTER);\n background(255);\n }\n\n function draw() {\n text('There are ' + table.getRowCount() + ' rows in the table.', 100, 50);\n }\n
\n \n function setup() {\n var table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n var newRow = table.addRow();\n newRow.setString('name', ' $Lion ,');\n newRow.setString('type', ',,,Mammal');\n\n newRow = table.addRow();\n newRow.setString('name', '$Snake ');\n newRow.setString('type', ',,,Reptile');\n\n table.removeTokens(',$ ');\n print(table.getArray());\n }\n\n // prints:\n // 0 \"Lion\" \"Mamal\"\n // 1 \"Snake\" \"Reptile\"\n
\n function setup() {\n let table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n let newRow = table.addRow();\n newRow.setString('name', ' $Lion ,');\n newRow.setString('type', ',,,Mammal');\n\n newRow = table.addRow();\n newRow.setString('name', '$Snake ');\n newRow.setString('type', ',,,Reptile');\n\n table.removeTokens(',$ ');\n print(table.getArray());\n }\n\n // prints:\n // 0 \"Lion\" \"Mamal\"\n // 1 \"Snake\" \"Reptile\"\n
\n function setup() {\n var table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n var newRow = table.addRow();\n newRow.setString('name', ' Lion ,');\n newRow.setString('type', ' Mammal ');\n\n newRow = table.addRow();\n newRow.setString('name', ' Snake ');\n newRow.setString('type', ' Reptile ');\n\n table.trim();\n print(table.getArray());\n }\n\n // prints:\n // 0 \"Lion\" \"Mamal\"\n // 1 \"Snake\" \"Reptile\"\n
\n function setup() {\n let table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n let newRow = table.addRow();\n newRow.setString('name', ' Lion ,');\n newRow.setString('type', ' Mammal ');\n\n newRow = table.addRow();\n newRow.setString('name', ' Snake ');\n newRow.setString('type', ' Reptile ');\n\n table.trim();\n print(table.getArray());\n }\n\n // prints:\n // 0 \"Lion\" \"Mamal\"\n // 1 \"Snake\" \"Reptile\"\n
\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 print(table.getColumnCount());\n }\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.removeColumn('id');\n print(table.getColumnCount());\n }\n
\n \n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\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 print(table.getString(r, c));\n}\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n table.set(0, 'species', 'Canis Lupus');\n table.set(0, 'name', 'Wolf');\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n}\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\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 print(table.getColumn(0));\n //[\"0\", 1, \"2\"]\n}\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n table.setNum(1, 'id', 1);\n\n print(table.getColumn(0));\n //[\"0\", 1, \"2\"]\n}\n
\n\n// Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\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 //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(table.getArray());\n}\n
\n// Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //add a row\n let newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Canis Lupus');\n newRow.setString('name', 'Wolf');\n\n print(table.getArray());\n}\n
\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 print(table.get(0, 1));\n //Capra hircus\n print(table.get(0, 'species'));\n //Capra hircus\n}\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.get(0, 1));\n //Capra hircus\n print(table.get(0, 'species'));\n //Capra hircus\n}\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\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 print(table.getNum(1, 0) + 100);\n //id 1 + 100 = 101\n}\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.getNum(1, 0) + 100);\n //id 1 + 100 = 101\n}\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n // table is comma separated value \"CSV\"\n // and has specifiying header for column labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.getString(0, 0)); // 0\n print(table.getString(0, 1)); // Capra hircus\n print(table.getString(0, 2)); // Goat\n print(table.getString(1, 0)); // 1\n print(table.getString(1, 1)); // Panthera pardus\n print(table.getString(1, 2)); // Leopard\n print(table.getString(2, 0)); // 2\n print(table.getString(2, 1)); // Equus zebra\n print(table.getString(2, 2)); // Zebra\n}\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n // table is comma separated value \"CSV\"\n // and has specifiying header for column labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.getString(0, 0)); // 0\n print(table.getString(0, 1)); // Capra hircus\n print(table.getString(0, 2)); // Goat\n print(table.getString(1, 0)); // 1\n print(table.getString(1, 1)); // Panthera pardus\n print(table.getString(1, 2)); // Leopard\n print(table.getString(2, 0)); // 2\n print(table.getString(2, 1)); // Equus zebra\n print(table.getString(2, 2)); // Zebra\n}\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\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 print(tableObject);\n //outputs an object\n}\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n let tableObject = table.getObject();\n\n print(tableObject);\n //outputs an object\n}\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leoperd\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n // table is comma separated value \"CSV\"\n // and has specifiying header for column labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n var tableArray = table.getArray();\n for (var i = 0; i < tableArray.length; i++) {\n print(tableArray[i]);\n }\n}\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leoperd\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n // table is comma separated value \"CSV\"\n // and has specifiying header for column labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n let tableArray = table.getArray();\n for (let i = 0; i < tableArray.length; i++) {\n print(tableArray[i]);\n }\n}\n
\n\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n 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 for (var r = 0; r < rows.length; r++) {\n rows[r].set('name', 'Unicorn');\n }\n\n //print the results\n print(table.getArray());\n }\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n rows[r].set('name', 'Unicorn');\n }\n\n //print the results\n print(table.getArray());\n }\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n 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 for (var r = 0; r < rows.length; r++) {\n rows[r].setNum('id', r + 10);\n }\n\n print(table.getArray());\n }\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n rows[r].setNum('id', r + 10);\n }\n\n print(table.getArray());\n }\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n 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 for (var r = 0; r < rows.length; r++) {\n var name = rows[r].getString('name');\n rows[r].setString('name', 'A ' + name + ' named George');\n }\n\n print(table.getArray());\n }\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n let name = rows[r].getString('name');\n rows[r].setString('name', 'A ' + name + ' named George');\n }\n\n print(table.getArray());\n }\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n 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 names = [];\n var rows = table.getRows();\n for (var r = 0; r < rows.length; r++) {\n names.push(rows[r].get('name'));\n }\n\n print(names);\n }\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let names = [];\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n names.push(rows[r].get('name'));\n }\n\n print(names);\n }\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n 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 var minId = Infinity;\n var maxId = -Infinity;\n for (var r = 0; r < rows.length; r++) {\n var id = rows[r].getNum('id');\n minId = min(minId, id);\n maxId = min(maxId, id);\n }\n print('minimum id = ' + minId + ', maximum id = ' + maxId);\n }\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n let minId = Infinity;\n let maxId = -Infinity;\n for (let r = 0; r < rows.length; r++) {\n let id = rows[r].getNum('id');\n minId = min(minId, id);\n maxId = min(maxId, id);\n }\n print('minimum id = ' + minId + ', maximum id = ' + maxId);\n }\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n 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 var longest = '';\n for (var r = 0; r < rows.length; r++) {\n var species = rows[r].getString('species');\n if (longest.length < species.length) {\n longest = species;\n }\n }\n\n print('longest: ' + longest);\n }\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n let longest = '';\n for (let r = 0; r < rows.length; r++) {\n let species = rows[r].getString('species');\n if (longest.length < species.length) {\n longest = species;\n }\n }\n\n print('longest: ' + longest);\n }\n
Gets a copy of the element's parent. Returns the parent as another\np5.XML object.
\n", "itemtype": "method", "name": "getParent", @@ -12401,7 +12645,7 @@ module.exports={ "type": "p5.XML" }, "example": [ - "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\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 print(parent.getName());\n}\n\n// Sketch prints:\n// mammals\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let children = xml.getChildren('animal');\n let parent = children[1].getParent();\n print(parent.getName());\n}\n\n// Sketch prints:\n// mammals\n
Gets the element's full name, which is returned as a String.
\n", "itemtype": "method", "name": "getName", @@ -12418,7 +12662,7 @@ module.exports={ "type": "String" }, "example": [ - "<animal\n\n // The following short XML file called \"mammals.xml\" is parsed\n // in the code below.\n //\n // \n // <mammals>\n // <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n // <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n // <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n // </mammals>\n\n var xml;\n\n function preload() {\n xml = loadXML('assets/mammals.xml');\n }\n\n function setup() {\n print(xml.getName());\n }\n\n // Sketch prints:\n // mammals\n
\n // The following short XML file called \"mammals.xml\" is parsed\n // in the code below.\n //\n // \n // <mammals>\n // <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n // <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n // <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n // </mammals>\n\n let xml;\n\n function preload() {\n xml = loadXML('assets/mammals.xml');\n }\n\n function setup() {\n print(xml.getName());\n }\n\n // Sketch prints:\n // mammals\n
Sets the element's name, which is specified as a String.
\n", "itemtype": "method", "name": "setName", @@ -12438,7 +12682,7 @@ module.exports={ } ], "example": [ - "<animal\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.getName());\n xml.setName('fish');\n print(xml.getName());\n}\n\n// Sketch prints:\n// mammals\n// fish\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.getName());\n xml.setName('fish');\n print(xml.getName());\n}\n\n// Sketch prints:\n// mammals\n// fish\n
Checks whether or not the element has any children, and returns the result\nas a boolean.
\n", "itemtype": "method", "name": "hasChildren", @@ -12455,7 +12699,7 @@ module.exports={ "type": "Boolean" }, "example": [ - "<animal\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.hasChildren());\n}\n\n// Sketch prints:\n// true\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.hasChildren());\n}\n\n// Sketch prints:\n// true\n
Get the names of all of the element's children, and returns the names as an\narray of Strings. This is the same as looping through and calling getName()\non each child element individually.
\n", "itemtype": "method", "name": "listChildren", @@ -12472,7 +12716,7 @@ module.exports={ "type": "String[]" }, "example": [ - "<animal\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.listChildren());\n}\n\n// Sketch prints:\n// [\"animal\", \"animal\", \"animal\"]\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.listChildren());\n}\n\n// Sketch prints:\n// [\"animal\", \"animal\", \"animal\"]\n
Returns all of the element's children as an array of p5.XML objects. When\nthe name parameter is specified, then it will return all children that match\nthat name.
\n", "itemtype": "method", "name": "getChildren", @@ -12497,7 +12741,7 @@ module.exports={ "type": "p5.XML[]" }, "example": [ - "<animal\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\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 print(animals[i].getContent());\n }\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Leopard\"\n// \"Zebra\"\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let animals = xml.getChildren('animal');\n\n for (let i = 0; i < animals.length; i++) {\n print(animals[i].getContent());\n }\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Leopard\"\n// \"Zebra\"\n
Returns the first of the element's children that matches the name parameter\nor the child of the given index.It returns undefined if no matching\nchild is found.
\n", "itemtype": "method", "name": "getChild", @@ -12521,7 +12765,7 @@ module.exports={ "type": "p5.XML" }, "example": [ - "<animal\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(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 print(secondChild.getContent());\n}\n\n// Sketch prints:\n// \"Leopard\"\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n
\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let secondChild = xml.getChild(1);\n print(secondChild.getContent());\n}\n\n// Sketch prints:\n// \"Leopard\"\n
Appends a new child to the element. The child can be specified with\neither a String, which will be used as the new tag's name, or as a\nreference to an existing p5.XML object.\nA reference to the newly created child is returned as an p5.XML object.
\n", "itemtype": "method", "name": "addChild", @@ -12541,7 +12785,7 @@ module.exports={ } ], "example": [ - "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var child = new p5.XML();\n child.setAttribute('id', '3');\n child.setAttribute('species', 'Ornithorhynchus anatinus');\n child.setContent('Platypus');\n xml.addChild(child);\n\n var animals = xml.getChildren('animal');\n print(animals[animals.length - 1].getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Leopard\"\n// \"Zebra\"\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let child = new p5.XML();\n child.setName('animal');\n child.setAttribute('id', '3');\n child.setAttribute('species', 'Ornithorhynchus anatinus');\n child.setContent('Platypus');\n xml.addChild(child);\n\n let animals = xml.getChildren('animal');\n print(animals[animals.length - 1].getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Leopard\"\n// \"Zebra\"\n
Removes the element specified by name or index.
\n", "itemtype": "method", "name": "removeChild", @@ -12561,7 +12805,7 @@ module.exports={ } ], "example": [ - "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\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 < children.length; i++) {\n print(children[i].getContent());\n }\n}\n\n// Sketch prints:\n// \"Leopard\"\n// \"Zebra\"\n
\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 < children.length; i++) {\n print(children[i].getContent());\n }\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Zebra\"\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n xml.removeChild('animal');\n let children = xml.getChildren();\n for (let i = 0; i < children.length; i++) {\n print(children[i].getContent());\n }\n}\n\n// Sketch prints:\n// \"Leopard\"\n// \"Zebra\"\n
\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n xml.removeChild(1);\n let children = xml.getChildren();\n for (let i = 0; i < children.length; i++) {\n print(children[i].getContent());\n }\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Zebra\"\n
Counts the specified element's number of attributes, returned as an Number.
\n", "itemtype": "method", "name": "getAttributeCount", @@ -12578,7 +12822,7 @@ module.exports={ "type": "Integer" }, "example": [ - "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getAttributeCount());\n}\n\n// Sketch prints:\n// 2\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.getAttributeCount());\n}\n\n// Sketch prints:\n// 2\n
Gets all of the specified element's attributes, and returns them as an\narray of Strings.
\n", "itemtype": "method", "name": "listAttributes", @@ -12595,7 +12839,7 @@ module.exports={ "type": "String[]" }, "example": [ - "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.listAttributes());\n}\n\n// Sketch prints:\n// [\"id\", \"species\"]\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.listAttributes());\n}\n\n// Sketch prints:\n// [\"id\", \"species\"]\n
Checks whether or not an element has the specified attribute.
\n", "itemtype": "method", "name": "hasAttribute", @@ -12619,7 +12863,7 @@ module.exports={ "type": "Boolean" }, "example": [ - "\n\n // The following short XML file called \"mammals.xml\" is parsed\n // in the code below.\n //\n // \n // <mammals>\n // <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n // <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n // <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n // </mammals>\n\n var xml;\n\n function preload() {\n xml = loadXML('assets/mammals.xml');\n }\n\n function setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.hasAttribute('species'));\n print(firstChild.hasAttribute('color'));\n }\n\n // Sketch prints:\n // true\n // false\n
\n // The following short XML file called \"mammals.xml\" is parsed\n // in the code below.\n //\n // \n // <mammals>\n // <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n // <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n // <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n // </mammals>\n\n let xml;\n\n function preload() {\n xml = loadXML('assets/mammals.xml');\n }\n\n function setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.hasAttribute('species'));\n print(firstChild.hasAttribute('color'));\n }\n\n // Sketch prints:\n // true\n // false\n
Returns an attribute value of the element as an Number. If the defaultValue\nparameter is specified and the attribute doesn't exist, then defaultValue\nis returned. If no defaultValue is specified and the attribute doesn't\nexist, the value 0 is returned.
\n", "itemtype": "method", "name": "getNum", @@ -12649,7 +12893,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getNum('id'));\n}\n\n// Sketch prints:\n// 0\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.getNum('id'));\n}\n\n// Sketch prints:\n// 0\n
Returns an attribute value of the element as an String. If the defaultValue\nparameter is specified and the attribute doesn't exist, then defaultValue\nis returned. If no defaultValue is specified and the attribute doesn't\nexist, null is returned.
\n", "itemtype": "method", "name": "getString", @@ -12679,7 +12923,7 @@ module.exports={ "type": "String" }, "example": [ - "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getString('species'));\n}\n\n// Sketch prints:\n// \"Capra hircus\"\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.getString('species'));\n}\n\n// Sketch prints:\n// \"Capra hircus\"\n
Sets the content of an element's attribute. The first parameter specifies\nthe attribute name, while the second specifies the new content.
\n", "itemtype": "method", "name": "setAttribute", @@ -12704,7 +12948,7 @@ module.exports={ } ], "example": [ - "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getString('species'));\n firstChild.setAttribute('species', 'Jamides zebra');\n print(firstChild.getString('species'));\n}\n\n// Sketch prints:\n// \"Capra hircus\"\n// \"Jamides zebra\"\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.getString('species'));\n firstChild.setAttribute('species', 'Jamides zebra');\n print(firstChild.getString('species'));\n}\n\n// Sketch prints:\n// \"Capra hircus\"\n// \"Jamides zebra\"\n
Returns the content of an element. If there is no such content,\ndefaultValue is returned if specified, otherwise null is returned.
\n", "itemtype": "method", "name": "getContent", @@ -12729,7 +12973,7 @@ module.exports={ "type": "String" }, "example": [ - "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n
Sets the element's content.
\n", "itemtype": "method", "name": "setContent", @@ -12749,7 +12993,7 @@ module.exports={ } ], "example": [ - "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getContent());\n firstChild.setContent('Mountain Goat');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Mountain Goat\"\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.getContent());\n firstChild.setContent('Mountain Goat');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Mountain Goat\"\n
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.
\n", - "class": "p5.XML", - "module": "IO", - "submodule": "XML" - }, - { - "file": "src/io/p5.XML.js", - "line": 818, - "description": "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.
\n", + "line": 839, + "description": "Serializes the element into a string. This function is useful for preparing\nthe content to be sent over a http request or saved to file.
\n", + "itemtype": "method", + "name": "serialize", + "return": { + "description": "Serialized string of the element", + "type": "String" + }, + "example": [ + "\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.serialize());\n}\n\n// Sketch prints:\n// \n// Goat \n// Leopard \n// Zebra \n// \n
\nfunction setup() {\n var x = -3;\n var y = abs(x);\n\n print(x); // -3\n print(y); // 3\n}\n
\nfunction setup() {\n let x = -3;\n let y = abs(x);\n\n print(x); // -3\n print(y); // 3\n}\n
\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), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n}\n
\nfunction draw() {\n background(200);\n // map, mouseX between 0 and 5.\n let ax = map(mouseX, 0, 100, 0, 5);\n let ay = 66;\n\n //Get the ceiling of the mapped number.\n let bx = ceil(map(mouseX, 0, 100, 0, 5));\n let by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n}\n
\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
\nfunction draw() {\n background(200);\n\n let leftWall = 25;\n let rightWall = 75;\n\n // xm is just the mouseX, while\n // xc is the mouseX, but constrained\n // between the leftWall and rightWall!\n let xm = mouseX;\n let xc = constrain(mouseX, leftWall, rightWall);\n\n // Draw the walls.\n stroke(150);\n line(leftWall, 0, leftWall, height);\n line(rightWall, 0, rightWall, height);\n\n // Draw xm and xc as circles.\n noStroke();\n fill(150);\n ellipse(xm, 33, 9, 9); // Not Constrained\n fill(0);\n ellipse(xc, 66, 9, 9); // Constrained\n}\n
\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), 0, -5);\n pop();\n // Fancy!\n}\n
\n// Move your mouse inside the canvas to see the\n// change in distance between two points!\nfunction draw() {\n background(200);\n fill(0);\n\n let x1 = 10;\n let y1 = 90;\n let x2 = mouseX;\n let y2 = mouseY;\n\n line(x1, y1, x2, y2);\n ellipse(x1, y1, 7, 7);\n ellipse(x2, y2, 7, 7);\n\n // d is the length of the line\n // the distance from point 1 to point 2.\n let d = 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), 0, -5);\n pop();\n // Fancy!\n}\n
\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
\nfunction draw() {\n background(200);\n\n // Compute the exp() function with a value between 0 and 2\n let xValue = map(mouseX, 0, width, 0, 2);\n let yValue = exp(xValue);\n\n let y = map(yValue, 0, 8, height, 0);\n\n let legend = 'exp (' + nfc(xValue, 3) + ')\\n= ' + nf(yValue, 1, 4);\n stroke(150);\n line(mouseX, y, mouseX, height);\n fill(0);\n text(legend, 5, 15);\n noStroke();\n ellipse(mouseX, y, 7, 7);\n\n // Draw the exp(x) curve,\n // over the domain of x from 0 to 2\n noFill();\n stroke(0);\n beginShape();\n for (let x = 0; x < width; x++) {\n xValue = map(x, 0, width, 0, 2);\n yValue = exp(xValue);\n y = map(yValue, 0, 8, height, 0);\n vertex(x, y);\n }\n\n endShape();\n line(0, 0, 0, height);\n line(0, height - 1, width, height - 1);\n}\n
\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), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n}\n
\nfunction draw() {\n background(200);\n //map, mouseX between 0 and 5.\n let ax = map(mouseX, 0, 100, 0, 5);\n let ay = 66;\n\n //Get the floor of the mapped number.\n let bx = floor(map(mouseX, 0, 100, 0, 5));\n let by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n}\n
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.
\n", + "description": "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, and 1.0 is equal to the second point. If the\nvalue of amt is more than 1.0 or less than 0.0, the number will be\ncalculated accordingly in the ratio of the two given numbers. The lerp\nfunction is convenient for creating motion along a straight\npath and for drawing dotted lines.
\n", "itemtype": "method", "name": "lerp", "params": [ @@ -13013,7 +13258,7 @@ module.exports={ }, { "name": "amt", - "description": "number between 0.0 and 1.0
\n", + "description": "number
\n", "type": "Number" } ], @@ -13022,7 +13267,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\nfunction setup() {\n background(200);\n var a = 20;\n var b = 80;\n var c = lerp(a, b, 0.2);\n var d = lerp(a, b, 0.5);\n var e = lerp(a, b, 0.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
\nfunction setup() {\n background(200);\n let a = 20;\n let b = 80;\n let c = lerp(a, b, 0.2);\n let d = lerp(a, b, 0.5);\n let e = lerp(a, b, 0.8);\n\n let y = 50;\n\n strokeWeight(5);\n stroke(0); // Draw the original points in black\n point(a, y);\n point(b, y);\n\n stroke(100); // Draw the lerp points in gray\n point(c, y);\n point(d, y);\n point(e, y);\n}\n
Calculates the natural logarithm (the base-e logarithm) of a number. This\nfunction expects the n parameter to be a value greater than 0.0. Maps to\nMath.log().
\n", "itemtype": "method", "name": "log", @@ -13047,7 +13292,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\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) {\n // 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
\nfunction draw() {\n background(200);\n let maxX = 2.8;\n let maxY = 1.5;\n\n // Compute the natural log of a value between 0 and maxX\n let xValue = map(mouseX, 0, width, 0, maxX);\n let yValue, y;\n if (xValue > 0) {\n // Cannot take the log of a negative number.\n yValue = log(xValue);\n y = map(yValue, -maxY, maxY, height, 0);\n\n // Display the calculation occurring.\n let legend = 'log(' + nf(xValue, 1, 2) + ')\\n= ' + nf(yValue, 1, 3);\n stroke(150);\n line(mouseX, y, mouseX, height);\n fill(0);\n text(legend, 5, 15);\n noStroke();\n ellipse(mouseX, y, 7, 7);\n }\n\n // Draw the log(x) curve,\n // over the domain of x from 0 to maxX\n noFill();\n stroke(0);\n beginShape();\n for (let x = 0; x < width; x++) {\n xValue = map(x, 0, width, 0, maxX);\n yValue = log(xValue);\n y = map(yValue, -maxY, maxY, height, 0);\n vertex(x, y);\n }\n endShape();\n line(0, 0, 0, height);\n line(0, height / 2, width, height / 2);\n}\n
Calculates the magnitude (or length) of a vector. A vector is a direction\nin space commonly used in computer graphics and linear algebra. Because it\nhas no "start" position, the magnitude of a vector can be thought of as\nthe distance from the coordinate 0,0 to its x,y value. Therefore, mag() is\na shortcut for writing dist(0, 0, x, y).
\n", "itemtype": "method", "name": "mag", @@ -13077,7 +13322,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\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 print(mag(x1, y1)); // Prints \"36.05551275463989\"\n line(0, 0, x2, y1);\n print(mag(x2, y1)); // Prints \"85.44003745317531\"\n line(0, 0, x1, y2);\n print(mag(x1, y2)); // Prints \"72.80109889280519\"\n line(0, 0, x2, y2);\n print(mag(x2, y2)); // Prints \"106.3014581273465\"\n}\n
\nfunction setup() {\n let x1 = 20;\n let x2 = 80;\n let y1 = 30;\n let y2 = 70;\n\n line(0, 0, x1, y1);\n print(mag(x1, y1)); // Prints \"36.05551275463989\"\n line(0, 0, x2, y1);\n print(mag(x2, y1)); // Prints \"85.44003745317531\"\n line(0, 0, x1, y2);\n print(mag(x1, y2)); // Prints \"72.80109889280519\"\n line(0, 0, x2, y2);\n print(mag(x2, y2)); // Prints \"106.3014581273465\"\n}\n
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).
\nvar value = 25;\nvar m = map(value, 0, 100, 0, width);\nellipse(m, 50, 10, 10);\n
\nfunction setup() {\n noStroke();\n}\n\nfunction draw() {\n background(204);\n var x1 = map(mouseX, 0, width, 25, 75);\n ellipse(x1, 25, 25, 25);\n //This ellipse is constrained to the 0-100 range\n //after setting withinBounds to true\n var x2 = map(mouseX, 0, width, 0, 100, true);\n ellipse(x2, 75, 25, 25);\n}\n
\nlet value = 25;\nlet m = map(value, 0, 100, 0, width);\nellipse(m, 50, 10, 10);\n
\nfunction setup() {\n noStroke();\n}\n\nfunction draw() {\n background(204);\n let x1 = map(mouseX, 0, width, 25, 75);\n ellipse(x1, 25, 25, 25);\n //This ellipse is constrained to the 0-100 range\n //after setting withinBounds to true\n let x2 = map(mouseX, 0, width, 0, 100, true);\n ellipse(x2, 75, 25, 25);\n}\n
Determines the largest value in a sequence of numbers, and then returns\nthat value. max() accepts any number of Number parameters, or an Array\nof any length.
\n", "itemtype": "method", "name": "max", @@ -13146,7 +13391,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\nfunction setup() {\n // Change the elements in the array and run the sketch\n // to show how max() works!\n var numArray = [2, 1, 5, 4, 8, 9];\n fill(0);\n noStroke();\n text('Array Elements', 0, 10);\n // Draw all numbers in the array\n 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 var maxX = 33;\n var maxY = 80;\n // Draw the Maximum value in the array.\n textSize(32);\n text(max(numArray), maxX, maxY);\n}\n
\nfunction setup() {\n // Change the elements in the array and run the sketch\n // to show how max() works!\n let numArray = [2, 1, 5, 4, 8, 9];\n fill(0);\n noStroke();\n text('Array Elements', 0, 10);\n // Draw all numbers in the array\n let spacing = 15;\n let elemsY = 25;\n for (let i = 0; i < numArray.length; i++) {\n text(numArray[i], i * spacing, elemsY);\n }\n let maxX = 33;\n let maxY = 80;\n // Draw the Maximum value in the array.\n textSize(32);\n text(max(numArray), maxX, maxY);\n}\n
Determines the smallest value in a sequence of numbers, and then returns\nthat value. min() accepts any number of Number parameters, or an Array\nof any length.
\n", "itemtype": "method", "name": "min", @@ -13199,7 +13444,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\nfunction setup() {\n // Change the elements in the array and run the sketch\n // to show how min() works!\n var numArray = [2, 1, 5, 4, 8, 9];\n fill(0);\n noStroke();\n text('Array Elements', 0, 10);\n // Draw all numbers in the array\n 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 var maxX = 33;\n var maxY = 80;\n // Draw the Minimum value in the array.\n textSize(32);\n text(min(numArray), maxX, maxY);\n}\n
\nfunction setup() {\n // Change the elements in the array and run the sketch\n // to show how min() works!\n let numArray = [2, 1, 5, 4, 8, 9];\n fill(0);\n noStroke();\n text('Array Elements', 0, 10);\n // Draw all numbers in the array\n let spacing = 15;\n let elemsY = 25;\n for (let i = 0; i < numArray.length; i++) {\n text(numArray[i], i * spacing, elemsY);\n }\n let maxX = 33;\n let maxY = 80;\n // Draw the Minimum value in the array.\n textSize(32);\n text(min(numArray), maxX, maxY);\n}\n
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.)
\n", + "line": 578, + "description": "Normalizes a number from another range into a value between 0 and 1.\nIdentical to map(value, low, high, 0, 1).\nNumbers outside of the range are not clamped to 0 and 1, because\nout-of-range values are often intentional and useful. (See the example above.)
\n", "itemtype": "method", "name": "norm", "params": [ @@ -13269,7 +13514,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\nfunction draw() {\n background(200);\n var currentNum = mouseX;\n var lowerBound = 0;\n var upperBound = width; //100;\n var normalized = norm(currentNum, lowerBound, upperBound);\n var 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 var 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 var normalY = 40;\n var normalX = 20;\n text(normalized, normalX, normalY);\n}\n
\nfunction draw() {\n background(200);\n let currentNum = mouseX;\n let lowerBound = 0;\n let upperBound = width; //100;\n let normalized = norm(currentNum, lowerBound, upperBound);\n let lineY = 70;\n stroke(3);\n line(0, lineY, width, lineY);\n //Draw an ellipse mapped to the non-normalized value.\n noStroke();\n fill(50);\n let s = 7; // ellipse size\n ellipse(currentNum, lineY, s, s);\n\n // Draw the guide\n let guideY = lineY + 15;\n text('0', 0, guideY);\n textAlign(RIGHT);\n text('100', width, guideY);\n\n // Draw the normalized value\n textAlign(LEFT);\n fill(0);\n textSize(32);\n let normalY = 40;\n let normalX = 20;\n text(normalized, normalX, normalY);\n}\n
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().
\n", "itemtype": "method", "name": "pow", @@ -13299,7 +13544,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\nfunction setup() {\n //Exponentially increase the size of an ellipse.\n var eSize = 3; // Original Size\n var 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
\nfunction setup() {\n //Exponentially increase the size of an ellipse.\n let eSize = 3; // Original Size\n let eLoc = 10; // Original Location\n\n ellipse(eLoc, eLoc, eSize, eSize);\n\n ellipse(eLoc * 2, eLoc * 2, pow(eSize, 2), pow(eSize, 2));\n\n ellipse(eLoc * 4, eLoc * 4, pow(eSize, 3), pow(eSize, 3));\n\n ellipse(eLoc * 8, eLoc * 8, pow(eSize, 4), pow(eSize, 4));\n}\n
Calculates the integer closest to the n parameter. For example,\nround(133.8) returns the value 134. Maps to Math.round().
\n", "itemtype": "method", "name": "round", @@ -13324,7 +13569,7 @@ module.exports={ "type": "Integer" }, "example": [ - "\n\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), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n}\n
\nfunction draw() {\n background(200);\n //map, mouseX between 0 and 5.\n let ax = map(mouseX, 0, 100, 0, 5);\n let ay = 66;\n\n // Round the mapped number.\n let bx = round(map(mouseX, 0, 100, 0, 5));\n let by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n}\n
Squares a number (multiplies a number by itself). The result is always a\npositive number, as multiplying two negative numbers always yields a\npositive result. For example, -1 * -1 = 1.
\n", "itemtype": "method", "name": "sq", @@ -13349,7 +13594,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\nfunction draw() {\n background(200);\n var eSize = 7;\n var x1 = map(mouseX, 0, width, 0, 10);\n var y1 = 80;\n var x2 = sq(x1);\n var 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
\nfunction draw() {\n background(200);\n let eSize = 7;\n let x1 = map(mouseX, 0, width, 0, 10);\n let y1 = 80;\n let x2 = sq(x1);\n let y2 = 20;\n\n // Draw the non-squared.\n line(0, y1, width, y1);\n ellipse(x1, y1, eSize, eSize);\n\n // Draw the squared.\n line(0, y2, width, y2);\n ellipse(x2, y2, eSize, eSize);\n\n // Draw dividing line.\n stroke(100);\n line(0, height / 2, width, height / 2);\n\n // Draw text.\n let spacing = 15;\n noStroke();\n fill(0);\n text('x = ' + x1, 0, y1 + spacing);\n text('sq(x) = ' + x2, 0, y2 + spacing);\n}\n
Calculates the square root of a number. The square root of a number is\nalways positive, even though there may be a valid negative root. The\nsquare root s of number a is such that s*s = a. It is the opposite of\nsquaring. Maps to Math.sqrt().
\n", "itemtype": "method", "name": "sqrt", @@ -13374,7 +13619,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\nfunction draw() {\n background(200);\n var eSize = 7;\n var x1 = mouseX;\n var y1 = 80;\n var x2 = sqrt(x1);\n var 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
\nfunction draw() {\n background(200);\n let eSize = 7;\n let x1 = mouseX;\n let y1 = 80;\n let x2 = sqrt(x1);\n let y2 = 20;\n\n // Draw the non-squared.\n line(0, y1, width, y1);\n ellipse(x1, y1, eSize, eSize);\n\n // Draw the squared.\n line(0, y2, width, y2);\n ellipse(x2, y2, eSize, eSize);\n\n // Draw dividing line.\n stroke(100);\n line(0, height / 2, width, height / 2);\n\n // Draw text.\n noStroke();\n fill(0);\n let spacing = 15;\n text('x = ' + x1, 0, y1 + spacing);\n text('sqrt(x) = ' + x2, 0, y2 + spacing);\n}\n
\nvar xoff = 0.0;\n\nfunction draw() {\n background(204);\n xoff = xoff + 0.01;\n var n = noise(xoff) * width;\n line(n, 0, n, height);\n}\n
\nvar 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
\n\nlet xoff = 0.0;\n\nfunction draw() {\n background(204);\n xoff = xoff + 0.01;\n let n = noise(xoff) * width;\n line(n, 0, n, height);\n}\n
\nlet noiseScale=0.02;\n\nfunction draw() {\n background(0);\n for (let x=0; x < width; x++) {\n let noiseVal = noise((mouseX+x)*noiseScale, mouseY*noiseScale);\n stroke(noiseVal*255);\n line(x, mouseY+noiseVal*80, x, height);\n }\n}\n
\n\n var 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, (mouseY + y) * noiseScale);\n stroke(noiseVal * 255);\n point(x, y);\n noiseDetail(8, 0.65);\n noiseVal = noise(\n (mouseX + x + width / 2) * noiseScale,\n (mouseY + y) * noiseScale\n );\n stroke(noiseVal * 255);\n point(x + width / 2, y);\n }\n }\n }\n
\n \n let noiseVal;\n let noiseScale = 0.02;\nfunction setup() {\n createCanvas(100, 100);\n }\nfunction draw() {\n background(0);\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width / 2; x++) {\n noiseDetail(2, 0.2);\n noiseVal = noise((mouseX + x) * noiseScale, (mouseY + y) * noiseScale);\n stroke(noiseVal * 255);\n point(x, y);\n noiseDetail(8, 0.65);\n noiseVal = noise(\n (mouseX + x + width / 2) * noiseScale,\n (mouseY + y) * noiseScale\n );\n stroke(noiseVal * 255);\n point(x + width / 2, y);\n }\n }\n }\n
\n 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
\nlet xoff = 0.0;\n\nfunction setup() {\n noiseSeed(99);\n stroke(0, 10);\n}\n\nfunction draw() {\n xoff = xoff + .01;\n let n = noise(xoff) * width;\n line(n, 0, n, height);\n}\n
\n\nfunction setup() {\n var v = createVector(20, 30);\n print(String(v)); // prints \"p5.Vector Object : [20, 30, 0]\"\n}\n
\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'black');\n\n noStroke();\n text(v1.toString(), 10, 25, 90, 75);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nfunction setup() {\n let v = createVector(20, 30);\n print(String(v)); // prints \"p5.Vector Object : [20, 30, 0]\"\n}\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'black');\n\n noStroke();\n text(v1.toString(), 10, 25, 90, 75);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\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
\n\nvar v0, v1;\nfunction setup() {\n createCanvas(100, 100);\n\n v0 = createVector(0, 0);\n v1 = createVector(50, 50);\n}\n\nfunction draw() {\n background(240);\n\n drawArrow(v0, v1, 'black');\n v1.set(v1.x + random(-1, 1), v1.y + random(-1, 1));\n\n noStroke();\n text('x: ' + round(v1.x) + ' y: ' + round(v1.y), 20, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nfunction setup() {\n let v = createVector(1, 2, 3);\n v.set(4, 5, 6); // Sets vector to [4, 5, 6]\n\n let v1 = createVector(0, 0, 0);\n let arr = [1, 2, 3];\n v1.set(arr); // Sets vector to [1, 2, 3]\n}\n
\n\nlet v0, v1;\nfunction setup() {\n createCanvas(100, 100);\n\n v0 = createVector(0, 0);\n v1 = createVector(50, 50);\n}\n\nfunction draw() {\n background(240);\n\n drawArrow(v0, v1, 'black');\n v1.set(v1.x + random(-1, 1), v1.y + random(-1, 1));\n\n noStroke();\n text('x: ' + round(v1.x) + ' y: ' + round(v1.y), 20, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nvar v1 = createVector(1, 2, 3);\nvar v2 = v1.copy();\nprint(v1.x === v2.x && v1.y === v2.y && v1.z === v2.z);\n// Prints \"true\"\n
\n\nlet v1 = createVector(1, 2, 3);\nlet v2 = v1.copy();\nprint(v1.x === v2.x && v1.y === v2.y && v1.z === v2.z);\n// Prints \"true\"\n
\n\nvar v = createVector(1, 2, 3);\nv.add(4, 5, 6);\n// v's components are set to [5, 7, 9]\n
\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]\nprint(v3);\n
\n\n// red vector + blue vector = purple vector\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'red');\n\n var v2 = createVector(-30, 20);\n drawArrow(v1, v2, 'blue');\n\n var v3 = p5.Vector.add(v1, v2);\n drawArrow(v0, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nlet v = createVector(1, 2, 3);\nv.add(4, 5, 6);\n// v's components are set to [5, 7, 9]\n
\n\n// Static method\nlet v1 = createVector(1, 2, 3);\nlet v2 = createVector(2, 3, 4);\n\nlet v3 = p5.Vector.add(v1, v2);\n// v3 has components [3, 5, 7]\nprint(v3);\n
\n\n// red vector + blue vector = purple vector\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'red');\n\n let v2 = createVector(-30, 20);\n drawArrow(v1, v2, 'blue');\n\n let v3 = p5.Vector.add(v1, v2);\n drawArrow(v0, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nvar v = createVector(4, 5, 6);\nv.sub(1, 1, 1);\n// v's components are set to [3, 4, 5]\n
\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 components [1, 1, 1]\nprint(v3);\n
\n\n// red vector - blue vector = purple vector\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(70, 50);\n drawArrow(v0, v1, 'red');\n\n var v2 = createVector(mouseX, mouseY);\n drawArrow(v0, v2, 'blue');\n\n var v3 = p5.Vector.sub(v1, v2);\n drawArrow(v2, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nlet v = createVector(4, 5, 6);\nv.sub(1, 1, 1);\n// v's components are set to [3, 4, 5]\n
\n\n// Static method\nlet v1 = createVector(2, 3, 4);\nlet v2 = createVector(1, 2, 3);\n\nlet v3 = p5.Vector.sub(v1, v2);\n// v3 has components [1, 1, 1]\nprint(v3);\n
\n\n// red vector - blue vector = purple vector\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(70, 50);\n drawArrow(v0, v1, 'red');\n\n let v2 = createVector(mouseX, mouseY);\n drawArrow(v0, v2, 'blue');\n\n let v3 = p5.Vector.sub(v1, v2);\n drawArrow(v2, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nvar v = createVector(1, 2, 3);\nv.mult(2);\n// v's components are set to [2, 4, 6]\n
\n\n// Static method\nvar v1 = createVector(1, 2, 3);\nvar v2 = p5.Vector.mult(v1, 2);\n// v2 has components [2, 4, 6]\nprint(v2);\n
\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = createVector(25, -25);\n drawArrow(v0, v1, 'red');\n\n var num = map(mouseX, 0, width, -2, 2, true);\n var v2 = p5.Vector.mult(v1, num);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('multiplied by ' + num.toFixed(2), 5, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nlet v = createVector(1, 2, 3);\nv.mult(2);\n// v's components are set to [2, 4, 6]\n
\n\n// Static method\nlet v1 = createVector(1, 2, 3);\nlet v2 = p5.Vector.mult(v1, 2);\n// v2 has components [2, 4, 6]\nprint(v2);\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = createVector(25, -25);\n drawArrow(v0, v1, 'red');\n\n let num = map(mouseX, 0, width, -2, 2, true);\n let v2 = p5.Vector.mult(v1, num);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('multiplied by ' + num.toFixed(2), 5, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nvar v = createVector(6, 4, 2);\nv.div(2); //v's components are set to [3, 2, 1]\n
\n\n// Static method\nvar v1 = createVector(6, 4, 2);\nvar v2 = p5.Vector.div(v1, 2);\n// v2 has components [3, 2, 1]\nprint(v2);\n
\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 100);\n var v1 = createVector(50, -50);\n drawArrow(v0, v1, 'red');\n\n var num = map(mouseX, 0, width, 10, 0.5, true);\n var v2 = p5.Vector.div(v1, num);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('divided by ' + num.toFixed(2), 10, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nlet v = createVector(6, 4, 2);\nv.div(2); //v's components are set to [3, 2, 1]\n
\n\n// Static method\nlet v1 = createVector(6, 4, 2);\nlet v2 = p5.Vector.div(v1, 2);\n// v2 has components [3, 2, 1]\nprint(v2);\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 100);\n let v1 = createVector(50, -50);\n drawArrow(v0, v1, 'red');\n\n let num = map(mouseX, 0, width, 10, 0.5, true);\n let v2 = p5.Vector.div(v1, num);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('divided by ' + num.toFixed(2), 10, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'black');\n\n noStroke();\n text('vector length: ' + v1.mag().toFixed(2), 10, 70, 90, 30);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nvar v = createVector(20.0, 30.0, 40.0);\nvar m = v.mag();\nprint(m); // Prints \"53.85164807134504\"\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'black');\n\n noStroke();\n text('vector length: ' + v1.mag().toFixed(2), 10, 70, 90, 30);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nlet v = createVector(20.0, 30.0, 40.0);\nlet m = v.mag();\nprint(m); // Prints \"53.85164807134504\"\n
\n\n// Static method\nvar v1 = createVector(6, 4, 2);\nprint(v1.magSq()); // Prints \"56\"\n
\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'black');\n\n noStroke();\n text('vector length squared: ' + v1.magSq().toFixed(2), 10, 45, 90, 55);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\n// Static method\nlet v1 = createVector(6, 4, 2);\nprint(v1.magSq()); // Prints \"56\"\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'black');\n\n noStroke();\n text('vector length squared: ' + v1.magSq().toFixed(2), 10, 45, 90, 55);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nvar v1 = createVector(1, 2, 3);\nvar v2 = createVector(2, 3, 4);\n\nprint(v1.dot(v2)); // Prints \"20\"\n
\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
\n\nlet v1 = createVector(1, 2, 3);\nlet v2 = createVector(2, 3, 4);\n\nprint(v1.dot(v2)); // Prints \"20\"\n
\n\n//Static method\nlet v1 = createVector(1, 2, 3);\nlet v2 = createVector(3, 2, 1);\nprint(p5.Vector.dot(v1, v2)); // Prints \"10\"\n
\n\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\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]\nprint(crossProduct);\n
\n\nlet v1 = createVector(1, 2, 3);\nlet v2 = createVector(1, 2, 3);\n\nv1.cross(v2); // v's components are [0, 0, 0]\n
\n\n// Static method\nlet v1 = createVector(1, 0, 0);\nlet v2 = createVector(0, 1, 0);\n\nlet crossProduct = p5.Vector.cross(v1, v2);\n// crossProduct has components [0, 0, 1]\nprint(crossProduct);\n
\n\nvar v1 = createVector(1, 0, 0);\nvar v2 = createVector(0, 1, 0);\n\nvar distance = v1.dist(v2); // distance is 1.4142...\nprint(distance);\n
\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...\nprint(distance);\n
\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n\n var v1 = createVector(70, 50);\n drawArrow(v0, v1, 'red');\n\n var v2 = createVector(mouseX, mouseY);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('distance between vectors: ' + v2.dist(v1).toFixed(2), 5, 50, 95, 50);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nlet v1 = createVector(1, 0, 0);\nlet v2 = createVector(0, 1, 0);\n\nlet distance = v1.dist(v2); // distance is 1.4142...\nprint(distance);\n
\n\n// Static method\nlet v1 = createVector(1, 0, 0);\nlet v2 = createVector(0, 1, 0);\n\nlet distance = p5.Vector.dist(v1, v2);\n// distance is 1.4142...\nprint(distance);\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n\n let v1 = createVector(70, 50);\n drawArrow(v0, v1, 'red');\n\n let v2 = createVector(mouseX, mouseY);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('distance between vectors: ' + v2.dist(v1).toFixed(2), 5, 50, 95, 50);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nvar v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.normalize();\n// v's components are set to\n// [0.4454354, 0.8908708, 0.089087084]\n
\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'red');\n v1.normalize();\n drawArrow(v0, v1.mult(35), 'blue');\n\n noFill();\n ellipse(50, 50, 35 * 2);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nlet v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.normalize();\n// v's components are set to\n// [0.4454354, 0.8908708, 0.089087084]\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'red');\n v1.normalize();\n drawArrow(v0, v1.mult(35), 'blue');\n\n noFill();\n ellipse(50, 50, 35 * 2);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nvar v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.limit(5);\n// v's components are set to\n// [2.2271771, 4.4543543, 0.4454354]\n
\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'red');\n drawArrow(v0, v1.limit(35), 'blue');\n\n noFill();\n ellipse(50, 50, 35 * 2);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nlet v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.limit(5);\n// v's components are set to\n// [2.2271771, 4.4543543, 0.4454354]\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'red');\n drawArrow(v0, v1.limit(35), 'blue');\n\n noFill();\n ellipse(50, 50, 35 * 2);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nvar v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.setMag(10);\n// v's components are set to [6.0, 8.0, 0.0]\n
\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(50, 50);\n\n drawArrow(v0, v1, 'red');\n\n var length = map(mouseX, 0, width, 0, 141, true);\n v1.setMag(length);\n drawArrow(v0, v1, 'blue');\n\n noStroke();\n text('magnitude set to: ' + length.toFixed(2), 10, 70, 90, 30);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nlet v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.setMag(10);\n// v's components are set to [6.0, 8.0, 0.0]\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(50, 50);\n\n drawArrow(v0, v1, 'red');\n\n let length = map(mouseX, 0, width, 0, 141, true);\n v1.setMag(length);\n drawArrow(v0, v1, 'blue');\n\n noStroke();\n text('magnitude set to: ' + length.toFixed(2), 10, 70, 90, 30);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nfunction setup() {\n var v1 = createVector(30, 50);\n print(v1.heading()); // 1.0303768265243125\n\n v1 = createVector(40, 50);\n print(v1.heading()); // 0.8960553845713439\n\n v1 = createVector(30, 70);\n print(v1.heading()); // 1.1659045405098132\n}\n
\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'black');\n\n var myHeading = v1.heading();\n noStroke();\n text(\n 'vector heading: ' +\n myHeading.toFixed(2) +\n ' radians or ' +\n degrees(myHeading).toFixed(2) +\n ' degrees',\n 10,\n 50,\n 90,\n 50\n );\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nfunction setup() {\n let v1 = createVector(30, 50);\n print(v1.heading()); // 1.0303768265243125\n\n v1 = createVector(40, 50);\n print(v1.heading()); // 0.8960553845713439\n\n v1 = createVector(30, 70);\n print(v1.heading()); // 1.1659045405098132\n}\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'black');\n\n let myHeading = v1.heading();\n noStroke();\n text(\n 'vector heading: ' +\n myHeading.toFixed(2) +\n ' radians or ' +\n degrees(myHeading).toFixed(2) +\n ' degrees',\n 10,\n 50,\n 90,\n 50\n );\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nvar v = createVector(10.0, 20.0);\n// v has components [10.0, 20.0, 0.0]\nv.rotate(HALF_PI);\n// v's components are set to [-20.0, 9.999999, 0.0]\n
\n\nvar angle = 0;\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = createVector(50, 0);\n\n drawArrow(v0, v1.rotate(angle), 'black');\n angle += 0.01;\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nlet v = createVector(10.0, 20.0);\n// v has components [10.0, 20.0, 0.0]\nv.rotate(HALF_PI);\n// v's components are set to [-20.0, 9.999999, 0.0]\n
\n\nlet angle = 0;\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = createVector(50, 0);\n\n drawArrow(v0, v1.rotate(angle), 'black');\n angle += 0.01;\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nvar v1 = createVector(1, 0, 0);\nvar v2 = createVector(0, 1, 0);\n\nvar angle = v1.angleBetween(v2);\n// angle is PI/2\nprint(angle);\n
\n\nfunction draw() {\n background(240);\n var v0 = createVector(50, 50);\n\n var v1 = createVector(50, 0);\n drawArrow(v0, v1, 'red');\n\n var v2 = createVector(mouseX - 50, mouseY - 50);\n drawArrow(v0, v2, 'blue');\n\n var angleBetween = v1.angleBetween(v2);\n noStroke();\n text(\n 'angle between: ' +\n angleBetween.toFixed(2) +\n ' radians or ' +\n degrees(angleBetween).toFixed(2) +\n ' degrees',\n 10,\n 50,\n 90,\n 50\n );\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nlet v1 = createVector(1, 0, 0);\nlet v2 = createVector(0, 1, 0);\n\nlet angle = v1.angleBetween(v2);\n// angle is PI/2\nprint(angle);\n
\n\nfunction draw() {\n background(240);\n let v0 = createVector(50, 50);\n\n let v1 = createVector(50, 0);\n drawArrow(v0, v1, 'red');\n\n let v2 = createVector(mouseX - 50, mouseY - 50);\n drawArrow(v0, v2, 'blue');\n\n let angleBetween = v1.angleBetween(v2);\n noStroke();\n text(\n 'angle between: ' +\n angleBetween.toFixed(2) +\n ' radians or ' +\n degrees(angleBetween).toFixed(2) +\n ' degrees',\n 10,\n 50,\n 90,\n 50\n );\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nvar v = createVector(1, 1, 0);\n\nv.lerp(3, 3, 0, 0.5); // v now has components [2,2,0]\n
\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]\nprint(v3);\n
\n\nvar step = 0.01;\nvar amount = 0;\n\nfunction draw() {\n background(240);\n var v0 = createVector(0, 0);\n\n var v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'red');\n\n var v2 = createVector(90, 90);\n drawArrow(v0, v2, 'blue');\n\n if (amount > 1 || amount < 0) {\n step *= -1;\n }\n amount += step;\n var v3 = p5.Vector.lerp(v1, v2, amount);\n\n drawArrow(v0, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nlet v = createVector(1, 1, 0);\n\nv.lerp(3, 3, 0, 0.5); // v now has components [2,2,0]\n
\n\nlet v1 = createVector(0, 0, 0);\nlet v2 = createVector(100, 100, 0);\n\nlet v3 = p5.Vector.lerp(v1, v2, 0.5);\n// v3 has components [50,50,0]\nprint(v3);\n
\n\nlet step = 0.01;\nlet amount = 0;\n\nfunction draw() {\n background(240);\n let v0 = createVector(0, 0);\n\n let v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'red');\n\n let v2 = createVector(90, 90);\n drawArrow(v0, v2, 'blue');\n\n if (amount > 1 || amount < 0) {\n step *= -1;\n }\n amount += step;\n let v3 = p5.Vector.lerp(v1, v2, amount);\n\n drawArrow(v0, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nfunction setup() {\n var v = createVector(20, 30);\n print(v.array()); // Prints : Array [20, 30, 0]\n}\n
\n\nvar v = createVector(10.0, 20.0, 30.0);\nvar f = v.array();\nprint(f[0]); // Prints \"10.0\"\nprint(f[1]); // Prints \"20.0\"\nprint(f[2]); // Prints \"30.0\"\n
\n\nfunction setup() {\n let v = createVector(20, 30);\n print(v.array()); // Prints : Array [20, 30, 0]\n}\n
\n\nlet v = createVector(10.0, 20.0, 30.0);\nlet f = v.array();\nprint(f[0]); // Prints \"10.0\"\nprint(f[1]); // Prints \"20.0\"\nprint(f[2]); // Prints \"30.0\"\n
\n\nvar v1 = createVector(5, 10, 20);\nvar v2 = createVector(5, 10, 20);\nvar v3 = createVector(13, 10, 19);\n\nprint(v1.equals(v2.x, v2.y, v2.z)); // true\nprint(v1.equals(v3.x, v3.y, v3.z)); // false\n
\n\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
\n\nlet v1 = createVector(5, 10, 20);\nlet v2 = createVector(5, 10, 20);\nlet v3 = createVector(13, 10, 19);\n\nprint(v1.equals(v2.x, v2.y, v2.z)); // true\nprint(v1.equals(v3.x, v3.y, v3.z)); // false\n
\n\nlet v1 = createVector(10.0, 20.0, 30.0);\nlet v2 = createVector(10.0, 20.0, 30.0);\nlet v3 = createVector(0.0, 0.0, 0.0);\nprint(v1.equals(v2)); // true\nprint(v1.equals(v3)); // false\n
\n\nfunction draw() {\n background(200);\n\n // Create a variable, proportional to the mouseX,\n // varying from 0-360, to represent an angle in degrees.\n 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) + '\\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), 30);\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, vx, vy);\n pop();\n}\n
\n\nfunction draw() {\n background(200);\n\n // Create a variable, proportional to the mouseX,\n // varying from 0-360, to represent an angle in degrees.\n angleMode(DEGREES);\n let myDegrees = map(mouseX, 0, width, 0, 360);\n\n // Display that variable in an onscreen text.\n // (Note the nfc() function to truncate additional decimal places,\n // and the \"\\xB0\" character for the degree symbol.)\n let readout = 'angle = ' + nfc(myDegrees, 1) + '\\xB0';\n noStroke();\n fill(0);\n text(readout, 5, 15);\n\n // Create a p5.Vector using the fromAngle function,\n // and extract its x and y components.\n let v = p5.Vector.fromAngle(radians(myDegrees), 30);\n let vx = v.x;\n let vy = v.y;\n\n push();\n translate(width / 2, height / 2);\n noFill();\n stroke(150);\n line(0, 0, 30, 0);\n stroke(0);\n line(0, 0, vx, vy);\n pop();\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n fill(255);\n noStroke();\n}\nfunction draw() {\n background(255);\n\n var t = millis() / 1000;\n\n // add three point lights\n pointLight(color('#f00'), p5.Vector.fromAngles(t * 1.0, t * 1.3, 100));\n pointLight(color('#0f0'), p5.Vector.fromAngles(t * 1.1, t * 1.2, 100));\n pointLight(color('#00f'), p5.Vector.fromAngles(t * 1.2, t * 1.1, 100));\n\n sphere(35);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n fill(255);\n noStroke();\n}\nfunction draw() {\n background(255);\n\n let t = millis() / 1000;\n\n // add three point lights\n pointLight(color('#f00'), p5.Vector.fromAngles(t * 1.0, t * 1.3, 100));\n pointLight(color('#0f0'), p5.Vector.fromAngles(t * 1.1, t * 1.2, 100));\n pointLight(color('#00f'), p5.Vector.fromAngles(t * 1.2, t * 1.1, 100));\n\n sphere(35);\n}\n
\n\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]\nprint(v);\n
\n\nfunction setup() {\n frameRate(1);\n}\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = p5.Vector.random2D();\n drawArrow(v0, v1.mult(50), 'black');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\nlet v = p5.Vector.random2D();\n// May make v's attributes something like:\n// [0.61554617, -0.51195765, 0.0] or\n// [-0.4695841, -0.14366731, 0.0] or\n// [0.6091097, -0.22805278, 0.0]\nprint(v);\n
\n\nfunction setup() {\n frameRate(1);\n}\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = p5.Vector.random2D();\n drawArrow(v0, v1.mult(50), 'black');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n
\n\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]\nprint(v);\n
\n\nlet v = p5.Vector.random3D();\n// May make v's attributes something like:\n// [0.61554617, -0.51195765, 0.599168] or\n// [-0.4695841, -0.14366731, -0.8711202] or\n// [0.6091097, -0.22805278, -0.7595902]\nprint(v);\n
\n\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
\n\nrandomSeed(99);\nfor (let i = 0; i < 100; i++) {\n let r = random(0, 255);\n stroke(r);\n line(i, 0, i, 100);\n}\n
\n\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
\n\nfor (var i = 0; i < 100; i++) {\n var r = random(-50, 50);\n line(50, i, 50 + r, i);\n}\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
\n\nfor (let i = 0; i < 100; i++) {\n let r = random(50);\n stroke(r * 5);\n line(50, i, 50 + r, i);\n}\n
\n\nfor (let i = 0; i < 100; i++) {\n let r = random(-50, 50);\n line(50, i, 50 + r, i);\n}\n
\n\n// Get a random element from an array using the random(Array) syntax\nlet words = ['apple', 'bear', 'cat', 'dog'];\nlet word = random(words); // select random word\ntext(word, 10, 50); // draw the word\n
\n\n for (var y = 0; y < 100; y++) {\n var x = randomGaussian(50, 15);\n line(50, y, x, y);\n }\n
\n \n var distribution = new Array(360);\nfunction setup() {\n createCanvas(100, 100);\n for (var i = 0; i < distribution.length; i++) {\n distribution[i] = floor(randomGaussian(0, 15));\n }\n }\nfunction draw() {\n background(204);\n translate(width / 2, width / 2);\n for (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
\n \n for (let y = 0; y < 100; y++) {\n let x = randomGaussian(50, 15);\n line(50, y, x, y);\n }\n
\n \n let distribution = new Array(360);\nfunction setup() {\n createCanvas(100, 100);\n for (let i = 0; i < distribution.length; i++) {\n distribution[i] = floor(randomGaussian(0, 15));\n }\n }\nfunction draw() {\n background(204);\n translate(width / 2, width / 2);\n for (let i = 0; i < distribution.length; i++) {\n rotate(TWO_PI / distribution.length);\n stroke(0);\n let dist = abs(distribution[i]);\n line(0, 0, dist, 0);\n }\n }\n
\n \nvar a = PI;\nvar c = cos(a);\nvar ac = acos(c);\n// Prints: \"3.1415927 : -1.0 : 3.1415927\"\nprint(a + ' : ' + c + ' : ' + ac);\n
\n\nvar a = PI + PI / 4.0;\nvar c = cos(a);\nvar ac = acos(c);\n// Prints: \"3.926991 : -0.70710665 : 2.3561943\"\nprint(a + ' : ' + c + ' : ' + ac);\n
\n\nlet a = PI;\nlet c = cos(a);\nlet ac = acos(c);\n// Prints: \"3.1415927 : -1.0 : 3.1415927\"\nprint(a + ' : ' + c + ' : ' + ac);\n
\n\nlet a = PI + PI / 4.0;\nlet c = cos(a);\nlet ac = acos(c);\n// Prints: \"3.926991 : -0.70710665 : 2.3561943\"\nprint(a + ' : ' + c + ' : ' + ac);\n
\n\nvar a = PI + PI / 3;\nvar s = sin(a);\nvar as = asin(s);\n// Prints: \"1.0471976 : 0.86602545 : 1.0471976\"\nprint(a + ' : ' + s + ' : ' + as);\n
\n\nvar a = PI + PI / 3.0;\nvar s = sin(a);\nvar as = asin(s);\n// Prints: \"4.1887903 : -0.86602545 : -1.0471976\"\nprint(a + ' : ' + s + ' : ' + as);\n
\n\nlet a = PI + PI / 3;\nlet s = sin(a);\nlet as = asin(s);\n// Prints: \"1.0471976 : 0.86602545 : 1.0471976\"\nprint(a + ' : ' + s + ' : ' + as);\n
\n\nlet a = PI + PI / 3.0;\nlet s = sin(a);\nlet as = asin(s);\n// Prints: \"4.1887903 : -0.86602545 : -1.0471976\"\nprint(a + ' : ' + s + ' : ' + as);\n
\n\nvar a = PI + PI / 3;\nvar t = tan(a);\nvar at = atan(t);\n// Prints: \"1.0471976 : 1.7320509 : 1.0471976\"\nprint(a + ' : ' + t + ' : ' + at);\n
\n\nvar a = PI + PI / 3.0;\nvar t = tan(a);\nvar at = atan(t);\n// Prints: \"4.1887903 : 1.7320513 : 1.0471977\"\nprint(a + ' : ' + t + ' : ' + at);\n
\n\nlet a = PI + PI / 3;\nlet t = tan(a);\nlet at = atan(t);\n// Prints: \"1.0471976 : 1.7320509 : 1.0471976\"\nprint(a + ' : ' + t + ' : ' + at);\n
\n\nlet a = PI + PI / 3.0;\nlet t = tan(a);\nlet at = atan(t);\n// Prints: \"4.1887903 : 1.7320513 : 1.0471977\"\nprint(a + ' : ' + t + ' : ' + at);\n
\n\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
\n\nfunction draw() {\n background(204);\n translate(width / 2, height / 2);\n let a = atan2(mouseY - height / 2, mouseX - width / 2);\n rotate(a);\n rect(-30, -5, 60, 10);\n}\n
\n\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
\n\nlet a = 0.0;\nlet inc = TWO_PI / 25.0;\nfor (let i = 0; i < 25; i++) {\n line(i * 4, 50, i * 4, 50 + cos(a) * 40.0);\n a = a + inc;\n}\n
\n\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
\n\nlet a = 0.0;\nlet inc = TWO_PI / 25.0;\nfor (let i = 0; i < 25; i++) {\n line(i * 4, 50, i * 4, 50 + sin(a) * 40.0);\n a = a + inc;\n}\n
\n\nvar a = 0.0;\nvar inc = TWO_PI / 50.0;\nfor (var i = 0; i < 100; i = i + 2) {\n line(i, 50, i, 50 + tan(a) * 2.0);\n a = a + inc;\n}\n
"
+ "\n\nlet a = 0.0;\nlet inc = TWO_PI / 50.0;\nfor (let i = 0; i < 100; i = i + 2) {\n line(i, 50, i, 50 + tan(a) * 2.0);\n a = a + inc;\n}\n
"
],
"alt": "vertical black lines end down and up from center to form spike pattern",
"class": "p5",
@@ -14942,7 +15187,7 @@ module.exports={
"type": "Number"
},
"example": [
- "\n\nvar rad = PI / 4;\nvar deg = degrees(rad);\nprint(rad + ' radians is ' + deg + ' degrees');\n// Prints: 0.7853981633974483 radians is 45 degrees\n
\n\nlet rad = PI / 4;\nlet deg = degrees(rad);\nprint(rad + ' radians is ' + deg + ' degrees');\n// Prints: 0.7853981633974483 radians is 45 degrees\n
\n\nvar deg = 45.0;\nvar rad = radians(deg);\nprint(deg + ' degrees is ' + rad + ' radians');\n// Prints: 45 degrees is 0.7853981633974483 radians\n
\n\nlet deg = 45.0;\nlet rad = radians(deg);\nprint(deg + ' degrees is ' + rad + ' radians');\n// Prints: 45 degrees is 0.7853981633974483 radians\n
\n\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
\n\nfunction draw() {\n background(204);\n angleMode(DEGREES); // Change the mode to DEGREES\n let a = atan2(mouseY - height / 2, mouseX - width / 2);\n translate(width / 2, height / 2);\n push();\n rotate(a);\n rect(-20, -5, 40, 10); // Larger rectangle is rotating in degrees\n pop();\n angleMode(RADIANS); // Change the mode to RADIANS\n rotate(a); // variable a stays the same\n rect(-40, -5, 20, 10); // Smaller rectangle is rotating in radians\n}\n
\n\n// Text to display. The \"\\n\" is a \"new line\" character\nvar lines = '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
\n\n// Text to display. The \"\\n\" is a \"new line\" character\nlet lines = '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
\nSets/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.
\n", + "description": "Sets/gets the style of the text for system fonts to NORMAL, ITALIC, BOLD or BOLDITALIC.\nNote: this may be is overridden by CSS styling. For non-system fonts\n(opentype, truetype, etc.) please load styled fonts instead.
\n", "itemtype": "method", "name": "textStyle", "chainable": 1, "example": [ - "\n\nstrokeWeight(0);\ntextSize(12);\ntextStyle(NORMAL);\ntext('Font Style Normal', 10, 30);\ntextStyle(ITALIC);\ntext('Font Style Italic', 10, 60);\ntextStyle(BOLD);\ntext('Font Style Bold', 10, 90);\n
\n\nstrokeWeight(0);\ntextSize(12);\ntextStyle(NORMAL);\ntext('Font Style Normal', 10, 15);\ntextStyle(ITALIC);\ntext('Font Style Italic', 10, 40);\ntextStyle(BOLD);\ntext('Font Style Bold', 10, 65);\ntextStyle(BOLDITALIC);\ntext('Font Style Bold Italic', 10, 90);\n
\nstyling for text, either NORMAL,\n ITALIC, or BOLD
\n", + "description": "styling for text, either NORMAL,\n ITALIC, BOLD or BOLDITALIC
\n", "type": "Constant" } ], "chainable": 1 }, { - "line": 180, + "line": 182, "params": [], "return": { "description": "", @@ -15145,7 +15390,7 @@ module.exports={ }, { "file": "src/typography/attributes.js", - "line": 189, + "line": 191, "description": "Calculates and returns the width of any character or text string.
\n", "itemtype": "method", "name": "textWidth", @@ -15161,7 +15406,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\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
\n\ntextSize(28);\n\nlet aChar = 'P';\nlet cWidth = textWidth(aChar);\ntext(aChar, 0, 40);\nline(cWidth, 0, cWidth, 50);\n\nlet aString = 'p5.js';\nlet sWidth = textWidth(aString);\ntext(aString, 0, 85);\nline(sWidth, 50, sWidth, 100);\n
\nReturns the ascent of the current font at its current size. The ascent\nrepresents the distance, in pixels, of the tallest character above\nthe baseline.
\n", "itemtype": "method", "name": "textAscent", @@ -15179,7 +15424,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\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
\n\nlet base = height * 0.75;\nlet scalar = 0.8; // Different for each font\n\ntextSize(32); // Set initial text size\nlet asc = textAscent() * scalar; // Calc ascent\nline(0, base - asc, width, base - asc);\ntext('dp', 0, base); // Draw text on baseline\n\ntextSize(64); // Increase text size\nasc = textAscent() * scalar; // Recalc ascent\nline(40, base - asc, width, base - asc);\ntext('dp', 40, base); // Draw text on baseline\n
\nReturns the descent of the current font at its current size. The descent\nrepresents the distance, in pixels, of the character with the longest\ndescender below the baseline.
\n", "itemtype": "method", "name": "textDescent", @@ -15196,7 +15441,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\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
\n\nlet base = height * 0.75;\nlet scalar = 0.8; // Different for each font\n\ntextSize(32); // Set initial text size\nlet desc = textDescent() * scalar; // Calc 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
\nHelper function to measure ascent and descent.
\n", "class": "p5", "module": "Typography", @@ -15213,7 +15458,7 @@ module.exports={ { "file": "src/typography/loading_displaying.js", "line": 16, - "description": "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.
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 fonts from a URL or other\nremote location may be blocked due to your browser's built-in\nsecurity.
Calling loadFont() inside preload() guarantees that the load\noperation will have completed before setup() and draw() are called.
\n\n\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
You can also use the string name of the font to style other HTML\nelements.
\n\n\nfunction preload() {\n loadFont('assets/Avenir.otf');\n}\n\nfunction setup() {\n var myDiv = createDiv('hello there');\n myDiv.style('font-family', 'Avenir');\n}\n
Calling loadFont() inside preload() guarantees that the load\noperation will have completed before setup() and draw() are called.
\n\n\nlet myFont;\nfunction preload() {\n myFont = loadFont('assets/inconsolata.otf');\n}\n\nfunction setup() {\n fill('#ED225D');\n textFont(myFont);\n textSize(36);\n text('p5*js', 10, 50);\n}\n
\nfunction setup() {\n loadFont('assets/inconsolata.otf', drawText);\n}\n\nfunction drawText(font) {\n fill('#ED225D');\n textFont(font, 36);\n text('p5*js', 10, 50);\n}\n
You can also use the font filename string (without the file extension) to style other HTML\nelements.
\n\n\nfunction preload() {\n loadFont('assets/inconsolata.otf');\n}\n\nfunction setup() {\n let myDiv = createDiv('hello there');\n myDiv.style('font-family', 'Inconsolata');\n}\n
\ntextSize(32);\ntext('word', 10, 30);\nfill(0, 102, 153);\ntext('word', 10, 60);\nfill(0, 102, 153, 51);\ntext('word', 10, 90);\n
\n\nvar s = 'The quick brown fox jumped over the lazy dog.';\nfill(50);\ntext(s, 10, 10, 70, 80); // Text wraps within text box\n
\n\nvar avenir;\nfunction preload() {\n avenir = loadFont('assets/Avenir.otf');\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n textFont(avenir);\n textSize(width / 3);\n textAlign(CENTER, CENTER);\n}\nfunction draw() {\n background(0);\n var time = millis();\n rotateX(time / 1000);\n rotateZ(time / 1234);\n text('p5.js', 0, 0);\n}\n
\n\ntextSize(32);\ntext('word', 10, 30);\nfill(0, 102, 153);\ntext('word', 10, 60);\nfill(0, 102, 153, 51);\ntext('word', 10, 90);\n
\n\nlet s = 'The quick brown fox jumped over the lazy dog.';\nfill(50);\ntext(s, 10, 10, 70, 80); // Text wraps within text box\n
\n\nlet inconsolata;\nfunction preload() {\n inconsolata = loadFont('assets/inconsolata.otf');\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n textFont(inconsolata);\n textSize(width / 3);\n textAlign(CENTER, CENTER);\n}\nfunction draw() {\n background(0);\n let time = millis();\n rotateX(time / 1000);\n rotateZ(time / 1234);\n text('p5.js', 0, 0);\n}\n
\n\nfill(0);\ntextSize(12);\ntextFont('Georgia');\ntext('Georgia', 12, 30);\ntextFont('Helvetica');\ntext('Helvetica', 12, 60);\n
\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)\n .strokeWeight(0)\n .textSize(10);\n textFont(fontRegular);\n text('Font Style Normal', 10, 30);\n textFont(fontItalic);\n text('Font Style Italic', 10, 50);\n textFont(fontBold);\n text('Font Style Bold', 10, 70);\n}\n
\n\nfill(0);\ntextSize(12);\ntextFont('Georgia');\ntext('Georgia', 12, 30);\ntextFont('Helvetica');\ntext('Helvetica', 12, 60);\n
\n\nlet fontRegular, fontItalic, fontBold;\nfunction preload() {\n fontRegular = loadFont('assets/Regular.otf');\n fontItalic = loadFont('assets/Italic.ttf');\n fontBold = loadFont('assets/Bold.ttf');\n}\nfunction setup() {\n background(210);\n fill(0)\n .strokeWeight(0)\n .textSize(10);\n textFont(fontRegular);\n text('Font Style Normal', 10, 30);\n textFont(fontItalic);\n text('Font Style Italic', 10, 50);\n textFont(fontBold);\n text('Font Style Bold', 10, 70);\n}\n
\nUnderlying opentype font implementation
\n", "itemtype": "property", "name": "font", @@ -15348,7 +15593,7 @@ module.exports={ }, { "file": "src/typography/p5.Font.js", - "line": 43, + "line": 32, "description": "Returns a tight bounding box for the given text string using this\nfont (currently only supports single lines)
\n", "itemtype": "method", "name": "textBounds", @@ -15370,13 +15615,13 @@ module.exports={ }, { "name": "fontSize", - "description": "font size to use (optional)
\n", + "description": "font size to use (optional) Default is 12.
\n", "type": "Number", "optional": true }, { "name": "options", - "description": "opentype options (optional)
\n", + "description": "opentype options (optional)\n opentype fonts contains alignment and baseline options.\n Default is 'LEFT' and 'alphabetic'
\n", "type": "Object", "optional": true } @@ -15386,7 +15631,7 @@ module.exports={ "type": "Object" }, "example": [ - "\n\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
\n\nlet font;\nlet textString = 'Lorem ipsum dolor sit amet.';\nfunction preload() {\n font = loadFont('./assets/Regular.otf');\n}\nfunction setup() {\n background(210);\n\n let bbox = font.textBounds(textString, 10, 30, 12);\n fill(255);\n stroke(0);\n rect(bbox.x, bbox.y, bbox.w, bbox.h);\n fill(0);\n noStroke();\n\n textFont(font);\n textSize(12);\n text(textString, 10, 30);\n}\n
\nComputes an array of points following the path for specified text
\n", "itemtype": "method", "name": "textToPoints", @@ -15422,7 +15667,7 @@ module.exports={ }, { "name": "options", - "description": "an (optional) object that can contain:
\n
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
an (optional) object that can contain:
\n
sampleFactor - the ratio of path-length to number of samples\n(default=.1); higher values yield more points and are therefore\nmore precise
simplifyThreshold - if set to a non-zero value, collinear points will be\nbe removed from the polygon; the value represents the threshold angle to use\nwhen determining whether two edges are collinear
\nvar font;\nfunction preload() {\n font = loadFont('./assets/Avenir.otf');\n}\n\nvar points;\nvar bounds;\nfunction setup() {\n createCanvas(100, 100);\n stroke(0);\n fill(255, 104, 204);\n\n points = font.textToPoints('p5', 0, 0, 10, {\n sampleFactor: 5,\n simplifyThreshold: 0\n });\n bounds = font.textBounds(' p5 ', 0, 0, 10);\n}\n\nfunction draw() {\n background(255);\n beginShape();\n translate(-bounds.x * width / bounds.w, -bounds.y * height / bounds.h);\n for (var i = 0; i < points.length; i++) {\n var p = points[i];\n vertex(\n p.x * width / bounds.w +\n sin(20 * p.y / bounds.h + millis() / 1000) * width / 30,\n p.y * height / bounds.h\n );\n }\n endShape(CLOSE);\n}\n
\n\nlet font;\nfunction preload() {\n font = loadFont('assets/inconsolata.otf');\n}\n\nlet points;\nlet bounds;\nfunction setup() {\n createCanvas(100, 100);\n stroke(0);\n fill(255, 104, 204);\n\n points = font.textToPoints('p5', 0, 0, 10, {\n sampleFactor: 5,\n simplifyThreshold: 0\n });\n bounds = font.textBounds(' p5 ', 0, 0, 10);\n}\n\nfunction draw() {\n background(255);\n beginShape();\n translate(-bounds.x * width / bounds.w, -bounds.y * height / bounds.h);\n for (let i = 0; i < points.length; i++) {\n let p = points[i];\n vertex(\n p.x * width / bounds.w +\n sin(20 * p.y / bounds.h + millis() / 1000) * width / 30,\n p.y * height / bounds.h\n );\n }\n endShape(CLOSE);\n}\n
\nRandomizes the order of the elements of an array. Implements\n\nFisher-Yates Shuffle Algorithm.
\n", "itemtype": "method", "name": "shuffle", - "deprecated": true, - "deprecationMessage": "See shuffling an array with JS instead.", "params": [ { "name": "array", @@ -15653,7 +15896,7 @@ module.exports={ }, { "file": "src/utilities/array_functions.js", - "line": 234, + "line": 233, "description": "Sorts an array of numbers from smallest to largest, or puts an array of\nwords in alphabetical order. The original array is not modified; a\nre-ordered array is returned. The count parameter states the number of\nelements to sort. For example, if there are 12 elements in an array and\ncount is set to 5, only the first 5 elements in the array will be sorted.
\n", "itemtype": "method", "name": "sort", @@ -15685,7 +15928,7 @@ module.exports={ }, { "file": "src/utilities/array_functions.js", - "line": 282, + "line": 281, "description": "Inserts a value or an array of values into an existing array. The first\nparameter specifies the initial array to be modified, and the second\nparameter defines the data to be inserted. The third parameter is an index\nvalue which specifies the array position from which to insert data.\n(Remember that array index numbering starts at zero, so the first position\nis 0, the second position is 1, and so on.)
\n", "itemtype": "method", "name": "splice", @@ -15721,7 +15964,7 @@ module.exports={ }, { "file": "src/utilities/array_functions.js", - "line": 317, + "line": 316, "description": "Extracts an array of elements from an existing array. The list parameter\ndefines the array from which the elements will be copied, and the start\nand count parameters specify which elements to extract. If no count is\ngiven, elements will be extracted from the start to the end of the array.\nWhen specifying the start, remember that the first array element is 0.\nThis function does not change the source array.
\n", "itemtype": "method", "name": "subset", @@ -15774,7 +16017,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n\nvar str = '20';\nvar diameter = float(str);\nellipse(width / 2, height / 2, diameter, diameter);\n
\nvar str = '20';\nvar diameter = float(str);\nellipse(width / 2, height / 2, diameter, diameter);\n
\nprint(float('10.31')); // 10.31\nprint(float('Infinity')); // Infinity\nprint(float('-Infinity')); // -Infinity\n
Converts a boolean, string, or float to its integer representation.\nWhen an array of values is passed in, then an int array of the same length\nis returned.
\n", "itemtype": "method", "name": "int", @@ -15792,14 +16035,14 @@ module.exports={ "type": "Number" }, "example": [ - "\n\nprint(int('10')); // 10\nprint(int(10.31)); // 10\nprint(int(-10)); // -10\nprint(int(true)); // 1\nprint(int(false)); // 0\nprint(int([false, true, '10.3', 9.8])); // [0, 1, 10, 9]\n
\nprint(int('10')); // 10\nprint(int(10.31)); // 10\nprint(int(-10)); // -10\nprint(int(true)); // 1\nprint(int(false)); // 0\nprint(int([false, true, '10.3', 9.8])); // [0, 1, 10, 9]\nprint(int(Infinity)); // Infinity\nprint(int('-Infinity')); // -Infinity\n
Converts a boolean, string or number to its string representation.\nWhen an array of values is passed in, then an array of strings of the same\nlength is returned.
\n", "itemtype": "method", "name": "str", @@ -15860,7 +16103,7 @@ module.exports={ }, { "file": "src/utilities/conversion.js", - "line": 108, + "line": 119, "description": "Converts a number or string to its boolean representation.\nFor a number, any non-zero value (positive or negative) evaluates to true,\nwhile zero evaluates to false. For a string, the value "true" evaluates to\ntrue, while any other value evaluates to false. When an array of number or\nstring values is passed in, then a array of booleans of the same length is\nreturned.
\n", "itemtype": "method", "name": "boolean", @@ -15876,7 +16119,7 @@ module.exports={ "type": "Boolean" }, "example": [ - "\n\nprint(boolean(0)); // false\nprint(boolean(1)); // true\nprint(boolean('true')); // true\nprint(boolean('abcd')); // false\nprint(boolean([0, 12, 'true'])); // [false, true, false]\n
\nprint(boolean(0)); // false\nprint(boolean(1)); // true\nprint(boolean('true')); // true\nprint(boolean('abcd')); // false\nprint(boolean([0, 12, 'true'])); // [false, true, true]\n
Converts a number, string representation of a number, or boolean to its byte\nrepresentation. A byte can be only a whole number between -128 and 127, so\nwhen a value outside of this range is converted, it wraps around to the\ncorresponding byte representation. When an array of number, string or boolean\nvalues is passed in, then an array of bytes the same length is returned.
\n", "itemtype": "method", "name": "byte", @@ -15900,7 +16143,7 @@ module.exports={ "submodule": "Conversion", "overloads": [ { - "line": 140, + "line": 151, "params": [ { "name": "n", @@ -15914,7 +16157,7 @@ module.exports={ } }, { - "line": 162, + "line": 173, "params": [ { "name": "ns", @@ -15931,7 +16174,7 @@ module.exports={ }, { "file": "src/utilities/conversion.js", - "line": 176, + "line": 187, "description": "Converts a number or string to its corresponding single-character\nstring representation. If a string parameter is provided, it is first\nparsed as an integer and then translated into a single-character string.\nWhen an array of number or string values is passed in, then an array of\nsingle-character strings of the same length is returned.
\n", "itemtype": "method", "name": "char", @@ -15947,7 +16190,7 @@ module.exports={ "submodule": "Conversion", "overloads": [ { - "line": 176, + "line": 187, "params": [ { "name": "n", @@ -15961,7 +16204,7 @@ module.exports={ } }, { - "line": 195, + "line": 206, "params": [ { "name": "ns", @@ -15978,7 +16221,7 @@ module.exports={ }, { "file": "src/utilities/conversion.js", - "line": 210, + "line": 221, "description": "Converts a single-character string to its corresponding integer\nrepresentation. When an array of single-character string values is passed\nin, then an array of integers of the same length is returned.
\n", "itemtype": "method", "name": "unchar", @@ -15994,7 +16237,7 @@ module.exports={ "submodule": "Conversion", "overloads": [ { - "line": 210, + "line": 221, "params": [ { "name": "n", @@ -16008,7 +16251,7 @@ module.exports={ } }, { - "line": 226, + "line": 237, "params": [ { "name": "ns", @@ -16025,7 +16268,7 @@ module.exports={ }, { "file": "src/utilities/conversion.js", - "line": 239, + "line": 250, "description": "Converts a number to a string in its equivalent hexadecimal notation. If a\nsecond parameter is passed, it is used to set the number of characters to\ngenerate in the hexadecimal notation. When an array is passed in, an\narray of strings in hexadecimal notation of the same length is returned.
\n", "itemtype": "method", "name": "hex", @@ -16034,14 +16277,14 @@ module.exports={ "type": "String" }, "example": [ - "\n\nprint(hex(255)); // \"000000FF\"\nprint(hex(255, 6)); // \"0000FF\"\nprint(hex([0, 127, 255], 6)); // [ \"000000\", \"00007F\", \"0000FF\" ]\n
\nprint(hex(255)); // \"000000FF\"\nprint(hex(255, 6)); // \"0000FF\"\nprint(hex([0, 127, 255], 6)); // [ \"000000\", \"00007F\", \"0000FF\" ]\nprint(Infinity); // \"FFFFFFFF\"\nprint(-Infinity); // \"00000000\"\n
Converts a string representation of a hexadecimal number to its equivalent\ninteger value. When an array of strings in hexadecimal notation is passed\nin, an array of integers of the same length is returned.
\n", "itemtype": "method", "name": "unhex", @@ -16100,7 +16343,7 @@ module.exports={ "submodule": "Conversion", "overloads": [ { - "line": 286, + "line": 302, "params": [ { "name": "n", @@ -16114,7 +16357,7 @@ module.exports={ } }, { - "line": 302, + "line": 318, "params": [ { "name": "ns", @@ -16221,7 +16464,7 @@ module.exports={ { "file": "src/utilities/string_functions.js", "line": 132, - "description": "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.
\n", + "description": "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.\n(NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter\nif greater than the current length of the number.\nFor example if number is 123.2 and left parameter passed is 4 which is greater than length of 123\n(integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than\nthe result will be 123.200.
\n", "itemtype": "method", "name": "nf", "return": { @@ -16229,9 +16472,9 @@ module.exports={ "type": "String" }, "example": [ - "\n\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
\n\nvar myFont;\nfunction preload() {\n myFont = loadFont('assets/fonts/inconsolata.ttf');\n}\nfunction setup() {\n background(200);\n var num1 = 321;\n var num2 = -1321;\n\n noStroke();\n fill(0);\n textFont(myFont);\n textSize(22);\n\n text(nf(num1, 4, 2), 10, 30);\n text(nf(num2, 4, 2), 10, 80);\n // Draw dividing line\n stroke(120);\n line(0, 50, width, 50);\n}\n
\nUtility function for formatting numbers into strings and placing\nappropriate commas to mark units of 1000. There are two versions: one\nfor formatting ints, and one for formatting an array of ints. The value\nfor the right parameter should always be a positive integer.
\n", "itemtype": "method", "name": "nfc", @@ -16309,7 +16552,7 @@ module.exports={ "submodule": "String Functions", "overloads": [ { - "line": 237, + "line": 243, "params": [ { "name": "num", @@ -16329,7 +16572,7 @@ module.exports={ } }, { - "line": 275, + "line": 281, "params": [ { "name": "nums", @@ -16352,7 +16595,7 @@ module.exports={ }, { "file": "src/utilities/string_functions.js", - "line": 313, + "line": 319, "description": "Utility function for formatting numbers into strings. Similar to nf() but\nputs a "+" in front of positive numbers and a "-" in front of negative\nnumbers. There are two versions: one for formatting floats, and one for\nformatting ints. The values for left, and right parameters\nshould always be positive integers.
\n", "itemtype": "method", "name": "nfp", @@ -16369,7 +16612,7 @@ module.exports={ "submodule": "String Functions", "overloads": [ { - "line": 313, + "line": 319, "params": [ { "name": "num", @@ -16395,7 +16638,7 @@ module.exports={ } }, { - "line": 354, + "line": 360, "params": [ { "name": "nums", @@ -16424,8 +16667,8 @@ module.exports={ }, { "file": "src/utilities/string_functions.js", - "line": 375, - "description": "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.
\n", + "line": 381, + "description": "Utility function for formatting numbers into strings. Similar to nf() but\nputs an additional "_" (space) in front of positive numbers just in case to align it with negative\nnumbers which includes "-" (minus) sign.\nThe main usecase of nfs() can be seen when one wants to align the digits (place values) of a positive\nnumber with some negative number (See the example to get a clear picture).\nThere are two versions: one for formatting float, and one for formatting int.\nThe values for the digits, left, and right parameters should always be positive integers.\n(IMP): The result on the canvas basically the expected alignment can vary based on the typeface you are using.\n(NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter\nif greater than the current length of the number.\nFor example if number is 123.2 and left parameter passed is 4 which is greater than length of 123\n(integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than\nthe result will be 123.200.
\n", "itemtype": "method", "name": "nfs", "return": { @@ -16433,15 +16676,15 @@ module.exports={ "type": "String" }, "example": [ - "\n\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
\n\nvar myFont;\nfunction preload() {\n myFont = loadFont('assets/fonts/inconsolata.ttf');\n}\nfunction setup() {\n background(200);\n var num1 = 321;\n var num2 = -1321;\n\n noStroke();\n fill(0);\n textFont(myFont);\n textSize(22);\n\n // nfs() aligns num1 (positive number) with num2 (negative number) by\n // adding a blank space in front of the num1 (positive number)\n // [left = 4] in num1 add one 0 in front, to align the digits with num2\n // [right = 2] in num1 and num2 adds two 0's after both numbers\n // To see the differences check the example of nf() too.\n text(nfs(num1, 4, 2), 10, 30);\n text(nfs(num2, 4, 2), 10, 80);\n // Draw dividing line\n stroke(120);\n line(0, 50, width, 50);\n}\n
\nThe split() function maps to String.split(), it breaks a String into\npieces using a character or string as the delimiter. The delim parameter\nspecifies the character or characters that mark the boundaries between\neach piece. A String[] array is returned that contains each of the pieces.
\nThe splitTokens() function works in a similar fashion, except that it\nsplits using a range of characters instead of a specific character or\nsequence.
\n", "itemtype": "method", "name": "split", @@ -16526,7 +16769,7 @@ module.exports={ }, { "file": "src/utilities/string_functions.js", - "line": 471, + "line": 493, "description": "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.
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.
\n", "itemtype": "method", "name": "trim", @@ -16573,7 +16816,7 @@ module.exports={ "submodule": "String Functions", "overloads": [ { - "line": 526, + "line": 548, "params": [ { "name": "str", @@ -16587,7 +16830,7 @@ module.exports={ } }, { - "line": 546, + "line": 568, "params": [ { "name": "strs", @@ -16730,7 +16973,7 @@ module.exports={ }, { "file": "src/webgl/3d_primitives.js", - "line": 15, + "line": 14, "description": "Draw a plane with given a width and height
\n", "itemtype": "method", "name": "plane", @@ -16762,7 +17005,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n\n//draw a plane with width 50 and height 50\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n plane(50, 50);\n}\n
\n\n// draw a plane\n// with width 50 and height 50\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n plane(50, 50);\n}\n
\n\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(50);\n}\n
\n\n// draw a spinning box\n// with width, height and depth of 50\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(50);\n}\n
\nDraw a sphere with given radius
\n", "itemtype": "method", "name": "sphere", @@ -16843,7 +17086,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n\n// draw a sphere with radius 200\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n sphere(40);\n}\n
\n\n// draw a sphere with radius 40\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n sphere(40);\n}\n
\nDraw a cylinder with given radius and height
\n", "itemtype": "method", "name": "cylinder", @@ -16895,7 +17138,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n\n//draw a spinning cylinder with radius 20 and height 50\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(20, 50);\n}\n
\n\n// draw a spinning cylinder\n// with radius 20 and height 50\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(20, 50);\n}\n
\nDraw a cone with given radius and height
\n", "itemtype": "method", "name": "cone", @@ -16941,7 +17184,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n\n//draw a spinning cone with radius 40 and height 70\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(40, 70);\n}\n
\n\n// draw a spinning cone\n// with radius 40 and height 70\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(40, 70);\n}\n
\nDraw an ellipsoid with given radius
\n", "itemtype": "method", "name": "ellipsoid", "params": [ { "name": "radiusx", - "description": "xradius of circle
\n", + "description": "x-radius of ellipsoid
\n", "type": "Number", "optional": true }, { "name": "radiusy", - "description": "yradius of circle
\n", + "description": "y-radius of ellipsoid
\n", "type": "Number", "optional": true }, { "name": "radiusz", - "description": "zradius of circle
\n", + "description": "z-radius of ellipsoid
\n", "type": "Number", "optional": true }, @@ -16987,7 +17230,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n\n// draw an ellipsoid with radius 20, 30 and 40.\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n ellipsoid(20, 30, 40);\n}\n
\n\n// draw an ellipsoid\n// with radius 30, 40 and 40.\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n ellipsoid(30, 40, 40);\n}\n
\nDraw a torus with given radius and tube radius
\n", "itemtype": "method", "name": "torus", @@ -17027,7 +17270,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n\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(50, 15);\n}\n
\n\n// draw a spinning torus\n// with ring radius 30 and tube radius 15\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(30, 15);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n ambientLight(150);\n ambientMaterial(250);\n noStroke();\n sphere(25);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n ambientLight(150);\n ambientMaterial(250);\n noStroke();\n sphere(40);\n}\n
\nCreates a directional light with a color and a direction
\n", "itemtype": "method", "name": "directionalLight", "chainable": 1, "example": [ - "\n\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 noStroke();\n sphere(25);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n //move your mouse to change light direction\n let dirX = (mouseX / width - 0.5) * 2;\n let dirY = (mouseY / height - 0.5) * 2;\n directionalLight(250, 250, 250, -dirX, -dirY, -1);\n noStroke();\n sphere(40);\n}\n
\nCreates a point light with a color and a light position
\n", "itemtype": "method", "name": "pointLight", "chainable": 1, "example": [ - "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n //move your mouse to change light position\n var locX = mouseX - width / 2;\n var locY = mouseY - height / 2;\n // to set the light position,\n // think of the world's coordinate as:\n // -width/2,-height/2 -------- width/2,-height/2\n // | |\n // | 0,0 |\n // | |\n // -width/2,height/2--------width/2,height/2\n pointLight(250, 250, 250, locX, locY, 50);\n ambientMaterial(250);\n noStroke();\n sphere(25);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n //move your mouse to change light position\n let locX = mouseX - width / 2;\n let locY = mouseY - height / 2;\n // to set the light position,\n // think of the world's coordinate as:\n // -width/2,-height/2 -------- width/2,-height/2\n // | |\n // | 0,0 |\n // | |\n // -width/2,height/2--------width/2,height/2\n pointLight(250, 250, 250, locX, locY, 50);\n noStroke();\n sphere(40);\n}\n
\nSets the default ambient and directional light. The defaults are ambientLight(128, 128, 128) and directionalLight(128, 128, 128, 0, 0, -1). Lights need to be included in the draw() to remain persistent in a looping program. Placing them in the setup() of a looping program will cause them to only have an effect the first time through the loop.
\n", + "itemtype": "method", + "name": "lights", + "chainable": 1, + "example": [ + "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n lights();\n rotateX(millis() / 1000);\n rotateY(millis() / 1000);\n rotateZ(millis() / 1000);\n box();\n}\n
\n\n//draw a spinning octahedron\nvar octahedron;\n\nfunction preload() {\n octahedron = loadModel('assets/octahedron.obj');\n}\n\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 model(octahedron);\n}\n
\n\n//draw a spinning teapot\nvar teapot;\n\nfunction preload() {\n // Load model with normalise parameter set to true\n teapot = loadModel('assets/teapot.obj', true);\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n scale(0.4); // Scaled to make model fit into canvas\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n normalMaterial(); // For effect\n model(teapot);\n}\n
\n\n//draw a spinning octahedron\nlet octahedron;\n\nfunction preload() {\n octahedron = loadModel('assets/octahedron.obj');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n model(octahedron);\n}\n
\n\n//draw a spinning teapot\nlet teapot;\n\nfunction preload() {\n // Load model with normalise parameter set to true\n teapot = loadModel('assets/teapot.obj', true);\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n scale(0.4); // Scaled to make model fit into canvas\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n normalMaterial(); // For effect\n model(teapot);\n}\n
\n\n//draw a spinning octahedron\nvar octahedron;\n\nfunction preload() {\n octahedron = loadModel('assets/octahedron.obj');\n}\n\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 model(octahedron);\n}\n
\n\n//draw a spinning octahedron\nlet octahedron;\n\nfunction preload() {\n octahedron = loadModel('assets/octahedron.obj');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n model(octahedron);\n}\n
\npath to file containing vertex shader\nsource code
\n", - "type": "String", - "optional": true + "type": "String" }, { "name": "fragFilename", "description": "path to file containing fragment shader\nsource code
\n", - "type": "String", + "type": "String" + }, + { + "name": "callback", + "description": "callback to be executed after loadShader\ncompletes. On success, the Shader object is passed as the first argument.
\n", + "type": "Function", + "optional": true + }, + { + "name": "errorCallback", + "description": "callback to be executed when an error\noccurs inside loadShader. On error, the error is passed as the first\nargument.
\n", + "type": "Function", "optional": true } ], @@ -17711,7 +17979,7 @@ module.exports={ "type": "p5.Shader" }, "example": [ - "\n\nvar mandel;\nfunction preload() {\n // load the shader definitions from files\n mandel = loadShader('assets/shader.vert', 'assets/shader.frag');\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n // use the shader\n shader(mandel);\n noStroke();\n mandel.setUniform('p', [-0.74364388703, 0.13182590421]);\n}\n\nfunction draw() {\n mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000))));\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n
\n\nlet mandel;\nfunction preload() {\n // load the shader definitions from files\n mandel = loadShader('assets/shader.vert', 'assets/shader.frag');\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n // use the shader\n shader(mandel);\n noStroke();\n mandel.setUniform('p', [-0.74364388703, 0.13182590421]);\n}\n\nfunction draw() {\n mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000))));\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n
\n\n// the 'varying's are shared between both vertex & fragment shaders\nvar varying = 'precision highp float; varying vec2 vPos;';\n\n// the vertex shader is called for each vertex\nvar vs =\n varying +\n 'attribute vec3 aPosition;' +\n 'void main() { vPos = (gl_Position = vec4(aPosition,1.0)).xy; }';\n\n// the fragment shader is called for each pixel\nvar fs =\n varying +\n 'uniform vec2 p;' +\n 'uniform float r;' +\n 'const int I = 500;' +\n 'void main() {' +\n ' vec2 c = p + vPos * r, z = c;' +\n ' float n = 0.0;' +\n ' for (int i = I; i > 0; i --) {' +\n ' if(z.x*z.x+z.y*z.y > 4.0) {' +\n ' n = float(i)/float(I);' +\n ' break;' +\n ' }' +\n ' z = vec2(z.x*z.x-z.y*z.y, 2.0*z.x*z.y) + c;' +\n ' }' +\n ' gl_FragColor = vec4(0.5-cos(n*17.0)/2.0,0.5-cos(n*13.0)/2.0,0.5-cos(n*23.0)/2.0,1.0);' +\n '}';\n\nvar mandel;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // create and initialize the shader\n mandel = createShader(vs, fs);\n shader(mandel);\n noStroke();\n\n // 'p' is the center point of the Mandelbrot image\n mandel.setUniform('p', [-0.74364388703, 0.13182590421]);\n}\n\nfunction draw() {\n // 'r' is the size of the image in Mandelbrot-space\n mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000))));\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n
\n\n// the 'varying's are shared between both vertex & fragment shaders\nlet varying = 'precision highp float; varying vec2 vPos;';\n\n// the vertex shader is called for each vertex\nlet vs =\n varying +\n 'attribute vec3 aPosition;' +\n 'void main() { vPos = (gl_Position = vec4(aPosition,1.0)).xy; }';\n\n// the fragment shader is called for each pixel\nlet fs =\n varying +\n 'uniform vec2 p;' +\n 'uniform float r;' +\n 'const int I = 500;' +\n 'void main() {' +\n ' vec2 c = p + vPos * r, z = c;' +\n ' float n = 0.0;' +\n ' for (int i = I; i > 0; i --) {' +\n ' if(z.x*z.x+z.y*z.y > 4.0) {' +\n ' n = float(i)/float(I);' +\n ' break;' +\n ' }' +\n ' z = vec2(z.x*z.x-z.y*z.y, 2.0*z.x*z.y) + c;' +\n ' }' +\n ' gl_FragColor = vec4(0.5-cos(n*17.0)/2.0,0.5-cos(n*13.0)/2.0,0.5-cos(n*23.0)/2.0,1.0);' +\n '}';\n\nlet mandel;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // create and initialize the shader\n mandel = createShader(vs, fs);\n shader(mandel);\n noStroke();\n\n // 'p' is the center point of the Mandelbrot image\n mandel.setUniform('p', [-0.74364388703, 0.13182590421]);\n}\n\nfunction draw() {\n // 'r' is the size of the image in Mandelbrot-space\n mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000))));\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n
\nThe shader() function lets the user provide a custom shader\nto fill in shapes in WEBGL mode. Users can create their\nown shaders by loading vertex and fragment shaders with\nloadShader().
\n", "itemtype": "method", "name": "shader", @@ -17768,13 +18036,24 @@ module.exports={ }, { "file": "src/webgl/material.js", - "line": 176, + "line": 212, + "description": "This function restores the default shaders in WEBGL mode. Code that runs\nafter resetShader() will not be affected by previously defined\nshaders. Should be run after shader().
\n", + "itemtype": "method", + "name": "resetShader", + "chainable": 1, + "class": "p5", + "module": "Lights, Camera", + "submodule": "Material" + }, + { + "file": "src/webgl/material.js", + "line": 225, "description": "Normal material for geometry. You can view all\npossible materials in this\nexample.
\n", "itemtype": "method", "name": "normalMaterial", "chainable": 1, "example": [ - "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n normalMaterial();\n sphere(50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n normalMaterial();\n sphere(40);\n}\n
\nTexture for geometry. You can view other possible materials in this\nexample.
\n", "itemtype": "method", "name": "texture", @@ -17796,7 +18075,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\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
\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
\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
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\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
\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n pg = createGraphics(200, 200);\n pg.textSize(75);\n}\n\nfunction draw() {\n background(0);\n pg.background(255);\n pg.text('hello!', 0, 100);\n //pass image as texture\n texture(pg);\n rotateX(0.5);\n noStroke();\n plane(50);\n}\n
\n\nlet vid;\nfunction preload() {\n vid = createVideo('assets/fingers.mov');\n vid.hide();\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(0);\n //pass video frame as texture\n texture(vid);\n rect(-40, -40, 80, 80);\n}\n\nfunction mousePressed() {\n vid.loop();\n}\n
\nSets the coordinate space for texture mapping. The default mode is IMAGE\nwhich refers to the actual coordinates of the image.\nNORMAL refers to a normalized space of values ranging from 0 to 1.\nThis function only works in WEBGL mode.
\nWith IMAGE, if an image is 100 x 200 pixels, mapping the image onto the entire\nsize of a quad would require the points (0,0) (100, 0) (100,200) (0,200).\nThe same mapping in NORMAL is (0,0) (1,0) (1,1) (0,1).
\n", + "itemtype": "method", + "name": "textureMode", + "params": [ + { + "name": "mode", + "description": "either IMAGE or NORMAL
\n", + "type": "Constant" + } + ], + "example": [ + "\n\nlet img;\n\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n texture(img);\n textureMode(NORMAL);\n beginShape();\n vertex(-50, -50, 0, 0);\n vertex(50, -50, 1, 0);\n vertex(50, 50, 1, 1);\n vertex(-50, 50, 0, 1);\n endShape();\n}\n
\nSets the global texture wrapping mode. This controls how textures behave\nwhen their uv's go outside of the 0 - 1 range. There are three options:\nCLAMP, REPEAT, and MIRROR.
\nCLAMP causes the pixels at the edge of the texture to extend to the bounds\nREPEAT causes the texture to tile repeatedly until reaching the bounds\nMIRROR works similarly to REPEAT but it flips the texture with every new tile
\nREPEAT & MIRROR are only available if the texture\nis a power of two size (128, 256, 512, 1024, etc.).
\nThis method will affect all textures in your sketch until a subsequent\ntextureWrap call is made.
\nIf only one argument is provided, it will be applied to both the\nhorizontal and vertical axes.
\n", + "itemtype": "method", + "name": "textureWrap", + "params": [ + { + "name": "wrapX", + "description": "either CLAMP, REPEAT, or MIRROR
\n", + "type": "Constant" + }, + { + "name": "wrapY", + "description": "either CLAMP, REPEAT, or MIRROR
\n", + "type": "Constant", + "optional": true + } + ], + "example": [ + "\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies128.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n textureWrap(MIRROR);\n}\n\nfunction draw() {\n background(0);\n\n let dX = mouseX;\n let dY = mouseY;\n\n let u = lerp(1.0, 2.0, dX);\n let v = lerp(1.0, 2.0, dY);\n\n scale(width / 2);\n\n texture(img);\n\n beginShape(TRIANGLES);\n vertex(-1, -1, 0, 0, 0);\n vertex(1, -1, 0, u, 0);\n vertex(1, 1, 0, u, v);\n\n vertex(1, 1, 0, u, v);\n vertex(-1, 1, 0, 0, v);\n vertex(-1, -1, 0, 0, 0);\n endShape();\n}\n
\nAmbient material for geometry with a given color. You can view all\npossible materials in this\nexample.
\n", "itemtype": "method", "name": "ambientMaterial", "chainable": 1, "example": [ - "\n\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(50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n noStroke();\n ambientLight(200);\n ambientMaterial(70, 130, 230);\n sphere(40);\n}\n
\nSpecular material for geometry with a given color. You can view all\npossible materials in this\nexample.
\n", "itemtype": "method", "name": "specularMaterial", "chainable": 1, "example": [ - "\n\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(50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n noStroke();\n ambientLight(50);\n pointLight(250, 250, 250, 100, 100, 30);\n specularMaterial(250);\n sphere(40);\n}\n
\nSets the amount of gloss in the surface of shapes.\nUsed in combination with specularMaterial() in setting\nthe material properties of shapes. The default and minimum value is 1.
\n", + "itemtype": "method", + "name": "shininess", + "params": [ + { + "name": "shine", + "description": "Degree of Shininess.\n Defaults to 1.
\n", + "type": "Number" + } + ], + "chainable": 1, + "example": [ + "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n noStroke();\n let locX = mouseX - width / 2;\n let locY = mouseY - height / 2;\n ambientLight(60, 60, 60);\n pointLight(255, 255, 255, locX, locY, 50);\n specularMaterial(250);\n translate(-25, 0, 0);\n shininess(1);\n sphere(20);\n translate(50, 0, 0);\n shininess(20);\n sphere(20);\n}\n
\nSets an orthographic projection for a p5.Camera object and sets parameters\nfor that projection according to ortho() syntax.
\n", "itemtype": "method", "name": "ortho", @@ -18118,7 +18467,7 @@ module.exports={ }, { "file": "src/webgl/p5.Camera.js", - "line": 487, + "line": 486, "description": "Panning rotates the camera view to the left and right.
\n", "itemtype": "method", "name": "pan", @@ -18130,7 +18479,7 @@ module.exports={ } ], "example": [ - "\n\nvar cam;\nvar delta = 0.01;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n // set initial pan angle\n cam.pan(-0.8);\n}\n\nfunction draw() {\n background(200);\n\n // pan camera according to angle 'delta'\n cam.pan(delta);\n\n // every 160 frames, switch direction\n if (frameCount % 160 === 0) {\n delta *= -1;\n }\n\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n
\n\nlet cam;\nlet delta = 0.01;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n // set initial pan angle\n cam.pan(-0.8);\n}\n\nfunction draw() {\n background(200);\n\n // pan camera according to angle 'delta'\n cam.pan(delta);\n\n // every 160 frames, switch direction\n if (frameCount % 160 === 0) {\n delta *= -1;\n }\n\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n
\nTilting rotates the camera view up and down.
\n", "itemtype": "method", "name": "tilt", @@ -18151,7 +18500,7 @@ module.exports={ } ], "example": [ - "\n\nvar cam;\nvar delta = 0.01;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n // set initial tilt\n cam.tilt(-0.8);\n}\n\nfunction draw() {\n background(200);\n\n // pan camera according to angle 'delta'\n cam.tilt(delta);\n\n // every 160 frames, switch direction\n if (frameCount % 160 === 0) {\n delta *= -1;\n }\n\n rotateY(frameCount * 0.01);\n translate(0, -100, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n}\n
\n\nlet cam;\nlet delta = 0.01;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n // set initial tilt\n cam.tilt(-0.8);\n}\n\nfunction draw() {\n background(200);\n\n // pan camera according to angle 'delta'\n cam.tilt(delta);\n\n // every 160 frames, switch direction\n if (frameCount % 160 === 0) {\n delta *= -1;\n }\n\n rotateY(frameCount * 0.01);\n translate(0, -100, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n}\n
\nReorients the camera to look at a position in world space.
\n", "itemtype": "method", "name": "lookAt", @@ -18182,7 +18531,7 @@ module.exports={ } ], "example": [ - "\n\nvar cam;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n}\n\nfunction draw() {\n background(200);\n\n // look at a new random point every 60 frames\n if (frameCount % 60 === 0) {\n cam.lookAt(random(-100, 100), random(-50, 50), 0);\n }\n\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n
\n\nlet cam;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n}\n\nfunction draw() {\n background(200);\n\n // look at a new random point every 60 frames\n if (frameCount % 60 === 0) {\n cam.lookAt(random(-100, 100), random(-50, 50), 0);\n }\n\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n
\nSets a camera's position and orientation. This is equivalent to calling\ncamera() on a p5.Camera object.
\n", "itemtype": "method", "name": "camera", @@ -18201,7 +18550,7 @@ module.exports={ }, { "file": "src/webgl/p5.Camera.js", - "line": 752, + "line": 751, "description": "Move camera along its local axes while maintaining current camera orientation.
\n", "itemtype": "method", "name": "move", @@ -18223,7 +18572,7 @@ module.exports={ } ], "example": [ - "\n\n// see the camera move along its own axes while maintaining its orientation\nvar cam;\nvar delta = 0.5;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n}\n\nfunction draw() {\n background(200);\n\n // move the camera along its local axes\n cam.move(delta, delta, 0);\n\n // every 100 frames, switch direction\n if (frameCount % 150 === 0) {\n delta *= -1;\n }\n\n translate(-10, -10, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n}\n
\n\n// see the camera move along its own axes while maintaining its orientation\nlet cam;\nlet delta = 0.5;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n}\n\nfunction draw() {\n background(200);\n\n // move the camera along its local axes\n cam.move(delta, delta, 0);\n\n // every 100 frames, switch direction\n if (frameCount % 150 === 0) {\n delta *= -1;\n }\n\n translate(-10, -10, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n}\n
\nSet camera position in world-space while maintaining current camera\norientation.
\n", "itemtype": "method", "name": "setPosition", @@ -18254,7 +18603,7 @@ module.exports={ } ], "example": [ - "\n\n// press '1' '2' or '3' keys to set camera position\n\nvar cam;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n}\n\nfunction draw() {\n background(200);\n\n // '1' key\n if (keyIsDown(49)) {\n cam.setPosition(30, 0, 80);\n }\n // '2' key\n if (keyIsDown(50)) {\n cam.setPosition(0, 0, 80);\n }\n // '3' key\n if (keyIsDown(51)) {\n cam.setPosition(-30, 0, 80);\n }\n\n box(20);\n}\n
\n\n// press '1' '2' or '3' keys to set camera position\n\nlet cam;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n}\n\nfunction draw() {\n background(200);\n\n // '1' key\n if (keyIsDown(49)) {\n cam.setPosition(30, 0, 80);\n }\n // '2' key\n if (keyIsDown(50)) {\n cam.setPosition(0, 0, 80);\n }\n // '3' key\n if (keyIsDown(51)) {\n cam.setPosition(-30, 0, 80);\n }\n\n box(20);\n}\n
\nSets rendererGL's current camera to a p5.Camera object. Allows switching\nbetween multiple cameras.
\n", "itemtype": "method", "name": "setCamera", @@ -18275,7 +18624,7 @@ module.exports={ } ], "example": [ - "\n\nvar cam1, cam2;\nvar currentCamera;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n\n cam1 = createCamera();\n cam2 = createCamera();\n cam2.setPosition(30, 0, 50);\n cam2.lookAt(0, 0, 0);\n cam2.ortho();\n\n // set variable for previously active camera:\n currentCamera = 1;\n}\n\nfunction draw() {\n background(200);\n\n // camera 1:\n cam1.lookAt(0, 0, 0);\n cam1.setPosition(sin(frameCount / 60) * 200, 0, 100);\n\n // every 100 frames, switch between the two cameras\n if (frameCount % 100 === 0) {\n if (currentCamera === 1) {\n setCamera(cam1);\n currentCamera = 0;\n } else {\n setCamera(cam2);\n currentCamera = 1;\n }\n }\n\n drawBoxes();\n}\n\nfunction drawBoxes() {\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n
\n\nlet cam1, cam2;\nlet currentCamera;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n\n cam1 = createCamera();\n cam2 = createCamera();\n cam2.setPosition(30, 0, 50);\n cam2.lookAt(0, 0, 0);\n cam2.ortho();\n\n // set variable for previously active camera:\n currentCamera = 1;\n}\n\nfunction draw() {\n background(200);\n\n // camera 1:\n cam1.lookAt(0, 0, 0);\n cam1.setPosition(sin(frameCount / 60) * 200, 0, 100);\n\n // every 100 frames, switch between the two cameras\n if (frameCount % 100 === 0) {\n if (currentCamera === 1) {\n setCamera(cam1);\n currentCamera = 0;\n } else {\n setCamera(cam2);\n currentCamera = 1;\n }\n }\n\n drawBoxes();\n}\n\nfunction drawBoxes() {\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n
\nSet attributes for the WebGL Drawing context.\nThis is a way of adjusting ways that the WebGL\nrenderer works to fine-tune the display and performance.\nThis should be put in setup().\nThe available attributes are:\n
\nalpha - indicates if the canvas contains an alpha buffer\ndefault is true\n
\ndepth - indicates whether the drawing buffer has a depth buffer\nof at least 16 bits - default is true\n
\nstencil - indicates whether the drawing buffer has a stencil buffer\nof at least 8 bits\n
\nantialias - indicates whether or not to perform anti-aliasing\ndefault is false\n
\npremultipliedAlpha - indicates that the page compositor will assume\nthe drawing buffer contains colors with pre-multiplied alpha\ndefault is false\n
\npreserveDrawingBuffer - if true the buffers will not be cleared and\nand will preserve their values until cleared or overwritten by author\n(note that p5 clears automatically on draw loop)\ndefault is true\n
\nperPixelLighting - if true, per-pixel lighting will be used in the\nlighting shader.\ndefault is false\n
Set attributes for the WebGL Drawing context.\nThis is a way of adjusting how the WebGL\nrenderer works to fine-tune the display and performance.\n
\nNote that this will reinitialize the drawing context\nif called after the WebGL canvas is made.\n
\nIf an object is passed as the parameter, all attributes\nnot declared in the object will be set to defaults.\n
\nThe available attributes are:\n
\nalpha - indicates if the canvas contains an alpha buffer\ndefault is false\n
\ndepth - indicates whether the drawing buffer has a depth buffer\nof at least 16 bits - default is true\n
\nstencil - indicates whether the drawing buffer has a stencil buffer\nof at least 8 bits\n
\nantialias - indicates whether or not to perform anti-aliasing\ndefault is false\n
\npremultipliedAlpha - indicates that the page compositor will assume\nthe drawing buffer contains colors with pre-multiplied alpha\ndefault is false\n
\npreserveDrawingBuffer - if true the buffers will not be cleared and\nand will preserve their values until cleared or overwritten by author\n(note that p5 clears automatically on draw loop)\ndefault is true\n
\nperPixelLighting - if true, per-pixel lighting will be used in the\nlighting shader.\ndefault is false\n
\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(255);\n push();\n rotateZ(frameCount * 0.02);\n rotateX(frameCount * 0.02);\n rotateY(frameCount * 0.02);\n fill(0, 0, 0);\n box(50);\n pop();\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n setAttributes('antialias', true);\n}\n\nfunction draw() {\n background(255);\n push();\n rotateZ(frameCount * 0.02);\n rotateX(frameCount * 0.02);\n rotateY(frameCount * 0.02);\n fill(0, 0, 0);\n box(50);\n pop();\n}\n
\n\n// press the mouse button to enable perPixelLighting\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noStroke();\n fill(255);\n}\n\nvar lights = [\n { c: '#f00', t: 1.12, p: 1.91, r: 0.2 },\n { c: '#0f0', t: 1.21, p: 1.31, r: 0.2 },\n { c: '#00f', t: 1.37, p: 1.57, r: 0.2 },\n { c: '#ff0', t: 1.12, p: 1.91, r: 0.7 },\n { c: '#0ff', t: 1.21, p: 1.31, r: 0.7 },\n { c: '#f0f', t: 1.37, p: 1.57, r: 0.7 }\n];\n\nfunction draw() {\n var t = millis() / 1000 + 1000;\n background(0);\n directionalLight(color('#222'), 1, 1, 1);\n\n for (var i = 0; i < lights.length; i++) {\n var light = lights[i];\n pointLight(\n color(light.c),\n p5.Vector.fromAngles(t * light.t, t * light.p, width * light.r)\n );\n }\n\n specularMaterial(255);\n sphere(width * 0.1);\n\n rotateX(t * 0.77);\n rotateY(t * 0.83);\n rotateZ(t * 0.91);\n torus(width * 0.3, width * 0.07, 30, 10);\n}\n\nfunction mousePressed() {\n setAttributes('perPixelLighting', true);\n noStroke();\n fill(255);\n}\nfunction mouseReleased() {\n setAttributes('perPixelLighting', false);\n noStroke();\n fill(255);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(255);\n push();\n rotateZ(frameCount * 0.02);\n rotateX(frameCount * 0.02);\n rotateY(frameCount * 0.02);\n fill(0, 0, 0);\n box(50);\n pop();\n}\n
\n\nfunction setup() {\n setAttributes('antialias', true);\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(255);\n push();\n rotateZ(frameCount * 0.02);\n rotateX(frameCount * 0.02);\n rotateY(frameCount * 0.02);\n fill(0, 0, 0);\n box(50);\n pop();\n}\n
\n\n// press the mouse button to enable perPixelLighting\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noStroke();\n fill(255);\n}\n\nvar lights = [\n { c: '#f00', t: 1.12, p: 1.91, r: 0.2 },\n { c: '#0f0', t: 1.21, p: 1.31, r: 0.2 },\n { c: '#00f', t: 1.37, p: 1.57, r: 0.2 },\n { c: '#ff0', t: 1.12, p: 1.91, r: 0.7 },\n { c: '#0ff', t: 1.21, p: 1.31, r: 0.7 },\n { c: '#f0f', t: 1.37, p: 1.57, r: 0.7 }\n];\n\nfunction draw() {\n var t = millis() / 1000 + 1000;\n background(0);\n directionalLight(color('#222'), 1, 1, 1);\n\n for (var i = 0; i < lights.length; i++) {\n var light = lights[i];\n pointLight(\n color(light.c),\n p5.Vector.fromAngles(t * light.t, t * light.p, width * light.r)\n );\n }\n\n specularMaterial(255);\n sphere(width * 0.1);\n\n rotateX(t * 0.77);\n rotateY(t * 0.83);\n rotateZ(t * 0.91);\n torus(width * 0.3, width * 0.07, 24, 10);\n}\n\nfunction mousePressed() {\n setAttributes('perPixelLighting', true);\n noStroke();\n fill(255);\n}\nfunction mouseReleased() {\n setAttributes('perPixelLighting', false);\n noStroke();\n fill(255);\n}\n
\nWrapper around gl.uniform functions.\nAs we store uniform info in the shader we can use that\nto do type checking on the supplied data and call\nthe appropriate function.
\n", "itemtype": "method", "name": "setUniform", @@ -18487,6 +18836,50 @@ module.exports={ { "file": "lib/addons/p5.dom.js", "line": 245, + "description": "The .changed() function is called when the value of an\nelement changes.\nThis can be used to attach an element specific event listener.
\n", + "itemtype": "method", + "name": "changed", + "params": [ + { + "name": "fxn", + "description": "function to be fired when the value of\n an element changes.\n if false
is passed instead, the previously\n firing function will no longer fire.
\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.
\n", + "itemtype": "method", + "name": "input", + "params": [ + { + "name": "fxn", + "description": "function to be fired when any user input is\n detected within the element.\n if false
is passed instead, the previously\n firing function will no longer fire.
\n// Open your console to see the output\nfunction setup() {\n var inp = createInput('');\n inp.input(myInputEvent);\n}\n\nfunction myInputEvent() {\n console.log('you are typing: ', this.value());\n}\n
Helpers for create methods.
\n", "class": "p5", "module": "p5.dom", @@ -18494,7 +18887,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 258, + "line": 361, "description": "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.
\n", "itemtype": "method", "name": "createDiv", @@ -18519,7 +18912,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 272, + "line": 375, "description": "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.
\n", "itemtype": "method", "name": "createP", @@ -18544,7 +18937,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 287, + "line": 390, "description": "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.
\n", "itemtype": "method", "name": "createSpan", @@ -18569,7 +18962,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 310, + "line": 413, "description": "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.
\n", "itemtype": "method", "name": "createImg", @@ -18585,7 +18978,7 @@ module.exports={ "submodule": "p5.dom", "overloads": [ { - "line": 310, + "line": 413, "params": [ { "name": "src", @@ -18611,7 +19004,7 @@ module.exports={ } }, { - "line": 326, + "line": 429, "params": [ { "name": "src", @@ -18633,7 +19026,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 359, + "line": 463, "description": "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.
\n", "itemtype": "method", "name": "createA", @@ -18668,14 +19061,14 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 384, + "line": 488, "class": "p5", "module": "p5.dom", "submodule": "p5.dom" }, { "file": "lib/addons/p5.dom.js", - "line": 386, + "line": 490, "description": "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.
\n", "itemtype": "method", "name": "createSlider", @@ -18716,7 +19109,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 443, + "line": 547, "description": "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.
\n", "itemtype": "method", "name": "createButton", @@ -18746,7 +19139,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 479, + "line": 583, "description": "Creates a checkbox <input></input> element in the DOM.\nCalling .checked() on a checkbox returns if it is checked or not
\n", "itemtype": "method", "name": "createCheckbox", @@ -18777,7 +19170,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 547, + "line": 651, "description": "Creates a dropdown menu <select></select> element in the DOM.\nIt also helps to assign select-box methods to p5.Element when selecting existing select box
\n", "itemtype": "method", "name": "createSelect", @@ -18786,14 +19179,14 @@ module.exports={ "type": "p5.Element" }, "example": [ - "\n\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 is a' + item + '!', 50, 50);\n}\n
\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 is a ' + item + '!', 50, 50);\n}\n
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.
\n", "itemtype": "method", "name": "createRadio", @@ -18850,7 +19243,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 789, + "line": 893, "description": "Creates a colorPicker element in the DOM for color input.\nThe .value() method will return a hex string (#rrggbb) of the color.\nThe .color() method will return a p5.Color object with the current chosen color.
\n", "itemtype": "method", "name": "createColorPicker", @@ -18875,7 +19268,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 863, + "line": 967, "description": "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.
\n", "itemtype": "method", "name": "createInput", @@ -18906,7 +19299,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 893, + "line": 997, "description": "Creates an <input></input> element in the DOM of type 'file'.\nThis allows users to select local files for use in a sketch.
\n", "itemtype": "method", "name": "createFileInput", @@ -18929,7 +19322,7 @@ module.exports={ "type": "p5.Element" }, "example": [ - "\n\nvar input;\nvar img;\n\nfunction setup() {\n input = createFileInput(handleFile);\n input.position(0, 0);\n}\n\nfunction draw() {\n if (img) {\n image(img, 0, 0, width, height);\n }\n}\n\nfunction handleFile(file) {\n print(file);\n if (file.type === 'image') {\n img = createImg(file.data);\n img.hide();\n }\n}\n
\nlet input;\nlet img;\n\nfunction setup() {\n input = createFileInput(handleFile);\n input.position(0, 0);\n}\n\nfunction draw() {\n background(255);\n if (img) {\n image(img, 0, 0, width, height);\n }\n}\n\nfunction handleFile(file) {\n print(file);\n if (file.type === 'image') {\n img = createImg(file.data);\n img.hide();\n } else {\n img = null;\n }\n}\n
Creates an HTML5 <video> element in the DOM for simple playback\nof audio/video. Shown by default, can be hidden with .hide()\nand drawn into canvas using 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.
\n", "itemtype": "method", "name": "createVideo", @@ -18966,7 +19359,7 @@ module.exports={ "type": "p5.MediaElement" }, "example": [ - "\n\nvar vid;\nfunction setup() {\n vid = createVideo(['small.mp4', 'small.ogv', 'small.webm'], vidLoad);\n}\n\n// This function is called when the video loads\nfunction vidLoad() {\n vid.play();\n}\n
\nvar vid;\nfunction setup() {\n noCanvas();\n\n vid = createVideo(\n ['assets/small.mp4', 'assets/small.ogv', 'assets/small.webm'],\n vidLoad\n );\n\n vid.size(100, 100);\n}\n\n// This function is called when the video loads\nfunction vidLoad() {\n vid.loop();\n vid.volume(0);\n}\n
Creates a hidden HTML5 <audio> element in the DOM for simple audio\nplayback. 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.
\n", "itemtype": "method", "name": "createAudio", @@ -19012,14 +19405,14 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 1102, + "line": 1199, "class": "p5", "module": "p5.dom", "submodule": "p5.dom" }, { "file": "lib/addons/p5.dom.js", - "line": 1104, + "line": 1201, "itemtype": "property", "name": "VIDEO", "type": "String", @@ -19033,7 +19426,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 1110, + "line": 1207, "itemtype": "property", "name": "AUDIO", "type": "String", @@ -19047,7 +19440,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 1147, + "line": 1244, "description": "Creates a new HTML5 <video> element that contains the audio/video\nfeed from a webcam. The element is separate from the canvas and is\ndisplayed by default. The element can be hidden using .hide(). The feed\ncan be drawn onto the canvas using image(). The loadedmetadata property can\nbe used to detect when the element has fully loaded (see second example).
\nMore 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.
\nSecurity 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.
", "itemtype": "method", "name": "createCapture", @@ -19069,7 +19462,7 @@ module.exports={ "type": "p5.Element" }, "example": [ - "\n\nvar capture;\n\nfunction setup() {\n createCanvas(480, 480);\n capture = createCapture(VIDEO);\n capture.hide();\n}\n\nfunction draw() {\n image(capture, 0, 0, width, width * capture.height / capture.width);\n filter(INVERT);\n}\n
\nfunction setup() {\n createCanvas(480, 120);\n var constraints = {\n video: {\n mandatory: {\n minWidth: 1280,\n minHeight: 720\n },\n optional: [{ maxFrameRate: 10 }]\n },\n audio: true\n };\n createCapture(constraints, function(stream) {\n console.log(stream);\n });\n}\n
\nvar capture;\n\nfunction setup() {\n createCanvas(640, 480);\n capture = createCapture(VIDEO);\n}\nfunction draw() {\n background(0);\n if (capture.loadedmetadata) {\n var c = capture.get(0, 0, 100, 100);\n image(c, 0, 0);\n }\n}"
+ "\n\nvar capture;\n\nfunction setup() {\n createCanvas(480, 480);\n capture = createCapture(VIDEO);\n capture.hide();\n}\n\nfunction draw() {\n image(capture, 0, 0, width, width * capture.height / capture.width);\n filter(INVERT);\n}\n
\n\nfunction setup() {\n createCanvas(480, 120);\n var constraints = {\n video: {\n mandatory: {\n minWidth: 1280,\n minHeight: 720\n },\n optional: [{ maxFrameRate: 10 }]\n },\n audio: true\n };\n createCapture(constraints, function(stream) {\n console.log(stream);\n });\n}\n
\n\nvar capture;\n\nfunction setup() {\n createCanvas(640, 480);\n capture = createCapture(VIDEO);\n}\nfunction draw() {\n background(0);\n if (capture.loadedmetadata) {\n var c = capture.get(0, 0, 100, 100);\n image(c, 0, 0);\n }\n}\n"
],
"class": "p5",
"module": "p5.dom",
@@ -19077,7 +19470,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 1283,
+ "line": 1381,
"description": "Creates element with given tag in the DOM with given content.\nAppends to the container node if one is specified, otherwise\nappends to body.
\n",
"itemtype": "method",
"name": "createElement",
@@ -19107,7 +19500,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 1309,
+ "line": 1407,
"description": "Adds specified class to the element.
\n",
"itemtype": "method",
"name": "addClass",
@@ -19128,7 +19521,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 1336,
+ "line": 1432,
"description": "Removes specified class from the element.
\n",
"itemtype": "method",
"name": "removeClass",
@@ -19149,7 +19542,52 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 1368,
+ "line": 1463,
+ "description": "Checks if specified class already set to element
\n",
+ "itemtype": "method",
+ "name": "hasClass",
+ "return": {
+ "description": "a boolean value if element has specified class",
+ "type": "Boolean"
+ },
+ "params": [
+ {
+ "name": "c",
+ "description": "class name of class to check
\n",
+ "type": "String"
+ }
+ ],
+ "example": [
+ "\n \n var div;\nfunction setup() {\n div = createDiv('div');\n div.addClass('show');\n }\nfunction mousePressed() {\n if (div.hasClass('show')) {\n div.addClass('show');\n } else {\n div.removeClass('show');\n }\n }\n
"
+ ],
+ "class": "p5.Element",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 1492,
+ "description": "Toggles element class
\n",
+ "itemtype": "method",
+ "name": "toggleClass",
+ "params": [
+ {
+ "name": "c",
+ "description": "class name to toggle
\n",
+ "type": "String"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n \n var div;\nfunction setup() {\n div = createDiv('div');\n div.addClass('show');\n }\nfunction mousePressed() {\n div.toggleClass('show');\n }\n
"
+ ],
+ "class": "p5.Element",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 1525,
"description": "Attaches the element as a child to the parent specified.\n Accepts either a string ID, DOM node, or p5.Element.\n If no argument is specified, an array of children DOM nodes is returned.
\n",
"itemtype": "method",
"name": "child",
@@ -19158,14 +19596,14 @@ module.exports={
"type": "Node[]"
},
"example": [
- "\n \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 \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 \n var div0 = createDiv('this is the parent');\n var elt = document.getElementById('myChildDiv');\n div0.child(elt); // use element from page\n
"
+ "\n \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 \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 \n // this example assumes there is a div already on the page\n // with id \"myChildDiv\"\n var div0 = createDiv('this is the parent');\n var elt = document.getElementById('myChildDiv');\n div0.child(elt); // use element from page\n
"
],
"class": "p5.Element",
"module": "p5.dom",
"submodule": "p5.dom",
"overloads": [
{
- "line": 1368,
+ "line": 1525,
"params": [],
"return": {
"description": "an array of child nodes",
@@ -19173,7 +19611,7 @@ module.exports={
}
},
{
- "line": 1394,
+ "line": 1553,
"params": [
{
"name": "child",
@@ -19188,7 +19626,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 1416,
+ "line": 1575,
"description": "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.
\n",
"itemtype": "method",
"name": "center",
@@ -19210,7 +19648,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 1470,
+ "line": 1629,
"description": "If an argument is given, sets the inner HTML of the element,\n replacing any existing html. If true is included as a second\n argument, html is appended instead of replacing existing html.\n If no arguments are given, returns\n the inner HTML of the element.
\n",
"itemtype": "method",
"name": "html",
@@ -19226,7 +19664,7 @@ module.exports={
"submodule": "p5.dom",
"overloads": [
{
- "line": 1470,
+ "line": 1629,
"params": [],
"return": {
"description": "the inner HTML of the element",
@@ -19234,7 +19672,7 @@ module.exports={
}
},
{
- "line": 1491,
+ "line": 1650,
"params": [
{
"name": "html",
@@ -19255,7 +19693,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 1509,
+ "line": 1668,
"description": "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.
\n",
"itemtype": "method",
"name": "position",
@@ -19271,7 +19709,7 @@ module.exports={
"submodule": "p5.dom",
"overloads": [
{
- "line": 1509,
+ "line": 1668,
"params": [],
"return": {
"description": "the x and y position of the element in an object",
@@ -19279,7 +19717,7 @@ module.exports={
}
},
{
- "line": 1528,
+ "line": 1687,
"params": [
{
"name": "x",
@@ -19300,8 +19738,8 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 1603,
- "description": "Sets the given style (css) property (1st arg) of the element with the\ngiven value (2nd arg). If a single argument is given, .style()\nreturns the value of the given property; however, if 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);
\n",
+ "line": 1762,
+ "description": "Sets the given style (css) property (1st arg) of the element with the\ngiven value (2nd arg). If a single argument is given, .style()\nreturns the value of the given property; however, if the single argument\nis given in css syntax ('text-align:center'), .style() sets the css\nappropriately.
\n",
"itemtype": "method",
"name": "style",
"return": {
@@ -19309,14 +19747,14 @@ module.exports={
"type": "String"
},
"example": [
- "\n\nvar myDiv = createDiv('I like pandas.');\nmyDiv.style('font-size', '18px');\nmyDiv.style('color', '#ff0000');\n
\n\nvar col = color(25, 23, 200, 50);\nvar button = createButton('button');\nbutton.style('background-color', col);\nbutton.position(10, 10);\n
\n\nvar myDiv = createDiv('I like lizards.');\nmyDiv.style('position', 20, 20);\nmyDiv.style('rotate', 45);\n
\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
"
+ "\n\nvar myDiv = createDiv('I like pandas.');\nmyDiv.style('font-size', '18px');\nmyDiv.style('color', '#ff0000');\n
\n\nvar col = color(25, 23, 200, 50);\nvar button = createButton('button');\nbutton.style('background-color', col);\nbutton.position(10, 10);\n
\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
"
],
"class": "p5.Element",
"module": "p5.dom",
"submodule": "p5.dom",
"overloads": [
{
- "line": 1603,
+ "line": 1762,
"params": [
{
"name": "property",
@@ -19330,7 +19768,7 @@ module.exports={
}
},
{
- "line": 1645,
+ "line": 1797,
"params": [
{
"name": "property",
@@ -19339,29 +19777,21 @@ module.exports={
},
{
"name": "value",
- "description": "value to assign to property (only String|Number for rotate/translate)
\n",
+ "description": "value to assign to property
\n",
"type": "String|Number|p5.Color"
- },
- {
- "name": "value2",
- "description": "position can take a 2nd value
\n",
- "type": "String|Number|p5.Color",
- "optional": true
- },
- {
- "name": "value3",
- "description": "translate can take a 2nd & 3rd value
\n",
- "type": "String|Number|p5.Color",
- "optional": true
}
],
- "chainable": 1
+ "chainable": 1,
+ "return": {
+ "description": "current value of property, if no value is given as second argument",
+ "type": "String"
+ }
}
]
},
{
"file": "lib/addons/p5.dom.js",
- "line": 1704,
+ "line": 1851,
"description": "Adds a new attribute or changes the value of an existing attribute\n on the specified element. If no value is specified, returns the\n value of the given attribute, or null if attribute is not set.
\n",
"itemtype": "method",
"name": "attribute",
@@ -19377,7 +19807,7 @@ module.exports={
"submodule": "p5.dom",
"overloads": [
{
- "line": 1704,
+ "line": 1851,
"params": [],
"return": {
"description": "value of attribute",
@@ -19385,7 +19815,7 @@ module.exports={
}
},
{
- "line": 1719,
+ "line": 1866,
"params": [
{
"name": "attr",
@@ -19404,7 +19834,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 1748,
+ "line": 1895,
"description": "Removes an attribute on the specified element.
\n",
"itemtype": "method",
"name": "removeAttribute",
@@ -19425,7 +19855,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 1793,
+ "line": 1940,
"description": "Either returns the value of the element if no arguments\ngiven, or sets the value of the element.
\n",
"itemtype": "method",
"name": "value",
@@ -19441,7 +19871,7 @@ module.exports={
"submodule": "p5.dom",
"overloads": [
{
- "line": 1793,
+ "line": 1940,
"params": [],
"return": {
"description": "value of the element",
@@ -19449,7 +19879,7 @@ module.exports={
}
},
{
- "line": 1823,
+ "line": 1970,
"params": [
{
"name": "value",
@@ -19463,7 +19893,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 1839,
+ "line": 1986,
"description": "Shows the current element. Essentially, setting display:block for the style.
\n",
"itemtype": "method",
"name": "show",
@@ -19477,7 +19907,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 1857,
+ "line": 2004,
"description": "Hides the current element. Essentially, setting display:none for the style.
\n",
"itemtype": "method",
"name": "hide",
@@ -19491,8 +19921,8 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 1873,
- "description": "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.
\n",
+ "line": 2020,
+ "description": "Sets the width and height of the element. AUTO can be used to\n only adjust one dimension at a time. If no arguments are given, it\n returns the width and height of the element in an object. In case of\n elements which need to be loaded, such as images, it is recommended\n to call the function after the element has finished loading.
\n",
"itemtype": "method",
"name": "size",
"return": {
@@ -19500,14 +19930,14 @@ module.exports={
"type": "Object"
},
"example": [
- "\n \n var div = createDiv('this is a div');\n div.size(100, 100);\n
"
+ "\n \n let div = createDiv('this is a div');\n div.size(100, 100);\n let img = createImg('assets/laDefense.jpg', () => {\n img.size(10, AUTO);\n });\n
"
],
"class": "p5.Element",
"module": "p5.dom",
"submodule": "p5.dom",
"overloads": [
{
- "line": 1873,
+ "line": 2020,
"params": [],
"return": {
"description": "the width and height of the element in an object",
@@ -19515,7 +19945,7 @@ module.exports={
}
},
{
- "line": 1887,
+ "line": 2039,
"params": [
{
"name": "w",
@@ -19535,7 +19965,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 1951,
+ "line": 2099,
"description": "Removes the element and deregisters all listeners.
\n",
"itemtype": "method",
"name": "remove",
@@ -19548,7 +19978,35 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 1999,
+ "line": 2119,
+ "description": "Registers a callback that gets called every time a file that is\ndropped on the element has been loaded.\np5 will load every dropped file into memory and pass it as a p5.File object to the callback.\nMultiple files dropped at the same time will result in multiple calls to the callback.
\nYou can optionally pass a second callback which will be registered to the raw\ndrop event.\nThe callback will thus be provided the original\nDragEvent.\nDropping multiple files at the same time will trigger the second callback once per drop,\nwhereas the first callback will trigger for each loaded file.
\n",
+ "itemtype": "method",
+ "name": "drop",
+ "params": [
+ {
+ "name": "callback",
+ "description": "callback to receive loaded file, called for each file dropped.
\n",
+ "type": "Function"
+ },
+ {
+ "name": "fxn",
+ "description": "callback triggered once when files are dropped with the drop event.
\n",
+ "type": "Function",
+ "optional": true
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\nfunction setup() {\n var c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('drop file', width / 2, height / 2);\n c.drop(gotFile);\n}\n\nfunction gotFile(file) {\n background(200);\n text('received file:', width / 2, height / 2);\n text(file.name, width / 2, height / 2 + 50);\n}\n
\n\n\nvar img;\n\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 draw() {\n if (img) {\n image(img, 0, 0, width, height);\n }\n}\n\nfunction gotFile(file) {\n img = createImg(file.data).hide();\n}\n
"
+ ],
+ "alt": "Canvas turns into whatever image is dragged/dropped onto it.",
+ "class": "p5.Element",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2253,
"description": "Path to the media element source.
\n",
"itemtype": "property",
"name": "src",
@@ -19565,7 +20023,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 2065,
+ "line": 2319,
"description": "Play an HTML5 media element.
\n",
"itemtype": "method",
"name": "play",
@@ -19579,7 +20037,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 2126,
+ "line": 2380,
"description": "Stops an HTML5 media element (sets current time to zero).
\n",
"itemtype": "method",
"name": "stop",
@@ -19593,7 +20051,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 2190,
+ "line": 2444,
"description": "Pauses an HTML5 media element.
\n",
"itemtype": "method",
"name": "pause",
@@ -19607,7 +20065,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 2252,
+ "line": 2506,
"description": "Set 'loop' to true for an HTML5 media element, and starts playing.
\n",
"itemtype": "method",
"name": "loop",
@@ -19621,7 +20079,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 2308,
+ "line": 2562,
"description": "Set 'loop' to false for an HTML5 media element. Element will stop\nwhen it reaches the end.
\n",
"itemtype": "method",
"name": "noLoop",
@@ -19635,7 +20093,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 2360,
+ "line": 2614,
"description": "Set HTML5 media element to autoplay or not.
\n",
"itemtype": "method",
"name": "autoplay",
@@ -19653,7 +20111,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 2372,
+ "line": 2626,
"description": "Sets volume for this HTML5 media element. If no argument is given,\nreturns the current volume.
\n",
"itemtype": "method",
"name": "volume",
@@ -19669,7 +20127,7 @@ module.exports={
"submodule": "p5.dom",
"overloads": [
{
- "line": 2372,
+ "line": 2626,
"params": [],
"return": {
"description": "current volume",
@@ -19677,7 +20135,7 @@ module.exports={
}
},
{
- "line": 2445,
+ "line": 2699,
"params": [
{
"name": "val",
@@ -19691,7 +20149,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 2458,
+ "line": 2712,
"description": "If no arguments are given, returns the current playback speed of the\nelement. The speed parameter sets the speed where 2.0 will play the\nelement twice as fast, 0.5 will play at half the speed, and -1 will play\nthe element in normal speed in reverse.(Note that not all browsers support\nbackward playback and even if they do, playback might not be smooth.)
\n",
"itemtype": "method",
"name": "speed",
@@ -19707,7 +20165,7 @@ module.exports={
"submodule": "p5.dom",
"overloads": [
{
- "line": 2458,
+ "line": 2712,
"params": [],
"return": {
"description": "current playback speed of the element",
@@ -19715,7 +20173,7 @@ module.exports={
}
},
{
- "line": 2529,
+ "line": 2783,
"params": [
{
"name": "speed",
@@ -19729,7 +20187,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 2546,
+ "line": 2800,
"description": "If no arguments are given, returns the current time of the element.\nIf an argument is given the current time of the element is set to it.
\n",
"itemtype": "method",
"name": "time",
@@ -19745,7 +20203,7 @@ module.exports={
"submodule": "p5.dom",
"overloads": [
{
- "line": 2546,
+ "line": 2800,
"params": [],
"return": {
"description": "current time (in seconds)",
@@ -19753,7 +20211,7 @@ module.exports={
}
},
{
- "line": 2591,
+ "line": 2845,
"params": [
{
"name": "time",
@@ -19767,7 +20225,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 2605,
+ "line": 2859,
"description": "Returns the duration of the HTML5 media element.
\n",
"itemtype": "method",
"name": "duration",
@@ -19784,7 +20242,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 2746,
+ "line": 2998,
"description": "Schedule an event to be called when the audio or video\nelement reaches the end. If the element is looping,\nthis will not be called. The element is passed in\nas the argument to the onended callback.
\n",
"itemtype": "method",
"name": "onended",
@@ -19805,14 +20263,14 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 2777,
+ "line": 3029,
"class": "p5.MediaElement",
"module": "p5.dom",
"submodule": "p5.dom"
},
{
"file": "lib/addons/p5.dom.js",
- "line": 2779,
+ "line": 3031,
"description": "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.
\nThis method is meant to be used with the p5.sound.js addon library.
\n",
"itemtype": "method",
"name": "connect",
@@ -19829,7 +20287,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 2828,
+ "line": 3080,
"description": "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.
\n",
"itemtype": "method",
"name": "disconnect",
@@ -19839,14 +20297,14 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 2843,
+ "line": 3095,
"class": "p5.MediaElement",
"module": "p5.dom",
"submodule": "p5.dom"
},
{
"file": "lib/addons/p5.dom.js",
- "line": 2845,
+ "line": 3097,
"description": "Show the default MediaElement controls, as determined by the web browser.
\n",
"itemtype": "method",
"name": "showControls",
@@ -19859,7 +20317,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 2876,
+ "line": 3128,
"description": "Hide the default mediaElement controls.
\n",
"itemtype": "method",
"name": "hideControls",
@@ -19872,14 +20330,14 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 2905,
+ "line": 3157,
"class": "p5.MediaElement",
"module": "p5.dom",
"submodule": "p5.dom"
},
{
"file": "lib/addons/p5.dom.js",
- "line": 2916,
+ "line": 3168,
"description": "Schedule events to trigger every time a MediaElement\n(audio/video) reaches a playback cue point.
\nAccepts a callback function, a time (in seconds) at which to trigger\nthe callback, and an optional parameter for the callback.
\nTime will be passed as the first parameter to the callback function,\nand param will be the second parameter.
\n",
"itemtype": "method",
"name": "addCue",
@@ -19914,7 +20372,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 2980,
+ "line": 3232,
"description": "Remove a callback based on its ID. The ID is returned by the\naddCue method.
\n",
"itemtype": "method",
"name": "removeCue",
@@ -19934,7 +20392,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 3022,
+ "line": 3274,
"description": "Remove all of the callbacks that had originally been scheduled\nvia the addCue method.
\n",
"itemtype": "method",
"name": "clearCues",
@@ -19954,7 +20412,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 3092,
+ "line": 3340,
"description": "Underlying File object. All normal File methods can be called on this.
\n",
"itemtype": "property",
"name": "file",
@@ -19964,7 +20422,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 3104,
+ "line": 3352,
"description": "File type (image, text, etc.)
\n",
"itemtype": "property",
"name": "type",
@@ -19974,7 +20432,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 3110,
+ "line": 3358,
"description": "File subtype (usually the file extension jpg, png, xml, etc.)
\n",
"itemtype": "property",
"name": "subtype",
@@ -19984,7 +20442,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 3116,
+ "line": 3364,
"description": "File name
\n",
"itemtype": "property",
"name": "name",
@@ -19994,7 +20452,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 3122,
+ "line": 3370,
"description": "File size
\n",
"itemtype": "property",
"name": "size",
@@ -20004,7 +20462,7 @@ module.exports={
},
{
"file": "lib/addons/p5.dom.js",
- "line": 3129,
+ "line": 3377,
"description": "URL string containing image data.
\n",
"itemtype": "property",
"name": "data",
@@ -20030,7 +20488,28 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 262,
+ "line": 363,
+ "class": "p5.sound",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 740,
+ "class": "p5.sound",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 810,
+ "class": "p5.sound",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1005,
"description": "Returns the Audio Context for this sketch. Useful for users\nwho would like to dig deeper into the Web Audio API\n.
\n\nSome browsers require users to startAudioContext\nwith a user gesture, such as touchStarted in the example below.
",
"itemtype": "method",
"name": "getAudioContext",
@@ -20047,7 +20526,38 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 328,
+ "line": 1042,
+ "description": "It is a good practice to give users control over starting audio playback.\nThis practice is enforced by Google Chrome's autoplay policy as of r70\n(info), iOS Safari, and other browsers.\n
\n\n\nuserStartAudio() starts the Audio Context on a user gesture. It utilizes\nthe StartAudioContext library by\nYotam Mann (MIT Licence, 2016). Read more at https://github.com/tambien/StartAudioContext.\n
\n\nStarting the audio context on a user gesture can be as simple as userStartAudio()
.\nOptional parameters let you decide on a specific element that will start the audio context,\nand/or call a function once the audio context is started.
",
+ "params": [
+ {
+ "name": "element(s)",
+ "description": "This argument can be an Element,\n Selector String, NodeList, p5.Element,\n jQuery Element, or an Array of any of those.
\n",
+ "type": "Element|Array",
+ "optional": true
+ },
+ {
+ "name": "callback",
+ "description": "Callback to invoke when the AudioContext has started
\n",
+ "type": "Function",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "Returns a Promise which is resolved when\n the AudioContext state is 'running'",
+ "type": "Promise"
+ },
+ "itemtype": "method",
+ "name": "userStartAudio",
+ "example": [
+ "\n\nfunction setup() {\n var myDiv = createDiv('click to start audio');\n myDiv.position(0, 0);\n\n var mySynth = new p5.MonoSynth();\n\n // This won't play until the context has started\n mySynth.play('A6');\n\n // Start the audio context on a click/touch event\n userStartAudio().then(function() {\n myDiv.remove();\n });\n}\n
"
+ ],
+ "class": "p5.sound",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1099,
"description": "Master contains AudioContext and the master sound output.
\n",
"class": "p5.sound",
"module": "p5.sound",
@@ -20055,7 +20565,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 361,
+ "line": 1132,
"description": "Returns a number representing the master amplitude (volume) for sound\nin this sketch.
\n",
"itemtype": "method",
"name": "getMasterVolume",
@@ -20069,7 +20579,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 372,
+ "line": 1143,
"description": "Scale the output of all sound in this sketch
\nScaled between 0.0 (silence) and 1.0 (full volume).\n1.0 is the maximum amplitude of a digital sound, so multiplying\nby greater than 1.0 may cause digital distortion. To\nfade, provide a rampTime
parameter. For more\ncomplex fades, see the Envelope class.\n\nAlternately, you can pass in a signal source such as an\noscillator to modulate the amplitude with an audio signal.\n\nHow This Works: When you load the p5.sound module, it\ncreates a single instance of p5sound. All sound objects in this\nmodule output to p5sound before reaching your computer's output.\nSo if you change the amplitude of p5sound, it impacts all of the\nsound in this module.
\n\nIf no value is provided, returns a Web Audio API Gain Node
",
"itemtype": "method",
"name": "masterVolume",
@@ -20098,7 +20608,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 414,
+ "line": 1185,
"description": "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
.
\n",
"itemtype": "property",
"name": "soundOut",
@@ -20109,14 +20619,14 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 439,
+ "line": 1210,
"class": "p5",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 442,
+ "line": 1213,
"description": "Returns a number representing the sample rate, in samples per second,\nof all sound objects in this audio context. It is determined by the\nsampling rate of your operating system's sound card, and it is not\ncurrently possile to change.\nIt is often 44100, or twice the range of human hearing.
\n",
"itemtype": "method",
"name": "sampleRate",
@@ -20130,7 +20640,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 455,
+ "line": 1226,
"description": "Returns the closest MIDI note value for\na given frequency.
\n",
"itemtype": "method",
"name": "freqToMidi",
@@ -20151,7 +20661,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 469,
+ "line": 1240,
"description": "Returns the frequency value of a MIDI note value.\nGeneral MIDI treats notes as integers where middle C\nis 60, C# is 61, D is 62 etc. Useful for generating\nmusical frequencies with oscillators.
\n",
"itemtype": "method",
"name": "midiToFreq",
@@ -20175,7 +20685,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 531,
+ "line": 1302,
"description": "List the SoundFile formats that you will include. LoadSound\nwill search your directory for these extensions, and will pick\na format that is compatable with the client's web browser.\nHere is a free online file\nconverter.
\n",
"itemtype": "method",
"name": "soundFormats",
@@ -20197,7 +20707,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 644,
+ "line": 1415,
"description": "Used by Osc and Envelope to chain signal math
\n",
"class": "p5",
"module": "p5.sound",
@@ -20205,7 +20715,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 923,
+ "line": 1763,
"description": "loadSound() returns a new p5.SoundFile from a specified\npath. If called during preload(), the p5.SoundFile will be ready\nto play in time for setup() and draw(). If called outside of\npreload, the p5.SoundFile will not be ready immediately, so\nloadSound accepts a callback as the second parameter. Using a\n\nlocal server is recommended when loading external files.
\n",
"itemtype": "method",
"name": "loadSound",
@@ -20247,7 +20757,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1065,
+ "line": 1919,
"description": "Returns true if the sound file finished loading successfully.
\n",
"itemtype": "method",
"name": "isLoaded",
@@ -20261,7 +20771,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1078,
+ "line": 1932,
"description": "Play the p5.SoundFile
\n",
"itemtype": "method",
"name": "play",
@@ -20303,7 +20813,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1183,
+ "line": 2022,
"description": "p5.SoundFile has two play modes: restart
and\nsustain
. Play Mode determines what happens to a\np5.SoundFile if it is triggered while in the middle of playback.\nIn sustain mode, playback will continue simultaneous to the\nnew playback. In restart mode, play() will stop playback\nand start over. With untilDone, a sound will play only if it's\nnot already playing. Sustain is the default mode.
\n",
"itemtype": "method",
"name": "playMode",
@@ -20323,7 +20833,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1227,
+ "line": 2066,
"description": "Pauses a file that is currently playing. If the file is not\nplaying, then nothing will happen.
\nAfter pausing, .play() will resume from the paused\nposition.\nIf p5.SoundFile had been set to loop before it was paused,\nit will continue to loop after it is unpaused with .play().
\n",
"itemtype": "method",
"name": "pause",
@@ -20344,7 +20854,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1283,
+ "line": 2122,
"description": "Loop the p5.SoundFile. Accepts optional parameters to set the\nplayback rate, playback volume, loopStart, loopEnd.
\n",
"itemtype": "method",
"name": "loop",
@@ -20386,7 +20896,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1299,
+ "line": 2138,
"description": "Set a p5.SoundFile's looping flag to true or false. If the sound\nis currently playing, this change will take effect when it\nreaches the end of the current playback.
\n",
"itemtype": "method",
"name": "setLoop",
@@ -20403,7 +20913,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1320,
+ "line": 2159,
"description": "Returns 'true' if a p5.SoundFile is currently looping and playing, 'false' if not.
\n",
"itemtype": "method",
"name": "isLooping",
@@ -20417,7 +20927,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1335,
+ "line": 2174,
"description": "Returns true if a p5.SoundFile is playing, false if not (i.e.\npaused or stopped).
\n",
"itemtype": "method",
"name": "isPlaying",
@@ -20431,7 +20941,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1345,
+ "line": 2184,
"description": "Returns true if a p5.SoundFile is paused, false if not (i.e.\nplaying or stopped).
\n",
"itemtype": "method",
"name": "isPaused",
@@ -20445,7 +20955,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1355,
+ "line": 2194,
"description": "Stop soundfile playback.
\n",
"itemtype": "method",
"name": "stop",
@@ -20463,7 +20973,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1401,
+ "line": 2239,
"description": "Multiply the output volume (amplitude) of a sound file\nbetween 0.0 (silence) and 1.0 (full volume).\n1.0 is the maximum amplitude of a digital sound, so multiplying\nby greater than 1.0 may cause digital distortion. To\nfade, provide a rampTime
parameter. For more\ncomplex fades, see the Envelope class.
\nAlternately, you can pass in a signal source such as an\noscillator to modulate the amplitude with an audio signal.
\n",
"itemtype": "method",
"name": "setVolume",
@@ -20492,7 +21002,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1442,
+ "line": 2280,
"description": "Set the stereo panning of a p5.sound object to\na floating point number between -1.0 (left) and 1.0 (right).\nDefault is 0.0 (center).
\n",
"itemtype": "method",
"name": "pan",
@@ -20519,7 +21029,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1481,
+ "line": 2319,
"description": "Returns the current stereo pan position (-1.0 to 1.0)
\n",
"itemtype": "method",
"name": "getPan",
@@ -20533,7 +21043,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1492,
+ "line": 2330,
"description": "Set the playback rate of a sound file. Will change the speed and the pitch.\nValues less than zero will reverse the audio buffer.
\n",
"itemtype": "method",
"name": "rate",
@@ -20554,7 +21064,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1565,
+ "line": 2403,
"description": "Returns the duration of a sound file in seconds.
\n",
"itemtype": "method",
"name": "duration",
@@ -20568,7 +21078,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1579,
+ "line": 2417,
"description": "Return the current position of the p5.SoundFile playhead, in seconds.\nTime is relative to the normal buffer direction, so if reverseBuffer
\nhas been called, currentTime will count backwards.
\n",
"itemtype": "method",
"name": "currentTime",
@@ -20582,7 +21092,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1590,
+ "line": 2428,
"description": "Move the playhead of the song to a position, in seconds. Start timing\nand playback duration. If none are given, will reset the file to play\nentire duration from start to finish.
\n",
"itemtype": "method",
"name": "jump",
@@ -20604,7 +21114,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1613,
+ "line": 2451,
"description": "Return the number of channels in a sound file.\nFor example, Mono = 1, Stereo = 2.
\n",
"itemtype": "method",
"name": "channels",
@@ -20618,7 +21128,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1623,
+ "line": 2461,
"description": "Return the sample rate of the sound file.
\n",
"itemtype": "method",
"name": "sampleRate",
@@ -20632,7 +21142,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1632,
+ "line": 2470,
"description": "Return the number of samples in a sound file.\nEqual to sampleRate * duration.
\n",
"itemtype": "method",
"name": "frames",
@@ -20646,7 +21156,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1642,
+ "line": 2480,
"description": "Returns an array of amplitude peaks in a p5.SoundFile that can be\nused to draw a static waveform. Scans through the p5.SoundFile's\naudio buffer to find the greatest amplitudes. Accepts one\nparameter, 'length', which determines size of the array.\nLarger arrays result in more precise waveform visualizations.
\nInspired by Wavesurfer.js.
\n",
"itemtype": "method",
"name": "getPeaks",
@@ -20668,7 +21178,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1694,
+ "line": 2532,
"description": "Reverses the p5.SoundFile's buffer source.\nPlayback must be handled separately (see example).
\n",
"itemtype": "method",
"name": "reverseBuffer",
@@ -20681,7 +21191,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1734,
+ "line": 2572,
"description": "Schedule an event to be called when the soundfile\nreaches the end of a buffer. If the soundfile is\nplaying through once, this will be called when it\nends. If it is looping, it will be called when\nstop is called.
\n",
"itemtype": "method",
"name": "onended",
@@ -20698,7 +21208,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1787,
+ "line": 2625,
"description": "Connects the output of a p5sound object to input of another\np5.sound object. For example, you may connect a p5.SoundFile to an\nFFT or an Effect. If no parameter is given, it will connect to\nthe master output. Most p5sound objects connect to the master\noutput when they are created.
\n",
"itemtype": "method",
"name": "connect",
@@ -20716,7 +21226,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1808,
+ "line": 2646,
"description": "Disconnects the output of this p5sound object.
\n",
"itemtype": "method",
"name": "disconnect",
@@ -20726,14 +21236,14 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1818,
+ "line": 2656,
"class": "p5.SoundFile",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1823,
+ "line": 2661,
"description": "Reset the source for this SoundFile to a\nnew path (URL).
\n",
"itemtype": "method",
"name": "setPath",
@@ -20755,7 +21265,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1836,
+ "line": 2674,
"description": "Replace the current Audio Buffer with a new Buffer.
\n",
"itemtype": "method",
"name": "setBuffer",
@@ -20772,7 +21282,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 1908,
+ "line": 2741,
"description": "processPeaks returns an array of timestamps where it thinks there is a beat.
\nThis is an asynchronous function that processes the soundfile in an offline audio context,\nand sends the results to your callback function.
\nThe 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.
\n",
"itemtype": "method",
"name": "processPeaks",
@@ -20811,14 +21321,14 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 2099,
+ "line": 2934,
"class": "p5.SoundFile",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 2108,
+ "line": 2943,
"description": "Schedule events to trigger every time a MediaElement\n(audio/video) reaches a playback cue point.
\nAccepts a callback function, a time (in seconds) at which to trigger\nthe callback, and an optional parameter for the callback.
\nTime will be passed as the first parameter to the callback function,\nand param will be the second parameter.
\n",
"itemtype": "method",
"name": "addCue",
@@ -20853,7 +21363,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 2186,
+ "line": 3021,
"description": "Remove a callback based on its ID. The ID is returned by the\naddCue method.
\n",
"itemtype": "method",
"name": "removeCue",
@@ -20870,7 +21380,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 2204,
+ "line": 3040,
"description": "Remove all of the callbacks that had originally been scheduled\nvia the addCue method.
\n",
"itemtype": "method",
"name": "clearCues",
@@ -20880,7 +21390,45 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 2312,
+ "line": 3065,
+ "description": "Save a p5.SoundFile as a .wav file. The browser will prompt the user\nto download the file to their device. To upload a file to a server, see\ngetBlob
\n",
+ "itemtype": "method",
+ "name": "save",
+ "params": [
+ {
+ "name": "fileName",
+ "description": "name of the resulting .wav file.
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n \n var inp, button, mySound;\n var fileName = 'cool';\n function preload() {\n mySound = loadSound('assets/doorbell.mp3');\n }\n function setup() {\n btn = createButton('click to save file');\n btn.position(0, 0);\n btn.mouseClicked(handleMouseClick);\n }\n\n function handleMouseClick() {\n mySound.save(fileName);\n }\n
"
+ ],
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 3094,
+ "description": "This method is useful for sending a SoundFile to a server. It returns the\n.wav-encoded audio data as a "Blob".\nA Blob is a file-like data object that can be uploaded to a server\nwith an http request. We'll\nuse the httpDo
options object to send a POST request with some\nspecific options: we encode the request as multipart/form-data
,\nand attach the blob as one of the form values using FormData
.
\n",
+ "itemtype": "method",
+ "name": "getBlob",
+ "return": {
+ "description": "A file-like data object",
+ "type": "Blob"
+ },
+ "example": [
+ "\n \n\n function preload() {\n mySound = loadSound('assets/doorbell.mp3');\n }\n\n function setup() {\n noCanvas();\n var soundBlob = mySound.getBlob();\n\n // Now we can send the blob to a server...\n var serverUrl = 'https://jsonplaceholder.typicode.com/posts';\n var httpRequestOptions = {\n method: 'POST',\n body: new FormData().append('soundBlob', soundBlob),\n headers: new Headers({\n 'Content-Type': 'multipart/form-data'\n })\n };\n httpDo(serverUrl, httpRequestOptions);\n\n // We can also create an `ObjectURL` pointing to the Blob\n var blobUrl = URL.createObjectURL(soundBlob);\n\n // The `
"
+ ],
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 3257,
"description": "Connects to the p5sound instance (master output) by default.\nOptionally, you can pass in a specific source (i.e. a soundfile).
\n",
"itemtype": "method",
"name": "setInput",
@@ -20907,7 +21455,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 2419,
+ "line": 3364,
"description": "Returns a single Amplitude reading at the moment it is called.\nFor continuous readings, run in the draw loop.
\n",
"itemtype": "method",
"name": "getLevel",
@@ -20932,7 +21480,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 2460,
+ "line": 3405,
"description": "Determines whether the results of Amplitude.process() will be\nNormalized. To normalize, Amplitude finds the difference the\nloudest reading it has processed and the maximum amplitude of\n1.0. Amplitude adds this difference to all values to produce\nresults that will reliably map between 0.0 and 1.0. However,\nif a louder moment occurs, the amount that Normalize adds to\nall the values will change. Accepts an optional boolean parameter\n(true or false). Normalizing is off by default.
\n",
"itemtype": "method",
"name": "toggleNormalize",
@@ -20950,7 +21498,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 2480,
+ "line": 3425,
"description": "Smooth Amplitude analysis by averaging with the last analysis\nframe. Off by default.
\n",
"itemtype": "method",
"name": "smooth",
@@ -20967,7 +21515,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 2654,
+ "line": 3599,
"description": "Set the input source for the FFT analysis. If no source is\nprovided, FFT will analyze all sound in the sketch.
\n",
"itemtype": "method",
"name": "setInput",
@@ -20985,7 +21533,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 2673,
+ "line": 3618,
"description": "Returns an array of amplitude values (between -1.0 and +1.0) that represent\na snapshot of amplitude readings in a single buffer. Length will be\nequal to bins (defaults to 1024). Can be used to draw the waveform\nof a sound.
\n",
"itemtype": "method",
"name": "waveform",
@@ -21013,7 +21561,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 2716,
+ "line": 3661,
"description": "Returns an array of amplitude values (between 0 and 255)\nacross the frequency spectrum. Length is equal to FFT bins\n(1024 by default). The array indices correspond to frequencies\n(i.e. pitches), from the lowest to the highest that humans can\nhear. Each value represents amplitude at that slice of the\nfrequency spectrum. Must be called prior to using\ngetEnergy()
.
\n",
"itemtype": "method",
"name": "analyze",
@@ -21044,7 +21592,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 2808,
+ "line": 3753,
"description": "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.
\n",
"itemtype": "method",
"name": "getEnergy",
@@ -21071,7 +21619,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 2890,
+ "line": 3835,
"description": "Returns the\n\nspectral centroid of the input signal.\nNOTE: analyze() must be called prior to getCentroid(). Analyze()\ntells the FFT to analyze frequency data, and getCentroid() uses\nthe results determine the spectral centroid.
\n",
"itemtype": "method",
"name": "getCentroid",
@@ -21088,7 +21636,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 2970,
+ "line": 3915,
"description": "Smooth FFT analysis by averaging with the last analysis frame.
\n",
"itemtype": "method",
"name": "smooth",
@@ -21105,7 +21653,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 2992,
+ "line": 3937,
"description": "Returns an array of average amplitude values for a given number\nof frequency bands split equally. N defaults to 16.\nNOTE: analyze() must be called prior to linAverages(). Analyze()\ntells the FFT to analyze frequency data, and linAverages() uses\nthe results to group them into a smaller set of averages.
\n",
"itemtype": "method",
"name": "linAverages",
@@ -21126,7 +21674,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 3022,
+ "line": 3967,
"description": "Returns an array of average amplitude values of the spectrum, for a given\nset of \nOctave Bands\nNOTE: analyze() must be called prior to logAverages(). Analyze()\ntells the FFT to analyze frequency data, and logAverages() uses\nthe results to group them into a smaller set of averages.
\n",
"itemtype": "method",
"name": "logAverages",
@@ -21147,7 +21695,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 3052,
+ "line": 3997,
"description": "Calculates and Returns the 1/N\nOctave Bands\nN defaults to 3 and minimum central frequency to 15.625Hz.\n(1/3 Octave Bands ~= 31 Frequency Bands)\nSetting fCtr0 to a central value of a higher octave will ignore the lower bands\nand produce less frequency groups.
\n",
"itemtype": "method",
"name": "getOctaveBands",
@@ -21173,119 +21721,98 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 3110,
- "class": "p5.FFT",
- "module": "p5.sound",
- "submodule": "p5.sound"
- },
- {
- "file": "lib/addons/p5.sound.js",
- "line": 3487,
- "class": "p5.FFT",
- "module": "p5.sound",
- "submodule": "p5.sound"
- },
- {
- "file": "lib/addons/p5.sound.js",
- "line": 3508,
- "class": "p5.FFT",
- "module": "p5.sound",
- "submodule": "p5.sound"
- },
- {
- "file": "lib/addons/p5.sound.js",
- "line": 3567,
+ "line": 4055,
"class": "p5.FFT",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 3885,
+ "line": 4076,
"class": "p5.FFT",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 4057,
+ "line": 4135,
"class": "p5.FFT",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 4215,
+ "line": 4453,
"class": "p5.FFT",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 4256,
+ "line": 4625,
"class": "p5.FFT",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 4326,
+ "line": 4783,
"class": "p5.FFT",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 4514,
+ "line": 4824,
"class": "p5.FFT",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 4571,
+ "line": 4881,
"class": "p5.FFT",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 4739,
+ "line": 5049,
"class": "p5.FFT",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 4787,
+ "line": 5097,
"class": "p5.FFT",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 4818,
+ "line": 5128,
"class": "p5.FFT",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 4839,
+ "line": 5149,
"class": "p5.FFT",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 4859,
+ "line": 5169,
"class": "p5.FFT",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 4961,
+ "line": 5268,
"description": "Fade to value, for smooth transitions
\n",
"itemtype": "method",
"name": "fade",
@@ -21308,7 +21835,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 4972,
+ "line": 5279,
"description": "Connect a p5.sound object or Web Audio node to this\np5.Signal so that its amplitude values can be scaled.
\n",
"itemtype": "method",
"name": "setInput",
@@ -21325,7 +21852,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 4986,
+ "line": 5293,
"description": "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.
\n",
"itemtype": "method",
"name": "add",
@@ -21346,7 +21873,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 5005,
+ "line": 5312,
"description": "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.
\n",
"itemtype": "method",
"name": "mult",
@@ -21367,7 +21894,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 5024,
+ "line": 5331,
"description": "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.
\n",
"itemtype": "method",
"name": "scale",
@@ -21408,7 +21935,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 5158,
+ "line": 5465,
"description": "Start an oscillator. Accepts an optional parameter to\ndetermine how long (in seconds from now) until the\noscillator starts.
\n",
"itemtype": "method",
"name": "start",
@@ -21432,7 +21959,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 5198,
+ "line": 5505,
"description": "Stop an oscillator. Accepts an optional parameter\nto determine how long (in seconds from now) until the\noscillator stops.
\n",
"itemtype": "method",
"name": "stop",
@@ -21449,7 +21976,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 5214,
+ "line": 5521,
"description": "Set the amplitude between 0 and 1.0. Or, pass in an object\nsuch as an oscillator to modulate amplitude with an audio signal.
\n",
"itemtype": "method",
"name": "amp",
@@ -21482,7 +22009,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 5249,
+ "line": 5556,
"description": "Set frequency of an oscillator to a value. Or, pass in an object\nsuch as an oscillator to modulate the frequency with an audio signal.
\n",
"itemtype": "method",
"name": "freq",
@@ -21518,7 +22045,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 5308,
+ "line": 5615,
"description": "Set type to 'sine', 'triangle', 'sawtooth' or 'square'.
\n",
"itemtype": "method",
"name": "setType",
@@ -21535,7 +22062,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 5320,
+ "line": 5627,
"description": "Connect to a p5.sound / Web Audio object.
\n",
"itemtype": "method",
"name": "connect",
@@ -21552,7 +22079,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 5337,
+ "line": 5644,
"description": "Disconnect all outputs
\n",
"itemtype": "method",
"name": "disconnect",
@@ -21562,7 +22089,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 5354,
+ "line": 5661,
"description": "Pan between Left (-1) and Right (1)
\n",
"itemtype": "method",
"name": "pan",
@@ -21584,7 +22111,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 5386,
+ "line": 5693,
"description": "Set the phase of an oscillator between 0.0 and 1.0.\nIn this implementation, phase is a delay time\nbased on the oscillator's current frequency.
\n",
"itemtype": "method",
"name": "phase",
@@ -21601,7 +22128,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 5440,
+ "line": 5747,
"description": "Add a value to the p5.Oscillator's output amplitude,\nand return the oscillator. Calling this method again\nwill override the initial add() with a new value.
\n",
"itemtype": "method",
"name": "add",
@@ -21622,7 +22149,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 5457,
+ "line": 5764,
"description": "Multiply the p5.Oscillator's output amplitude\nby a fixed value (i.e. turn it up!). Calling this method\nagain will override the initial mult() with a new value.
\n",
"itemtype": "method",
"name": "mult",
@@ -21643,7 +22170,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 5473,
+ "line": 5780,
"description": "Scale this oscillator's amplitude values to a given\nrange, and return the oscillator. Calling this method\nagain will override the initial scale() with new values.
\n",
"itemtype": "method",
"name": "scale",
@@ -21679,21 +22206,21 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 5572,
+ "line": 5879,
"class": "p5.SqrOsc",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 5775,
+ "line": 6082,
"class": "p5.SqrOsc",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 6064,
+ "line": 6369,
"description": "Time until envelope reaches attackLevel
\n",
"itemtype": "property",
"name": "attackTime",
@@ -21703,7 +22230,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 6069,
+ "line": 6374,
"description": "Level once attack is complete.
\n",
"itemtype": "property",
"name": "attackLevel",
@@ -21713,7 +22240,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 6074,
+ "line": 6379,
"description": "Time until envelope reaches decayLevel.
\n",
"itemtype": "property",
"name": "decayTime",
@@ -21723,7 +22250,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 6079,
+ "line": 6384,
"description": "Level after decay. The envelope will sustain here until it is released.
\n",
"itemtype": "property",
"name": "decayLevel",
@@ -21733,7 +22260,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 6084,
+ "line": 6389,
"description": "Duration of the release portion of the envelope.
\n",
"itemtype": "property",
"name": "releaseTime",
@@ -21743,7 +22270,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 6089,
+ "line": 6394,
"description": "Level at the end of the release.
\n",
"itemtype": "property",
"name": "releaseLevel",
@@ -21753,7 +22280,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 6125,
+ "line": 6430,
"description": "Reset the envelope with a series of time/value pairs.
\n",
"itemtype": "method",
"name": "set",
@@ -21798,7 +22325,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 6184,
+ "line": 6489,
"description": "Set values like a traditional\n\nADSR envelope\n.
\n",
"itemtype": "method",
"name": "setADSR",
@@ -21828,7 +22355,7 @@ module.exports={
}
],
"example": [
- "\n\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.Envelope();\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
"
+ "\n\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.Envelope();\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
"
],
"class": "p5.Envelope",
"module": "p5.sound",
@@ -21836,7 +22363,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 6249,
+ "line": 6554,
"description": "Set max (attackLevel) and min (releaseLevel) of envelope.
\n",
"itemtype": "method",
"name": "setRange",
@@ -21853,7 +22380,7 @@ module.exports={
}
],
"example": [
- "\n\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.Envelope();\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
"
+ "\n\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.Envelope();\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
"
],
"class": "p5.Envelope",
"module": "p5.sound",
@@ -21861,7 +22388,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 6328,
+ "line": 6633,
"description": "Assign a parameter to be controlled by this envelope.\nIf a p5.Sound object is given, then the p5.Envelope will control its\noutput gain. If multiple inputs are provided, the env will\ncontrol all of them.
\n",
"itemtype": "method",
"name": "setInput",
@@ -21880,7 +22407,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 6343,
+ "line": 6648,
"description": "Set whether the envelope ramp is linear (default) or exponential.\nExponential ramps can be useful because we perceive amplitude\nand frequency logarithmically.
\n",
"itemtype": "method",
"name": "setExp",
@@ -21897,7 +22424,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 6361,
+ "line": 6666,
"description": "Play tells the envelope to start acting on a given input.\nIf the input is a p5.sound object (i.e. AudioIn, Oscillator,\nSoundFile), then Envelope will control its output volume.\nEnvelopes can also be used to control any \nWeb Audio Audio Param.
\n",
"itemtype": "method",
"name": "play",
@@ -21921,7 +22448,7 @@ module.exports={
}
],
"example": [
- "\n\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.Envelope();\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
"
+ "\n\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.Envelope();\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
"
],
"class": "p5.Envelope",
"module": "p5.sound",
@@ -21929,7 +22456,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 6422,
+ "line": 6727,
"description": "Trigger the Attack, and Decay portion of the Envelope.\nSimilar to holding down a key on a piano, but it will\nhold the sustain level until you let go. Input can be\nany p5.sound object, or a \nWeb Audio Param.
\n",
"itemtype": "method",
"name": "triggerAttack",
@@ -21946,7 +22473,7 @@ module.exports={
}
],
"example": [
- "\n\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.Envelope();\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
"
+ "\n\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.Envelope();\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
"
],
"class": "p5.Envelope",
"module": "p5.sound",
@@ -21954,7 +22481,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 6529,
+ "line": 6834,
"description": "Trigger the Release of the Envelope. This is similar to releasing\nthe key on a piano and letting the sound fade according to the\nrelease level and release time.
\n",
"itemtype": "method",
"name": "triggerRelease",
@@ -21971,7 +22498,7 @@ module.exports={
}
],
"example": [
- "\n\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.Envelope();\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
"
+ "\n\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.Envelope();\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
"
],
"class": "p5.Envelope",
"module": "p5.sound",
@@ -21979,7 +22506,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 6626,
+ "line": 6931,
"description": "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.
\n",
"itemtype": "method",
"name": "ramp",
@@ -22015,7 +22542,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 6733,
+ "line": 7038,
"description": "Add a value to the p5.Oscillator's output amplitude,\nand return the oscillator. Calling this method\nagain will override the initial add() with new values.
\n",
"itemtype": "method",
"name": "add",
@@ -22036,7 +22563,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 6749,
+ "line": 7054,
"description": "Multiply the p5.Envelope's output amplitude\nby a fixed value. Calling this method\nagain will override the initial mult() with new values.
\n",
"itemtype": "method",
"name": "mult",
@@ -22057,7 +22584,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 6765,
+ "line": 7070,
"description": "Scale this envelope's amplitude values to a given\nrange, and return the envelope. Calling this method\nagain will override the initial scale() with new values.
\n",
"itemtype": "method",
"name": "scale",
@@ -22093,7 +22620,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 6873,
+ "line": 7178,
"description": "Set the width of a Pulse object (an oscillator that implements\nPulse Width Modulation).
\n",
"itemtype": "method",
"name": "width",
@@ -22111,7 +22638,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 7060,
+ "line": 7365,
"description": "Set type of noise to 'white', 'pink' or 'brown'.\nWhite is the default.
\n",
"itemtype": "method",
"name": "setType",
@@ -22129,7 +22656,57 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 7178,
+ "line": 7478,
+ "itemtype": "property",
+ "name": "input",
+ "type": "GainNode",
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7482,
+ "itemtype": "property",
+ "name": "output",
+ "type": "GainNode",
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7486,
+ "itemtype": "property",
+ "name": "stream",
+ "type": "MediaStream|null",
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7490,
+ "itemtype": "property",
+ "name": "mediaStream",
+ "type": "MediaStreamAudioSourceNode|null",
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7494,
+ "itemtype": "property",
+ "name": "currentSource",
+ "type": "Number|null",
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7498,
"description": "Client must allow browser to access their microphone / audioin source.\nDefault: false. Will become true when the client enables acces.
\n",
"itemtype": "property",
"name": "enabled",
@@ -22140,7 +22717,18 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 7194,
+ "line": 7505,
+ "description": "Input amplitude, connect to it by default but not to master out
\n",
+ "itemtype": "property",
+ "name": "amplitude",
+ "type": "p5.Amplitude",
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7518,
"description": "Start processing audio input. This enables the use of other\nAudioIn methods like getLevel(). Note that by default, AudioIn\nis not connected to p5.sound's output. So you won't hear\nanything unless you use the connect() method.
\nCertain browsers limit access to the user's microphone. For example,\nChrome only allows access from localhost and over https. For this reason,\nyou may want to include an errorCallback—a function that is called in case\nthe browser won't provide mic access.
\n",
"itemtype": "method",
"name": "start",
@@ -22164,7 +22752,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 7247,
+ "line": 7571,
"description": "Turn the AudioIn off. If the AudioIn is stopped, it cannot getLevel().\nIf re-starting, the user may be prompted for permission access.
\n",
"itemtype": "method",
"name": "stop",
@@ -22174,7 +22762,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 7263,
+ "line": 7587,
"description": "Connect to an audio unit. If no parameter is provided, will\nconnect to the master output (i.e. your speakers).
\n",
"itemtype": "method",
"name": "connect",
@@ -22192,7 +22780,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 7284,
+ "line": 7608,
"description": "Disconnect the AudioIn from all audio units. For example, if\nconnect() had been called, disconnect() will stop sending\nsignal to your speakers.
\n",
"itemtype": "method",
"name": "disconnect",
@@ -22202,7 +22790,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 7298,
+ "line": 7622,
"description": "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().
\n",
"itemtype": "method",
"name": "getLevel",
@@ -22224,7 +22812,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 7316,
+ "line": 7640,
"description": "Set amplitude (volume) of a mic input between 0 and 1.0.
\n",
"itemtype": "method",
"name": "amp",
@@ -22247,8 +22835,8 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 7335,
- "description": "Returns a list of available input sources. This is a wrapper\nfor <a title="MediaDevices.enumerateDevices() - Web APIs | MDN" target="_blank" href=\n "https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices"
\n\nand it returns a Promise.
\n
\n",
+ "line": 7659,
+ "description": "Returns a list of available input sources. This is a wrapper\nfor <a title="MediaDevices.enumerateDevices() - Web APIs | MDN" target="_blank" href=\n "https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices"
\n\nand it returns a Promise.
\n
\n",
"itemtype": "method",
"name": "getSources",
"params": [
@@ -22278,8 +22866,8 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 7386,
- "description": "Set the input source. Accepts a number representing a\nposition in the array returned by getSources().\nThis is only available in browsers that support\n<a title="MediaDevices.enumerateDevices() - Web APIs | MDN" target="_blank" href=\n"https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices"
\n\nnavigator.mediaDevices.enumerateDevices().
\n
\n",
+ "line": 7710,
+ "description": "Set the input source. Accepts a number representing a\nposition in the array returned by getSources().\nThis is only available in browsers that support\n<a title="MediaDevices.enumerateDevices() - Web APIs | MDN" target="_blank" href=\n"https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices"
\n\nnavigator.mediaDevices.enumerateDevices().
\n
\n",
"itemtype": "method",
"name": "setSource",
"params": [
@@ -22295,84 +22883,84 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 7426,
+ "line": 7750,
"class": "p5.AudioIn",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 7442,
+ "line": 7766,
"class": "p5.AudioIn",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 7466,
+ "line": 7790,
"class": "p5.AudioIn",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 7492,
+ "line": 7816,
"class": "p5.AudioIn",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 7514,
+ "line": 7838,
"class": "p5.AudioIn",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 7536,
+ "line": 7860,
"class": "p5.AudioIn",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 7582,
+ "line": 7906,
"class": "p5.AudioIn",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 7613,
+ "line": 7937,
"class": "p5.AudioIn",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 7631,
+ "line": 7955,
"class": "p5.AudioIn",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 7968,
+ "line": 8292,
"class": "p5.AudioIn",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 7990,
+ "line": 8314,
"class": "p5.AudioIn",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8066,
+ "line": 8390,
"description": "In classes that extend\np5.Effect, connect effect nodes\nto the wet parameter
\n",
"class": "p5.Effect",
"module": "p5.sound",
@@ -22380,7 +22968,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8079,
+ "line": 8403,
"description": "Set the output volume of the filter.
\n",
"itemtype": "method",
"name": "amp",
@@ -22410,7 +22998,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8096,
+ "line": 8420,
"description": "Link effects together in a chain
Example usage: filter.chain(reverb, delay, panner);\nMay be used with an open-ended number of arguments
\n",
"itemtype": "method",
"name": "chain",
@@ -22428,7 +23016,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8113,
+ "line": 8437,
"description": "Adjust the dry/wet value.
\n",
"itemtype": "method",
"name": "drywet",
@@ -22446,7 +23034,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8125,
+ "line": 8449,
"description": "Send output to a p5.js-sound, Web Audio Node, or use signal to\ncontrol an AudioParam
\n",
"itemtype": "method",
"name": "connect",
@@ -22463,7 +23051,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8136,
+ "line": 8460,
"description": "Disconnect all output.
\n",
"itemtype": "method",
"name": "disconnect",
@@ -22473,7 +23061,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8254,
+ "line": 8578,
"description": "The p5.Filter is built with a\n\nWeb Audio BiquadFilter Node.
\n",
"itemtype": "property",
"name": "biquadFilter",
@@ -22484,7 +23072,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8272,
+ "line": 8596,
"description": "Filter an audio signal according to a set\nof filter parameters.
\n",
"itemtype": "method",
"name": "process",
@@ -22513,7 +23101,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8286,
+ "line": 8610,
"description": "Set the frequency and the resonance of the filter.
\n",
"itemtype": "method",
"name": "set",
@@ -22543,7 +23131,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8303,
+ "line": 8627,
"description": "Set the filter frequency, in Hz, from 10 to 22050 (the range of\nhuman hearing, although in reality most people hear in a narrower\nrange).
\n",
"itemtype": "method",
"name": "freq",
@@ -22570,7 +23158,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8328,
+ "line": 8651,
"description": "Controls either width of a bandpass frequency,\nor the resonance of a low/highpass cutoff frequency.
\n",
"itemtype": "method",
"name": "res",
@@ -22597,7 +23185,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8350,
+ "line": 8673,
"description": "Controls the gain attribute of a Biquad Filter.\nThis is distinctly different from .amp() which is inherited from p5.Effect\n.amp() controls the volume via the output gain node\np5.Filter.gain() controls the gain parameter of a Biquad Filter node.
\n",
"itemtype": "method",
"name": "gain",
@@ -22618,7 +23206,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8371,
+ "line": 8694,
"description": "Toggle function. Switches between the specified type and allpass
\n",
"itemtype": "method",
"name": "toggle",
@@ -22632,7 +23220,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8386,
+ "line": 8709,
"description": "Set the type of a p5.Filter. Possible types include:\n"lowpass" (default), "highpass", "bandpass",\n"lowshelf", "highshelf", "peaking", "notch",\n"allpass".
\n",
"itemtype": "method",
"name": "setType",
@@ -22649,7 +23237,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8593,
+ "line": 8916,
"description": "The p5.EQ is built with abstracted p5.Filter objects.\nTo modify any bands, use methods of the \np5.Filter API, especially gain
and freq
.\nBands are stored in an array, with indices 0 - 3, or 0 - 7
\n",
"itemtype": "property",
"name": "bands",
@@ -22660,7 +23248,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8628,
+ "line": 8951,
"description": "Process an input by connecting it to the EQ
\n",
"itemtype": "method",
"name": "process",
@@ -22677,8 +23265,8 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8716,
- "description": "\nWeb Audio Spatial Panner Node
\nProperties include
\n\n- <a title="w3 spec for Panning Model"\nhref="https://www.w3.org/TR/webaudio/#idl-def-PanningModelType"
\npanningModel: "equal power" or "HRTF"
\n
\n \n- <a title="w3 spec for Distance Model"\nhref="https://www.w3.org/TR/webaudio/#idl-def-DistanceModelType"
\ndistanceModel: "linear", "inverse", or "exponential"
\n
\n \n
\n",
+ "line": 9039,
+ "description": "\nWeb Audio Spatial Panner Node
\nProperties include
\n\n- <a title="w3 spec for Panning Model"\nhref="https://www.w3.org/TR/webaudio/#idl-def-PanningModelType"
\npanningModel: "equal power" or "HRTF"
\n
\n \n- <a title="w3 spec for Distance Model"\nhref="https://www.w3.org/TR/webaudio/#idl-def-DistanceModelType"
\ndistanceModel: "linear", "inverse", or "exponential"
\n
\n \n
\n",
"itemtype": "property",
"name": "panner",
"type": "AudioNode",
@@ -22688,7 +23276,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8739,
+ "line": 9062,
"description": "Connect an audio sorce
\n",
"itemtype": "method",
"name": "process",
@@ -22705,7 +23293,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8748,
+ "line": 9071,
"description": "Set the X,Y,Z position of the Panner
\n",
"itemtype": "method",
"name": "set",
@@ -22741,7 +23329,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8767,
+ "line": 9090,
"description": "Getter and setter methods for position coordinates
\n",
"itemtype": "method",
"name": "positionX",
@@ -22755,7 +23343,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8772,
+ "line": 9095,
"description": "Getter and setter methods for position coordinates
\n",
"itemtype": "method",
"name": "positionY",
@@ -22769,7 +23357,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8777,
+ "line": 9100,
"description": "Getter and setter methods for position coordinates
\n",
"itemtype": "method",
"name": "positionZ",
@@ -22783,7 +23371,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8815,
+ "line": 9138,
"description": "Set the X,Y,Z position of the Panner
\n",
"itemtype": "method",
"name": "orient",
@@ -22819,7 +23407,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8834,
+ "line": 9157,
"description": "Getter and setter methods for orient coordinates
\n",
"itemtype": "method",
"name": "orientX",
@@ -22833,7 +23421,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8839,
+ "line": 9162,
"description": "Getter and setter methods for orient coordinates
\n",
"itemtype": "method",
"name": "orientY",
@@ -22847,7 +23435,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8844,
+ "line": 9167,
"description": "Getter and setter methods for orient coordinates
\n",
"itemtype": "method",
"name": "orientZ",
@@ -22861,7 +23449,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8882,
+ "line": 9205,
"description": "Set the rolloff factor and max distance
\n",
"itemtype": "method",
"name": "setFalloff",
@@ -22885,7 +23473,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8892,
+ "line": 9215,
"description": "Maxium distance between the source and the listener
\n",
"itemtype": "method",
"name": "maxDist",
@@ -22906,7 +23494,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 8904,
+ "line": 9227,
"description": "How quickly the volume is reduced as the source moves away from the listener
\n",
"itemtype": "method",
"name": "rollof",
@@ -22927,7 +23515,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9209,
+ "line": 9532,
"description": "The p5.Delay is built with two\n\nWeb Audio Delay Nodes, one for each stereo channel.
\n",
"itemtype": "property",
"name": "leftDelay",
@@ -22938,7 +23526,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9217,
+ "line": 9540,
"description": "The p5.Delay is built with two\n\nWeb Audio Delay Nodes, one for each stereo channel.
\n",
"itemtype": "property",
"name": "rightDelay",
@@ -22949,7 +23537,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9249,
+ "line": 9572,
"description": "Add delay to an audio signal according to a set\nof delay parameters.
\n",
"itemtype": "method",
"name": "process",
@@ -22984,7 +23572,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9284,
+ "line": 9607,
"description": "Set the delay (echo) time, in seconds. Usually this value will be\na floating point number between 0.0 and 1.0.
\n",
"itemtype": "method",
"name": "delayTime",
@@ -23001,7 +23589,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9303,
+ "line": 9626,
"description": "Feedback occurs when Delay sends its signal back through its input\nin a loop. The feedback amount determines how much signal to send each\ntime through the loop. A feedback greater than 1.0 is not desirable because\nit will increase the overall output each time through the loop,\ncreating an infinite feedback loop. The default value is 0.5
\n",
"itemtype": "method",
"name": "feedback",
@@ -23022,7 +23610,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9331,
+ "line": 9654,
"description": "Set a lowpass filter frequency for the delay. A lowpass filter\nwill cut off any frequencies higher than the filter frequency.
\n",
"itemtype": "method",
"name": "filter",
@@ -23044,7 +23632,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9348,
+ "line": 9671,
"description": "Choose a preset type of delay. 'pingPong' bounces the signal\nfrom the left to the right channel to produce a stereo effect.\nAny other parameter will revert to the default delay setting.
\n",
"itemtype": "method",
"name": "setType",
@@ -23061,7 +23649,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9381,
+ "line": 9704,
"description": "Set the output level of the delay effect.
\n",
"itemtype": "method",
"name": "amp",
@@ -23090,7 +23678,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9390,
+ "line": 9713,
"description": "Send output to a p5.sound or web audio object
\n",
"itemtype": "method",
"name": "connect",
@@ -23107,7 +23695,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9396,
+ "line": 9719,
"description": "Disconnect all output.
\n",
"itemtype": "method",
"name": "disconnect",
@@ -23117,7 +23705,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9475,
+ "line": 9812,
"description": "Connect a source to the reverb, and assign reverb parameters.
\n",
"itemtype": "method",
"name": "process",
@@ -23152,7 +23740,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9504,
+ "line": 9841,
"description": "Set the reverb settings. Similar to .process(), but without\nassigning a new input.
\n",
"itemtype": "method",
"name": "set",
@@ -23182,7 +23770,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9532,
+ "line": 9869,
"description": "Set the output level of the reverb effect.
\n",
"itemtype": "method",
"name": "amp",
@@ -23211,7 +23799,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9541,
+ "line": 9878,
"description": "Send output to a p5.sound or web audio object
\n",
"itemtype": "method",
"name": "connect",
@@ -23228,7 +23816,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9547,
+ "line": 9884,
"description": "Disconnect all output.
\n",
"itemtype": "method",
"name": "disconnect",
@@ -23238,10 +23826,10 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9641,
+ "line": 9975,
"description": "Internally, the p5.Convolver uses the a\n\nWeb Audio Convolver Node.
\n",
"itemtype": "property",
- "name": "convolverNod",
+ "name": "convolverNode",
"type": "ConvolverNode",
"class": "p5.Convolver",
"module": "p5.sound",
@@ -23249,7 +23837,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9666,
+ "line": 9998,
"description": "Create a p5.Convolver. Accepts a path to a soundfile\nthat will be used to generate an impulse response.
\n",
"itemtype": "method",
"name": "createConvolver",
@@ -23285,7 +23873,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9790,
+ "line": 10122,
"description": "Connect a source to the reverb, and assign reverb parameters.
\n",
"itemtype": "method",
"name": "process",
@@ -23305,7 +23893,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9822,
+ "line": 10154,
"description": "If you load multiple impulse files using the .addImpulse method,\nthey will be stored as Objects in this Array. Toggle between them\nwith the toggleImpulse(id)
method.
\n",
"itemtype": "property",
"name": "impulses",
@@ -23316,7 +23904,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9830,
+ "line": 10162,
"description": "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.
\n",
"itemtype": "method",
"name": "addImpulse",
@@ -23343,7 +23931,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9848,
+ "line": 10180,
"description": "Similar to .addImpulse, except that the .impulses
\nArray is reset to save memory. A new .impulses
\narray is created with this impulse as the only item.
\n",
"itemtype": "method",
"name": "resetImpulse",
@@ -23370,7 +23958,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9866,
+ "line": 10198,
"description": "If you have used .addImpulse()
to add multiple impulses\nto a p5.Convolver, then you can use this method to toggle between\nthe items in the .impulses
Array. Accepts a parameter\nto identify which impulse you wish to use, identified either by its\noriginal filename (String) or by its position in the .impulses\n
Array (Number).
\nYou can access the objects in the .impulses Array directly. Each\nObject has two attributes: an .audioBuffer
(type:\nWeb Audio \nAudioBuffer) and a .name
, a String that corresponds\nwith the original filename.
\n",
"itemtype": "method",
"name": "toggleImpulse",
@@ -23387,21 +23975,21 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9912,
+ "line": 10240,
"class": "p5.Convolver",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 9937,
+ "line": 10265,
"class": "p5.Convolver",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10132,
+ "line": 10460,
"description": "Set the global tempo, in beats per minute, for all\np5.Parts. This method will impact all active p5.Parts.
\n",
"itemtype": "method",
"name": "setBPM",
@@ -23423,7 +24011,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10222,
+ "line": 10550,
"description": "Array of values to pass into the callback\nat each step of the phrase. Depending on the callback\nfunction's requirements, these values may be numbers,\nstrings, or an object with multiple parameters.\nZero (0) indicates a rest.
\n",
"itemtype": "property",
"name": "sequence",
@@ -23434,7 +24022,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10310,
+ "line": 10638,
"description": "Set the tempo of this part, in Beats Per Minute.
\n",
"itemtype": "method",
"name": "setBPM",
@@ -23457,8 +24045,8 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10320,
- "description": "Returns the Beats Per Minute of this currently part.
\n",
+ "line": 10648,
+ "description": "Returns the tempo, in Beats Per Minute, of this part.
\n",
"itemtype": "method",
"name": "getBPM",
"return": {
@@ -23471,7 +24059,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10329,
+ "line": 10657,
"description": "Start playback of this part. It will play\nthrough all of its phrases at a speed\ndetermined by setBPM.
\n",
"itemtype": "method",
"name": "start",
@@ -23489,7 +24077,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10345,
+ "line": 10673,
"description": "Loop playback of this part. It will begin\nlooping through all of its phrases at a speed\ndetermined by setBPM.
\n",
"itemtype": "method",
"name": "loop",
@@ -23507,7 +24095,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10362,
+ "line": 10690,
"description": "Tell the part to stop looping.
\n",
"itemtype": "method",
"name": "noLoop",
@@ -23517,8 +24105,8 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10374,
- "description": "Stop the part and cue it to step 0.
\n",
+ "line": 10702,
+ "description": "Stop the part and cue it to step 0. Playback will resume from the begining of the Part when it is played again.
\n",
"itemtype": "method",
"name": "stop",
"params": [
@@ -23535,7 +24123,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10384,
+ "line": 10712,
"description": "Pause the part. Playback will resume\nfrom the current step.
\n",
"itemtype": "method",
"name": "pause",
@@ -23552,7 +24140,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10396,
+ "line": 10724,
"description": "Add a p5.Phrase to this Part.
\n",
"itemtype": "method",
"name": "addPhrase",
@@ -23569,7 +24157,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10417,
+ "line": 10745,
"description": "Remove a phrase from this part, based on the name it was\ngiven when it was created.
\n",
"itemtype": "method",
"name": "removePhrase",
@@ -23586,7 +24174,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10431,
+ "line": 10759,
"description": "Get a phrase from this part, based on the name it was\ngiven when it was created. Now you can modify its array.
\n",
"itemtype": "method",
"name": "getPhrase",
@@ -23603,8 +24191,8 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10445,
- "description": "Get a phrase from this part, based on the name it was\ngiven when it was created. Now you can modify its array.
\n",
+ "line": 10773,
+ "description": "Find all sequences with the specified name, and replace their patterns with the specified array.
\n",
"itemtype": "method",
"name": "replaceSequence",
"params": [
@@ -23625,8 +24213,8 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10473,
- "description": "Fire a callback function at every step.
\n",
+ "line": 10800,
+ "description": "Set the function that will be called at every step. This will clear the previous function.
\n",
"itemtype": "method",
"name": "onStep",
"params": [
@@ -23642,7 +24230,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10526,
+ "line": 10853,
"description": "Start playback of the score.
\n",
"itemtype": "method",
"name": "start",
@@ -23652,7 +24240,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10535,
+ "line": 10862,
"description": "Stop playback of the score.
\n",
"itemtype": "method",
"name": "stop",
@@ -23662,7 +24250,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10545,
+ "line": 10872,
"description": "Pause playback of the score.
\n",
"itemtype": "method",
"name": "pause",
@@ -23672,7 +24260,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10553,
+ "line": 10880,
"description": "Loop playback of the score.
\n",
"itemtype": "method",
"name": "loop",
@@ -23682,7 +24270,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10562,
+ "line": 10889,
"description": "Stop looping playback of the score. If it\nis currently playing, this will go into effect\nafter the current round of playback completes.
\n",
"itemtype": "method",
"name": "noLoop",
@@ -23692,7 +24280,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10587,
+ "line": 10914,
"description": "Set the tempo for all parts in the score
\n",
"itemtype": "method",
"name": "setBPM",
@@ -23714,7 +24302,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10655,
+ "line": 10982,
"description": "musicalTimeMode uses Tone.Time convention\ntrue if string, false if number
\n",
"itemtype": "property",
"name": "musicalTimeMode",
@@ -23725,7 +24313,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10662,
+ "line": 10989,
"description": "musicalTimeMode variables\nmodify these only when the interval is specified in musicalTime format as a string
\n",
"class": "p5.SoundLoop",
"module": "p5.sound",
@@ -23733,7 +24321,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10669,
+ "line": 10996,
"description": "Set a limit to the number of loops to play. defaults to Infinity
\n",
"itemtype": "property",
"name": "maxIterations",
@@ -23744,7 +24332,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10678,
+ "line": 11005,
"description": "Do not initiate the callback if timeFromNow is < 0\nThis ususually occurs for a few milliseconds when the page\nis not fully loaded
\nThe callback should only be called until maxIterations is reached
\n",
"class": "p5.SoundLoop",
"module": "p5.sound",
@@ -23752,7 +24340,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10692,
+ "line": 11019,
"description": "Start the loop
\n",
"itemtype": "method",
"name": "start",
@@ -23770,7 +24358,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10705,
+ "line": 11032,
"description": "Stop the loop
\n",
"itemtype": "method",
"name": "stop",
@@ -23788,7 +24376,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10718,
+ "line": 11045,
"description": "Pause the loop
\n",
"itemtype": "method",
"name": "pause",
@@ -23806,7 +24394,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10731,
+ "line": 11058,
"description": "Synchronize loops. Use this method to start two more more loops in synchronization\nor to start a loop in synchronization with a loop that is already playing\nThis method will schedule the implicit loop in sync with the explicit master loop\ni.e. loopToStart.syncedStart(loopToSyncWith)
\n",
"itemtype": "method",
"name": "syncedStart",
@@ -23829,7 +24417,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10812,
+ "line": 11139,
"description": "Getters and Setters, setting any paramter will result in a change in the clock's\nfrequency, that will be reflected after the next callback\nbeats per minute (defaults to 60)
\n",
"itemtype": "property",
"name": "bpm",
@@ -23840,7 +24428,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10830,
+ "line": 11157,
"description": "number of quarter notes in a measure (defaults to 4)
\n",
"itemtype": "property",
"name": "timeSignature",
@@ -23851,7 +24439,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10846,
+ "line": 11173,
"description": "length of the loops interval
\n",
"itemtype": "property",
"name": "interval",
@@ -23862,7 +24450,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10860,
+ "line": 11187,
"description": "how many times the callback has been called so far
\n",
"itemtype": "property",
"name": "iterations",
@@ -23874,7 +24462,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10901,
+ "line": 11228,
"description": "The p5.Compressor is built with a Web Audio Dynamics Compressor Node\n
\n",
"itemtype": "property",
"name": "compressor",
@@ -23885,7 +24473,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10912,
+ "line": 11239,
"description": "Performs the same function as .connect, but also accepts\noptional parameters to set compressor's audioParams
\n",
"itemtype": "method",
"name": "process",
@@ -23932,7 +24520,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10935,
+ "line": 11262,
"description": "Set the paramters of a compressor.
\n",
"itemtype": "method",
"name": "set",
@@ -23969,7 +24557,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10967,
+ "line": 11294,
"description": "Get current attack or set value w/ time ramp
\n",
"itemtype": "method",
"name": "attack",
@@ -23993,7 +24581,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 10987,
+ "line": 11314,
"description": "Get current knee or set value w/ time ramp
\n",
"itemtype": "method",
"name": "knee",
@@ -24017,7 +24605,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11007,
+ "line": 11334,
"description": "Get current ratio or set value w/ time ramp
\n",
"itemtype": "method",
"name": "ratio",
@@ -24041,7 +24629,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11026,
+ "line": 11353,
"description": "Get current threshold or set value w/ time ramp
\n",
"itemtype": "method",
"name": "threshold",
@@ -24064,7 +24652,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11045,
+ "line": 11372,
"description": "Get current release or set value w/ time ramp
\n",
"itemtype": "method",
"name": "release",
@@ -24087,7 +24675,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11065,
+ "line": 11392,
"description": "Return the current reduction value
\n",
"itemtype": "method",
"name": "reduction",
@@ -24101,7 +24689,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11180,
+ "line": 11508,
"description": "Connect a specific device to the p5.SoundRecorder.\nIf no parameter is given, p5.SoundRecorer will record\nall audible p5.sound from your sketch.
\n",
"itemtype": "method",
"name": "setInput",
@@ -24119,7 +24707,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11201,
+ "line": 11529,
"description": "Start recording. To access the recording, provide\na p5.SoundFile as the first parameter. The p5.SoundRecorder\nwill send its recording to that p5.SoundFile for playback once\nrecording is complete. Optional parameters include duration\n(in seconds) of the recording, and a callback function that\nwill be called once the complete recording has been\ntransfered to the p5.SoundFile.
\n",
"itemtype": "method",
"name": "record",
@@ -24148,7 +24736,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11234,
+ "line": 11562,
"description": "Stop the recording. Once the recording is stopped,\nthe results will be sent to the p5.SoundFile that\nwas given on .record(), and if a callback function\nwas provided on record, that function will be called.
\n",
"itemtype": "method",
"name": "stop",
@@ -24158,8 +24746,8 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11307,
- "description": "Save a p5.SoundFile as a .wav audio file.
\n",
+ "line": 11635,
+ "description": "Save a p5.SoundFile as a .wav file. The browser will prompt the user\nto download the file to their device.\nFor uploading audio to a server, use\np5.SoundFile.saveBlob
.
\n",
"itemtype": "method",
"name": "saveSound",
"params": [
@@ -24169,18 +24757,18 @@ module.exports={
"type": "p5.SoundFile"
},
{
- "name": "name",
+ "name": "fileName",
"description": "name of the resulting .wav file.
\n",
"type": "String"
}
],
- "class": "p5.SoundRecorder",
+ "class": "p5",
"module": "p5.sound",
"submodule": "p5.sound"
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11484,
+ "line": 11761,
"description": "isDetected is set to true when a peak is detected.
\n",
"itemtype": "attribute",
"name": "isDetected",
@@ -24192,7 +24780,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11497,
+ "line": 11774,
"description": "The update method is run in the draw loop.
\nAccepts an FFT object. You must call .analyze()\non the FFT object prior to updating the peakDetect\nbecause it relies on a completed FFT analysis.
\n",
"itemtype": "method",
"name": "update",
@@ -24209,7 +24797,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11528,
+ "line": 11805,
"description": "onPeak accepts two arguments: a function to call when\na peak is detected. The value of the peak,\nbetween 0.0 and 1.0, is passed to the callback.
\n",
"itemtype": "method",
"name": "onPeak",
@@ -24235,7 +24823,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11677,
+ "line": 11954,
"description": "Connect a source to the gain node.
\n",
"itemtype": "method",
"name": "setInput",
@@ -24252,7 +24840,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11687,
+ "line": 11964,
"description": "Send output to a p5.sound or web audio object
\n",
"itemtype": "method",
"name": "connect",
@@ -24269,7 +24857,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11697,
+ "line": 11974,
"description": "Disconnect all output.
\n",
"itemtype": "method",
"name": "disconnect",
@@ -24279,7 +24867,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11707,
+ "line": 11984,
"description": "Set the output level of the gain node.
\n",
"itemtype": "method",
"name": "amp",
@@ -24308,7 +24896,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11765,
+ "line": 12042,
"description": "Connect to p5 objects or Web Audio Nodes
\n",
"itemtype": "method",
"name": "connect",
@@ -24325,7 +24913,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11774,
+ "line": 12051,
"description": "Disconnect from soundOut
\n",
"itemtype": "method",
"name": "disconnect",
@@ -24335,7 +24923,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11860,
+ "line": 12131,
"description": "Play tells the MonoSynth to start playing a note. This method schedules\nthe calling of .triggerAttack and .triggerRelease.
\n",
"itemtype": "method",
"name": "play",
@@ -24373,7 +24961,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11908,
+ "line": 12179,
"description": "Trigger the Attack, and Decay portion of the Envelope.\nSimilar to holding down a key on a piano, but it will\nhold the sustain level until you let go.
\n",
"params": [
{
@@ -24405,7 +24993,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11942,
+ "line": 12212,
"description": "Trigger the release of the Envelope. This is similar to releasing\nthe key on a piano and letting the sound fade according to the\nrelease level and release time.
\n",
"params": [
{
@@ -24425,7 +25013,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11967,
+ "line": 12236,
"description": "Set values like a traditional\n\nADSR envelope\n.
\n",
"itemtype": "method",
"name": "setADSR",
@@ -24460,7 +25048,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11991,
+ "line": 12260,
"description": "Getters and Setters
\n",
"itemtype": "property",
"name": "attack",
@@ -24471,7 +25059,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11995,
+ "line": 12264,
"itemtype": "property",
"name": "decay",
"type": "Number",
@@ -24481,7 +25069,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 11998,
+ "line": 12267,
"itemtype": "property",
"name": "sustain",
"type": "Number",
@@ -24491,7 +25079,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 12001,
+ "line": 12270,
"itemtype": "property",
"name": "release",
"type": "Number",
@@ -24501,7 +25089,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 12038,
+ "line": 12307,
"description": "MonoSynth amp
\n",
"itemtype": "method",
"name": "amp",
@@ -24528,7 +25116,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 12052,
+ "line": 12321,
"description": "Connect to a p5.sound / Web Audio object.
\n",
"itemtype": "method",
"name": "connect",
@@ -24545,7 +25133,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 12062,
+ "line": 12331,
"description": "Disconnect all outputs
\n",
"itemtype": "method",
"name": "disconnect",
@@ -24555,7 +25143,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 12072,
+ "line": 12341,
"description": "Get rid of the MonoSynth and free up its resources / memory.
\n",
"itemtype": "method",
"name": "dispose",
@@ -24565,7 +25153,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 12145,
+ "line": 12411,
"description": "An object that holds information about which notes have been played and\nwhich notes are currently being played. New notes are added as keys\non the fly. While a note has been attacked, but not released, the value of the\nkey is the audiovoice which is generating that note. When notes are released,\nthe value of the key becomes undefined.
\n",
"itemtype": "property",
"name": "notes",
@@ -24575,7 +25163,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 12157,
+ "line": 12423,
"description": "A PolySynth must have at least 1 voice, defaults to 8
\n",
"itemtype": "property",
"name": "polyvalue",
@@ -24585,7 +25173,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 12162,
+ "line": 12428,
"description": "Monosynth that generates the sound for each note that is triggered. The\np5.PolySynth defaults to using the p5.MonoSynth as its voice.
\n",
"itemtype": "property",
"name": "AudioVoice",
@@ -24595,7 +25183,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 12193,
+ "line": 12459,
"description": "Play a note by triggering noteAttack and noteRelease with sustain time
\n",
"itemtype": "method",
"name": "play",
@@ -24634,7 +25222,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 12239,
+ "line": 12505,
"description": "noteADSR sets the envelope for a specific note that has just been triggered.\nUsing this method modifies the envelope of whichever audiovoice is being used\nto play the desired note. The envelope should be reset before noteRelease is called\nin order to prevent the modified envelope from being used on other notes.
\n",
"itemtype": "method",
"name": "noteADSR",
@@ -24676,7 +25264,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 12267,
+ "line": 12533,
"description": "Set the PolySynths global envelope. This method modifies the envelopes of each\nmonosynth so that all notes are played with this envelope.
\n",
"itemtype": "method",
"name": "setADSR",
@@ -24712,7 +25300,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 12291,
+ "line": 12557,
"description": "Trigger the Attack, and Decay portion of a MonoSynth.\nSimilar to holding down a key on a piano, but it will\nhold the sustain level until you let go.
\n",
"itemtype": "method",
"name": "noteAttack",
@@ -24745,7 +25333,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 12381,
+ "line": 12647,
"description": "Trigger the Release of an AudioVoice note. This is similar to releasing\nthe key on a piano and letting the sound fade according to the\nrelease level and release time.
\n",
"itemtype": "method",
"name": "noteRelease",
@@ -24772,7 +25360,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 12446,
+ "line": 12712,
"description": "Connect to a p5.sound / Web Audio object.
\n",
"itemtype": "method",
"name": "connect",
@@ -24789,7 +25377,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 12456,
+ "line": 12722,
"description": "Disconnect all outputs
\n",
"itemtype": "method",
"name": "disconnect",
@@ -24799,7 +25387,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 12466,
+ "line": 12732,
"description": "Get rid of the MonoSynth and free up its resources / memory.
\n",
"itemtype": "method",
"name": "dispose",
@@ -24809,7 +25397,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 12534,
+ "line": 12800,
"description": "The p5.Distortion is built with a\n\nWeb Audio WaveShaper Node.
\n",
"itemtype": "property",
"name": "WaveShaperNode",
@@ -24820,7 +25408,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 12549,
+ "line": 12815,
"description": "Process a sound source, optionally specify amount and oversample values.
\n",
"itemtype": "method",
"name": "process",
@@ -24846,7 +25434,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 12561,
+ "line": 12827,
"description": "Set the amount and oversample of the waveshaper distortion.
\n",
"itemtype": "method",
"name": "set",
@@ -24872,7 +25460,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 12579,
+ "line": 12845,
"description": "Return the distortion amount, typically between 0-1.
\n",
"itemtype": "method",
"name": "getAmount",
@@ -24886,7 +25474,7 @@ module.exports={
},
{
"file": "lib/addons/p5.sound.js",
- "line": 12589,
+ "line": 12855,
"description": "Return the oversampling.
\n",
"itemtype": "method",
"name": "getOversample",
@@ -24914,31 +25502,31 @@ module.exports={
},
{
"message": "unknown tag: alt",
- "line": " src/color/creating_reading.js:121"
+ "line": " src/color/creating_reading.js:134"
},
{
"message": "unknown tag: alt",
- "line": " src/color/creating_reading.js:319"
+ "line": " src/color/creating_reading.js:332"
},
{
"message": "unknown tag: alt",
- "line": " src/color/creating_reading.js:350"
+ "line": " src/color/creating_reading.js:363"
},
{
"message": "unknown tag: alt",
- "line": " src/color/creating_reading.js:387"
+ "line": " src/color/creating_reading.js:400"
},
{
"message": "unknown tag: alt",
- "line": " src/color/creating_reading.js:484"
+ "line": " src/color/creating_reading.js:497"
},
{
"message": "unknown tag: alt",
- "line": " src/color/creating_reading.js:514"
+ "line": " src/color/creating_reading.js:527"
},
{
"message": "unknown tag: alt",
- "line": " src/color/creating_reading.js:554"
+ "line": " src/color/creating_reading.js:567"
},
{
"message": "unknown tag: alt",
@@ -24946,23 +25534,23 @@ module.exports={
},
{
"message": "unknown tag: alt",
- "line": " src/color/p5.Color.js:248"
+ "line": " src/color/p5.Color.js:253"
},
{
"message": "unknown tag: alt",
- "line": " src/color/p5.Color.js:275"
+ "line": " src/color/p5.Color.js:280"
},
{
"message": "unknown tag: alt",
- "line": " src/color/p5.Color.js:302"
+ "line": " src/color/p5.Color.js:307"
},
{
"message": "unknown tag: alt",
- "line": " src/color/p5.Color.js:329"
+ "line": " src/color/p5.Color.js:334"
},
{
"message": "unknown tag: alt",
- "line": " src/color/p5.Color.js:763"
+ "line": " src/color/p5.Color.js:768"
},
{
"message": "unknown tag: alt",
@@ -24970,55 +25558,63 @@ module.exports={
},
{
"message": "unknown tag: alt",
- "line": " src/color/setting.js:185"
+ "line": " src/color/setting.js:181"
},
{
"message": "unknown tag: alt",
- "line": " src/color/setting.js:223"
+ "line": " src/color/setting.js:220"
},
{
"message": "unknown tag: alt",
- "line": " src/color/setting.js:344"
+ "line": " src/color/setting.js:341"
},
{
"message": "unknown tag: alt",
- "line": " src/color/setting.js:501"
+ "line": " src/color/setting.js:498"
},
{
"message": "unknown tag: alt",
- "line": " src/color/setting.js:542"
+ "line": " src/color/setting.js:539"
},
{
"message": "unknown tag: alt",
- "line": " src/color/setting.js:582"
+ "line": " src/color/setting.js:579"
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/2d_primitives.js:16"
+ "line": " src/core/shape/2d_primitives.js:102"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/shape/2d_primitives.js:210"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/shape/2d_primitives.js:270"
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/2d_primitives.js:149"
+ "line": " src/core/shape/2d_primitives.js:300"
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/2d_primitives.js:208"
+ "line": " src/core/shape/2d_primitives.js:356"
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/2d_primitives.js:264"
+ "line": " src/core/shape/2d_primitives.js:391"
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/2d_primitives.js:299"
+ "line": " src/core/shape/2d_primitives.js:458"
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/2d_primitives.js:353"
+ "line": " src/core/shape/2d_primitives.js:541"
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/2d_primitives.js:436"
+ "line": " src/core/shape/2d_primitives.js:595"
},
{
"message": "unknown tag: alt",
@@ -25030,23 +25626,23 @@ module.exports={
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/attributes.js:113"
+ "line": " src/core/shape/attributes.js:116"
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/attributes.js:182"
+ "line": " src/core/shape/attributes.js:185"
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/attributes.js:213"
+ "line": " src/core/shape/attributes.js:219"
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/attributes.js:250"
+ "line": " src/core/shape/attributes.js:256"
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/attributes.js:317"
+ "line": " src/core/shape/attributes.js:323"
},
{
"message": "unknown tag: alt",
@@ -25094,47 +25690,51 @@ module.exports={
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/vertex.js:317"
+ "line": " src/core/shape/vertex.js:270"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/shape/vertex.js:270"
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/vertex.js:390"
+ "line": " src/core/shape/vertex.js:398"
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/vertex.js:435"
+ "line": " src/core/shape/vertex.js:443"
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/vertex.js:500"
+ "line": " src/core/shape/vertex.js:508"
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/vertex.js:560"
+ "line": " src/core/shape/vertex.js:568"
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/vertex.js:646"
+ "line": " src/core/shape/vertex.js:654"
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/vertex.js:709"
+ "line": " src/core/shape/vertex.js:720"
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/vertex.js:800"
+ "line": " src/core/shape/vertex.js:813"
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/vertex.js:800"
+ "line": " src/core/shape/vertex.js:813"
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/vertex.js:800"
+ "line": " src/core/shape/vertex.js:813"
},
{
"message": "unknown tag: alt",
- "line": " src/core/shape/vertex.js:800"
+ "line": " src/core/shape/vertex.js:813"
},
{
"message": "unknown tag: alt",
@@ -25162,75 +25762,75 @@ module.exports={
},
{
"message": "unknown tag: alt",
- "line": " src/core/environment.js:49"
+ "line": " src/core/environment.js:53"
},
{
"message": "unknown tag: alt",
- "line": " src/core/environment.js:76"
+ "line": " src/core/environment.js:80"
},
{
"message": "unknown tag: alt",
- "line": " src/core/environment.js:108"
+ "line": " src/core/environment.js:112"
},
{
"message": "unknown tag: alt",
- "line": " src/core/environment.js:167"
+ "line": " src/core/environment.js:181"
},
{
"message": "unknown tag: alt",
- "line": " src/core/environment.js:268"
+ "line": " src/core/environment.js:281"
},
{
"message": "unknown tag: alt",
- "line": " src/core/environment.js:293"
+ "line": " src/core/environment.js:306"
},
{
"message": "unknown tag: alt",
- "line": " src/core/environment.js:312"
+ "line": " src/core/environment.js:325"
},
{
"message": "unknown tag: alt",
- "line": " src/core/environment.js:331"
+ "line": " src/core/environment.js:344"
},
{
"message": "unknown tag: alt",
- "line": " src/core/environment.js:347"
+ "line": " src/core/environment.js:360"
},
{
"message": "unknown tag: alt",
- "line": " src/core/environment.js:363"
+ "line": " src/core/environment.js:376"
},
{
"message": "unknown tag: alt",
- "line": " src/core/environment.js:441"
+ "line": " src/core/environment.js:454"
},
{
"message": "unknown tag: alt",
- "line": " src/core/environment.js:492"
+ "line": " src/core/environment.js:505"
},
{
"message": "replacing incorrect tag: returns with return",
- "line": " src/core/environment.js:527"
+ "line": " src/core/environment.js:540"
},
{
"message": "replacing incorrect tag: returns with return",
- "line": " src/core/environment.js:547"
+ "line": " src/core/environment.js:560"
},
{
"message": "unknown tag: alt",
- "line": " src/core/environment.js:547"
+ "line": " src/core/environment.js:560"
},
{
"message": "unknown tag: alt",
- "line": " src/core/environment.js:604"
+ "line": " src/core/environment.js:617"
},
{
"message": "unknown tag: alt",
- "line": " src/core/environment.js:635"
+ "line": " src/core/environment.js:648"
},
{
"message": "unknown tag: alt",
- "line": " src/core/environment.js:658"
+ "line": " src/core/environment.js:671"
},
{
"message": "unknown tag: alt",
@@ -25246,87 +25846,79 @@ module.exports={
},
{
"message": "unknown tag: alt",
- "line": " src/core/main.js:408"
- },
- {
- "message": "unknown tag: alt",
- "line": " src/core/p5.Element.js:51"
- },
- {
- "message": "unknown tag: alt",
- "line": " src/core/p5.Element.js:116"
+ "line": " src/core/main.js:401"
},
{
"message": "unknown tag: alt",
- "line": " src/core/p5.Element.js:153"
+ "line": " src/core/p5.Element.js:52"
},
{
"message": "unknown tag: alt",
- "line": " src/core/p5.Element.js:188"
+ "line": " src/core/p5.Element.js:122"
},
{
"message": "unknown tag: alt",
- "line": " src/core/p5.Element.js:249"
+ "line": " src/core/p5.Element.js:162"
},
{
"message": "unknown tag: alt",
- "line": " src/core/p5.Element.js:298"
+ "line": " src/core/p5.Element.js:197"
},
{
"message": "unknown tag: alt",
- "line": " src/core/p5.Element.js:364"
+ "line": " src/core/p5.Element.js:258"
},
{
"message": "unknown tag: alt",
- "line": " src/core/p5.Element.js:418"
+ "line": " src/core/p5.Element.js:307"
},
{
"message": "unknown tag: alt",
- "line": " src/core/p5.Element.js:474"
+ "line": " src/core/p5.Element.js:373"
},
{
"message": "unknown tag: alt",
- "line": " src/core/p5.Element.js:532"
+ "line": " src/core/p5.Element.js:427"
},
{
"message": "unknown tag: alt",
- "line": " src/core/p5.Element.js:575"
+ "line": " src/core/p5.Element.js:483"
},
{
"message": "unknown tag: alt",
- "line": " src/core/p5.Element.js:642"
+ "line": " src/core/p5.Element.js:541"
},
{
"message": "unknown tag: alt",
- "line": " src/core/p5.Element.js:677"
+ "line": " src/core/p5.Element.js:584"
},
{
"message": "unknown tag: alt",
- "line": " src/core/p5.Element.js:719"
+ "line": " src/core/p5.Element.js:626"
},
{
"message": "unknown tag: alt",
- "line": " src/core/p5.Element.js:767"
+ "line": " src/core/p5.Element.js:674"
},
{
"message": "unknown tag: alt",
- "line": " src/core/p5.Element.js:807"
+ "line": " src/core/p5.Element.js:714"
},
{
"message": "unknown tag: alt",
- "line": " src/core/p5.Element.js:856"
+ "line": " src/core/p5.Element.js:763"
},
{
"message": "unknown tag: alt",
- "line": " src/core/p5.Element.js:894"
+ "line": " src/core/p5.Element.js:801"
},
{
"message": "unknown tag: alt",
- "line": " src/core/p5.Element.js:932"
+ "line": " src/core/p5.Graphics.js:65"
},
{
"message": "unknown tag: alt",
- "line": " src/core/p5.Graphics.js:65"
+ "line": " src/core/p5.Graphics.js:117"
},
{
"message": "unknown tag: alt",
@@ -25358,15 +25950,15 @@ module.exports={
},
{
"message": "unknown tag: alt",
- "line": " src/core/structure.js:116"
+ "line": " src/core/structure.js:122"
},
{
"message": "unknown tag: alt",
- "line": " src/core/structure.js:181"
+ "line": " src/core/structure.js:191"
},
{
"message": "unknown tag: alt",
- "line": " src/core/structure.js:247"
+ "line": " src/core/structure.js:261"
},
{
"message": "unknown tag: alt",
@@ -25374,111 +25966,127 @@ module.exports={
},
{
"message": "unknown tag: alt",
- "line": " src/core/transform.js:135"
+ "line": " src/core/transform.js:150"
},
{
"message": "unknown tag: alt",
- "line": " src/core/transform.js:161"
+ "line": " src/core/transform.js:176"
},
{
"message": "unknown tag: alt",
- "line": " src/core/transform.js:201"
+ "line": " src/core/transform.js:216"
},
{
"message": "unknown tag: alt",
- "line": " src/core/transform.js:231"
+ "line": " src/core/transform.js:246"
},
{
"message": "unknown tag: alt",
- "line": " src/core/transform.js:261"
+ "line": " src/core/transform.js:276"
},
{
"message": "unknown tag: alt",
- "line": " src/core/transform.js:291"
+ "line": " src/core/transform.js:306"
},
{
"message": "unknown tag: alt",
- "line": " src/core/transform.js:366"
+ "line": " src/core/transform.js:381"
},
{
"message": "unknown tag: alt",
- "line": " src/core/transform.js:405"
+ "line": " src/core/transform.js:421"
},
{
"message": "unknown tag: alt",
- "line": " src/core/transform.js:444"
+ "line": " src/core/transform.js:461"
},
{
"message": "unknown tag: alt",
- "line": " src/events/acceleration.js:91"
+ "line": " src/events/acceleration.js:23"
},
{
"message": "unknown tag: alt",
- "line": " src/events/acceleration.js:125"
+ "line": " src/events/acceleration.js:46"
},
{
"message": "unknown tag: alt",
- "line": " src/events/acceleration.js:158"
+ "line": " src/events/acceleration.js:69"
},
{
"message": "unknown tag: alt",
- "line": " src/events/acceleration.js:194"
+ "line": " src/events/acceleration.js:135"
},
{
"message": "unknown tag: alt",
- "line": " src/events/acceleration.js:239"
+ "line": " src/events/acceleration.js:166"
},
{
"message": "unknown tag: alt",
- "line": " src/events/acceleration.js:283"
+ "line": " src/events/acceleration.js:197"
},
{
"message": "unknown tag: alt",
- "line": " src/events/acceleration.js:350"
+ "line": " src/events/acceleration.js:233"
},
{
"message": "unknown tag: alt",
- "line": " src/events/acceleration.js:393"
+ "line": " src/events/acceleration.js:278"
},
{
"message": "unknown tag: alt",
- "line": " src/events/acceleration.js:437"
+ "line": " src/events/acceleration.js:322"
},
{
"message": "unknown tag: alt",
- "line": " src/events/acceleration.js:468"
+ "line": " src/events/acceleration.js:380"
},
{
"message": "unknown tag: alt",
- "line": " src/events/acceleration.js:527"
+ "line": " src/events/acceleration.js:419"
},
{
"message": "unknown tag: alt",
- "line": " src/events/keyboard.js:18"
+ "line": " src/events/acceleration.js:462"
},
{
"message": "unknown tag: alt",
- "line": " src/events/keyboard.js:45"
+ "line": " src/events/acceleration.js:506"
},
{
"message": "unknown tag: alt",
- "line": " src/events/keyboard.js:74"
+ "line": " src/events/acceleration.js:538"
},
{
"message": "unknown tag: alt",
- "line": " src/events/keyboard.js:107"
+ "line": " src/events/acceleration.js:597"
},
{
"message": "unknown tag: alt",
- "line": " src/events/keyboard.js:194"
+ "line": " src/events/keyboard.js:12"
},
{
"message": "unknown tag: alt",
- "line": " src/events/keyboard.js:246"
+ "line": " src/events/keyboard.js:39"
},
{
"message": "unknown tag: alt",
- "line": " src/events/keyboard.js:310"
+ "line": " src/events/keyboard.js:68"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/keyboard.js:109"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/keyboard.js:196"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/keyboard.js:248"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/keyboard.js:312"
},
{
"message": "unknown tag: alt",
@@ -25502,51 +26110,51 @@ module.exports={
},
{
"message": "unknown tag: alt",
- "line": " src/events/mouse.js:174"
+ "line": " src/events/mouse.js:176"
},
{
"message": "unknown tag: alt",
- "line": " src/events/mouse.js:211"
+ "line": " src/events/mouse.js:215"
},
{
"message": "unknown tag: alt",
- "line": " src/events/mouse.js:252"
+ "line": " src/events/mouse.js:256"
},
{
"message": "unknown tag: alt",
- "line": " src/events/mouse.js:294"
+ "line": " src/events/mouse.js:298"
},
{
"message": "unknown tag: alt",
- "line": " src/events/mouse.js:333"
+ "line": " src/events/mouse.js:337"
},
{
"message": "unknown tag: alt",
- "line": " src/events/mouse.js:424"
+ "line": " src/events/mouse.js:428"
},
{
"message": "unknown tag: alt",
- "line": " src/events/mouse.js:468"
+ "line": " src/events/mouse.js:483"
},
{
"message": "unknown tag: alt",
- "line": " src/events/mouse.js:538"
+ "line": " src/events/mouse.js:564"
},
{
"message": "unknown tag: alt",
- "line": " src/events/mouse.js:604"
+ "line": " src/events/mouse.js:641"
},
{
"message": "unknown tag: alt",
- "line": " src/events/mouse.js:671"
+ "line": " src/events/mouse.js:719"
},
{
"message": "unknown tag: alt",
- "line": " src/events/mouse.js:730"
+ "line": " src/events/mouse.js:789"
},
{
"message": "unknown tag: alt",
- "line": " src/events/mouse.js:804"
+ "line": " src/events/mouse.js:874"
},
{
"message": "unknown tag: alt",
@@ -25558,11 +26166,11 @@ module.exports={
},
{
"message": "unknown tag: alt",
- "line": " src/events/touch.js:138"
+ "line": " src/events/touch.js:149"
},
{
"message": "unknown tag: alt",
- "line": " src/events/touch.js:200"
+ "line": " src/events/touch.js:222"
},
{
"message": "unknown tag: alt",
@@ -25582,23 +26190,23 @@ module.exports={
},
{
"message": "replacing incorrect tag: returns with return",
- "line": " src/image/loading_displaying.js:108"
+ "line": " src/image/loading_displaying.js:110"
},
{
"message": "unknown tag: alt",
- "line": " src/image/loading_displaying.js:125"
+ "line": " src/image/loading_displaying.js:127"
},
{
"message": "unknown tag: alt",
- "line": " src/image/loading_displaying.js:296"
+ "line": " src/image/loading_displaying.js:298"
},
{
"message": "unknown tag: alt",
- "line": " src/image/loading_displaying.js:396"
+ "line": " src/image/loading_displaying.js:398"
},
{
"message": "unknown tag: alt",
- "line": " src/image/loading_displaying.js:462"
+ "line": " src/image/loading_displaying.js:464"
},
{
"message": "unknown tag: alt",
@@ -25610,47 +26218,47 @@ module.exports={
},
{
"message": "unknown tag: alt",
- "line": " src/image/p5.Image.js:152"
+ "line": " src/image/p5.Image.js:153"
},
{
"message": "unknown tag: alt",
- "line": " src/image/p5.Image.js:231"
+ "line": " src/image/p5.Image.js:232"
},
{
"message": "unknown tag: alt",
- "line": " src/image/p5.Image.js:267"
+ "line": " src/image/p5.Image.js:268"
},
{
"message": "unknown tag: alt",
- "line": " src/image/p5.Image.js:315"
+ "line": " src/image/p5.Image.js:316"
},
{
"message": "unknown tag: alt",
- "line": " src/image/p5.Image.js:360"
+ "line": " src/image/p5.Image.js:371"
},
{
"message": "unknown tag: alt",
- "line": " src/image/p5.Image.js:398"
+ "line": " src/image/p5.Image.js:409"
},
{
"message": "unknown tag: alt",
- "line": " src/image/p5.Image.js:483"
+ "line": " src/image/p5.Image.js:494"
},
{
"message": "unknown tag: alt",
- "line": " src/image/p5.Image.js:564"
+ "line": " src/image/p5.Image.js:575"
},
{
"message": "unknown tag: alt",
- "line": " src/image/p5.Image.js:627"
+ "line": " src/image/p5.Image.js:638"
},
{
"message": "unknown tag: alt",
- "line": " src/image/p5.Image.js:663"
+ "line": " src/image/p5.Image.js:674"
},
{
"message": "unknown tag: alt",
- "line": " src/image/p5.Image.js:785"
+ "line": " src/image/p5.Image.js:796"
},
{
"message": "unknown tag: alt",
@@ -25674,15 +26282,15 @@ module.exports={
},
{
"message": "unknown tag: alt",
- "line": " src/image/pixels.js:494"
+ "line": " src/image/pixels.js:506"
},
{
"message": "unknown tag: alt",
- "line": " src/image/pixels.js:531"
+ "line": " src/image/pixels.js:543"
},
{
"message": "unknown tag: alt",
- "line": " src/image/pixels.js:605"
+ "line": " src/image/pixels.js:617"
},
{
"message": "unknown tag: alt",
@@ -25698,27 +26306,27 @@ module.exports={
},
{
"message": "unknown tag: alt",
- "line": " src/io/files.js:626"
+ "line": " src/io/files.js:603"
},
{
"message": "replacing incorrect tag: returns with return",
- "line": " src/io/files.js:737"
+ "line": " src/io/files.js:714"
},
{
"message": "unknown tag: alt",
- "line": " src/io/files.js:737"
+ "line": " src/io/files.js:714"
},
{
"message": "unknown tag: alt",
- "line": " src/io/files.js:1530"
+ "line": " src/io/files.js:1519"
},
{
"message": "unknown tag: alt",
- "line": " src/io/files.js:1582"
+ "line": " src/io/files.js:1577"
},
{
"message": "unknown tag: alt",
- "line": " src/io/files.js:1644"
+ "line": " src/io/files.js:1645"
},
{
"message": "unknown tag: alt",
@@ -25850,43 +26458,43 @@ module.exports={
},
{
"message": "unknown tag: alt",
- "line": " src/math/calculation.js:324"
+ "line": " src/math/calculation.js:327"
},
{
"message": "unknown tag: alt",
- "line": " src/math/calculation.js:379"
+ "line": " src/math/calculation.js:383"
},
{
"message": "unknown tag: alt",
- "line": " src/math/calculation.js:418"
+ "line": " src/math/calculation.js:422"
},
{
"message": "unknown tag: alt",
- "line": " src/math/calculation.js:474"
+ "line": " src/math/calculation.js:478"
},
{
"message": "unknown tag: alt",
- "line": " src/math/calculation.js:524"
+ "line": " src/math/calculation.js:528"
},
{
"message": "unknown tag: alt",
- "line": " src/math/calculation.js:574"
+ "line": " src/math/calculation.js:578"
},
{
"message": "unknown tag: alt",
- "line": " src/math/calculation.js:627"
+ "line": " src/math/calculation.js:631"
},
{
"message": "unknown tag: alt",
- "line": " src/math/calculation.js:661"
+ "line": " src/math/calculation.js:665"
},
{
"message": "unknown tag: alt",
- "line": " src/math/calculation.js:700"
+ "line": " src/math/calculation.js:704"
},
{
"message": "unknown tag: alt",
- "line": " src/math/calculation.js:747"
+ "line": " src/math/calculation.js:751"
},
{
"message": "unknown tag: alt",
@@ -25970,7 +26578,7 @@ module.exports={
},
{
"message": "unknown tag: alt",
- "line": " src/typography/attributes.js:189"
+ "line": " src/typography/attributes.js:191"
},
{
"message": "unknown tag: alt",
@@ -25986,7 +26594,7 @@ module.exports={
},
{
"message": "unknown tag: alt",
- "line": " src/typography/p5.Font.js:43"
+ "line": " src/typography/p5.Font.js:32"
},
{
"message": "unknown tag: alt",
@@ -26006,23 +26614,23 @@ module.exports={
},
{
"message": "unknown tag: alt",
- "line": " src/utilities/string_functions.js:237"
+ "line": " src/utilities/string_functions.js:243"
},
{
"message": "unknown tag: alt",
- "line": " src/utilities/string_functions.js:313"
+ "line": " src/utilities/string_functions.js:319"
},
{
"message": "unknown tag: alt",
- "line": " src/utilities/string_functions.js:375"
+ "line": " src/utilities/string_functions.js:381"
},
{
"message": "unknown tag: alt",
- "line": " src/utilities/string_functions.js:437"
+ "line": " src/utilities/string_functions.js:459"
},
{
"message": "unknown tag: alt",
- "line": " src/utilities/string_functions.js:526"
+ "line": " src/utilities/string_functions.js:548"
},
{
"message": "unknown tag: alt",
@@ -26054,7 +26662,7 @@ module.exports={
},
{
"message": "unknown tag: alt",
- "line": " src/webgl/3d_primitives.js:15"
+ "line": " src/webgl/3d_primitives.js:14"
},
{
"message": "unknown tag: alt",
@@ -26090,11 +26698,15 @@ module.exports={
},
{
"message": "unknown tag: alt",
- "line": " src/webgl/light.js:101"
+ "line": " src/webgl/light.js:87"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/light.js:185"
},
{
"message": "unknown tag: alt",
- "line": " src/webgl/light.js:212"
+ "line": " src/webgl/light.js:287"
},
{
"message": "unknown tag: alt",
@@ -26114,27 +26726,43 @@ module.exports={
},
{
"message": "replacing incorrect tag: returns with return",
- "line": " src/webgl/material.js:83"
+ "line": " src/webgl/material.js:113"
},
{
"message": "unknown tag: alt",
- "line": " src/webgl/material.js:83"
+ "line": " src/webgl/material.js:113"
},
{
"message": "unknown tag: alt",
- "line": " src/webgl/material.js:176"
+ "line": " src/webgl/material.js:225"
},
{
"message": "unknown tag: alt",
- "line": " src/webgl/material.js:211"
+ "line": " src/webgl/material.js:262"
},
{
"message": "unknown tag: alt",
- "line": " src/webgl/material.js:301"
+ "line": " src/webgl/material.js:359"
},
{
"message": "unknown tag: alt",
- "line": " src/webgl/material.js:350"
+ "line": " src/webgl/material.js:359"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/material.js:438"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/material.js:513"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/material.js:563"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/material.js:614"
},
{
"message": "unknown tag: alt",
@@ -26154,43 +26782,43 @@ module.exports={
},
{
"message": "unknown tag: alt",
- "line": " src/webgl/p5.Camera.js:487"
+ "line": " src/webgl/p5.Camera.js:486"
},
{
"message": "unknown tag: alt",
- "line": " src/webgl/p5.Camera.js:546"
+ "line": " src/webgl/p5.Camera.js:545"
},
{
"message": "unknown tag: alt",
- "line": " src/webgl/p5.Camera.js:604"
+ "line": " src/webgl/p5.Camera.js:603"
},
{
"message": "unknown tag: alt",
- "line": " src/webgl/p5.Camera.js:752"
+ "line": " src/webgl/p5.Camera.js:751"
},
{
"message": "unknown tag: alt",
- "line": " src/webgl/p5.Camera.js:824"
+ "line": " src/webgl/p5.Camera.js:823"
},
{
"message": "unknown tag: alt",
- "line": " src/webgl/p5.Camera.js:1089"
+ "line": " src/webgl/p5.Camera.js:1088"
},
{
"message": "unknown tag: alt",
- "line": " src/webgl/p5.RendererGL.js:215"
+ "line": " src/webgl/p5.RendererGL.js:228"
},
{
"message": "unknown tag: alt",
- "line": " src/webgl/p5.RendererGL.js:427"
+ "line": " src/webgl/p5.RendererGL.js:474"
},
{
"message": "unknown tag: alt",
- "line": " src/webgl/p5.RendererGL.js:474"
+ "line": " src/webgl/p5.RendererGL.js:516"
},
{
"message": "unknown tag: alt",
- "line": " src/webgl/p5.RendererGL.js:515"
+ "line": " src/webgl/p5.RendererGL.js:586"
},
{
"message": "replacing incorrect tag: function with method",
@@ -26236,37 +26864,57 @@ module.exports={
"message": "replacing incorrect tag: function with method",
"line": " src/webgl/text.js:547"
},
+ {
+ "message": "unknown tag: alt",
+ "line": " lib/addons/p5.dom.js:245"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " lib/addons/p5.dom.js:313"
+ },
+ {
+ "message": "replacing incorrect tag: returns with return",
+ "line": " lib/addons/p5.dom.js:1463"
+ },
{
"message": "replacing incorrect tag: returns with return",
- "line": " lib/addons/p5.dom.js:1368"
+ "line": " lib/addons/p5.dom.js:1525"
},
{
"message": "replacing incorrect tag: returns with return",
- "line": " lib/addons/p5.dom.js:1470"
+ "line": " lib/addons/p5.dom.js:1629"
},
{
"message": "replacing incorrect tag: returns with return",
- "line": " lib/addons/p5.dom.js:1509"
+ "line": " lib/addons/p5.dom.js:1668"
},
{
"message": "replacing incorrect tag: returns with return",
- "line": " lib/addons/p5.dom.js:1603"
+ "line": " lib/addons/p5.dom.js:1762"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " lib/addons/p5.dom.js:2119"
},
{
"message": "replacing incorrect tag: params with param",
- "line": " lib/addons/p5.sound.js:1642"
+ "line": " lib/addons/p5.sound.js:2480"
},
{
"message": "replacing incorrect tag: returns with return",
- "line": " lib/addons/p5.sound.js:1642"
+ "line": " lib/addons/p5.sound.js:2480"
},
{
"message": "replacing incorrect tag: returns with return",
- "line": " lib/addons/p5.sound.js:7335"
+ "line": " lib/addons/p5.sound.js:3094"
},
{
"message": "replacing incorrect tag: returns with return",
- "line": " lib/addons/p5.sound.js:9303"
+ "line": " lib/addons/p5.sound.js:7659"
+ },
+ {
+ "message": "replacing incorrect tag: returns with return",
+ "line": " lib/addons/p5.sound.js:9626"
},
{
"message": "Missing item type\nConversions adapted from .\n\nIn these functions, hue is always in the range [0, 1], just like all other\ncomponents are in the range [0, 1]. 'Brightness' and 'value' are used\ninterchangeably.",
@@ -26298,55 +26946,55 @@ module.exports={
},
{
"message": "Missing item type\nHue is the same in HSB and HSL, but the maximum value may be different.\nThis function will return the HSB-normalized saturation when supplied with\nan HSB color object, but will default to the HSL-normalized saturation\notherwise.",
- "line": " src/color/p5.Color.js:410"
+ "line": " src/color/p5.Color.js:415"
},
{
"message": "Missing item type\nSaturation 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.",
- "line": " src/color/p5.Color.js:441"
+ "line": " src/color/p5.Color.js:446"
},
{
"message": "Missing item type\nCSS named colors.",
- "line": " src/color/p5.Color.js:460"
+ "line": " src/color/p5.Color.js:465"
},
{
"message": "Missing item type\nThese 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.\n\nNote that RGB values of .9 are not parsed by IE, but are supported here for\ncolor string consistency.",
- "line": " src/color/p5.Color.js:613"
+ "line": " src/color/p5.Color.js:618"
},
{
"message": "Missing item type\nFull color string patterns. The capture groups are necessary.",
- "line": " src/color/p5.Color.js:626"
+ "line": " src/color/p5.Color.js:631"
},
{
"message": "Missing item type\nFor a number of different inputs, returns a color formatted as [r, g, b, a]\narrays, with each component normalized between 0 and 1.",
- "line": " src/color/p5.Color.js:763"
+ "line": " src/color/p5.Color.js:768"
},
{
"message": "Missing item type\nFor 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.",
- "line": " src/color/p5.Color.js:989"
+ "line": " src/color/p5.Color.js:994"
+ },
+ {
+ "message": "Missing item type\nThis function does 3 things:\n\n 1. Bounds the desired start/stop angles for an arc (in radians) so that:\n\n 0 <= start < TWO_PI ; start <= stop < start + TWO_PI\n\n This means that the arc rendering functions don't have to be concerned\n with what happens if stop is smaller than start, or if the arc 'goes\n round more than once', etc.: they can just start at start and increase\n until stop and the correct arc will be drawn.\n\n 2. Optionally adjusts the angles within each quadrant to counter the naive\n scaling of the underlying ellipse up from the unit circle. Without\n this, the angles become arbitrary when width != height: 45 degrees\n might be drawn at 5 degrees on a 'wide' ellipse, or at 85 degrees on\n a 'tall' ellipse.\n\n 3. Flags up when start and stop correspond to the same place on the\n underlying ellipse. This is useful if you want to do something special\n there (like rendering a whole ellipse instead).",
+ "line": " src/core/shape/2d_primitives.js:16"
},
{
"message": "Missing item type\nReturns the current framerate.",
- "line": " src/core/environment.js:242"
+ "line": " src/core/environment.js:255"
},
{
"message": "Missing item type\nSpecifies 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.\n\nCalling frameRate() with no arguments returns the current framerate.",
- "line": " src/core/environment.js:252"
+ "line": " src/core/environment.js:265"
},
{
"message": "Missing item type",
"line": " src/core/error_helpers.js:1"
},
- {
- "message": "Missing item type\nPrints out a fancy, colorful message to the console log",
- "line": " src/core/error_helpers.js:65"
- },
{
"message": "Missing item type\nValidates parameters\nparam {String} func the name of the function\nparam {Array} args user input arguments\n\nexample:\n var a;\n ellipse(10,10,a,5);\nconsole ouput:\n \"It looks like ellipse received an empty variable in spot #2.\"\n\nexample:\n ellipse(10,\"foo\",5,5);\nconsole output:\n \"ellipse was expecting a number for parameter #1,\n received \"foo\" instead.\"",
- "line": " src/core/error_helpers.js:563"
+ "line": " src/core/error_helpers.js:584"
},
{
"message": "Missing item type\nPrints out all the colors in the color pallete with white text.\nFor color blindness testing.",
- "line": " src/core/error_helpers.js:624"
+ "line": " src/core/error_helpers.js:645"
},
{
"message": "Missing item type",
@@ -26362,19 +27010,19 @@ module.exports={
},
{
"message": "Missing item type\nHelper fxn for sharing pixel methods",
- "line": " src/core/p5.Element.js:1088"
+ "line": " src/core/p5.Element.js:865"
},
{
"message": "Missing item type\nResize our canvas element.",
- "line": " src/core/p5.Renderer.js:96"
+ "line": " src/core/p5.Renderer.js:97"
},
{
"message": "Missing item type\nHelper fxn to check font type (system or otf)",
- "line": " src/core/p5.Renderer.js:300"
+ "line": " src/core/p5.Renderer.js:335"
},
{
"message": "Missing item type\nHelper fxn to measure ascent and descent.\nAdapted from http://stackoverflow.com/a/25355178",
- "line": " src/core/p5.Renderer.js:353"
+ "line": " src/core/p5.Renderer.js:388"
},
{
"message": "Missing item type\np5.Renderer2D\nThe 2D graphics canvas renderer class.\nextends p5.Renderer",
@@ -26382,7 +27030,7 @@ module.exports={
},
{
"message": "Missing item type\nGenerate 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.\n\nSee www.joecridge.me/bezier.pdf for an explanation of the method.",
- "line": " src/core/p5.Renderer2D.js:414"
+ "line": " src/core/p5.Renderer2D.js:405"
},
{
"message": "Missing item type\nshim for Uint8ClampedArray.slice\n(allows arrayCopy to work with pixels[])\nwith thanks to http://halfpapstudios.com/blog/tag/html5-canvas/\nEnumerable set to false to protect for...in from\nUint8ClampedArray.prototype pollution.",
@@ -26398,35 +27046,31 @@ module.exports={
},
{
"message": "Missing item type\nprivate helper function to ensure that the user passed in valid\nvalues for the Dictionary type",
- "line": " src/data/p5.TypedDict.js:382"
+ "line": " src/data/p5.TypedDict.js:394"
},
{
"message": "Missing item type\nprivate helper function to ensure that the user passed in valid\nvalues for the Dictionary type",
- "line": " src/data/p5.TypedDict.js:425"
+ "line": " src/data/p5.TypedDict.js:437"
},
{
"message": "Missing item type\nprivate helper function for finding lowest or highest value\nthe argument 'flip' is used to flip the comparison arrow\nfrom 'less than' to 'greater than'",
- "line": " src/data/p5.TypedDict.js:542"
+ "line": " src/data/p5.TypedDict.js:554"
},
{
"message": "Missing item type\nprivate helper function for finding lowest or highest key\nthe argument 'flip' is used to flip the comparison arrow\nfrom 'less than' to 'greater than'",
- "line": " src/data/p5.TypedDict.js:609"
+ "line": " src/data/p5.TypedDict.js:621"
},
{
"message": "Missing item type\n_updatePAccelerations updates the pAcceleration values",
- "line": " src/events/acceleration.js:80"
- },
- {
- "message": "Missing item type\nHolds the key codes of currently pressed keys.",
- "line": " src/events/keyboard.js:12"
+ "line": " src/events/acceleration.js:124"
},
{
"message": "Missing item type\nThe onblur function is called when the user is no longer focused\non the p5 element. Because the keyup events will not fire if the user is\nnot focused on the element we must assume all keys currently down have\nbeen released.",
- "line": " src/events/keyboard.js:300"
+ "line": " src/events/keyboard.js:302"
},
{
- "message": "Missing item type\nThe checkDownKeys function returns a boolean true if any keys pressed\nand a false if no keys are currently pressed.\n\nHelps avoid instances where a multiple keys are pressed simultaneously and\nreleasing a single key will then switch the\nkeyIsPressed property to true.",
- "line": " src/events/keyboard.js:387"
+ "message": "Missing item type\nThe _areDownKeys function returns a boolean true if any keys pressed\nand a false if no keys are currently pressed.\n\nHelps avoid instances where multiple keys are pressed simultaneously and\nreleasing a single key will then switch the\nkeyIsPressed property to true.",
+ "line": " src/events/keyboard.js:389"
},
{
"message": "Missing item type\nThis module defines the filters for use with image buffers.\n\nThis module is basically a collection of functions stored in an object\nas opposed to modules. The functions are destructive, modifying\nthe passed in canvas rather than creating a copy.\n\nGenerally speaking users of this module will use the Filters.apply method\non a canvas to create an effect.\n\nA number of functions are borrowed/adapted from\nhttp://www.html5rocks.com/en/tutorials/canvas/imagefilters/\nor the java processing implementation.",
@@ -26458,31 +27102,31 @@ module.exports={
},
{
"message": "Missing item type\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\nBorrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/",
- "line": " src/image/filters.js:159"
+ "line": " src/image/filters.js:175"
},
{
"message": "Missing item type\nConverts any colors in the image to grayscale equivalents.\nNo parameter is used.\n\nBorrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/",
- "line": " src/image/filters.js:193"
+ "line": " src/image/filters.js:209"
},
{
"message": "Missing item type\nSets the alpha channel to entirely opaque. No parameter is used.",
- "line": " src/image/filters.js:216"
+ "line": " src/image/filters.js:232"
},
{
"message": "Missing item type\nSets each pixel to its inverse value. No parameter is used.",
- "line": " src/image/filters.js:232"
+ "line": " src/image/filters.js:248"
},
{
"message": "Missing item type\nLimits 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.\n\nAdapted from java based processing implementation",
- "line": " src/image/filters.js:247"
+ "line": " src/image/filters.js:263"
},
{
"message": "Missing item type\nreduces the bright areas in an image",
- "line": " src/image/filters.js:279"
+ "line": " src/image/filters.js:295"
},
{
"message": "Missing item type\nincreases the bright areas in an image",
- "line": " src/image/filters.js:367"
+ "line": " src/image/filters.js:383"
},
{
"message": "Missing item type\nThis module defines the p5 methods for the p5.Image class\nfor drawing images to the main display canvas.",
@@ -26490,11 +27134,11 @@ module.exports={
},
{
"message": "Missing item type\nValidates clipping params. Per drawImage spec sWidth and sHight cannot be\nnegative or greater than image intrinsic width and height",
- "line": " src/image/loading_displaying.js:108"
+ "line": " src/image/loading_displaying.js:110"
},
{
"message": "Missing item type\nApply the current tint color to the input image, return the resulting\ncanvas.",
- "line": " src/image/loading_displaying.js:425"
+ "line": " src/image/loading_displaying.js:427"
},
{
"message": "Missing item type\nThis module defines the p5.Image class and P5 methods for\ndrawing images to the main display canvas.",
@@ -26502,36 +27146,28 @@ module.exports={
},
{
"message": "Missing item type\nHelper fxn for sharing pixel methods",
- "line": " src/image/p5.Image.js:222"
+ "line": " src/image/p5.Image.js:223"
},
{
"message": "Missing item type\nGenerate 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.",
- "line": " src/io/files.js:1770"
+ "line": " src/io/files.js:1771"
},
{
"message": "Missing item type\nReturns a file extension, or another string\nif the provided parameter has no extension.",
- "line": " src/io/files.js:1839"
+ "line": " src/io/files.js:1840"
},
{
"message": "Missing item type\nReturns true if the browser is Safari, false if not.\nSafari makes trouble for downloading files.",
- "line": " src/io/files.js:1872"
+ "line": " src/io/files.js:1873"
},
{
"message": "Missing item type\nHelper function, a callback for download that deletes\nan invisible anchor element from the DOM once the file\nhas been automatically downloaded.",
- "line": " src/io/files.js:1884"
+ "line": " src/io/files.js:1885"
},
{
"message": "Missing item type\nTable Options\nGeneric class for handling tabular data, typically from a\nCSV, TSV, or other sort of spreadsheet file.
\nCSV files are\n\ncomma separated values, often with the data in quotes. TSV\nfiles use tabs as separators, and usually don't bother with the\nquotes.
\nFile names should end with .csv if they're comma separated.
\nA rough \"spec\" for CSV can be found\nhere.
\nTo load files, use the loadTable method.
\nTo save tables to your computer, use the save method\n or the saveTable method.
\n\nPossible options include:\n\n- csv - parse the table as comma-separated values\n
- tsv - parse the table as tab-separated values\n
- header - this table has a header (title) row\n
",
"line": " src/io/p5.Table.js:11"
},
- {
- "message": "Missing item type\nThis 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.",
- "line": " src/io/p5.XML.js:801"
- },
- {
- "message": "Missing item type\nThis 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.",
- "line": " src/io/p5.XML.js:818"
- },
{
"message": "Missing item type\nMultiplies a vector by a scalar and returns a new vector.",
"line": " src/math/p5.Vector.js:1611"
@@ -26558,27 +27194,27 @@ module.exports={
},
{
"message": "Missing item type\nHelper function to measure ascent and descent.",
- "line": " src/typography/attributes.js:282"
+ "line": " src/typography/attributes.js:284"
},
{
"message": "Missing item type\nReturns the set of opentype glyphs for the supplied string.\n\nNote 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.",
- "line": " src/typography/p5.Font.js:256"
+ "line": " src/typography/p5.Font.js:255"
},
{
"message": "Missing item type\nReturns an opentype path for the supplied string and position.",
- "line": " src/typography/p5.Font.js:271"
+ "line": " src/typography/p5.Font.js:270"
},
{
"message": "Missing item type",
- "line": " src/webgl/3d_primitives.js:259"
+ "line": " src/webgl/3d_primitives.js:260"
},
{
"message": "Missing item type\nDraws a point, a coordinate in space at the dimension of one pixel,\ngiven x, y and z coordinates. The color of the point is determined\nby the current stroke, while the point size is determined by current\nstroke weight.",
- "line": " src/webgl/3d_primitives.js:745"
+ "line": " src/webgl/3d_primitives.js:732"
},
{
"message": "Missing item type\nDraw a line given two points",
- "line": " src/webgl/3d_primitives.js:1162"
+ "line": " src/webgl/3d_primitives.js:1155"
},
{
"message": "Missing item type\nParse OBJ lines into model. For reference, this is what a simple model of a\nsquare might look like:\n\nv -0.5 -0.5 0.5\nv -0.5 -0.5 -0.5\nv -0.5 0.5 -0.5\nv -0.5 0.5 0.5\n\nf 4 3 2 1",
@@ -26586,7 +27222,11 @@ module.exports={
},
{
"message": "Missing item type",
- "line": " src/webgl/material.js:399"
+ "line": " src/webgl/material.js:659"
+ },
+ {
+ "message": "Missing item type",
+ "line": " src/webgl/material.js:681"
},
{
"message": "Missing item type\nCreate a 2D array for establishing stroke connections",
@@ -26602,7 +27242,7 @@ module.exports={
},
{
"message": "Missing item type\nPRIVATE",
- "line": " src/webgl/p5.Matrix.js:673"
+ "line": " src/webgl/p5.Matrix.js:730"
},
{
"message": "Missing item type\nWelcome 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.",
@@ -26610,7 +27250,7 @@ module.exports={
},
{
"message": "Missing item type\nEnd shape drawing and render vertices to screen.",
- "line": " src/webgl/p5.RendererGL.Immediate.js:118"
+ "line": " src/webgl/p5.RendererGL.Immediate.js:133"
},
{
"message": "Missing item type\ninitializes buffer defaults. runs each time a new geometry is\nregistered",
@@ -26622,43 +27262,43 @@ module.exports={
},
{
"message": "Missing item type\nDraws buffers given a geometry key ID",
- "line": " src/webgl/p5.RendererGL.Retained.js:191"
+ "line": " src/webgl/p5.RendererGL.Retained.js:196"
},
{
"message": "Missing item type\nmodel view, projection, & normal\nmatrices",
- "line": " src/webgl/p5.RendererGL.js:83"
+ "line": " src/webgl/p5.RendererGL.js:80"
},
{
"message": "Missing item type\n[background description]",
- "line": " src/webgl/p5.RendererGL.js:405"
+ "line": " src/webgl/p5.RendererGL.js:456"
},
{
"message": "Missing item type\n[resize description]",
- "line": " src/webgl/p5.RendererGL.js:644"
+ "line": " src/webgl/p5.RendererGL.js:707"
},
{
"message": "Missing item type\nclears color and depth buffers\nwith r,g,b,a",
- "line": " src/webgl/p5.RendererGL.js:670"
+ "line": " src/webgl/p5.RendererGL.js:738"
},
{
"message": "Missing item type\n[translate description]",
- "line": " src/webgl/p5.RendererGL.js:688"
+ "line": " src/webgl/p5.RendererGL.js:771"
},
{
"message": "Missing item type\nScales the Model View Matrix by a vector",
- "line": " src/webgl/p5.RendererGL.js:707"
+ "line": " src/webgl/p5.RendererGL.js:790"
},
{
"message": "Missing item type\nturn a two dimensional array into one dimensional array",
- "line": " src/webgl/p5.RendererGL.js:1028"
+ "line": " src/webgl/p5.RendererGL.js:1139"
},
{
"message": "Missing item type\nturn a p5.Vector Array into a one dimensional number array",
- "line": " src/webgl/p5.RendererGL.js:1065"
+ "line": " src/webgl/p5.RendererGL.js:1176"
},
{
"message": "Missing item type\nensures that p5 is using a 3d renderer. throws an error if not.",
- "line": " src/webgl/p5.RendererGL.js:1081"
+ "line": " src/webgl/p5.RendererGL.js:1192"
},
{
"message": "Missing item type\nHelper function for select and selectAll",
@@ -26670,35 +27310,35 @@ module.exports={
},
{
"message": "Missing item type\nHelpers for create methods.",
- "line": " lib/addons/p5.dom.js:245"
+ "line": " lib/addons/p5.dom.js:348"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.dom.js:384"
+ "line": " lib/addons/p5.dom.js:488"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.dom.js:981"
+ "line": " lib/addons/p5.dom.js:1070"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.dom.js:1062"
+ "line": " lib/addons/p5.dom.js:1159"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.dom.js:1102"
+ "line": " lib/addons/p5.dom.js:1199"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.dom.js:2777"
+ "line": " lib/addons/p5.dom.js:3029"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.dom.js:2843"
+ "line": " lib/addons/p5.dom.js:3095"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.dom.js:2905"
+ "line": " lib/addons/p5.dom.js:3157"
},
{
"message": "Missing item type\np5.sound \nhttps://p5js.org/reference/#/libraries/p5.sound\n\nFrom the Processing Foundation and contributors\nhttps://github.com/processing/p5.js-sound/graphs/contributors\n\nMIT License (MIT)\nhttps://github.com/processing/p5.js-sound/blob/master/LICENSE\n\nSome of the many audio libraries & resources that inspire p5.sound:\n - TONE.js (c) Yotam Mann. Licensed under The MIT License (MIT). https://github.com/TONEnoTONE/Tone.js\n - buzz.js (c) Jay Salvat. Licensed under The MIT License (MIT). http://buzz.jaysalvat.com/\n - Boris Smus Web Audio API book, 2013. Licensed under the Apache License http://www.apache.org/licenses/LICENSE-2.0\n - wavesurfer.js https://github.com/katspaugh/wavesurfer.js\n - Web Audio Components by Jordan Santell https://github.com/web-audio-components\n - Wilm Thoben's Sound library for Processing https://github.com/processing/processing/tree/master/java/libraries/sound\n\n Web Audio API: http://w3.org/TR/webaudio/",
@@ -26709,200 +27349,200 @@ module.exports={
"line": " lib/addons/p5.sound.js:214"
},
{
- "message": "Missing item type\nMaster contains AudioContext and the master sound output.",
- "line": " lib/addons/p5.sound.js:328"
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:363"
},
{
- "message": "Missing item type\na silent connection to the DesinationNode\nwhich will ensure that anything connected to it\nwill not be garbage collected",
- "line": " lib/addons/p5.sound.js:423"
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:740"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:439"
+ "line": " lib/addons/p5.sound.js:810"
},
{
- "message": "Missing item type\nUsed by Osc and Envelope to chain signal math",
- "line": " lib/addons/p5.sound.js:644"
+ "message": "Missing item type\nMaster contains AudioContext and the master sound output.",
+ "line": " lib/addons/p5.sound.js:1099"
},
{
- "message": "Missing item type\nThis is a helper function that the p5.SoundFile calls to load\nitself. Accepts a callback (the name of another function)\nas an optional parameter.",
- "line": " lib/addons/p5.sound.js:973"
+ "message": "Missing item type\na silent connection to the DesinationNode\nwhich will ensure that anything connected to it\nwill not be garbage collected",
+ "line": " lib/addons/p5.sound.js:1194"
},
{
- "message": "Missing item type\nStop playback on all of this soundfile's sources.",
- "line": " lib/addons/p5.sound.js:1379"
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:1210"
},
{
- "message": "Missing item type",
- "line": " lib/addons/p5.sound.js:1818"
+ "message": "Missing item type\nUsed by Osc and Envelope to chain signal math",
+ "line": " lib/addons/p5.sound.js:1415"
},
{
- "message": "Missing item type",
- "line": " lib/addons/p5.sound.js:2099"
+ "message": "Missing item type\nThis is a helper function that the p5.SoundFile calls to load\nitself. Accepts a callback (the name of another function)\nas an optional parameter.",
+ "line": " lib/addons/p5.sound.js:1813"
},
{
- "message": "Missing item type",
- "line": " lib/addons/p5.sound.js:3110"
+ "message": "Missing item type\nStop playback on all of this soundfile's sources.",
+ "line": " lib/addons/p5.sound.js:2218"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:3487"
+ "line": " lib/addons/p5.sound.js:2656"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:3508"
+ "line": " lib/addons/p5.sound.js:2934"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:3567"
+ "line": " lib/addons/p5.sound.js:4055"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:3885"
+ "line": " lib/addons/p5.sound.js:4076"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:4057"
+ "line": " lib/addons/p5.sound.js:4135"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:4215"
+ "line": " lib/addons/p5.sound.js:4453"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:4256"
+ "line": " lib/addons/p5.sound.js:4625"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:4326"
+ "line": " lib/addons/p5.sound.js:4783"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:4514"
+ "line": " lib/addons/p5.sound.js:4824"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:4571"
+ "line": " lib/addons/p5.sound.js:4881"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:4739"
+ "line": " lib/addons/p5.sound.js:5049"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:4787"
+ "line": " lib/addons/p5.sound.js:5097"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:4818"
+ "line": " lib/addons/p5.sound.js:5128"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:4839"
+ "line": " lib/addons/p5.sound.js:5149"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:4859"
+ "line": " lib/addons/p5.sound.js:5169"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:5572"
+ "line": " lib/addons/p5.sound.js:5879"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:5775"
+ "line": " lib/addons/p5.sound.js:6082"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:7426"
+ "line": " lib/addons/p5.sound.js:7750"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:7442"
+ "line": " lib/addons/p5.sound.js:7766"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:7466"
+ "line": " lib/addons/p5.sound.js:7790"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:7492"
+ "line": " lib/addons/p5.sound.js:7816"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:7514"
+ "line": " lib/addons/p5.sound.js:7838"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:7536"
+ "line": " lib/addons/p5.sound.js:7860"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:7582"
+ "line": " lib/addons/p5.sound.js:7906"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:7613"
+ "line": " lib/addons/p5.sound.js:7937"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:7631"
+ "line": " lib/addons/p5.sound.js:7955"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:7968"
+ "line": " lib/addons/p5.sound.js:8292"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:7990"
+ "line": " lib/addons/p5.sound.js:8314"
},
{
"message": "Missing item type\nThe p5.Effect class is built\n \tusing Tone.js CrossFade",
- "line": " lib/addons/p5.sound.js:8060"
+ "line": " lib/addons/p5.sound.js:8384"
},
{
"message": "Missing item type\nIn classes that extend\np5.Effect, connect effect nodes\nto the wet parameter",
- "line": " lib/addons/p5.sound.js:8066"
+ "line": " lib/addons/p5.sound.js:8390"
},
{
"message": "Missing item type\nEQFilter extends p5.Filter with constraints\nnecessary for the p5.EQ",
- "line": " lib/addons/p5.sound.js:8456"
+ "line": " lib/addons/p5.sound.js:8779"
},
{
"message": "Missing item type\nInspired by Simple Reverb by Jordan Santell\nhttps://github.com/web-audio-components/simple-reverb/blob/master/index.js\n\nUtility function for building an impulse response\nbased on the module parameters.",
- "line": " lib/addons/p5.sound.js:9552"
+ "line": " lib/addons/p5.sound.js:9889"
},
{
"message": "Missing item type\nPrivate method to load a buffer as an Impulse Response,\nassign it to the convolverNode, and add to the Array of .impulses.",
- "line": " lib/addons/p5.sound.js:9724"
+ "line": " lib/addons/p5.sound.js:10056"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:9912"
+ "line": " lib/addons/p5.sound.js:10240"
},
{
"message": "Missing item type",
- "line": " lib/addons/p5.sound.js:9937"
+ "line": " lib/addons/p5.sound.js:10265"
},
{
"message": "Missing item type\nmusicalTimeMode variables\nmodify these only when the interval is specified in musicalTime format as a string",
- "line": " lib/addons/p5.sound.js:10662"
+ "line": " lib/addons/p5.sound.js:10989"
},
{
"message": "Missing item type\nDo not initiate the callback if timeFromNow is < 0\nThis ususually occurs for a few milliseconds when the page\nis not fully loaded\n\nThe callback should only be called until maxIterations is reached",
- "line": " lib/addons/p5.sound.js:10678"
+ "line": " lib/addons/p5.sound.js:11005"
},
{
"message": "Missing item type\ncallback invoked when the recording is over",
- "line": " lib/addons/p5.sound.js:11167"
+ "line": " lib/addons/p5.sound.js:11495"
},
{
"message": "Missing item type\ninternal method called on audio process",
- "line": " lib/addons/p5.sound.js:11253"
+ "line": " lib/addons/p5.sound.js:11581"
},
{
"message": "Missing item type\nPrivate method to ensure accurate values of this._voicesInUse\nAny time a new value is scheduled, it is necessary to increment all subsequent\nscheduledValues after attack, and decrement all subsequent\nscheduledValues after release",
- "line": " lib/addons/p5.sound.js:12361"
+ "line": " lib/addons/p5.sound.js:12627"
},
{
"message": "Missing item type\np5.sound \nhttps://p5js.org/reference/#/libraries/p5.sound\n\nFrom the Processing Foundation and contributors\nhttps://github.com/processing/p5.js-sound/graphs/contributors\n\nMIT License (MIT)\nhttps://github.com/processing/p5.js-sound/blob/master/LICENSE\n\nSome of the many audio libraries & resources that inspire p5.sound:\n - TONE.js (c) Yotam Mann. Licensed under The MIT License (MIT). https://github.com/TONEnoTONE/Tone.js\n - buzz.js (c) Jay Salvat. Licensed under The MIT License (MIT). http://buzz.jaysalvat.com/\n - Boris Smus Web Audio API book, 2013. Licensed under the Apache License http://www.apache.org/licenses/LICENSE-2.0\n - wavesurfer.js https://github.com/katspaugh/wavesurfer.js\n - Web Audio Components by Jordan Santell https://github.com/web-audio-components\n - Wilm Thoben's Sound library for Processing https://github.com/processing/processing/tree/master/java/libraries/sound\n\n Web Audio API: http://w3.org/TR/webaudio/",
@@ -27003,9 +27643,6 @@ module.exports={
"TEXT": [
"p5.cursor"
],
- "WAIT": [
- "p5.cursor"
- ],
"P2D": [
"p5.createCanvas",
"p5.createGraphics"
@@ -27084,11 +27721,8 @@ module.exports={
"p5.Image.blend",
"p5.blend"
],
- "NORMAL": [
- "p5.blendMode",
- "p5.Image.blend",
- "p5.blend",
- "p5.textStyle"
+ "SUBTRACT": [
+ "p5.blendMode"
],
"THRESHOLD": [
"p5.Image.filter",
@@ -27122,6 +27756,12 @@ module.exports={
"p5.Image.filter",
"p5.filter"
],
+ "NORMAL": [
+ "p5.Image.blend",
+ "p5.blend",
+ "p5.textStyle",
+ "p5.textureMode"
+ ],
"RADIANS": [
"p5.angleMode"
],
@@ -27149,6 +27789,21 @@ module.exports={
"BOLD": [
"p5.textStyle"
],
+ "BOLDITALIC": [
+ "p5.textStyle"
+ ],
+ "IMAGE": [
+ "p5.textureMode"
+ ],
+ "CLAMP": [
+ "p5.textureWrap"
+ ],
+ "REPEAT": [
+ "p5.textureWrap"
+ ],
+ "MIRROR": [
+ "p5.textureWrap"
+ ],
"VIDEO": [
"p5.createCapture"
],
@@ -27158,139 +27813,165 @@ module.exports={
}
}
},{}],2:[function(_dereq_,module,exports){
-var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
-
-;(function (exports) {
- 'use strict';
-
- var Arr = (typeof Uint8Array !== 'undefined')
- ? Uint8Array
- : Array
-
- var PLUS = '+'.charCodeAt(0)
- var SLASH = '/'.charCodeAt(0)
- var NUMBER = '0'.charCodeAt(0)
- var LOWER = 'a'.charCodeAt(0)
- var UPPER = 'A'.charCodeAt(0)
- var PLUS_URL_SAFE = '-'.charCodeAt(0)
- var SLASH_URL_SAFE = '_'.charCodeAt(0)
-
- function decode (elt) {
- var code = elt.charCodeAt(0)
- if (code === PLUS ||
- code === PLUS_URL_SAFE)
- return 62 // '+'
- if (code === SLASH ||
- code === SLASH_URL_SAFE)
- return 63 // '/'
- if (code < NUMBER)
- return -1 //no match
- if (code < NUMBER + 10)
- return code - NUMBER + 26 + 26
- if (code < UPPER + 26)
- return code - UPPER
- if (code < LOWER + 26)
- return code - LOWER + 26
- }
+'use strict'
- function b64ToByteArray (b64) {
- var i, j, l, tmp, placeHolders, arr
+exports.byteLength = byteLength
+exports.toByteArray = toByteArray
+exports.fromByteArray = fromByteArray
- if (b64.length % 4 > 0) {
- throw new Error('Invalid string. Length must be a multiple of 4')
- }
+var lookup = []
+var revLookup = []
+var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
- // the number of equal signs (place holders)
- // if there are two placeholders, than the two characters before it
- // represent one byte
- // if there is only one, then the three characters before it represent 2 bytes
- // this is just a cheap hack to not do indexOf twice
- var len = b64.length
- placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
+var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
+for (var i = 0, len = code.length; i < len; ++i) {
+ lookup[i] = code[i]
+ revLookup[code.charCodeAt(i)] = i
+}
- // base64 is 4/3 + up to two characters of the original data
- arr = new Arr(b64.length * 3 / 4 - placeHolders)
+// Support decoding URL-safe base64 strings, as Node.js does.
+// See: https://en.wikipedia.org/wiki/Base64#URL_applications
+revLookup['-'.charCodeAt(0)] = 62
+revLookup['_'.charCodeAt(0)] = 63
- // if there are placeholders, only get up to the last complete 4 chars
- l = placeHolders > 0 ? b64.length - 4 : b64.length
+function getLens (b64) {
+ var len = b64.length
- var L = 0
+ if (len % 4 > 0) {
+ throw new Error('Invalid string. Length must be a multiple of 4')
+ }
- function push (v) {
- arr[L++] = v
- }
+ // Trim off extra bytes after placeholder bytes are found
+ // See: https://github.com/beatgammit/base64-js/issues/42
+ var validLen = b64.indexOf('=')
+ if (validLen === -1) validLen = len
- for (i = 0, j = 0; i < l; i += 4, j += 3) {
- tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
- push((tmp & 0xFF0000) >> 16)
- push((tmp & 0xFF00) >> 8)
- push(tmp & 0xFF)
- }
+ var placeHoldersLen = validLen === len
+ ? 0
+ : 4 - (validLen % 4)
- if (placeHolders === 2) {
- tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
- push(tmp & 0xFF)
- } else if (placeHolders === 1) {
- tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
- push((tmp >> 8) & 0xFF)
- push(tmp & 0xFF)
- }
+ return [validLen, placeHoldersLen]
+}
- return arr
- }
+// base64 is 4/3 + up to two characters of the original data
+function byteLength (b64) {
+ var lens = getLens(b64)
+ var validLen = lens[0]
+ var placeHoldersLen = lens[1]
+ return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
+}
- function uint8ToBase64 (uint8) {
- var i,
- extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
- output = "",
- temp, length
+function _byteLength (b64, validLen, placeHoldersLen) {
+ return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
+}
- function encode (num) {
- return lookup.charAt(num)
- }
+function toByteArray (b64) {
+ var tmp
+ var lens = getLens(b64)
+ var validLen = lens[0]
+ var placeHoldersLen = lens[1]
- function tripletToBase64 (num) {
- return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
- }
+ var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
- // go through the array every three bytes, we'll deal with trailing stuff later
- for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
- temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
- output += tripletToBase64(temp)
- }
+ var curByte = 0
- // pad the end with zeros, but make sure to not forget the extra bytes
- switch (extraBytes) {
- case 1:
- temp = uint8[uint8.length - 1]
- output += encode(temp >> 2)
- output += encode((temp << 4) & 0x3F)
- output += '=='
- break
- case 2:
- temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
- output += encode(temp >> 10)
- output += encode((temp >> 4) & 0x3F)
- output += encode((temp << 2) & 0x3F)
- output += '='
- break
- }
+ // if there are placeholders, only get up to the last complete 4 chars
+ var len = placeHoldersLen > 0
+ ? validLen - 4
+ : validLen
- return output
- }
+ for (var i = 0; i < len; i += 4) {
+ tmp =
+ (revLookup[b64.charCodeAt(i)] << 18) |
+ (revLookup[b64.charCodeAt(i + 1)] << 12) |
+ (revLookup[b64.charCodeAt(i + 2)] << 6) |
+ revLookup[b64.charCodeAt(i + 3)]
+ arr[curByte++] = (tmp >> 16) & 0xFF
+ arr[curByte++] = (tmp >> 8) & 0xFF
+ arr[curByte++] = tmp & 0xFF
+ }
- exports.toByteArray = b64ToByteArray
- exports.fromByteArray = uint8ToBase64
-}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
+ if (placeHoldersLen === 2) {
+ tmp =
+ (revLookup[b64.charCodeAt(i)] << 2) |
+ (revLookup[b64.charCodeAt(i + 1)] >> 4)
+ arr[curByte++] = tmp & 0xFF
+ }
+
+ if (placeHoldersLen === 1) {
+ tmp =
+ (revLookup[b64.charCodeAt(i)] << 10) |
+ (revLookup[b64.charCodeAt(i + 1)] << 4) |
+ (revLookup[b64.charCodeAt(i + 2)] >> 2)
+ arr[curByte++] = (tmp >> 8) & 0xFF
+ arr[curByte++] = tmp & 0xFF
+ }
+
+ return arr
+}
+
+function tripletToBase64 (num) {
+ return lookup[num >> 18 & 0x3F] +
+ lookup[num >> 12 & 0x3F] +
+ lookup[num >> 6 & 0x3F] +
+ lookup[num & 0x3F]
+}
+
+function encodeChunk (uint8, start, end) {
+ var tmp
+ var output = []
+ for (var i = start; i < end; i += 3) {
+ tmp =
+ ((uint8[i] << 16) & 0xFF0000) +
+ ((uint8[i + 1] << 8) & 0xFF00) +
+ (uint8[i + 2] & 0xFF)
+ output.push(tripletToBase64(tmp))
+ }
+ return output.join('')
+}
+
+function fromByteArray (uint8) {
+ var tmp
+ var len = uint8.length
+ var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
+ var parts = []
+ var maxChunkLength = 16383 // must be multiple of 3
+
+ // go through the array every three bytes, we'll deal with trailing stuff later
+ for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
+ parts.push(encodeChunk(
+ uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
+ ))
+ }
+
+ // pad the end with zeros, but make sure to not forget the extra bytes
+ if (extraBytes === 1) {
+ tmp = uint8[len - 1]
+ parts.push(
+ lookup[tmp >> 2] +
+ lookup[(tmp << 4) & 0x3F] +
+ '=='
+ )
+ } else if (extraBytes === 2) {
+ tmp = (uint8[len - 2] << 8) + uint8[len - 1]
+ parts.push(
+ lookup[tmp >> 10] +
+ lookup[(tmp >> 4) & 0x3F] +
+ lookup[(tmp << 2) & 0x3F] +
+ '='
+ )
+ }
+
+ return parts.join('')
+}
},{}],3:[function(_dereq_,module,exports){
},{}],4:[function(_dereq_,module,exports){
-(function (global){
/*!
* The buffer module from node.js, for the browser.
*
- * @author Feross Aboukhadijeh
+ * @author Feross Aboukhadijeh
* @license MIT
*/
/* eslint-disable no-proto */
@@ -27299,268 +27980,336 @@ var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var base64 = _dereq_('base64-js')
var ieee754 = _dereq_('ieee754')
-var isArray = _dereq_('isarray')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
-Buffer.poolSize = 8192 // not used by this implementation
-var rootParent = {}
+var K_MAX_LENGTH = 0x7fffffff
+exports.kMaxLength = K_MAX_LENGTH
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
- * === false Use Object implementation (most compatible, even IE6)
+ * === false Print warning and recommend using `buffer` v4.x which has an Object
+ * implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
- * Due to various browser bugs, sometimes the Object implementation will be used even
- * when the browser supports typed arrays.
- *
- * Note:
- *
- * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
- * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
- *
- * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property
- * on objects.
- *
- * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
- *
- * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
- * incorrect length in some situations.
-
- * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
- * get the Object implementation, which is slower but behaves correctly.
+ * We report that the browser does not support typed arrays if the are not subclassable
+ * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
+ * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
+ * for __proto__ and has a buggy typed array implementation.
*/
-Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
- ? global.TYPED_ARRAY_SUPPORT
- : typedArraySupport()
+Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
+
+if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
+ typeof console.error === 'function') {
+ console.error(
+ 'This browser lacks typed array (Uint8Array) support which is required by ' +
+ '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
+ )
+}
function typedArraySupport () {
- function Bar () {}
+ // Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1)
- arr.foo = function () { return 42 }
- arr.constructor = Bar
- return arr.foo() === 42 && // typed array instances can be augmented
- arr.constructor === Bar && // constructor can be set
- typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
- arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
+ arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
+ return arr.foo() === 42
} catch (e) {
return false
}
}
-function kMaxLength () {
- return Buffer.TYPED_ARRAY_SUPPORT
- ? 0x7fffffff
- : 0x3fffffff
+Object.defineProperty(Buffer.prototype, 'parent', {
+ enumerable: true,
+ get: function () {
+ if (!Buffer.isBuffer(this)) return undefined
+ return this.buffer
+ }
+})
+
+Object.defineProperty(Buffer.prototype, 'offset', {
+ enumerable: true,
+ get: function () {
+ if (!Buffer.isBuffer(this)) return undefined
+ return this.byteOffset
+ }
+})
+
+function createBuffer (length) {
+ if (length > K_MAX_LENGTH) {
+ throw new RangeError('The value "' + length + '" is invalid for option "size"')
+ }
+ // Return an augmented `Uint8Array` instance
+ var buf = new Uint8Array(length)
+ buf.__proto__ = Buffer.prototype
+ return buf
}
/**
- * Class: Buffer
- * =============
+ * The Buffer constructor returns instances of `Uint8Array` that have their
+ * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
+ * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
+ * and the `Uint8Array` methods. Square bracket notation works as expected -- it
+ * returns a single octet.
*
- * The Buffer constructor returns instances of `Uint8Array` that are augmented
- * with function properties for all the node `Buffer` API functions. We use
- * `Uint8Array` so that square bracket notation works as expected -- it returns
- * a single octet.
- *
- * By augmenting the instances, we can avoid modifying the `Uint8Array`
- * prototype.
+ * The `Uint8Array` prototype remains unmodified.
*/
-function Buffer (arg) {
- if (!(this instanceof Buffer)) {
- // Avoid going through an ArgumentsAdaptorTrampoline in the common case.
- if (arguments.length > 1) return new Buffer(arg, arguments[1])
- return new Buffer(arg)
+
+function Buffer (arg, encodingOrOffset, length) {
+ // Common case.
+ if (typeof arg === 'number') {
+ if (typeof encodingOrOffset === 'string') {
+ throw new TypeError(
+ 'The "string" argument must be of type string. Received type number'
+ )
+ }
+ return allocUnsafe(arg)
}
+ return from(arg, encodingOrOffset, length)
+}
+
+// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
+if (typeof Symbol !== 'undefined' && Symbol.species != null &&
+ Buffer[Symbol.species] === Buffer) {
+ Object.defineProperty(Buffer, Symbol.species, {
+ value: null,
+ configurable: true,
+ enumerable: false,
+ writable: false
+ })
+}
+
+Buffer.poolSize = 8192 // not used by this implementation
- if (!Buffer.TYPED_ARRAY_SUPPORT) {
- this.length = 0
- this.parent = undefined
+function from (value, encodingOrOffset, length) {
+ if (typeof value === 'string') {
+ return fromString(value, encodingOrOffset)
}
- // Common case.
- if (typeof arg === 'number') {
- return fromNumber(this, arg)
+ if (ArrayBuffer.isView(value)) {
+ return fromArrayLike(value)
}
- // Slightly less common case.
- if (typeof arg === 'string') {
- return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
+ if (value == null) {
+ throw TypeError(
+ 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
+ 'or Array-like Object. Received type ' + (typeof value)
+ )
}
- // Unusual.
- return fromObject(this, arg)
-}
+ if (isInstance(value, ArrayBuffer) ||
+ (value && isInstance(value.buffer, ArrayBuffer))) {
+ return fromArrayBuffer(value, encodingOrOffset, length)
+ }
-function fromNumber (that, length) {
- that = allocate(that, length < 0 ? 0 : checked(length) | 0)
- if (!Buffer.TYPED_ARRAY_SUPPORT) {
- for (var i = 0; i < length; i++) {
- that[i] = 0
- }
+ if (typeof value === 'number') {
+ throw new TypeError(
+ 'The "value" argument must not be of type number. Received type number'
+ )
}
- return that
-}
-function fromString (that, string, encoding) {
- if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
+ var valueOf = value.valueOf && value.valueOf()
+ if (valueOf != null && valueOf !== value) {
+ return Buffer.from(valueOf, encodingOrOffset, length)
+ }
- // Assumption: byteLength() return value is always < kMaxLength.
- var length = byteLength(string, encoding) | 0
- that = allocate(that, length)
+ var b = fromObject(value)
+ if (b) return b
+
+ if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
+ typeof value[Symbol.toPrimitive] === 'function') {
+ return Buffer.from(
+ value[Symbol.toPrimitive]('string'), encodingOrOffset, length
+ )
+ }
- that.write(string, encoding)
- return that
+ throw new TypeError(
+ 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
+ 'or Array-like Object. Received type ' + (typeof value)
+ )
}
-function fromObject (that, object) {
- if (Buffer.isBuffer(object)) return fromBuffer(that, object)
+/**
+ * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
+ * if value is a number.
+ * Buffer.from(str[, encoding])
+ * Buffer.from(array)
+ * Buffer.from(buffer)
+ * Buffer.from(arrayBuffer[, byteOffset[, length]])
+ **/
+Buffer.from = function (value, encodingOrOffset, length) {
+ return from(value, encodingOrOffset, length)
+}
- if (isArray(object)) return fromArray(that, object)
+// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
+// https://github.com/feross/buffer/pull/148
+Buffer.prototype.__proto__ = Uint8Array.prototype
+Buffer.__proto__ = Uint8Array
- if (object == null) {
- throw new TypeError('must start with number, buffer, array or string')
+function assertSize (size) {
+ if (typeof size !== 'number') {
+ throw new TypeError('"size" argument must be of type number')
+ } else if (size < 0) {
+ throw new RangeError('The value "' + size + '" is invalid for option "size"')
}
+}
- if (typeof ArrayBuffer !== 'undefined') {
- if (object.buffer instanceof ArrayBuffer) {
- return fromTypedArray(that, object)
- }
- if (object instanceof ArrayBuffer) {
- return fromArrayBuffer(that, object)
- }
+function alloc (size, fill, encoding) {
+ assertSize(size)
+ if (size <= 0) {
+ return createBuffer(size)
}
+ if (fill !== undefined) {
+ // Only pay attention to encoding if it's a string. This
+ // prevents accidentally sending in a number that would
+ // be interpretted as a start offset.
+ return typeof encoding === 'string'
+ ? createBuffer(size).fill(fill, encoding)
+ : createBuffer(size).fill(fill)
+ }
+ return createBuffer(size)
+}
- if (object.length) return fromArrayLike(that, object)
+/**
+ * Creates a new filled Buffer instance.
+ * alloc(size[, fill[, encoding]])
+ **/
+Buffer.alloc = function (size, fill, encoding) {
+ return alloc(size, fill, encoding)
+}
- return fromJsonObject(that, object)
+function allocUnsafe (size) {
+ assertSize(size)
+ return createBuffer(size < 0 ? 0 : checked(size) | 0)
}
-function fromBuffer (that, buffer) {
- var length = checked(buffer.length) | 0
- that = allocate(that, length)
- buffer.copy(that, 0, 0, length)
- return that
+/**
+ * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
+ * */
+Buffer.allocUnsafe = function (size) {
+ return allocUnsafe(size)
+}
+/**
+ * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
+ */
+Buffer.allocUnsafeSlow = function (size) {
+ return allocUnsafe(size)
}
-function fromArray (that, array) {
- var length = checked(array.length) | 0
- that = allocate(that, length)
- for (var i = 0; i < length; i += 1) {
- that[i] = array[i] & 255
+function fromString (string, encoding) {
+ if (typeof encoding !== 'string' || encoding === '') {
+ encoding = 'utf8'
}
- return that
-}
-// Duplicate of fromArray() to keep fromArray() monomorphic.
-function fromTypedArray (that, array) {
- var length = checked(array.length) | 0
- that = allocate(that, length)
- // Truncating the elements is probably not what people expect from typed
- // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
- // of the old Buffer constructor.
- for (var i = 0; i < length; i += 1) {
- that[i] = array[i] & 255
+ if (!Buffer.isEncoding(encoding)) {
+ throw new TypeError('Unknown encoding: ' + encoding)
}
- return that
-}
-function fromArrayBuffer (that, array) {
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- // Return an augmented `Uint8Array` instance, for best performance
- array.byteLength
- that = Buffer._augment(new Uint8Array(array))
- } else {
- // Fallback: Return an object instance of the Buffer class
- that = fromTypedArray(that, new Uint8Array(array))
+ var length = byteLength(string, encoding) | 0
+ var buf = createBuffer(length)
+
+ var actual = buf.write(string, encoding)
+
+ if (actual !== length) {
+ // Writing a hex string, for example, that contains invalid characters will
+ // cause everything after the first invalid character to be ignored. (e.g.
+ // 'abxxcd' will be treated as 'ab')
+ buf = buf.slice(0, actual)
}
- return that
+
+ return buf
}
-function fromArrayLike (that, array) {
- var length = checked(array.length) | 0
- that = allocate(that, length)
+function fromArrayLike (array) {
+ var length = array.length < 0 ? 0 : checked(array.length) | 0
+ var buf = createBuffer(length)
for (var i = 0; i < length; i += 1) {
- that[i] = array[i] & 255
+ buf[i] = array[i] & 255
}
- return that
+ return buf
}
-// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
-// Returns a zero-length buffer for inputs that don't conform to the spec.
-function fromJsonObject (that, object) {
- var array
- var length = 0
+function fromArrayBuffer (array, byteOffset, length) {
+ if (byteOffset < 0 || array.byteLength < byteOffset) {
+ throw new RangeError('"offset" is outside of buffer bounds')
+ }
- if (object.type === 'Buffer' && isArray(object.data)) {
- array = object.data
- length = checked(array.length) | 0
+ if (array.byteLength < byteOffset + (length || 0)) {
+ throw new RangeError('"length" is outside of buffer bounds')
}
- that = allocate(that, length)
- for (var i = 0; i < length; i += 1) {
- that[i] = array[i] & 255
+ var buf
+ if (byteOffset === undefined && length === undefined) {
+ buf = new Uint8Array(array)
+ } else if (length === undefined) {
+ buf = new Uint8Array(array, byteOffset)
+ } else {
+ buf = new Uint8Array(array, byteOffset, length)
}
- return that
-}
-if (Buffer.TYPED_ARRAY_SUPPORT) {
- Buffer.prototype.__proto__ = Uint8Array.prototype
- Buffer.__proto__ = Uint8Array
-} else {
- // pre-set for values that may exist in the future
- Buffer.prototype.length = undefined
- Buffer.prototype.parent = undefined
+ // Return an augmented `Uint8Array` instance
+ buf.__proto__ = Buffer.prototype
+ return buf
}
-function allocate (that, length) {
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- // Return an augmented `Uint8Array` instance, for best performance
- that = Buffer._augment(new Uint8Array(length))
- that.__proto__ = Buffer.prototype
- } else {
- // Fallback: Return an object instance of the Buffer class
- that.length = length
- that._isBuffer = true
+function fromObject (obj) {
+ if (Buffer.isBuffer(obj)) {
+ var len = checked(obj.length) | 0
+ var buf = createBuffer(len)
+
+ if (buf.length === 0) {
+ return buf
+ }
+
+ obj.copy(buf, 0, 0, len)
+ return buf
}
- var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
- if (fromPool) that.parent = rootParent
+ if (obj.length !== undefined) {
+ if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
+ return createBuffer(0)
+ }
+ return fromArrayLike(obj)
+ }
- return that
+ if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
+ return fromArrayLike(obj.data)
+ }
}
function checked (length) {
- // Note: cannot use `length < kMaxLength` here because that fails when
+ // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
- if (length >= kMaxLength()) {
+ if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
- 'size: 0x' + kMaxLength().toString(16) + ' bytes')
+ 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
}
return length | 0
}
-function SlowBuffer (subject, encoding) {
- if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
-
- var buf = new Buffer(subject, encoding)
- delete buf.parent
- return buf
+function SlowBuffer (length) {
+ if (+length != length) { // eslint-disable-line eqeqeq
+ length = 0
+ }
+ return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
- return !!(b != null && b._isBuffer)
+ return b != null && b._isBuffer === true &&
+ b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
}
Buffer.compare = function compare (a, b) {
+ if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
+ if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
- throw new TypeError('Arguments must be Buffers')
+ throw new TypeError(
+ 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
+ )
}
if (a === b) return 0
@@ -27568,17 +28317,12 @@ Buffer.compare = function compare (a, b) {
var x = a.length
var y = b.length
- var i = 0
- var len = Math.min(x, y)
- while (i < len) {
- if (a[i] !== b[i]) break
-
- ++i
- }
-
- if (i !== len) {
- x = a[i]
- y = b[i]
+ for (var i = 0, len = Math.min(x, y); i < len; ++i) {
+ if (a[i] !== b[i]) {
+ x = a[i]
+ y = b[i]
+ break
+ }
}
if (x < y) return -1
@@ -27592,9 +28336,9 @@ Buffer.isEncoding = function isEncoding (encoding) {
case 'utf8':
case 'utf-8':
case 'ascii':
+ case 'latin1':
case 'binary':
case 'base64':
- case 'raw':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
@@ -27606,45 +28350,63 @@ Buffer.isEncoding = function isEncoding (encoding) {
}
Buffer.concat = function concat (list, length) {
- if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
+ if (!Array.isArray(list)) {
+ throw new TypeError('"list" argument must be an Array of Buffers')
+ }
if (list.length === 0) {
- return new Buffer(0)
+ return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
- for (i = 0; i < list.length; i++) {
+ for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
- var buf = new Buffer(length)
+ var buffer = Buffer.allocUnsafe(length)
var pos = 0
- for (i = 0; i < list.length; i++) {
- var item = list[i]
- item.copy(buf, pos)
- pos += item.length
+ for (i = 0; i < list.length; ++i) {
+ var buf = list[i]
+ if (isInstance(buf, Uint8Array)) {
+ buf = Buffer.from(buf)
+ }
+ if (!Buffer.isBuffer(buf)) {
+ throw new TypeError('"list" argument must be an Array of Buffers')
+ }
+ buf.copy(buffer, pos)
+ pos += buf.length
}
- return buf
+ return buffer
}
function byteLength (string, encoding) {
- if (typeof string !== 'string') string = '' + string
+ if (Buffer.isBuffer(string)) {
+ return string.length
+ }
+ if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
+ return string.byteLength
+ }
+ if (typeof string !== 'string') {
+ throw new TypeError(
+ 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
+ 'Received type ' + typeof string
+ )
+ }
var len = string.length
- if (len === 0) return 0
+ var mustMatch = (arguments.length > 2 && arguments[2] === true)
+ if (!mustMatch && len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
+ case 'latin1':
case 'binary':
- // Deprecated
- case 'raw':
- case 'raws':
return len
case 'utf8':
case 'utf-8':
@@ -27659,7 +28421,9 @@ function byteLength (string, encoding) {
case 'base64':
return base64ToBytes(string).length
default:
- if (loweredCase) return utf8ToBytes(string).length // assume utf8
+ if (loweredCase) {
+ return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
+ }
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
@@ -27670,13 +28434,39 @@ Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
- start = start | 0
- end = end === undefined || end === Infinity ? this.length : end | 0
+ // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
+ // property of a typed array.
+
+ // This behaves neither like String nor Uint8Array in that we set start/end
+ // to their upper/lower bounds if the value passed is out of range.
+ // undefined is handled specially as per ECMA-262 6th Edition,
+ // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
+ if (start === undefined || start < 0) {
+ start = 0
+ }
+ // Return early if start > this.length. Done here to prevent potential uint32
+ // coercion fail below.
+ if (start > this.length) {
+ return ''
+ }
+
+ if (end === undefined || end > this.length) {
+ end = this.length
+ }
+
+ if (end <= 0) {
+ return ''
+ }
+
+ // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
+ end >>>= 0
+ start >>>= 0
+
+ if (end <= start) {
+ return ''
+ }
if (!encoding) encoding = 'utf8'
- if (start < 0) start = 0
- if (end > this.length) end = this.length
- if (end <= start) return ''
while (true) {
switch (encoding) {
@@ -27690,8 +28480,9 @@ function slowToString (encoding, start, end) {
case 'ascii':
return asciiSlice(this, start, end)
+ case 'latin1':
case 'binary':
- return binarySlice(this, start, end)
+ return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
@@ -27710,13 +28501,66 @@ function slowToString (encoding, start, end) {
}
}
+// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
+// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
+// reliably in a browserify context because there could be multiple different
+// copies of the 'buffer' package in use. This method works even for Buffer
+// instances that were created from another copy of the `buffer` package.
+// See: https://github.com/feross/buffer/issues/154
+Buffer.prototype._isBuffer = true
+
+function swap (b, n, m) {
+ var i = b[n]
+ b[n] = b[m]
+ b[m] = i
+}
+
+Buffer.prototype.swap16 = function swap16 () {
+ var len = this.length
+ if (len % 2 !== 0) {
+ throw new RangeError('Buffer size must be a multiple of 16-bits')
+ }
+ for (var i = 0; i < len; i += 2) {
+ swap(this, i, i + 1)
+ }
+ return this
+}
+
+Buffer.prototype.swap32 = function swap32 () {
+ var len = this.length
+ if (len % 4 !== 0) {
+ throw new RangeError('Buffer size must be a multiple of 32-bits')
+ }
+ for (var i = 0; i < len; i += 4) {
+ swap(this, i, i + 3)
+ swap(this, i + 1, i + 2)
+ }
+ return this
+}
+
+Buffer.prototype.swap64 = function swap64 () {
+ var len = this.length
+ if (len % 8 !== 0) {
+ throw new RangeError('Buffer size must be a multiple of 64-bits')
+ }
+ for (var i = 0; i < len; i += 8) {
+ swap(this, i, i + 7)
+ swap(this, i + 1, i + 6)
+ swap(this, i + 2, i + 5)
+ swap(this, i + 3, i + 4)
+ }
+ return this
+}
+
Buffer.prototype.toString = function toString () {
- var length = this.length | 0
+ var length = this.length
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
+Buffer.prototype.toLocaleString = Buffer.prototype.toString
+
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
@@ -27726,70 +28570,207 @@ Buffer.prototype.equals = function equals (b) {
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
- if (this.length > 0) {
- str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
- if (this.length > max) str += ' ... '
- }
+ str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
+ if (this.length > max) str += ' ... '
return ''
}
-Buffer.prototype.compare = function compare (b) {
- if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
- if (this === b) return 0
- return Buffer.compare(this, b)
-}
+Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
+ if (isInstance(target, Uint8Array)) {
+ target = Buffer.from(target, target.offset, target.byteLength)
+ }
+ if (!Buffer.isBuffer(target)) {
+ throw new TypeError(
+ 'The "target" argument must be one of type Buffer or Uint8Array. ' +
+ 'Received type ' + (typeof target)
+ )
+ }
-Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
- if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
- else if (byteOffset < -0x80000000) byteOffset = -0x80000000
- byteOffset >>= 0
+ if (start === undefined) {
+ start = 0
+ }
+ if (end === undefined) {
+ end = target ? target.length : 0
+ }
+ if (thisStart === undefined) {
+ thisStart = 0
+ }
+ if (thisEnd === undefined) {
+ thisEnd = this.length
+ }
+
+ if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
+ throw new RangeError('out of range index')
+ }
+
+ if (thisStart >= thisEnd && start >= end) {
+ return 0
+ }
+ if (thisStart >= thisEnd) {
+ return -1
+ }
+ if (start >= end) {
+ return 1
+ }
- if (this.length === 0) return -1
- if (byteOffset >= this.length) return -1
+ start >>>= 0
+ end >>>= 0
+ thisStart >>>= 0
+ thisEnd >>>= 0
+
+ if (this === target) return 0
+
+ var x = thisEnd - thisStart
+ var y = end - start
+ var len = Math.min(x, y)
+
+ var thisCopy = this.slice(thisStart, thisEnd)
+ var targetCopy = target.slice(start, end)
+
+ for (var i = 0; i < len; ++i) {
+ if (thisCopy[i] !== targetCopy[i]) {
+ x = thisCopy[i]
+ y = targetCopy[i]
+ break
+ }
+ }
- // Negative offsets start from the end of the buffer
- if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
+ if (x < y) return -1
+ if (y < x) return 1
+ return 0
+}
+// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
+// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
+//
+// Arguments:
+// - buffer - a Buffer to search
+// - val - a string, Buffer, or number
+// - byteOffset - an index into `buffer`; will be clamped to an int32
+// - encoding - an optional encoding, relevant is val is a string
+// - dir - true for indexOf, false for lastIndexOf
+function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
+ // Empty buffer means no match
+ if (buffer.length === 0) return -1
+
+ // Normalize byteOffset
+ if (typeof byteOffset === 'string') {
+ encoding = byteOffset
+ byteOffset = 0
+ } else if (byteOffset > 0x7fffffff) {
+ byteOffset = 0x7fffffff
+ } else if (byteOffset < -0x80000000) {
+ byteOffset = -0x80000000
+ }
+ byteOffset = +byteOffset // Coerce to Number.
+ if (numberIsNaN(byteOffset)) {
+ // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
+ byteOffset = dir ? 0 : (buffer.length - 1)
+ }
+
+ // Normalize byteOffset: negative offsets start from the end of the buffer
+ if (byteOffset < 0) byteOffset = buffer.length + byteOffset
+ if (byteOffset >= buffer.length) {
+ if (dir) return -1
+ else byteOffset = buffer.length - 1
+ } else if (byteOffset < 0) {
+ if (dir) byteOffset = 0
+ else return -1
+ }
+
+ // Normalize val
if (typeof val === 'string') {
- if (val.length === 0) return -1 // special case: looking for empty string always fails
- return String.prototype.indexOf.call(this, val, byteOffset)
+ val = Buffer.from(val, encoding)
}
+
+ // Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
- return arrayIndexOf(this, val, byteOffset)
+ // Special case: looking for empty string/buffer always fails
+ if (val.length === 0) {
+ return -1
+ }
+ return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
+ } else if (typeof val === 'number') {
+ val = val & 0xFF // Search for a byte value [0-255]
+ if (typeof Uint8Array.prototype.indexOf === 'function') {
+ if (dir) {
+ return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
+ } else {
+ return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
+ }
+ }
+ return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
- if (typeof val === 'number') {
- if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
- return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
+
+ throw new TypeError('val must be string, number or Buffer')
+}
+
+function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
+ var indexSize = 1
+ var arrLength = arr.length
+ var valLength = val.length
+
+ if (encoding !== undefined) {
+ encoding = String(encoding).toLowerCase()
+ if (encoding === 'ucs2' || encoding === 'ucs-2' ||
+ encoding === 'utf16le' || encoding === 'utf-16le') {
+ if (arr.length < 2 || val.length < 2) {
+ return -1
+ }
+ indexSize = 2
+ arrLength /= 2
+ valLength /= 2
+ byteOffset /= 2
}
- return arrayIndexOf(this, [ val ], byteOffset)
}
- function arrayIndexOf (arr, val, byteOffset) {
+ function read (buf, i) {
+ if (indexSize === 1) {
+ return buf[i]
+ } else {
+ return buf.readUInt16BE(i * indexSize)
+ }
+ }
+
+ var i
+ if (dir) {
var foundIndex = -1
- for (var i = 0; byteOffset + i < arr.length; i++) {
- if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
+ for (i = byteOffset; i < arrLength; i++) {
+ if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
- if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
+ if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
+ if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
- return -1
+ } else {
+ if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
+ for (i = byteOffset; i >= 0; i--) {
+ var found = true
+ for (var j = 0; j < valLength; j++) {
+ if (read(arr, i + j) !== read(val, j)) {
+ found = false
+ break
+ }
+ }
+ if (found) return i
+ }
}
- throw new TypeError('val must be string, number or Buffer')
+ return -1
}
-// `get` is deprecated
-Buffer.prototype.get = function get (offset) {
- console.log('.get() is deprecated. Access using array indexes instead.')
- return this.readUInt8(offset)
+Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
+ return this.indexOf(val, byteOffset, encoding) !== -1
}
-// `set` is deprecated
-Buffer.prototype.set = function set (v, offset) {
- console.log('.set() is deprecated. Access using array indexes instead.')
- return this.writeUInt8(v, offset)
+Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
+}
+
+Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
@@ -27804,16 +28785,14 @@ function hexWrite (buf, string, offset, length) {
}
}
- // must be an even number of digits
var strLen = string.length
- if (strLen % 2 !== 0) throw new Error('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
- for (var i = 0; i < length; i++) {
+ for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
- if (isNaN(parsed)) throw new Error('Invalid hex string')
+ if (numberIsNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
@@ -27827,7 +28806,7 @@ function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
-function binaryWrite (buf, string, offset, length) {
+function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
@@ -27852,27 +28831,25 @@ Buffer.prototype.write = function write (string, offset, length, encoding) {
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
- offset = offset | 0
+ offset = offset >>> 0
if (isFinite(length)) {
- length = length | 0
+ length = length >>> 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
- // legacy write(string, encoding, offset, length) - remove in v0.13
} else {
- var swap = encoding
- encoding = offset
- offset = length | 0
- length = swap
+ throw new Error(
+ 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
+ )
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
- throw new RangeError('attempt to write outside buffer bounds')
+ throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
@@ -27890,8 +28867,9 @@ Buffer.prototype.write = function write (string, offset, length, encoding) {
case 'ascii':
return asciiWrite(this, string, offset, length)
+ case 'latin1':
case 'binary':
- return binaryWrite(this, string, offset, length)
+ return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
@@ -27936,8 +28914,8 @@ function utf8Slice (buf, start, end) {
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
- : (firstByte > 0xBF) ? 2
- : 1
+ : (firstByte > 0xBF) ? 2
+ : 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
@@ -28026,17 +29004,17 @@ function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
- for (var i = start; i < end; i++) {
+ for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
-function binarySlice (buf, start, end) {
+function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
- for (var i = start; i < end; i++) {
+ for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
@@ -28049,7 +29027,7 @@ function hexSlice (buf, start, end) {
if (!end || end < 0 || end > len) end = len
var out = ''
- for (var i = start; i < end; i++) {
+ for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
@@ -28059,7 +29037,7 @@ function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
- res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
+ res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
}
return res
}
@@ -28085,19 +29063,9 @@ Buffer.prototype.slice = function slice (start, end) {
if (end < start) end = start
- var newBuf
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- newBuf = Buffer._augment(this.subarray(start, end))
- } else {
- var sliceLen = end - start
- newBuf = new Buffer(sliceLen, undefined)
- for (var i = 0; i < sliceLen; i++) {
- newBuf[i] = this[i + start]
- }
- }
-
- if (newBuf.length) newBuf.parent = this.parent || this
-
+ var newBuf = this.subarray(start, end)
+ // Return an augmented `Uint8Array` instance
+ newBuf.__proto__ = Buffer.prototype
return newBuf
}
@@ -28110,8 +29078,8 @@ function checkOffset (offset, ext, length) {
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
- offset = offset | 0
- byteLength = byteLength | 0
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
@@ -28125,8 +29093,8 @@ Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert)
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
- offset = offset | 0
- byteLength = byteLength | 0
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
@@ -28141,21 +29109,25 @@ Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert)
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
+ offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
+ offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
+ offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
+ offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
@@ -28165,6 +29137,7 @@ Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
+ offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
@@ -28174,8 +29147,8 @@ Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
- offset = offset | 0
- byteLength = byteLength | 0
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
@@ -28192,8 +29165,8 @@ Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
- offset = offset | 0
- byteLength = byteLength | 0
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
@@ -28210,24 +29183,28 @@ Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
+ offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
+ offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
+ offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
+ offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
@@ -28237,6 +29214,7 @@ Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
+ offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
@@ -28246,36 +29224,43 @@ Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
+ offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
+ offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
+ offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
+ offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
- if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
- if (value > max || value < min) throw new RangeError('value is out of bounds')
- if (offset + ext > buf.length) throw new RangeError('index out of range')
+ if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
+ if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
+ if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
- offset = offset | 0
- byteLength = byteLength | 0
- if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
+ if (!noAssert) {
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1
+ checkInt(this, value, offset, byteLength, maxBytes, 0)
+ }
var mul = 1
var i = 0
@@ -28289,9 +29274,12 @@ Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength,
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
- offset = offset | 0
- byteLength = byteLength | 0
- if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
+ if (!noAssert) {
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1
+ checkInt(this, value, offset, byteLength, maxBytes, 0)
+ }
var i = byteLength - 1
var mul = 1
@@ -28305,98 +29293,69 @@ Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength,
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
- offset = offset | 0
+ offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
- if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = (value & 0xff)
return offset + 1
}
-function objectWriteUInt16 (buf, value, offset, littleEndian) {
- if (value < 0) value = 0xffff + value + 1
- for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
- buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
- (littleEndian ? i : 1 - i) * 8
- }
-}
-
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
- offset = offset | 0
+ offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value & 0xff)
- this[offset + 1] = (value >>> 8)
- } else {
- objectWriteUInt16(this, value, offset, true)
- }
+ this[offset] = (value & 0xff)
+ this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
- offset = offset | 0
+ offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value >>> 8)
- this[offset + 1] = (value & 0xff)
- } else {
- objectWriteUInt16(this, value, offset, false)
- }
+ this[offset] = (value >>> 8)
+ this[offset + 1] = (value & 0xff)
return offset + 2
}
-function objectWriteUInt32 (buf, value, offset, littleEndian) {
- if (value < 0) value = 0xffffffff + value + 1
- for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
- buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
- }
-}
-
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
- offset = offset | 0
+ offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset + 3] = (value >>> 24)
- this[offset + 2] = (value >>> 16)
- this[offset + 1] = (value >>> 8)
- this[offset] = (value & 0xff)
- } else {
- objectWriteUInt32(this, value, offset, true)
- }
+ this[offset + 3] = (value >>> 24)
+ this[offset + 2] = (value >>> 16)
+ this[offset + 1] = (value >>> 8)
+ this[offset] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
- offset = offset | 0
+ offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value >>> 24)
- this[offset + 1] = (value >>> 16)
- this[offset + 2] = (value >>> 8)
- this[offset + 3] = (value & 0xff)
- } else {
- objectWriteUInt32(this, value, offset, false)
- }
+ this[offset] = (value >>> 24)
+ this[offset + 1] = (value >>> 16)
+ this[offset + 2] = (value >>> 8)
+ this[offset + 3] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
- offset = offset | 0
+ offset = offset >>> 0
if (!noAssert) {
- var limit = Math.pow(2, 8 * byteLength - 1)
+ var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
- var sub = value < 0 ? 1 : 0
+ var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
+ if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
+ sub = 1
+ }
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
@@ -28405,18 +29364,21 @@ Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, no
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
- offset = offset | 0
+ offset = offset >>> 0
if (!noAssert) {
- var limit = Math.pow(2, 8 * byteLength - 1)
+ var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
- var sub = value < 0 ? 1 : 0
+ var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
+ if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
+ sub = 1
+ }
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
@@ -28425,9 +29387,8 @@ Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, no
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
- offset = offset | 0
+ offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
- if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
@@ -28435,68 +29396,53 @@ Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
- offset = offset | 0
+ offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value & 0xff)
- this[offset + 1] = (value >>> 8)
- } else {
- objectWriteUInt16(this, value, offset, true)
- }
+ this[offset] = (value & 0xff)
+ this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
- offset = offset | 0
+ offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value >>> 8)
- this[offset + 1] = (value & 0xff)
- } else {
- objectWriteUInt16(this, value, offset, false)
- }
+ this[offset] = (value >>> 8)
+ this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
- offset = offset | 0
+ offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value & 0xff)
- this[offset + 1] = (value >>> 8)
- this[offset + 2] = (value >>> 16)
- this[offset + 3] = (value >>> 24)
- } else {
- objectWriteUInt32(this, value, offset, true)
- }
+ this[offset] = (value & 0xff)
+ this[offset + 1] = (value >>> 8)
+ this[offset + 2] = (value >>> 16)
+ this[offset + 3] = (value >>> 24)
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
- offset = offset | 0
+ offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value >>> 24)
- this[offset + 1] = (value >>> 16)
- this[offset + 2] = (value >>> 8)
- this[offset + 3] = (value & 0xff)
- } else {
- objectWriteUInt32(this, value, offset, false)
- }
+ this[offset] = (value >>> 24)
+ this[offset + 1] = (value >>> 16)
+ this[offset + 2] = (value >>> 8)
+ this[offset + 3] = (value & 0xff)
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
- if (value > max || value < min) throw new RangeError('value is out of bounds')
- if (offset + ext > buf.length) throw new RangeError('index out of range')
- if (offset < 0) throw new RangeError('index out of range')
+ if (offset + ext > buf.length) throw new RangeError('Index out of range')
+ if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
+ value = +value
+ offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
@@ -28513,6 +29459,8 @@ Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
+ value = +value
+ offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
@@ -28530,6 +29478,7 @@ Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
+ if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
@@ -28544,7 +29493,7 @@ Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
- if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
+ if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
@@ -28554,152 +29503,105 @@ Buffer.prototype.copy = function copy (target, targetStart, start, end) {
}
var len = end - start
- var i
- if (this === target && start < targetStart && targetStart < end) {
+ if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
+ // Use built-in when available, missing from IE11
+ this.copyWithin(targetStart, start, end)
+ } else if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
- for (i = len - 1; i >= 0; i--) {
- target[i + targetStart] = this[i + start]
- }
- } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
- // ascending copy from start
- for (i = 0; i < len; i++) {
+ for (var i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else {
- target._set(this.subarray(start, start + len), targetStart)
+ Uint8Array.prototype.set.call(
+ target,
+ this.subarray(start, end),
+ targetStart
+ )
}
return len
}
-// fill(value, start=0, end=buffer.length)
-Buffer.prototype.fill = function fill (value, start, end) {
- if (!value) value = 0
- if (!start) start = 0
- if (!end) end = this.length
+// Usage:
+// buffer.fill(number[, offset[, end]])
+// buffer.fill(buffer[, offset[, end]])
+// buffer.fill(string[, offset[, end]][, encoding])
+Buffer.prototype.fill = function fill (val, start, end, encoding) {
+ // Handle string cases:
+ if (typeof val === 'string') {
+ if (typeof start === 'string') {
+ encoding = start
+ start = 0
+ end = this.length
+ } else if (typeof end === 'string') {
+ encoding = end
+ end = this.length
+ }
+ if (encoding !== undefined && typeof encoding !== 'string') {
+ throw new TypeError('encoding must be a string')
+ }
+ if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
+ throw new TypeError('Unknown encoding: ' + encoding)
+ }
+ if (val.length === 1) {
+ var code = val.charCodeAt(0)
+ if ((encoding === 'utf8' && code < 128) ||
+ encoding === 'latin1') {
+ // Fast path: If `val` fits into a single byte, use that numeric value.
+ val = code
+ }
+ }
+ } else if (typeof val === 'number') {
+ val = val & 255
+ }
- if (end < start) throw new RangeError('end < start')
+ // Invalid ranges are not set to a default, so can range check early.
+ if (start < 0 || this.length < start || this.length < end) {
+ throw new RangeError('Out of range index')
+ }
+
+ if (end <= start) {
+ return this
+ }
- // Fill 0 bytes; we're done
- if (end === start) return
- if (this.length === 0) return
+ start = start >>> 0
+ end = end === undefined ? this.length : end >>> 0
- if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
- if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
+ if (!val) val = 0
var i
- if (typeof value === 'number') {
- for (i = start; i < end; i++) {
- this[i] = value
+ if (typeof val === 'number') {
+ for (i = start; i < end; ++i) {
+ this[i] = val
}
} else {
- var bytes = utf8ToBytes(value.toString())
+ var bytes = Buffer.isBuffer(val)
+ ? val
+ : Buffer.from(val, encoding)
var len = bytes.length
- for (i = start; i < end; i++) {
- this[i] = bytes[i % len]
+ if (len === 0) {
+ throw new TypeError('The value "' + val +
+ '" is invalid for argument "value"')
+ }
+ for (i = 0; i < end - start; ++i) {
+ this[i + start] = bytes[i % len]
}
}
return this
}
-/**
- * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
- * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
- */
-Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
- if (typeof Uint8Array !== 'undefined') {
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- return (new Buffer(this)).buffer
- } else {
- var buf = new Uint8Array(this.length)
- for (var i = 0, len = buf.length; i < len; i += 1) {
- buf[i] = this[i]
- }
- return buf.buffer
- }
- } else {
- throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
- }
-}
-
// HELPER FUNCTIONS
// ================
-var BP = Buffer.prototype
-
-/**
- * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
- */
-Buffer._augment = function _augment (arr) {
- arr.constructor = Buffer
- arr._isBuffer = true
-
- // save reference to original Uint8Array set method before overwriting
- arr._set = arr.set
-
- // deprecated
- arr.get = BP.get
- arr.set = BP.set
-
- arr.write = BP.write
- arr.toString = BP.toString
- arr.toLocaleString = BP.toString
- arr.toJSON = BP.toJSON
- arr.equals = BP.equals
- arr.compare = BP.compare
- arr.indexOf = BP.indexOf
- arr.copy = BP.copy
- arr.slice = BP.slice
- arr.readUIntLE = BP.readUIntLE
- arr.readUIntBE = BP.readUIntBE
- arr.readUInt8 = BP.readUInt8
- arr.readUInt16LE = BP.readUInt16LE
- arr.readUInt16BE = BP.readUInt16BE
- arr.readUInt32LE = BP.readUInt32LE
- arr.readUInt32BE = BP.readUInt32BE
- arr.readIntLE = BP.readIntLE
- arr.readIntBE = BP.readIntBE
- arr.readInt8 = BP.readInt8
- arr.readInt16LE = BP.readInt16LE
- arr.readInt16BE = BP.readInt16BE
- arr.readInt32LE = BP.readInt32LE
- arr.readInt32BE = BP.readInt32BE
- arr.readFloatLE = BP.readFloatLE
- arr.readFloatBE = BP.readFloatBE
- arr.readDoubleLE = BP.readDoubleLE
- arr.readDoubleBE = BP.readDoubleBE
- arr.writeUInt8 = BP.writeUInt8
- arr.writeUIntLE = BP.writeUIntLE
- arr.writeUIntBE = BP.writeUIntBE
- arr.writeUInt16LE = BP.writeUInt16LE
- arr.writeUInt16BE = BP.writeUInt16BE
- arr.writeUInt32LE = BP.writeUInt32LE
- arr.writeUInt32BE = BP.writeUInt32BE
- arr.writeIntLE = BP.writeIntLE
- arr.writeIntBE = BP.writeIntBE
- arr.writeInt8 = BP.writeInt8
- arr.writeInt16LE = BP.writeInt16LE
- arr.writeInt16BE = BP.writeInt16BE
- arr.writeInt32LE = BP.writeInt32LE
- arr.writeInt32BE = BP.writeInt32BE
- arr.writeFloatLE = BP.writeFloatLE
- arr.writeFloatBE = BP.writeFloatBE
- arr.writeDoubleLE = BP.writeDoubleLE
- arr.writeDoubleBE = BP.writeDoubleBE
- arr.fill = BP.fill
- arr.inspect = BP.inspect
- arr.toArrayBuffer = BP.toArrayBuffer
-
- return arr
-}
-
-var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
+var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
function base64clean (str) {
+ // Node takes equal signs as end of the Base64 encoding
+ str = str.split('=')[0]
// Node strips out invalid characters like \n and \t from the string, base64-js does not
- str = stringtrim(str).replace(INVALID_BASE64_RE, '')
+ str = str.trim().replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
@@ -28709,11 +29611,6 @@ function base64clean (str) {
return str
}
-function stringtrim (str) {
- if (str.trim) return str.trim()
- return str.replace(/^\s+|\s+$/g, '')
-}
-
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
@@ -28726,7 +29623,7 @@ function utf8ToBytes (string, units) {
var leadSurrogate = null
var bytes = []
- for (var i = 0; i < length; i++) {
+ for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
@@ -28801,7 +29698,7 @@ function utf8ToBytes (string, units) {
function asciiToBytes (str) {
var byteArray = []
- for (var i = 0; i < str.length; i++) {
+ for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
@@ -28811,7 +29708,7 @@ function asciiToBytes (str) {
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
- for (var i = 0; i < str.length; i++) {
+ for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
@@ -28829,22 +29726,34 @@ function base64ToBytes (str) {
}
function blitBuffer (src, dst, offset, length) {
- for (var i = 0; i < length; i++) {
+ for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"base64-js":2,"ieee754":8,"isarray":9}],5:[function(_dereq_,module,exports){
+// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
+// the `instanceof` check but they should be treated as of that type.
+// See: https://github.com/feross/buffer/issues/166
+function isInstance (obj, type) {
+ return obj instanceof type ||
+ (obj != null && obj.constructor != null && obj.constructor.name != null &&
+ obj.constructor.name === type.name)
+}
+function numberIsNaN (obj) {
+ // For IE11 support
+ return obj !== obj // eslint-disable-line no-self-compare
+}
+
+},{"base64-js":2,"ieee754":8}],5:[function(_dereq_,module,exports){
(function (process,global){
/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
- * @version 4.1.1
+ * @version v4.2.6+9869a4bc
*/
(function (global, factory) {
@@ -28862,7 +29771,9 @@ function isFunction(x) {
return typeof x === 'function';
}
-var _isArray = undefined;
+
+
+var _isArray = void 0;
if (Array.isArray) {
_isArray = Array.isArray;
} else {
@@ -28874,8 +29785,8 @@ if (Array.isArray) {
var isArray = _isArray;
var len = 0;
-var vertxNext = undefined;
-var customSchedulerFn = undefined;
+var vertxNext = void 0;
+var customSchedulerFn = void 0;
var asap = function asap(callback, arg) {
queue[len] = callback;
@@ -28904,7 +29815,7 @@ function setAsap(asapFn) {
var browserWindow = typeof window !== 'undefined' ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
-var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';
+var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
@@ -28975,8 +29886,7 @@ function flush() {
function attemptVertx() {
try {
- var r = _dereq_;
- var vertx = r('vertx');
+ var vertx = Function('return this')().require('vertx');
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch (e) {
@@ -28984,7 +29894,7 @@ function attemptVertx() {
}
}
-var scheduleFlush = undefined;
+var scheduleFlush = void 0;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
scheduleFlush = useNextTick();
@@ -28999,8 +29909,6 @@ if (isNode) {
}
function then(onFulfillment, onRejection) {
- var _arguments = arguments;
-
var parent = this;
var child = new this.constructor(noop);
@@ -29011,13 +29919,12 @@ function then(onFulfillment, onRejection) {
var _state = parent._state;
+
if (_state) {
- (function () {
- var callback = _arguments[_state - 1];
- asap(function () {
- return invokeCallback(_state, child, callback, parent._result);
- });
- })();
+ var callback = arguments[_state - 1];
+ asap(function () {
+ return invokeCallback(_state, child, callback, parent._result);
+ });
} else {
subscribe(parent, child, onFulfillment, onRejection);
}
@@ -29069,7 +29976,7 @@ function resolve$1(object) {
return promise;
}
-var PROMISE_ID = Math.random().toString(36).substring(16);
+var PROMISE_ID = Math.random().toString(36).substring(2);
function noop() {}
@@ -29077,7 +29984,7 @@ var PENDING = void 0;
var FULFILLED = 1;
var REJECTED = 2;
-var GET_THEN_ERROR = new ErrorObject();
+var TRY_CATCH_ERROR = { error: null };
function selfFulfillment() {
return new TypeError("You cannot resolve a promise with itself");
@@ -29091,8 +29998,8 @@ function getThen(promise) {
try {
return promise.then;
} catch (error) {
- GET_THEN_ERROR.error = error;
- return GET_THEN_ERROR;
+ TRY_CATCH_ERROR.error = error;
+ return TRY_CATCH_ERROR;
}
}
@@ -29151,9 +30058,9 @@ function handleMaybeThenable(promise, maybeThenable, then$$1) {
if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
handleOwnThenable(promise, maybeThenable);
} else {
- if (then$$1 === GET_THEN_ERROR) {
- reject(promise, GET_THEN_ERROR.error);
- GET_THEN_ERROR.error = null;
+ if (then$$1 === TRY_CATCH_ERROR) {
+ reject(promise, TRY_CATCH_ERROR.error);
+ TRY_CATCH_ERROR.error = null;
} else if (then$$1 === undefined) {
fulfill(promise, maybeThenable);
} else if (isFunction(then$$1)) {
@@ -29209,6 +30116,7 @@ function subscribe(parent, child, onFulfillment, onRejection) {
var _subscribers = parent._subscribers;
var length = _subscribers.length;
+
parent._onerror = null;
_subscribers[length] = child;
@@ -29228,8 +30136,8 @@ function publish(promise) {
return;
}
- var child = undefined,
- callback = undefined,
+ var child = void 0,
+ callback = void 0,
detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
@@ -29246,12 +30154,6 @@ function publish(promise) {
promise._subscribers.length = 0;
}
-function ErrorObject() {
- this.error = null;
-}
-
-var TRY_CATCH_ERROR = new ErrorObject();
-
function tryCatch(callback, detail) {
try {
return callback(detail);
@@ -29263,10 +30165,10 @@ function tryCatch(callback, detail) {
function invokeCallback(settled, promise, callback, detail) {
var hasCallback = isFunction(callback),
- value = undefined,
- error = undefined,
- succeeded = undefined,
- failed = undefined;
+ value = void 0,
+ error = void 0,
+ succeeded = void 0,
+ failed = void 0;
if (hasCallback) {
value = tryCatch(callback, detail);
@@ -29291,14 +30193,14 @@ function invokeCallback(settled, promise, callback, detail) {
if (promise._state !== PENDING) {
// noop
} else if (hasCallback && succeeded) {
- resolve(promise, value);
- } else if (failed) {
- reject(promise, error);
- } else if (settled === FULFILLED) {
- fulfill(promise, value);
- } else if (settled === REJECTED) {
- reject(promise, value);
- }
+ resolve(promise, value);
+ } else if (failed) {
+ reject(promise, error);
+ } else if (settled === FULFILLED) {
+ fulfill(promise, value);
+ } else if (settled === REJECTED) {
+ reject(promise, value);
+ }
}
function initializePromise(promise, resolver) {
@@ -29325,97 +30227,103 @@ function makePromise(promise) {
promise._subscribers = [];
}
-function Enumerator$1(Constructor, input) {
- this._instanceConstructor = Constructor;
- this.promise = new Constructor(noop);
+function validationError() {
+ return new Error('Array Methods must be provided an Array');
+}
- if (!this.promise[PROMISE_ID]) {
- makePromise(this.promise);
- }
+var Enumerator = function () {
+ function Enumerator(Constructor, input) {
+ this._instanceConstructor = Constructor;
+ this.promise = new Constructor(noop);
- if (isArray(input)) {
- this.length = input.length;
- this._remaining = input.length;
+ if (!this.promise[PROMISE_ID]) {
+ makePromise(this.promise);
+ }
- this._result = new Array(this.length);
+ if (isArray(input)) {
+ this.length = input.length;
+ this._remaining = input.length;
- if (this.length === 0) {
- fulfill(this.promise, this._result);
- } else {
- this.length = this.length || 0;
- this._enumerate(input);
- if (this._remaining === 0) {
+ this._result = new Array(this.length);
+
+ if (this.length === 0) {
fulfill(this.promise, this._result);
+ } else {
+ this.length = this.length || 0;
+ this._enumerate(input);
+ if (this._remaining === 0) {
+ fulfill(this.promise, this._result);
+ }
}
+ } else {
+ reject(this.promise, validationError());
}
- } else {
- reject(this.promise, validationError());
}
-}
-function validationError() {
- return new Error('Array Methods must be provided an Array');
-}
+ Enumerator.prototype._enumerate = function _enumerate(input) {
+ for (var i = 0; this._state === PENDING && i < input.length; i++) {
+ this._eachEntry(input[i], i);
+ }
+ };
-Enumerator$1.prototype._enumerate = function (input) {
- for (var i = 0; this._state === PENDING && i < input.length; i++) {
- this._eachEntry(input[i], i);
- }
-};
+ Enumerator.prototype._eachEntry = function _eachEntry(entry, i) {
+ var c = this._instanceConstructor;
+ var resolve$$1 = c.resolve;
-Enumerator$1.prototype._eachEntry = function (entry, i) {
- var c = this._instanceConstructor;
- var resolve$$1 = c.resolve;
- if (resolve$$1 === resolve$1) {
- var _then = getThen(entry);
+ if (resolve$$1 === resolve$1) {
+ var _then = getThen(entry);
- if (_then === then && entry._state !== PENDING) {
- this._settledAt(entry._state, i, entry._result);
- } else if (typeof _then !== 'function') {
- this._remaining--;
- this._result[i] = entry;
- } else if (c === Promise$2) {
- var promise = new c(noop);
- handleMaybeThenable(promise, entry, _then);
- this._willSettleAt(promise, i);
+ if (_then === then && entry._state !== PENDING) {
+ this._settledAt(entry._state, i, entry._result);
+ } else if (typeof _then !== 'function') {
+ this._remaining--;
+ this._result[i] = entry;
+ } else if (c === Promise$1) {
+ var promise = new c(noop);
+ handleMaybeThenable(promise, entry, _then);
+ this._willSettleAt(promise, i);
+ } else {
+ this._willSettleAt(new c(function (resolve$$1) {
+ return resolve$$1(entry);
+ }), i);
+ }
} else {
- this._willSettleAt(new c(function (resolve$$1) {
- return resolve$$1(entry);
- }), i);
+ this._willSettleAt(resolve$$1(entry), i);
}
- } else {
- this._willSettleAt(resolve$$1(entry), i);
- }
-};
+ };
-Enumerator$1.prototype._settledAt = function (state, i, value) {
- var promise = this.promise;
+ Enumerator.prototype._settledAt = function _settledAt(state, i, value) {
+ var promise = this.promise;
- if (promise._state === PENDING) {
- this._remaining--;
- if (state === REJECTED) {
- reject(promise, value);
- } else {
- this._result[i] = value;
+ if (promise._state === PENDING) {
+ this._remaining--;
+
+ if (state === REJECTED) {
+ reject(promise, value);
+ } else {
+ this._result[i] = value;
+ }
}
- }
- if (this._remaining === 0) {
- fulfill(promise, this._result);
- }
-};
+ if (this._remaining === 0) {
+ fulfill(promise, this._result);
+ }
+ };
-Enumerator$1.prototype._willSettleAt = function (promise, i) {
- var enumerator = this;
+ Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) {
+ var enumerator = this;
- subscribe(promise, undefined, function (value) {
- return enumerator._settledAt(FULFILLED, i, value);
- }, function (reason) {
- return enumerator._settledAt(REJECTED, i, reason);
- });
-};
+ subscribe(promise, undefined, function (value) {
+ return enumerator._settledAt(FULFILLED, i, value);
+ }, function (reason) {
+ return enumerator._settledAt(REJECTED, i, reason);
+ });
+ };
+
+ return Enumerator;
+}();
/**
`Promise.all` accepts an array of promises, and returns a new promise which
@@ -29464,8 +30372,8 @@ Enumerator$1.prototype._willSettleAt = function (promise, i) {
fulfilled, or rejected if any of them become rejected.
@static
*/
-function all$1(entries) {
- return new Enumerator$1(this, entries).promise;
+function all(entries) {
+ return new Enumerator(this, entries).promise;
}
/**
@@ -29533,7 +30441,7 @@ function all$1(entries) {
@return {Promise} a promise which settles in the same way as the first passed
promise to settle.
*/
-function race$1(entries) {
+function race(entries) {
/*jshint validthis:true */
var Constructor = this;
@@ -29700,305 +30608,332 @@ function needsNew() {
```
@class Promise
- @param {function} resolver
+ @param {Function} resolver
Useful for tooling.
@constructor
*/
-function Promise$2(resolver) {
- this[PROMISE_ID] = nextId();
- this._result = this._state = undefined;
- this._subscribers = [];
-
- if (noop !== resolver) {
- typeof resolver !== 'function' && needsResolver();
- this instanceof Promise$2 ? initializePromise(this, resolver) : needsNew();
- }
-}
-Promise$2.all = all$1;
-Promise$2.race = race$1;
-Promise$2.resolve = resolve$1;
-Promise$2.reject = reject$1;
-Promise$2._setScheduler = setScheduler;
-Promise$2._setAsap = setAsap;
-Promise$2._asap = asap;
+var Promise$1 = function () {
+ function Promise(resolver) {
+ this[PROMISE_ID] = nextId();
+ this._result = this._state = undefined;
+ this._subscribers = [];
-Promise$2.prototype = {
- constructor: Promise$2,
+ if (noop !== resolver) {
+ typeof resolver !== 'function' && needsResolver();
+ this instanceof Promise ? initializePromise(this, resolver) : needsNew();
+ }
+ }
/**
- The primary way of interacting with a promise is through its `then` method,
- which registers callbacks to receive either a promise's eventual value or the
- reason why the promise cannot be fulfilled.
-
- ```js
- findUser().then(function(user){
- // user is available
- }, function(reason){
- // user is unavailable, and you are given the reason why
- });
- ```
-
- Chaining
- --------
-
- The return value of `then` is itself a promise. This second, 'downstream'
- promise is resolved with the return value of the first promise's fulfillment
- or rejection handler, or rejected if the handler throws an exception.
-
- ```js
- findUser().then(function (user) {
- return user.name;
- }, function (reason) {
- return 'default name';
- }).then(function (userName) {
- // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
- // will be `'default name'`
- });
-
- findUser().then(function (user) {
- throw new Error('Found user, but still unhappy');
- }, function (reason) {
- throw new Error('`findUser` rejected and we're unhappy');
- }).then(function (value) {
- // never reached
- }, function (reason) {
- // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
- // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
- });
- ```
- If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
-
- ```js
- findUser().then(function (user) {
- throw new PedagogicalException('Upstream error');
- }).then(function (value) {
- // never reached
- }).then(function (value) {
- // never reached
- }, function (reason) {
- // The `PedgagocialException` is propagated all the way down to here
- });
- ```
-
- Assimilation
- ------------
-
- Sometimes the value you want to propagate to a downstream promise can only be
- retrieved asynchronously. This can be achieved by returning a promise in the
- fulfillment or rejection handler. The downstream promise will then be pending
- until the returned promise is settled. This is called *assimilation*.
-
- ```js
- findUser().then(function (user) {
- return findCommentsByAuthor(user);
- }).then(function (comments) {
- // The user's comments are now available
- });
- ```
-
- If the assimliated promise rejects, then the downstream promise will also reject.
-
- ```js
- findUser().then(function (user) {
- return findCommentsByAuthor(user);
- }).then(function (comments) {
- // If `findCommentsByAuthor` fulfills, we'll have the value here
- }, function (reason) {
- // If `findCommentsByAuthor` rejects, we'll have the reason here
- });
- ```
-
- Simple Example
- --------------
-
- Synchronous Example
-
- ```javascript
- let result;
-
- try {
- result = findResult();
- // success
- } catch(reason) {
- // failure
- }
- ```
-
- Errback Example
-
- ```js
- findResult(function(result, err){
- if (err) {
- // failure
- } else {
- // success
- }
- });
- ```
-
- Promise Example;
-
- ```javascript
- findResult().then(function(result){
- // success
- }, function(reason){
+ The primary way of interacting with a promise is through its `then` method,
+ which registers callbacks to receive either a promise's eventual value or the
+ reason why the promise cannot be fulfilled.
+ ```js
+ findUser().then(function(user){
+ // user is available
+ }, function(reason){
+ // user is unavailable, and you are given the reason why
+ });
+ ```
+ Chaining
+ --------
+ The return value of `then` is itself a promise. This second, 'downstream'
+ promise is resolved with the return value of the first promise's fulfillment
+ or rejection handler, or rejected if the handler throws an exception.
+ ```js
+ findUser().then(function (user) {
+ return user.name;
+ }, function (reason) {
+ return 'default name';
+ }).then(function (userName) {
+ // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
+ // will be `'default name'`
+ });
+ findUser().then(function (user) {
+ throw new Error('Found user, but still unhappy');
+ }, function (reason) {
+ throw new Error('`findUser` rejected and we're unhappy');
+ }).then(function (value) {
+ // never reached
+ }, function (reason) {
+ // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
+ // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
+ });
+ ```
+ If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
+ ```js
+ findUser().then(function (user) {
+ throw new PedagogicalException('Upstream error');
+ }).then(function (value) {
+ // never reached
+ }).then(function (value) {
+ // never reached
+ }, function (reason) {
+ // The `PedgagocialException` is propagated all the way down to here
+ });
+ ```
+ Assimilation
+ ------------
+ Sometimes the value you want to propagate to a downstream promise can only be
+ retrieved asynchronously. This can be achieved by returning a promise in the
+ fulfillment or rejection handler. The downstream promise will then be pending
+ until the returned promise is settled. This is called *assimilation*.
+ ```js
+ findUser().then(function (user) {
+ return findCommentsByAuthor(user);
+ }).then(function (comments) {
+ // The user's comments are now available
+ });
+ ```
+ If the assimliated promise rejects, then the downstream promise will also reject.
+ ```js
+ findUser().then(function (user) {
+ return findCommentsByAuthor(user);
+ }).then(function (comments) {
+ // If `findCommentsByAuthor` fulfills, we'll have the value here
+ }, function (reason) {
+ // If `findCommentsByAuthor` rejects, we'll have the reason here
+ });
+ ```
+ Simple Example
+ --------------
+ Synchronous Example
+ ```javascript
+ let result;
+ try {
+ result = findResult();
+ // success
+ } catch(reason) {
+ // failure
+ }
+ ```
+ Errback Example
+ ```js
+ findResult(function(result, err){
+ if (err) {
// failure
- });
- ```
-
- Advanced Example
- --------------
-
- Synchronous Example
-
- ```javascript
- let author, books;
-
- try {
- author = findAuthor();
- books = findBooksByAuthor(author);
+ } else {
// success
- } catch(reason) {
- // failure
}
- ```
-
- Errback Example
-
- ```js
-
- function foundBooks(books) {
-
- }
-
- function failure(reason) {
-
- }
-
- findAuthor(function(author, err){
- if (err) {
- failure(err);
- // failure
- } else {
- try {
- findBoooksByAuthor(author, function(books, err) {
- if (err) {
- failure(err);
- } else {
- try {
- foundBooks(books);
- } catch(reason) {
- failure(reason);
- }
+ });
+ ```
+ Promise Example;
+ ```javascript
+ findResult().then(function(result){
+ // success
+ }, function(reason){
+ // failure
+ });
+ ```
+ Advanced Example
+ --------------
+ Synchronous Example
+ ```javascript
+ let author, books;
+ try {
+ author = findAuthor();
+ books = findBooksByAuthor(author);
+ // success
+ } catch(reason) {
+ // failure
+ }
+ ```
+ Errback Example
+ ```js
+ function foundBooks(books) {
+ }
+ function failure(reason) {
+ }
+ findAuthor(function(author, err){
+ if (err) {
+ failure(err);
+ // failure
+ } else {
+ try {
+ findBoooksByAuthor(author, function(books, err) {
+ if (err) {
+ failure(err);
+ } else {
+ try {
+ foundBooks(books);
+ } catch(reason) {
+ failure(reason);
}
- });
- } catch(error) {
- failure(err);
- }
- // success
+ }
+ });
+ } catch(error) {
+ failure(err);
}
- });
- ```
-
- Promise Example;
-
- ```javascript
- findAuthor().
- then(findBooksByAuthor).
- then(function(books){
- // found books
- }).catch(function(reason){
- // something went wrong
- });
- ```
-
- @method then
- @param {Function} onFulfilled
- @param {Function} onRejected
- Useful for tooling.
- @return {Promise}
+ // success
+ }
+ });
+ ```
+ Promise Example;
+ ```javascript
+ findAuthor().
+ then(findBooksByAuthor).
+ then(function(books){
+ // found books
+ }).catch(function(reason){
+ // something went wrong
+ });
+ ```
+ @method then
+ @param {Function} onFulfilled
+ @param {Function} onRejected
+ Useful for tooling.
+ @return {Promise}
+ */
+
+ /**
+ `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
+ as the catch block of a try/catch statement.
+ ```js
+ function findAuthor(){
+ throw new Error('couldn't find that author');
+ }
+ // synchronous
+ try {
+ findAuthor();
+ } catch(reason) {
+ // something went wrong
+ }
+ // async with promises
+ findAuthor().catch(function(reason){
+ // something went wrong
+ });
+ ```
+ @method catch
+ @param {Function} onRejection
+ Useful for tooling.
+ @return {Promise}
*/
- then: then,
+
+
+ Promise.prototype.catch = function _catch(onRejection) {
+ return this.then(null, onRejection);
+ };
/**
- `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
- as the catch block of a try/catch statement.
+ `finally` will be invoked regardless of the promise's fate just as native
+ try/catch/finally behaves
+
+ Synchronous example:
```js
- function findAuthor(){
- throw new Error('couldn't find that author');
+ findAuthor() {
+ if (Math.random() > 0.5) {
+ throw new Error();
+ }
+ return new Author();
}
- // synchronous
try {
- findAuthor();
- } catch(reason) {
- // something went wrong
+ return findAuthor(); // succeed or fail
+ } catch(error) {
+ return findOtherAuther();
+ } finally {
+ // always runs
+ // doesn't affect the return value
}
+ ```
+
+ Asynchronous example:
- // async with promises
+ ```js
findAuthor().catch(function(reason){
- // something went wrong
+ return findOtherAuther();
+ }).finally(function(){
+ // author was either found, or not
});
```
- @method catch
- @param {Function} onRejection
- Useful for tooling.
+ @method finally
+ @param {Function} callback
@return {Promise}
*/
- 'catch': function _catch(onRejection) {
- return this.then(null, onRejection);
- }
-};
+
+
+ Promise.prototype.finally = function _finally(callback) {
+ var promise = this;
+ var constructor = promise.constructor;
+
+ if (isFunction(callback)) {
+ return promise.then(function (value) {
+ return constructor.resolve(callback()).then(function () {
+ return value;
+ });
+ }, function (reason) {
+ return constructor.resolve(callback()).then(function () {
+ throw reason;
+ });
+ });
+ }
+
+ return promise.then(callback, callback);
+ };
+
+ return Promise;
+}();
+
+Promise$1.prototype.then = then;
+Promise$1.all = all;
+Promise$1.race = race;
+Promise$1.resolve = resolve$1;
+Promise$1.reject = reject$1;
+Promise$1._setScheduler = setScheduler;
+Promise$1._setAsap = setAsap;
+Promise$1._asap = asap;
/*global self*/
-function polyfill$1() {
- var local = undefined;
+function polyfill() {
+ var local = void 0;
- if (typeof global !== 'undefined') {
- local = global;
- } else if (typeof self !== 'undefined') {
- local = self;
- } else {
- try {
- local = Function('return this')();
- } catch (e) {
- throw new Error('polyfill failed because global object is unavailable in this environment');
- }
+ if (typeof global !== 'undefined') {
+ local = global;
+ } else if (typeof self !== 'undefined') {
+ local = self;
+ } else {
+ try {
+ local = Function('return this')();
+ } catch (e) {
+ throw new Error('polyfill failed because global object is unavailable in this environment');
}
+ }
- var P = local.Promise;
+ var P = local.Promise;
- if (P) {
- var promiseToString = null;
- try {
- promiseToString = Object.prototype.toString.call(P.resolve());
- } catch (e) {
- // silently ignored
- }
+ if (P) {
+ var promiseToString = null;
+ try {
+ promiseToString = Object.prototype.toString.call(P.resolve());
+ } catch (e) {
+ // silently ignored
+ }
- if (promiseToString === '[object Promise]' && !P.cast) {
- return;
- }
+ if (promiseToString === '[object Promise]' && !P.cast) {
+ return;
}
+ }
- local.Promise = Promise$2;
+ local.Promise = Promise$1;
}
// Strange compat..
-Promise$2.polyfill = polyfill$1;
-Promise$2.Promise = Promise$2;
+Promise$1.polyfill = polyfill;
+Promise$1.Promise = Promise$1;
-return Promise$2;
+return Promise$1;
})));
+
+
}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"_process":12}],6:[function(_dereq_,module,exports){
+},{"_process":11}],6:[function(_dereq_,module,exports){
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'module'], factory);
@@ -30315,7 +31250,7 @@ if (typeof module !== "undefined" && module.exports) {
},{}],8:[function(_dereq_,module,exports){
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
- var eLen = nBytes * 8 - mLen - 1
+ var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
@@ -30328,12 +31263,12 @@ exports.read = function (buffer, offset, isLE, mLen, nBytes) {
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
- for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
+ for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
- for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
+ for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
@@ -30348,7 +31283,7 @@ exports.read = function (buffer, offset, isLE, mLen, nBytes) {
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
- var eLen = nBytes * 8 - mLen - 1
+ var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
@@ -30381,7 +31316,7 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
- m = (value * c - 1) * Math.pow(2, mLen)
+ m = ((value * c) - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
@@ -30399,13 +31334,6 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
}
},{}],9:[function(_dereq_,module,exports){
-var toString = {}.toString;
-
-module.exports = Array.isArray || function (arr) {
- return toString.call(arr) == '[object Array]';
-};
-
-},{}],10:[function(_dereq_,module,exports){
/*
Copyright 2000, Silicon Graphics, Inc. All Rights Reserved.
@@ -30465,7 +31393,7 @@ function W(a,b){for(var c=a.d,d=a.e,e=a.c,f=b,g=c[f];;){var h=f<<1;h= 200 && this.status < 300
this.statusText = 'statusText' in options ? options.statusText : 'OK'
this.headers = new Headers(options.headers)
@@ -43581,6 +44512,8 @@ process.umask = function() { return 0; };
if (request.credentials === 'include') {
xhr.withCredentials = true
+ } else if (request.credentials === 'omit') {
+ xhr.withCredentials = false
}
if ('responseType' in xhr && support.blob) {
@@ -43597,7 +44530,7 @@ process.umask = function() { return 0; };
self.fetch.polyfill = true
})(typeof self !== 'undefined' ? self : this);
-},{}],14:[function(_dereq_,module,exports){
+},{}],13:[function(_dereq_,module,exports){
'use strict';
// core
@@ -43687,7 +44620,7 @@ _dereq_('./core/init');
module.exports = p5;
-},{"./color/color_conversion":15,"./color/creating_reading":16,"./color/p5.Color":17,"./color/setting":18,"./core/constants":19,"./core/environment":20,"./core/error_helpers":21,"./core/helpers":22,"./core/init":23,"./core/legacy":24,"./core/main":25,"./core/p5.Element":26,"./core/p5.Graphics":27,"./core/p5.Renderer":28,"./core/p5.Renderer2D":29,"./core/rendering":30,"./core/shape/2d_primitives":31,"./core/shape/attributes":32,"./core/shape/curves":33,"./core/shape/vertex":34,"./core/shim":35,"./core/structure":36,"./core/transform":37,"./data/p5.TypedDict":38,"./events/acceleration":39,"./events/keyboard":40,"./events/mouse":41,"./events/touch":42,"./image/filters":43,"./image/image":44,"./image/loading_displaying":45,"./image/p5.Image":46,"./image/pixels":47,"./io/files":48,"./io/p5.Table":49,"./io/p5.TableRow":50,"./io/p5.XML":51,"./math/calculation":52,"./math/math":53,"./math/noise":54,"./math/p5.Vector":55,"./math/random":56,"./math/trigonometry":57,"./typography/attributes":58,"./typography/loading_displaying":59,"./typography/p5.Font":60,"./utilities/array_functions":61,"./utilities/conversion":62,"./utilities/string_functions":63,"./utilities/time_date":64,"./webgl/3d_primitives":65,"./webgl/interaction":66,"./webgl/light":67,"./webgl/loading":68,"./webgl/material":69,"./webgl/p5.Camera":70,"./webgl/p5.Geometry":71,"./webgl/p5.Matrix":72,"./webgl/p5.RendererGL":75,"./webgl/p5.RendererGL.Immediate":73,"./webgl/p5.RendererGL.Retained":74,"./webgl/p5.Shader":76,"./webgl/p5.Texture":77,"./webgl/text":78}],15:[function(_dereq_,module,exports){
+},{"./color/color_conversion":14,"./color/creating_reading":15,"./color/p5.Color":16,"./color/setting":17,"./core/constants":18,"./core/environment":19,"./core/error_helpers":20,"./core/helpers":21,"./core/init":22,"./core/legacy":23,"./core/main":24,"./core/p5.Element":25,"./core/p5.Graphics":26,"./core/p5.Renderer":27,"./core/p5.Renderer2D":28,"./core/rendering":29,"./core/shape/2d_primitives":30,"./core/shape/attributes":31,"./core/shape/curves":32,"./core/shape/vertex":33,"./core/shim":34,"./core/structure":35,"./core/transform":36,"./data/p5.TypedDict":37,"./events/acceleration":38,"./events/keyboard":39,"./events/mouse":40,"./events/touch":41,"./image/filters":42,"./image/image":43,"./image/loading_displaying":44,"./image/p5.Image":45,"./image/pixels":46,"./io/files":47,"./io/p5.Table":48,"./io/p5.TableRow":49,"./io/p5.XML":50,"./math/calculation":51,"./math/math":52,"./math/noise":53,"./math/p5.Vector":54,"./math/random":55,"./math/trigonometry":56,"./typography/attributes":57,"./typography/loading_displaying":58,"./typography/p5.Font":59,"./utilities/array_functions":60,"./utilities/conversion":61,"./utilities/string_functions":62,"./utilities/time_date":63,"./webgl/3d_primitives":64,"./webgl/interaction":65,"./webgl/light":66,"./webgl/loading":67,"./webgl/material":68,"./webgl/p5.Camera":69,"./webgl/p5.Geometry":70,"./webgl/p5.Matrix":71,"./webgl/p5.RendererGL":74,"./webgl/p5.RendererGL.Immediate":72,"./webgl/p5.RendererGL.Retained":73,"./webgl/p5.Shader":75,"./webgl/p5.Texture":76,"./webgl/text":77}],14:[function(_dereq_,module,exports){
/**
* @module Color
* @submodule Color Conversion
@@ -43962,7 +44895,7 @@ p5.ColorConversion._rgbaToHSLA = function(rgba) {
module.exports = p5.ColorConversion;
-},{"../core/main":25}],16:[function(_dereq_,module,exports){
+},{"../core/main":24}],15:[function(_dereq_,module,exports){
/**
* @module Color
* @submodule Creating & Reading
@@ -43989,10 +44922,10 @@ _dereq_('../core/error_helpers');
*
*
* noStroke();
- * var c = color(0, 126, 255, 102);
+ * let c = color(0, 126, 255, 102);
* fill(c);
* rect(15, 15, 35, 70);
- * var value = alpha(c); // Sets 'value' to 102
+ * let value = alpha(c); // Sets 'value' to 102
* fill(value);
* rect(50, 15, 35, 70);
*
@@ -44004,7 +44937,7 @@ _dereq_('../core/error_helpers');
* Left half of canvas salmon pink and the right half white.
* Yellow rect in middle right of canvas, with 55 pixel width and height.
* Yellow ellipse in top left canvas, black ellipse in bottom right,both 80x80.
- * Bright fuschia rect in middle of canvas, 60 pixel width and height.
+ * Bright fuchsia rect in middle of canvas, 60 pixel width and height.
* Two bright green rects on opposite sides of the canvas, both 45x80.
* Four blue rects in each corner of the canvas, each are 35x35.
* Bright sea green rect on left and darker rect on right of canvas, both 45x80.
@@ -44033,11 +44966,11 @@ p5.prototype.alpha = function(c) {
* @example
*
*
- * var c = color(175, 100, 220); // Define color 'c'
+ * let c = color(175, 100, 220); // Define color 'c'
* fill(c); // Use color variable 'c' as fill color
* rect(15, 20, 35, 60); // Draw left rectangle
*
- * var blueValue = blue(c); // Get blue in 'c'
+ * let blueValue = blue(c); // Get blue in 'c'
* print(blueValue); // Prints "220.0"
* fill(0, 0, blueValue); // Use 'blueValue' in new fill
* rect(50, 20, 35, 60); // Draw right rectangle
@@ -44065,10 +44998,22 @@ p5.prototype.blue = function(c) {
*
* noStroke();
* colorMode(HSB, 255);
- * var c = color(0, 126, 255);
+ * let c = color(0, 126, 255);
+ * fill(c);
+ * rect(15, 20, 35, 60);
+ * let value = brightness(c); // Sets 'value' to 255
+ * fill(value);
+ * rect(50, 20, 35, 60);
+ *
+ *
+ *
+ *
+ * noStroke();
+ * colorMode(HSB, 255);
+ * let c = color('hsb(60, 100%, 50%)');
* fill(c);
* rect(15, 20, 35, 60);
- * var value = brightness(c); // Sets 'value' to 255
+ * let value = brightness(c); // A 'value' of 50% is 127.5
* fill(value);
* rect(50, 20, 35, 60);
*
@@ -44076,6 +45021,7 @@ p5.prototype.blue = function(c) {
*
* @alt
* Left half of canvas salmon pink and the right half white.
+ * Left half of canvas yellow at half brightness and the right gray .
*
*/
p5.prototype.brightness = function(c) {
@@ -44111,7 +45057,7 @@ p5.prototype.brightness = function(c) {
* @example
*
*
- * var c = color(255, 204, 0); // Define color 'c'
+ * let c = color(255, 204, 0); // Define color 'c'
* fill(c); // Use color variable 'c' as fill color
* noStroke(); // Don't draw a stroke around shapes
* rect(30, 20, 55, 55); // Draw rectangle
@@ -44120,7 +45066,7 @@ p5.prototype.brightness = function(c) {
*
*
*
- * var c = color(255, 204, 0); // Define color 'c'
+ * let c = color(255, 204, 0); // Define color 'c'
* fill(c); // Use color variable 'c' as fill color
* noStroke(); // Don't draw a stroke around shapes
* ellipse(25, 25, 80, 80); // Draw left circle
@@ -44136,7 +45082,7 @@ p5.prototype.brightness = function(c) {
*
*
* // Named SVG & CSS colors may be used,
- * var c = color('magenta');
+ * let c = color('magenta');
* fill(c); // Use 'c' as fill color
* noStroke(); // Don't draw a stroke around shapes
* rect(20, 20, 60, 60); // Draw rectangle
@@ -44147,7 +45093,7 @@ p5.prototype.brightness = function(c) {
*
* // as can hex color codes:
* noStroke(); // Don't draw a stroke around shapes
- * var c = color('#0f0');
+ * let c = color('#0f0');
* fill(c); // Use 'c' as fill color
* rect(0, 10, 45, 80); // Draw rectangle
*
@@ -44161,7 +45107,7 @@ p5.prototype.brightness = function(c) {
*
* // RGB and RGBA color strings are also supported:
* // these all set to the same color (solid blue)
- * var c;
+ * let c;
* noStroke(); // Don't draw a stroke around shapes
* c = color('rgb(0,0,255)');
* fill(c); // Use 'c' as fill color
@@ -44185,7 +45131,7 @@ p5.prototype.brightness = function(c) {
*
* // HSL color is also supported and can be specified
* // by value
- * var c;
+ * let c;
* noStroke(); // Don't draw a stroke around shapes
* c = color('hsl(160, 100%, 50%)');
* fill(c); // Use 'c' as fill color
@@ -44201,7 +45147,7 @@ p5.prototype.brightness = function(c) {
*
* // HSB color is also supported and can be specified
* // by value
- * var c;
+ * let c;
* noStroke(); // Don't draw a stroke around shapes
* c = color('hsb(160, 100%, 50%)');
* fill(c); // Use 'c' as fill color
@@ -44215,7 +45161,7 @@ p5.prototype.brightness = function(c) {
*
*
*
- * var c; // Declare color 'c'
+ * let c; // Declare color 'c'
* noStroke(); // Don't draw a stroke around shapes
*
* // If no colorMode is specified, then the
@@ -44234,7 +45180,7 @@ p5.prototype.brightness = function(c) {
* @alt
* Yellow rect in middle right of canvas, with 55 pixel width and height.
* Yellow ellipse in top left of canvas, black ellipse in bottom right,both 80x80.
- * Bright fuschia rect in middle of canvas, 60 pixel width and height.
+ * Bright fuchsia rect in middle of canvas, 60 pixel width and height.
* Two bright green rects on opposite sides of the canvas, both 45x80.
* Four blue rects in each corner of the canvas, each are 35x35.
* Bright sea green rect on left and darker rect on right of canvas, both 45x80.
@@ -44291,11 +45237,11 @@ p5.prototype.color = function() {
* @example
*
*
- * var c = color(20, 75, 200); // Define color 'c'
+ * let c = color(20, 75, 200); // Define color 'c'
* fill(c); // Use color variable 'c' as fill color
* rect(15, 20, 35, 60); // Draw left rectangle
*
- * var greenValue = green(c); // Get green in 'c'
+ * let greenValue = green(c); // Get green in 'c'
* print(greenValue); // Print "75.0"
* fill(0, greenValue, 0); // Use 'greenValue' in new fill
* rect(50, 20, 35, 60); // Draw right rectangle
@@ -44330,10 +45276,10 @@ p5.prototype.green = function(c) {
*
* noStroke();
* colorMode(HSB, 255);
- * var c = color(0, 126, 255);
+ * let c = color(0, 126, 255);
* fill(c);
* rect(15, 20, 35, 60);
- * var value = hue(c); // Sets 'value' to "0"
+ * let value = hue(c); // Sets 'value' to "0"
* fill(value);
* rect(50, 20, 35, 60);
*
@@ -44371,11 +45317,11 @@ p5.prototype.hue = function(c) {
* colorMode(RGB);
* stroke(255);
* background(51);
- * var from = color(218, 165, 32);
- * var to = color(72, 61, 139);
+ * let from = color(218, 165, 32);
+ * let to = color(72, 61, 139);
* colorMode(RGB); // Try changing to HSB.
- * var interA = lerpColor(from, to, 0.33);
- * var interB = lerpColor(from, to, 0.66);
+ * let interA = lerpColor(from, to, 0.33);
+ * let interB = lerpColor(from, to, 0.66);
* fill(from);
* rect(10, 20, 20, 60);
* fill(interA);
@@ -44458,10 +45404,10 @@ p5.prototype.lerpColor = function(c1, c2, amt) {
*
* noStroke();
* colorMode(HSL);
- * var c = color(156, 100, 50, 1);
+ * let c = color(156, 100, 50, 1);
* fill(c);
* rect(15, 20, 35, 60);
- * var value = lightness(c); // Sets 'value' to 50
+ * let value = lightness(c); // Sets 'value' to 50
* fill(value);
* rect(50, 20, 35, 60);
*
@@ -44486,24 +45432,24 @@ p5.prototype.lightness = function(c) {
* @example
*
*
- * var c = color(255, 204, 0); // Define color 'c'
+ * let c = color(255, 204, 0); // Define color 'c'
* fill(c); // Use color variable 'c' as fill color
* rect(15, 20, 35, 60); // Draw left rectangle
*
- * var redValue = red(c); // Get red in 'c'
+ * let redValue = red(c); // Get red in 'c'
* print(redValue); // Print "255.0"
* fill(redValue, 0, 0); // Use 'redValue' in new fill
* rect(50, 20, 35, 60); // Draw right rectangle
*
*
*
- *
+ *
*
- * colorMode(RGB, 255);
- * var c = color(127, 255, 0);
- * colorMode(RGB, 1);
- * var myColor = red(c);
- * print(myColor);
+ * colorMode(RGB, 255); // Sets the range for red, green, and blue to 255
+ * let c = color(127, 255, 0);
+ * colorMode(RGB, 1); // Sets the range for red, green, and blue to 1
+ * let myColor = red(c);
+ * print(myColor); // 0.4980392156862745
*
*
*
@@ -44533,10 +45479,10 @@ p5.prototype.red = function(c) {
*
* noStroke();
* colorMode(HSB, 255);
- * var c = color(0, 126, 255);
+ * let c = color(0, 126, 255);
* fill(c);
* rect(15, 20, 35, 60);
- * var value = saturation(c); // Sets 'value' to 126
+ * let value = saturation(c); // Sets 'value' to 126
* fill(value);
* rect(50, 20, 35, 60);
*
@@ -44554,7 +45500,7 @@ p5.prototype.saturation = function(c) {
module.exports = p5;
-},{"../core/constants":19,"../core/error_helpers":21,"../core/main":25,"./p5.Color":17}],17:[function(_dereq_,module,exports){
+},{"../core/constants":18,"../core/error_helpers":20,"../core/main":24,"./p5.Color":16}],16:[function(_dereq_,module,exports){
/**
* @module Color
* @submodule Creating & Reading
@@ -44620,7 +45566,7 @@ p5.Color = function(pInst, vals) {
* @example
*
*
- * var myColor;
+ * let myColor;
* function setup() {
* createCanvas(200, 200);
* stroke(255);
@@ -44641,9 +45587,6 @@ p5.Color = function(pInst, vals) {
* canvas with text representation of color
*/
p5.Color.prototype.toString = function(format) {
- if (!this.hsba) this.hsba = color_conversion._rgbaToHSBA(this._array);
- if (!this.hsla) this.hsla = color_conversion._rgbaToHSLA(this._array);
-
var a = this.levels;
var f = this._array;
var alpha = f[3]; // String representation uses normalized alpha
@@ -44706,6 +45649,7 @@ p5.Color.prototype.toString = function(format) {
case 'hsb':
case 'hsv':
+ if (!this.hsba) this.hsba = color_conversion._rgbaToHSBA(this._array);
return 'hsb('.concat(
this.hsba[0] * this.maxes[constants.HSB][0],
', ',
@@ -44717,6 +45661,7 @@ p5.Color.prototype.toString = function(format) {
case 'hsb%':
case 'hsv%':
+ if (!this.hsba) this.hsba = color_conversion._rgbaToHSBA(this._array);
return 'hsb('.concat(
(100 * this.hsba[0]).toPrecision(3),
'%, ',
@@ -44728,6 +45673,7 @@ p5.Color.prototype.toString = function(format) {
case 'hsba':
case 'hsva':
+ if (!this.hsba) this.hsba = color_conversion._rgbaToHSBA(this._array);
return 'hsba('.concat(
this.hsba[0] * this.maxes[constants.HSB][0],
', ',
@@ -44741,6 +45687,7 @@ p5.Color.prototype.toString = function(format) {
case 'hsba%':
case 'hsva%':
+ if (!this.hsba) this.hsba = color_conversion._rgbaToHSBA(this._array);
return 'hsba('.concat(
(100 * this.hsba[0]).toPrecision(3),
'%, ',
@@ -44753,6 +45700,7 @@ p5.Color.prototype.toString = function(format) {
);
case 'hsl':
+ if (!this.hsla) this.hsla = color_conversion._rgbaToHSLA(this._array);
return 'hsl('.concat(
this.hsla[0] * this.maxes[constants.HSL][0],
', ',
@@ -44763,6 +45711,7 @@ p5.Color.prototype.toString = function(format) {
);
case 'hsl%':
+ if (!this.hsla) this.hsla = color_conversion._rgbaToHSLA(this._array);
return 'hsl('.concat(
(100 * this.hsla[0]).toPrecision(3),
'%, ',
@@ -44773,6 +45722,7 @@ p5.Color.prototype.toString = function(format) {
);
case 'hsla':
+ if (!this.hsla) this.hsla = color_conversion._rgbaToHSLA(this._array);
return 'hsla('.concat(
this.hsla[0] * this.maxes[constants.HSL][0],
', ',
@@ -44785,6 +45735,7 @@ p5.Color.prototype.toString = function(format) {
);
case 'hsla%':
+ if (!this.hsla) this.hsla = color_conversion._rgbaToHSLA(this._array);
return 'hsl('.concat(
(100 * this.hsla[0]).toPrecision(3),
'%, ',
@@ -44798,7 +45749,7 @@ p5.Color.prototype.toString = function(format) {
case 'rgba':
default:
- return 'rgba(' + a[0] + ',' + a[1] + ',' + a[2] + ',' + alpha + ')';
+ return 'rgba('.concat(a[0], ',', a[1], ',', a[2], ',', alpha, ')');
}
};
@@ -44808,7 +45759,7 @@ p5.Color.prototype.toString = function(format) {
* @example
*
*
- * var backgroundColor;
+ * let backgroundColor;
*
* function setup() {
* backgroundColor = color(100, 50, 150);
@@ -44835,7 +45786,7 @@ p5.Color.prototype.setRed = function(new_red) {
* @example
*
*
- * var backgroundColor;
+ * let backgroundColor;
*
* function setup() {
* backgroundColor = color(100, 50, 150);
@@ -44862,7 +45813,7 @@ p5.Color.prototype.setGreen = function(new_green) {
* @example
*
*
- * var backgroundColor;
+ * let backgroundColor;
*
* function setup() {
* backgroundColor = color(100, 50, 150);
@@ -44889,7 +45840,7 @@ p5.Color.prototype.setBlue = function(new_blue) {
* @example
*
*
- * var squareColor;
+ * let squareColor;
*
* function setup() {
* ellipseMode(CORNERS);
@@ -45572,7 +46523,7 @@ p5.Color._parseInputs = function(r, g, b, a) {
module.exports = p5.Color;
-},{"../core/constants":19,"../core/main":25,"./color_conversion":15}],18:[function(_dereq_,module,exports){
+},{"../core/constants":18,"../core/main":24,"./color_conversion":14}],17:[function(_dereq_,module,exports){
/**
* @module Color
* @submodule Setting
@@ -45589,7 +46540,7 @@ _dereq_('./p5.Color');
/**
* The background() function sets the color used for the background of the
- * p5.js canvas. The default background is light gray. This function is
+ * p5.js canvas. The default background is transparent. This function is
* typically used within draw() to clear the display window at the beginning
* of each frame, but it can be used inside setup() to set the background on
* the first frame of animation or if the background need only be set once.
@@ -45734,7 +46685,7 @@ _dereq_('./p5.Color');
/**
* @method background
- * @param {Number[]} values an array containing the red,green,blue &
+ * @param {Number[]} values an array containing the red, green, blue
* and alpha components of the color
* @chainable
*/
@@ -45749,19 +46700,16 @@ _dereq_('./p5.Color');
*/
p5.prototype.background = function() {
- if (arguments[0] instanceof p5.Image) {
- this.image(arguments[0], 0, 0, this.width, this.height);
- } else {
- this._renderer.background.apply(this._renderer, arguments);
- }
+ this._renderer.background.apply(this._renderer, arguments);
return this;
};
/**
- * Clears the pixels within a buffer. This function only works on p5.Canvas
- * objects created with the createCanvas() function; it won't work with the
- * main display window. Unlike the main graphics context, pixels in
- * additional graphics areas created with createGraphics() can be entirely
+ * Clears the pixels within a buffer. This function only clears the canvas.
+ * It will not clear objects created by createX() methods such as
+ * createVideo() or createDiv().
+ * Unlike the main graphics context, pixels in additional graphics areas created
+ * with createGraphics() can be entirely
* or partially transparent. This function clears everything to make all of
* the pixels 100% transparent.
*
@@ -45819,8 +46767,8 @@ p5.prototype.clear = function() {
*
* noStroke();
* colorMode(RGB, 100);
- * for (var i = 0; i < 100; i++) {
- * for (var j = 0; j < 100; j++) {
+ * for (let i = 0; i < 100; i++) {
+ * for (let j = 0; j < 100; j++) {
* stroke(i, j, 0);
* point(i, j);
* }
@@ -45832,8 +46780,8 @@ p5.prototype.clear = function() {
*
* noStroke();
* colorMode(HSB, 100);
- * for (var i = 0; i < 100; i++) {
- * for (var j = 0; j < 100; j++) {
+ * for (let i = 0; i < 100; i++) {
+ * for (let j = 0; j < 100; j++) {
* stroke(i, j, 100);
* point(i, j);
* }
@@ -45844,10 +46792,10 @@ p5.prototype.clear = function() {
*
*
* colorMode(RGB, 255);
- * var c = color(127, 255, 0);
+ * let c = color(127, 255, 0);
*
* colorMode(RGB, 1);
- * var myColor = c._getRed();
+ * let myColor = c._getRed();
* text(myColor, 10, 10, 80, 80);
*
*
@@ -45869,7 +46817,7 @@ p5.prototype.clear = function() {
*Green to red gradient from bottom L to top R. shading originates from top left.
*Rainbow gradient from left to right. Brightness increasing to white at top.
*unknown image.
- *50x50 ellipse at middle L & 40x40 ellipse at center. Transluscent pink outlines.
+ *50x50 ellipse at middle L & 40x40 ellipse at center. Translucent pink outlines.
*
*/
/**
@@ -45879,7 +46827,7 @@ p5.prototype.clear = function() {
* current color mode
* @param {Number} max2 range for the green or saturation depending
* on the current color mode
- * @param {Number} max3 range for the blue or brightness/lighntess
+ * @param {Number} max3 range for the blue or brightness/lightness
* depending on the current color mode
* @param {Number} [maxA] range for the alpha
* @chainable
@@ -46037,7 +46985,7 @@ p5.prototype.colorMode = function(mode, max1, max2, max3, maxA) {
* 60x60 light green rect with black outline in center of canvas.
* 60x60 soft green rect with black outline in center of canvas.
* 60x60 red rect with black outline in center of canvas.
- * 60x60 dark fushcia rect with black outline in center of canvas.
+ * 60x60 dark fuchsia rect with black outline in center of canvas.
* 60x60 blue rect with black outline in center of canvas.
*/
@@ -46289,7 +47237,7 @@ p5.prototype.noStroke = function() {
* 60x60 white rect at center. Bright green outline.
* 60x60 white rect at center. Soft green outline.
* 60x60 white rect at center. Red outline.
- * 60x60 white rect at center. Dark fushcia outline.
+ * 60x60 white rect at center. Dark fuchsia outline.
* 60x60 white rect at center. Blue outline.
*/
@@ -46328,7 +47276,7 @@ p5.prototype.stroke = function() {
module.exports = p5;
-},{"../core/constants":19,"../core/main":25,"./p5.Color":17}],19:[function(_dereq_,module,exports){
+},{"../core/constants":18,"../core/main":24,"./p5.Color":16}],18:[function(_dereq_,module,exports){
/**
* @module Constants
* @submodule Constants
@@ -46679,6 +47627,10 @@ module.exports = {
// DOM EXTENSION
/**
+ * AUTO allows us to automatically set the width or height of an element (but not both),
+ * based on the current height and width of the element. Only one parameter can
+ * be passed to the size function as AUTO, at a time.
+ *
* @property {String} AUTO
* @final
*/
@@ -46731,6 +47683,11 @@ module.exports = {
* @final
*/
DIFFERENCE: 'difference',
+ /**
+ * @property {String} SUBTRACT
+ * @final
+ */
+ SUBTRACT: 'subtract',
/**
* @property {String} EXCLUSION
* @final
@@ -46838,6 +47795,11 @@ module.exports = {
* @final
*/
BOLD: 'bold',
+ /**
+ * @property {String} BOLDITALIC
+ * @final
+ */
+ BOLDITALIC: 'bold italic',
// TYPOGRAPHY-INTERNAL
_DEFAULT_TEXT_FILL: '#000000',
@@ -46856,7 +47818,15 @@ module.exports = {
TEXTURE: 'texture',
IMMEDIATE: 'immediate',
- //WEBGL TEXTURE WRAP AND FILTERING
+ // WEBGL TEXTURE MODE
+ // NORMAL already exists for typography
+ /**
+ * @property {String} IMAGE
+ * @final
+ */
+ IMAGE: 'image',
+
+ // WEBGL TEXTURE WRAP AND FILTERING
// LINEAR already exists above
NEAREST: 'nearest',
REPEAT: 'repeat',
@@ -46892,7 +47862,7 @@ module.exports = {
AXES: 'axes'
};
-},{}],20:[function(_dereq_,module,exports){
+},{}],19:[function(_dereq_,module,exports){
/**
* @module Environment
* @submodule Environment
@@ -46921,12 +47891,16 @@ var _windowPrint = window.print;
* the function. Individual elements can be
* separated with quotes ("") and joined with the addition operator (+).
*
+ * Note that calling print() without any arguments invokes the window.print()
+ * function which opens the browser's print dialog. To print a blank line
+ * to console you can write print('\n').
+ *
* @method print
* @param {Any} contents any combination of Number, String, Object, Boolean,
* Array to print
* @example
*
- * var x = 10;
+ * let x = 10;
* print('The value of x is ' + x);
* // prints "The value of x is 10"
*
@@ -47007,26 +47981,36 @@ p5.prototype.focused = document.hasFocus();
* must be less than the dimensions of the image.
*
* @method cursor
- * @param {String|Constant} type either ARROW, CROSS, HAND, MOVE, TEXT, or
- * WAIT, or path for image
- * @param {Number} [x] the horizontal active spot of the cursor
- * @param {Number} [y] the vertical active spot of the cursor
+ * @param {String|Constant} type Built-In: either ARROW, CROSS, HAND, MOVE, TEXT and WAIT
+ * Native CSS properties: 'grab', 'progress', 'cell' etc.
+ * External: path for cursor's images
+ * (Allowed File extensions: .cur, .gif, .jpg, .jpeg, .png)
+ * For more information on Native CSS cursors and url visit:
+ * https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
+ * @param {Number} [x] the horizontal active spot of the cursor (must be less than 32)
+ * @param {Number} [y] the vertical active spot of the cursor (must be less than 32)
* @example
*
- * // Move the mouse left and right across the image
- * // to see the cursor change from a cross to a hand
+ * // Move the mouse across the quadrants
+ * // to see the cursor change
* function draw() {
* line(width / 2, 0, width / 2, height);
- * if (mouseX < 50) {
+ * line(0, height / 2, width, height / 2);
+ * if (mouseX < 50 && mouseY < 50) {
* cursor(CROSS);
+ * } else if (mouseX > 50 && mouseY < 50) {
+ * cursor('progress');
+ * } else if (mouseX > 50 && mouseY > 50) {
+ * cursor('https://s3.amazonaws.com/mupublicdata/cursor.cur');
* } else {
- * cursor(HAND);
+ * cursor('grab');
* }
* }
*
*
* @alt
- * horizontal line divides canvas. cursor on left is a cross, right is hand.
+ * canvas is divided into four quadrants. cursor on first is a cross, second is a progress,
+ * third is a custom cursor using path to the cursor and fourth is a grab.
*
*/
p5.prototype.cursor = function(type, x, y) {
@@ -47084,9 +48068,9 @@ p5.prototype.cursor = function(type, x, y) {
* @example
*
*
- * var rectX = 0;
- * var fr = 30; //starting FPS
- * var clr;
+ * let rectX = 0;
+ * let fr = 30; //starting FPS
+ * let clr;
*
* function setup() {
* background(200);
@@ -47130,7 +48114,6 @@ p5.prototype.frameRate = function(fps) {
return this._frameRate;
} else {
this._setProperty('_targetFrameRate', fps);
- this._runFrames();
return this;
}
};
@@ -47353,7 +48336,7 @@ p5.prototype.height = 0;
* }
* function mousePressed() {
* if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {
- * var fs = fullscreen();
+ * let fs = fullscreen();
* fullscreen(!fs);
* }
* }
@@ -47448,7 +48431,7 @@ p5.prototype.pixelDensity = function(val) {
*
*
* function setup() {
- * var density = displayDensity();
+ * let density = displayDensity();
* pixelDensity(density);
* createCanvas(100, 100);
* background(200);
@@ -47503,8 +48486,8 @@ function exitFullscreen() {
* @example
*
*
- * var url;
- * var x = 100;
+ * let url;
+ * let x = 100;
*
* function setup() {
* fill(0);
@@ -47534,8 +48517,8 @@ p5.prototype.getURL = function() {
* @example
*
* function setup() {
- * var urlPath = getURLPath();
- * for (var i = 0; i < urlPath.length; i++) {
+ * let urlPath = getURLPath();
+ * for (let i = 0; i < urlPath.length; i++) {
* text(urlPath[i], 10, i * 20 + 20);
* }
* }
@@ -47560,7 +48543,7 @@ p5.prototype.getURLPath = function() {
* // Example: http://p5js.org?year=2014&month=May&day=15
*
* function setup() {
- * var params = getURLParams();
+ * let params = getURLParams();
* text(params.day, 10, 20);
* text(params.month, 10, 40);
* text(params.year, 10, 60);
@@ -47586,7 +48569,7 @@ p5.prototype.getURLParams = function() {
module.exports = p5;
-},{"./constants":19,"./main":25}],21:[function(_dereq_,module,exports){
+},{"./constants":18,"./main":24}],20:[function(_dereq_,module,exports){
/**
* @for p5
* @requires core
@@ -47597,8 +48580,12 @@ module.exports = p5;
var p5 = _dereq_('./main');
var constants = _dereq_('./constants');
+// p5.js blue, p5.js orange, auto dark green; fallback p5.js darkened magenta
+// See testColors below for all the color codes and names
+var typeColors = ['#2D7BB6', '#EE9900', '#4DB200', '#C83C00'];
+
if (typeof IS_MINIFIED !== 'undefined') {
- p5._validateParameters = p5._friendlyFileLoadError = function() {};
+ p5._validateParameters = p5._friendlyFileLoadError = p5._friendlyError = function() {};
} else {
var doFriendlyWelcome = false; // TEMP until we get it all working LM
// for parameter validation
@@ -47654,6 +48641,7 @@ if (typeof IS_MINIFIED !== 'undefined') {
/**
* Prints out a fancy, colorful message to the console log
*
+ * @method report
* @private
* @param {String} message the words to be said
* @param {String} func the name of the function to link
@@ -47661,12 +48649,6 @@ if (typeof IS_MINIFIED !== 'undefined') {
*
* @return console logs
*/
- // Wrong number of params, undefined param, wrong type
- var FILE_LOAD = 3;
- var ERR_PARAMS = 3;
- // p5.js blue, p5.js orange, auto dark green; fallback p5.js darkened magenta
- // See testColors below for all the color codes and names
- var typeColors = ['#2D7BB6', '#EE9900', '#4DB200', '#C83C00'];
var report = function(message, func, color) {
if (doFriendlyWelcome) {
friendlyWelcome();
@@ -47735,6 +48717,15 @@ if (typeof IS_MINIFIED !== 'undefined') {
'we recommend splitting the file into smaller segments and fetching those.'
}
};
+
+ /**
+ * This is called internally if there is a error during file loading.
+ *
+ * @method _friendlyFileLoadError
+ * @private
+ * @param {Number} errorType
+ * @param {String} filePath
+ */
p5._friendlyFileLoadError = function(errorType, filePath) {
var errorInfo = errorCases[errorType];
var message;
@@ -47752,7 +48743,20 @@ if (typeof IS_MINIFIED !== 'undefined') {
(errorInfo.message || '') +
' or running a local server.';
}
- report(message, errorInfo.method, FILE_LOAD);
+ report(message, errorInfo.method, 3);
+ };
+
+ /**
+ * This is a generic method that can be called from anywhere in the p5
+ * library to alert users to a common error.
+ *
+ * @method _friendlyError
+ * @private
+ * @param {Number} message message to be printed
+ * @param {String} method name of method
+ */
+ p5._friendlyError = function(message, method) {
+ report(message, method);
};
var docCache = {};
@@ -48145,7 +49149,7 @@ if (typeof IS_MINIFIED !== 'undefined') {
}
} catch (err) {}
- report(message + '.', func, ERR_PARAMS);
+ report(message + '.', func, 3);
}
};
@@ -48362,7 +49366,7 @@ if (document.readyState !== 'complete') {
module.exports = p5;
-},{"../../docs/reference/data.json":1,"./constants":19,"./main":25}],22:[function(_dereq_,module,exports){
+},{"../../docs/reference/data.json":1,"./constants":18,"./main":24}],21:[function(_dereq_,module,exports){
/**
* @requires constants
*/
@@ -48385,7 +49389,7 @@ module.exports = {
}
};
-},{"./constants":19}],23:[function(_dereq_,module,exports){
+},{"./constants":18}],22:[function(_dereq_,module,exports){
'use strict';
var p5 = _dereq_('../core/main');
@@ -48427,7 +49431,7 @@ if (document.readyState === 'complete') {
window.addEventListener('load', _globalInit, false);
}
-},{"../core/main":25}],24:[function(_dereq_,module,exports){
+},{"../core/main":24}],23:[function(_dereq_,module,exports){
/**
* @for p5
* @requires core
@@ -48442,10 +49446,6 @@ if (document.readyState === 'complete') {
var p5 = _dereq_('./main');
-p5.prototype.exit = function() {
- throw new Error('exit() not implemented, see remove()');
-};
-
p5.prototype.pushStyle = function() {
throw new Error('pushStyle() not used, see push()');
};
@@ -48454,15 +49454,25 @@ p5.prototype.popStyle = function() {
throw new Error('popStyle() not used, see pop()');
};
-p5.prototype.size = function() {
- var s = 'size() is not a valid p5 function, to set the size of the ';
- s += 'drawing canvas, please use createCanvas() instead';
- throw new Error(s);
+p5.prototype.popMatrix = function() {
+ throw new Error('popMatrix() not used, see pop()');
+};
+
+p5.prototype.printMatrix = function() {
+ throw new Error(
+ 'printMatrix() is not implemented in p5.js, ' +
+ 'refer to [https://simonsarris.com/a-transformation-class-for-canvas-to-keep-track-of-the-transformation-matrix/] ' +
+ 'to add your own implementation.'
+ );
+};
+
+p5.prototype.pushMatrix = function() {
+ throw new Error('pushMatrix() not used, see push()');
};
module.exports = p5;
-},{"./main":25}],25:[function(_dereq_,module,exports){
+},{"./main":24}],24:[function(_dereq_,module,exports){
/**
* @module Structure
* @submodule Structure
@@ -48527,15 +49537,15 @@ var p5 = function(sketch, node, sync) {
* @method preload
* @example
*
- * var img;
- * var c;
+ * let img;
+ * let c;
* function preload() {
- // preload() runs once
+ * // preload() runs once
* img = loadImage('assets/laDefense.jpg');
* }
*
* function setup() {
- // setup() waits until preload() is done
+ * // setup() waits until preload() is done
* img.loadPixels();
* // get color of middle pixel
* c = img.get(img.width / 2, img.height / 2);
@@ -48565,7 +49575,7 @@ var p5 = function(sketch, node, sync) {
* @method setup
* @example
*
- * var a = 0;
+ * let a = 0;
*
* function setup() {
* background(0);
@@ -48613,13 +49623,13 @@ var p5 = function(sketch, node, sync) {
* @method draw
* @example
*
- * var yPos = 0;
+ * let yPos = 0;
* function setup() {
- // setup() runs once
+ * // setup() runs once
* frameRate(30);
* }
* function draw() {
- // draw() loops forever, until stopped
+ * // draw() loops forever, until stopped
* background(204);
* yPos = yPos - 1;
* if (yPos < 0) {
@@ -48644,6 +49654,7 @@ var p5 = function(sketch, node, sync) {
this._userNode = node;
this._curElement = null;
this._elements = [];
+ this._glAttributes = null;
this._requestAnimId = 0;
this._preloadCount = 0;
this._isGlobal = false;
@@ -48738,7 +49749,6 @@ var p5 = function(sketch, node, sync) {
this._runIfPreloadsAreDone();
} else {
this._setup();
- this._runFrames();
this._draw();
}
}.bind(this);
@@ -48751,7 +49761,6 @@ var p5 = function(sketch, node, sync) {
loadingScreen.parentNode.removeChild(loadingScreen);
}
context._setup();
- context._runFrames();
context._draw();
}
};
@@ -48857,12 +49866,6 @@ var p5 = function(sketch, node, sync) {
}
}.bind(this);
- this._runFrames = function() {
- if (this._updateInterval) {
- clearInterval(this._updateInterval);
- }
- }.bind(this);
-
this._setProperty = function(prop, value) {
this[prop] = value;
if (this._isGlobal) {
@@ -49047,14 +50050,30 @@ p5.prototype._initializeInstanceVariables = function() {
};
this._pixelsDirty = true;
+
+ this._downKeys = {}; //Holds the key codes of currently pressed keys
};
// This is a pointer to our global mode p5 instance, if we're in
// global mode.
p5.instance = null;
-// Allows for the friendly error system to be turned off when creating a sketch,
-// which can give a significant boost to performance when needed.
+/**
+ * Allows for the friendly error system (FES) to be turned off when creating a sketch,
+ * which can give a significant boost to performance when needed.
+ * See
+ * disabling the friendly error system.
+ *
+ * @property {Boolean} disableFriendlyErrors
+ * @example
+ *
+ * p5.disableFriendlyErrors = true;
+ *
+ * function setup() {
+ * createCanvas(100, 50);
+ * }
+ *
+ */
p5.disableFriendlyErrors = false;
// attach constants to p5 prototype
@@ -49180,7 +50199,7 @@ p5.prototype._createFriendlyGlobalFunctionBinder = function(options) {
module.exports = p5;
-},{"./constants":19,"./shim":35}],26:[function(_dereq_,module,exports){
+},{"./constants":18,"./shim":34}],25:[function(_dereq_,module,exports){
/**
* @module DOM
* @submodule DOM
@@ -49211,13 +50230,14 @@ p5.Element = function(elt, pInst) {
* @example
*
*
- * createCanvas(300, 500);
- * background(0, 0, 0, 0);
- * var input = createInput();
- * input.position(20, 225);
- * var inputElem = new p5.Element(input.elt);
- * inputElem.style('width:450px;');
- * inputElem.value('some string');
+ * function setup() {
+ * let c = createCanvas(50, 50);
+ * c.elt.style.border = '5px solid red';
+ * }
+ *
+ * function draw() {
+ * background(220);
+ * }
*
*
*
@@ -49225,7 +50245,7 @@ p5.Element = function(elt, pInst) {
* @readOnly
*/
this.elt = elt;
- this._pInst = pInst;
+ this._pInst = this._pixelsState = pInst;
this._events = {};
this.width = this.elt.offsetWidth;
this.height = this.elt.offsetHeight;
@@ -49240,6 +50260,11 @@ p5.Element = function(elt, pInst) {
*
* positioning the canvas wiki page.
*
+ * All above examples except for the first one require the inclusion of
+ * the p5.dom library in your index.html. See the
+ * using a library
+ * section for information on how to include this library.
+ *
* @method parent
* @param {String|p5.Element|Object} parent the ID, DOM node, or p5.Element
* of desired parent element
@@ -49251,23 +50276,23 @@ p5.Element = function(elt, pInst) {
* // <div id="myContainer"></div>
*
* // in the js file:
- * var cnv = createCanvas(100, 100);
+ * let cnv = createCanvas(100, 100);
* cnv.parent('myContainer');
*
*
- * var div0 = createDiv('this is the parent');
- * var div1 = createDiv('this is the child');
+ * let div0 = createDiv('this is the parent');
+ * let div1 = createDiv('this is the child');
* div1.parent(div0); // use p5.Element
*
*
- * var div0 = createDiv('this is the parent');
+ * let div0 = createDiv('this is the parent');
* div0.id('apples');
- * var div1 = createDiv('this is the child');
+ * let div1 = createDiv('this is the child');
* div1.parent('apples'); // use id
*
*
- * var elt = document.getElementById('myParentDiv');
- * var div1 = createDiv('this is the child');
+ * let elt = document.getElementById('myParentDiv');
+ * let div1 = createDiv('this is the child');
* div1.parent(elt); // use element from page
*
*
@@ -49300,6 +50325,9 @@ p5.Element.prototype.parent = function(p) {
*
* Sets the ID of the element. If no ID argument is passed in, it instead
* returns the current ID of the element.
+ * Note that only one element can have a particular id in a page.
+ * The .class() function can be used
+ * to identify multiple elements with the same class name.
*
* @method id
* @param {String} id ID of the element
@@ -49308,7 +50336,7 @@ p5.Element.prototype.parent = function(p) {
* @example
*
* function setup() {
- * var cnv = createCanvas(100, 100);
+ * let cnv = createCanvas(100, 100);
* // Assigns a CSS selector ID to
* // the canvas element.
* cnv.id('mycanvas');
@@ -49345,7 +50373,7 @@ p5.Element.prototype.id = function(id) {
* @example
*
* function setup() {
- * var cnv = createCanvas(100, 100);
+ * let cnv = createCanvas(100, 100);
* // Assigns a CSS selector class 'small'
* // to the canvas element.
* cnv.class('small');
@@ -49383,9 +50411,9 @@ p5.Element.prototype.class = function(c) {
* @chainable
* @example
*
- * var cnv;
- * var d;
- * var g;
+ * let cnv;
+ * let d;
+ * let g;
* function setup() {
* cnv = createCanvas(100, 100);
* cnv.mousePressed(changeGray); // attach listener for
@@ -49422,10 +50450,10 @@ p5.Element.prototype.mousePressed = function(fxn) {
this._pInst._setProperty('mouseIsPressed', true);
this._pInst._setMouseButton(event);
// Pass along the return-value of the callback:
- return fxn();
+ return fxn.call(this);
};
// Pass along the event-prepended form of the callback.
- adjustListener('mousedown', eventPrependedFxn, this);
+ p5.Element._adjustListener('mousedown', eventPrependedFxn, this);
return this;
};
@@ -49442,9 +50470,9 @@ p5.Element.prototype.mousePressed = function(fxn) {
* @return {p5.Element}
* @example
*
- * var cnv;
- * var d;
- * var g;
+ * let cnv;
+ * let d;
+ * let g;
* function setup() {
* cnv = createCanvas(100, 100);
* cnv.doubleClicked(changeGray); // attach listener for
@@ -49474,7 +50502,7 @@ p5.Element.prototype.mousePressed = function(fxn) {
*
*/
p5.Element.prototype.doubleClicked = function(fxn) {
- adjustListener('dblclick', fxn, this);
+ p5.Element._adjustListener('dblclick', fxn, this);
return this;
};
@@ -49501,9 +50529,9 @@ p5.Element.prototype.doubleClicked = function(fxn) {
* @chainable
* @example
*
- * var cnv;
- * var d;
- * var g;
+ * let cnv;
+ * let d;
+ * let g;
* function setup() {
* cnv = createCanvas(100, 100);
* cnv.mouseWheel(changeSize); // attach listener for
@@ -49540,7 +50568,7 @@ p5.Element.prototype.doubleClicked = function(fxn) {
*
*/
p5.Element.prototype.mouseWheel = function(fxn) {
- adjustListener('wheel', fxn, this);
+ p5.Element._adjustListener('wheel', fxn, this);
return this;
};
@@ -49559,9 +50587,9 @@ p5.Element.prototype.mouseWheel = function(fxn) {
* @chainable
* @example
*
- * var cnv;
- * var d;
- * var g;
+ * let cnv;
+ * let d;
+ * let g;
* function setup() {
* cnv = createCanvas(100, 100);
* cnv.mouseReleased(changeGray); // attach listener for
@@ -49594,7 +50622,7 @@ p5.Element.prototype.mouseWheel = function(fxn) {
*
*/
p5.Element.prototype.mouseReleased = function(fxn) {
- adjustListener('mouseup', fxn, this);
+ p5.Element._adjustListener('mouseup', fxn, this);
return this;
};
@@ -49614,9 +50642,9 @@ p5.Element.prototype.mouseReleased = function(fxn) {
* @example
*
*
- * var cnv;
- * var d;
- * var g;
+ * let cnv;
+ * let d;
+ * let g;
*
* function setup() {
* cnv = createCanvas(100, 100);
@@ -49650,7 +50678,7 @@ p5.Element.prototype.mouseReleased = function(fxn) {
*
*/
p5.Element.prototype.mouseClicked = function(fxn) {
- adjustListener('click', fxn, this);
+ p5.Element._adjustListener('click', fxn, this);
return this;
};
@@ -49667,9 +50695,9 @@ p5.Element.prototype.mouseClicked = function(fxn) {
* @chainable
* @example
*
- * var cnv;
- * var d = 30;
- * var g;
+ * let cnv;
+ * let d = 30;
+ * let g;
* function setup() {
* cnv = createCanvas(100, 100);
* cnv.mouseMoved(changeSize); // attach listener for
@@ -49708,7 +50736,7 @@ p5.Element.prototype.mouseClicked = function(fxn) {
*
*/
p5.Element.prototype.mouseMoved = function(fxn) {
- adjustListener('mousemove', fxn, this);
+ p5.Element._adjustListener('mousemove', fxn, this);
return this;
};
@@ -49725,8 +50753,8 @@ p5.Element.prototype.mouseMoved = function(fxn) {
* @chainable
* @example
*
- * var cnv;
- * var d;
+ * let cnv;
+ * let d;
* function setup() {
* cnv = createCanvas(100, 100);
* cnv.mouseOver(changeGray);
@@ -49751,109 +50779,7 @@ p5.Element.prototype.mouseMoved = function(fxn) {
*
*/
p5.Element.prototype.mouseOver = function(fxn) {
- adjustListener('mouseover', fxn, this);
- return this;
-};
-
-/**
- * The .changed() function is called when the value of an
- * element changes.
- * This can be used to attach an element specific event listener.
- *
- * @method changed
- * @param {Function|Boolean} fxn function to be fired when the value of
- * an element changes.
- * if `false` is passed instead, the previously
- * firing function will no longer fire.
- * @chainable
- * @example
- *
- * var sel;
- *
- * function setup() {
- * textAlign(CENTER);
- * background(200);
- * sel = createSelect();
- * sel.position(10, 10);
- * sel.option('pear');
- * sel.option('kiwi');
- * sel.option('grape');
- * sel.changed(mySelectEvent);
- * }
- *
- * function mySelectEvent() {
- * var item = sel.value();
- * background(200);
- * text("it's a " + item + '!', 50, 50);
- * }
- *
- *
- * var checkbox;
- * var cnv;
- *
- * function setup() {
- * checkbox = createCheckbox(' fill');
- * checkbox.changed(changeFill);
- * cnv = createCanvas(100, 100);
- * cnv.position(0, 30);
- * noFill();
- * }
- *
- * function draw() {
- * background(200);
- * ellipse(50, 50, 50, 50);
- * }
- *
- * function changeFill() {
- * if (checkbox.checked()) {
- * fill(0);
- * } else {
- * noFill();
- * }
- * }
- *
- *
- * @alt
- * dropdown: pear, kiwi, grape. When selected text "its a" + selection shown.
- *
- */
-p5.Element.prototype.changed = function(fxn) {
- adjustListener('change', fxn, this);
- return this;
-};
-
-/**
- * The .input() function is called when any user input is
- * detected with an element. The input event is often used
- * to detect keystrokes in a input element, or changes on a
- * slider element. This can be used to attach an element specific
- * event listener.
- *
- * @method input
- * @param {Function|Boolean} fxn function to be fired when any user input is
- * detected within the element.
- * if `false` is passed instead, the previously
- * firing function will no longer fire.
- * @chainable
- * @example
- *
- * // Open your console to see the output
- * function setup() {
- * var inp = createInput('');
- * inp.input(myInputEvent);
- * }
- *
- * function myInputEvent() {
- * console.log('you are typing: ', this.value());
- * }
- *
- *
- * @alt
- * no display.
- *
- */
-p5.Element.prototype.input = function(fxn) {
- adjustListener('input', fxn, this);
+ p5.Element._adjustListener('mouseover', fxn, this);
return this;
};
@@ -49870,8 +50796,8 @@ p5.Element.prototype.input = function(fxn) {
* @chainable
* @example
*
- * var cnv;
- * var d;
+ * let cnv;
+ * let d;
* function setup() {
* cnv = createCanvas(100, 100);
* cnv.mouseOut(changeGray);
@@ -49895,7 +50821,7 @@ p5.Element.prototype.input = function(fxn) {
*
*/
p5.Element.prototype.mouseOut = function(fxn) {
- adjustListener('mouseout', fxn, this);
+ p5.Element._adjustListener('mouseout', fxn, this);
return this;
};
@@ -49911,9 +50837,9 @@ p5.Element.prototype.mouseOut = function(fxn) {
* @chainable
* @example
*
- * var cnv;
- * var d;
- * var g;
+ * let cnv;
+ * let d;
+ * let g;
* function setup() {
* cnv = createCanvas(100, 100);
* cnv.touchStarted(changeGray); // attach listener for
@@ -49943,7 +50869,7 @@ p5.Element.prototype.mouseOut = function(fxn) {
*
*/
p5.Element.prototype.touchStarted = function(fxn) {
- adjustListener('touchstart', fxn, this);
+ p5.Element._adjustListener('touchstart', fxn, this);
return this;
};
@@ -49959,8 +50885,8 @@ p5.Element.prototype.touchStarted = function(fxn) {
* @chainable
* @example
*
- * var cnv;
- * var g;
+ * let cnv;
+ * let g;
* function setup() {
* cnv = createCanvas(100, 100);
* cnv.touchMoved(changeGray); // attach listener for
@@ -49983,7 +50909,7 @@ p5.Element.prototype.touchStarted = function(fxn) {
*
*/
p5.Element.prototype.touchMoved = function(fxn) {
- adjustListener('touchmove', fxn, this);
+ p5.Element._adjustListener('touchmove', fxn, this);
return this;
};
@@ -49999,9 +50925,9 @@ p5.Element.prototype.touchMoved = function(fxn) {
* @chainable
* @example
*
- * var cnv;
- * var d;
- * var g;
+ * let cnv;
+ * let d;
+ * let g;
* function setup() {
* cnv = createCanvas(100, 100);
* cnv.touchEnded(changeGray); // attach listener for
@@ -50032,7 +50958,7 @@ p5.Element.prototype.touchMoved = function(fxn) {
*
*/
p5.Element.prototype.touchEnded = function(fxn) {
- adjustListener('touchend', fxn, this);
+ p5.Element._adjustListener('touchend', fxn, this);
return this;
};
@@ -50052,7 +50978,7 @@ p5.Element.prototype.touchEnded = function(fxn) {
* // To test this sketch, simply drag a
* // file over the canvas
* function setup() {
- * var c = createCanvas(100, 100);
+ * let c = createCanvas(100, 100);
* background(200);
* textAlign(CENTER);
* text('Drag file', width / 2, height / 2);
@@ -50070,7 +50996,7 @@ p5.Element.prototype.touchEnded = function(fxn) {
* nothing displayed
*/
p5.Element.prototype.dragOver = function(fxn) {
- adjustListener('dragover', fxn, this);
+ p5.Element._adjustListener('dragover', fxn, this);
return this;
};
@@ -50090,7 +51016,7 @@ p5.Element.prototype.dragOver = function(fxn) {
* // To test this sketch, simply drag a file
* // over and then out of the canvas area
* function setup() {
- * var c = createCanvas(100, 100);
+ * let c = createCanvas(100, 100);
* background(200);
* textAlign(CENTER);
* text('Drag file', width / 2, height / 2);
@@ -50108,165 +51034,35 @@ p5.Element.prototype.dragOver = function(fxn) {
* nothing displayed
*/
p5.Element.prototype.dragLeave = function(fxn) {
- adjustListener('dragleave', fxn, this);
- return this;
-};
-
-/**
- * The .drop() function is called for each file dropped on the element.
- * It requires a callback that is passed a p5.File object. You can
- * optionally pass two callbacks, the first one (required) is triggered
- * for each file dropped when the file is loaded. The second (optional)
- * is triggered just once when a file (or files) are dropped.
- *
- * @method drop
- * @param {Function} callback callback triggered when files are dropped.
- * @param {Function} [fxn] callback to receive loaded file.
- * @chainable
- * @example
- *
- * function setup() {
- * var c = createCanvas(100, 100);
- * background(200);
- * textAlign(CENTER);
- * text('drop file', width / 2, height / 2);
- * c.drop(gotFile);
- * }
- *
- * function gotFile(file) {
- * background(200);
- * text('received file:', width / 2, height / 2);
- * text(file.name, width / 2, height / 2 + 50);
- * }
- *
- *
- *
- * var img;
- *
- * function setup() {
- * var c = createCanvas(100, 100);
- * background(200);
- * textAlign(CENTER);
- * text('drop image', width / 2, height / 2);
- * c.drop(gotFile);
- * }
- *
- * function draw() {
- * if (img) {
- * image(img, 0, 0, width, height);
- * }
- * }
- *
- * function gotFile(file) {
- * img = createImg(file.data).hide();
- * }
- *
- *
- * @alt
- * Canvas turns into whatever image is dragged/dropped onto it.
- */
-p5.Element.prototype.drop = function(callback, fxn) {
- // Make a file loader callback and trigger user's callback
- function makeLoader(theFile) {
- // Making a p5.File object
- var p5file = new p5.File(theFile);
- return function(e) {
- p5file.data = e.target.result;
- callback(p5file);
- };
- }
-
- // Is the file stuff supported?
- if (window.File && window.FileReader && window.FileList && window.Blob) {
- // If you want to be able to drop you've got to turn off
- // a lot of default behavior
- attachListener(
- 'dragover',
- function(evt) {
- evt.stopPropagation();
- evt.preventDefault();
- },
- this
- );
-
- // If this is a drag area we need to turn off the default behavior
- attachListener(
- 'dragleave',
- function(evt) {
- evt.stopPropagation();
- evt.preventDefault();
- },
- this
- );
-
- // If just one argument it's the callback for the files
- if (typeof fxn !== 'undefined') {
- attachListener('drop', fxn, this);
- }
-
- // Deal with the files
- attachListener(
- 'drop',
- function(evt) {
- evt.stopPropagation();
- evt.preventDefault();
-
- // A FileList
- var files = evt.dataTransfer.files;
-
- // Load each one and trigger the callback
- for (var i = 0; i < files.length; i++) {
- var f = files[i];
- var reader = new FileReader();
- reader.onload = makeLoader(f);
-
- // Text or data?
- // This should likely be improved
- if (f.type.indexOf('text') > -1) {
- reader.readAsText(f);
- } else {
- reader.readAsDataURL(f);
- }
- }
- },
- this
- );
- } else {
- console.log('The File APIs are not fully supported in this browser.');
- }
-
+ p5.Element._adjustListener('dragleave', fxn, this);
return this;
};
// General handler for event attaching and detaching
-function adjustListener(ev, fxn, ctx) {
+p5.Element._adjustListener = function(ev, fxn, ctx) {
if (fxn === false) {
- detachListener(ev, ctx);
+ p5.Element._detachListener(ev, ctx);
} else {
- attachListener(ev, fxn, ctx);
+ p5.Element._attachListener(ev, fxn, ctx);
}
return this;
-}
-
-function attachListener(ev, fxn, ctx) {
- // LM removing, not sure why we had this?
- // var _this = ctx;
- // var f = function (e) { fxn(e, _this); };
+};
+p5.Element._attachListener = function(ev, fxn, ctx) {
// detach the old listener if there was one
if (ctx._events[ev]) {
- detachListener(ev, ctx);
+ p5.Element._detachListener(ev, ctx);
}
var f = fxn.bind(ctx);
ctx.elt.addEventListener(ev, f, false);
ctx._events[ev] = f;
-}
+};
-function detachListener(ev, ctx) {
+p5.Element._detachListener = function(ev, ctx) {
var f = ctx._events[ev];
ctx.elt.removeEventListener(ev, f, false);
ctx._events[ev] = null;
-}
+};
/**
* Helper fxn for sharing pixel methods
@@ -50278,7 +51074,7 @@ p5.Element.prototype._setProperty = function(prop, value) {
module.exports = p5.Element;
-},{"./main":25}],27:[function(_dereq_,module,exports){
+},{"./main":24}],26:[function(_dereq_,module,exports){
/**
* @module Rendering
* @submodule Rendering
@@ -50311,7 +51107,7 @@ p5.Graphics = function(w, h, renderer, pInst) {
var node = pInst._userNode || document.body;
node.appendChild(this.canvas);
- p5.Element.call(this, this.canvas, pInst, false);
+ p5.Element.call(this, this.canvas, pInst);
// bind methods and props of p5 to the new object
for (var p in p5.prototype) {
@@ -50343,6 +51139,58 @@ p5.Graphics = function(w, h, renderer, pInst) {
p5.Graphics.prototype = Object.create(p5.Element.prototype);
+/**
+ * Resets certain values such as those modified by functions in the Transform category
+ * and in the Lights category that are not automatically reset
+ * with graphics buffer objects. Calling this in draw() will copy the behavior
+ * of the standard canvas.
+ *
+ * @method reset
+ * @example
+ *
+ *
+ * let pg;
+ * function setup() {
+ * createCanvas(100, 100);
+ * background(0);
+ * pg = createGraphics(50, 100);
+ * pg.fill(0);
+ * frameRate(5);
+ * }
+ * function draw() {
+ * image(pg, width / 2, 0);
+ * pg.background(255);
+ * // p5.Graphics object behave a bit differently in some cases
+ * // The normal canvas on the left resets the translate
+ * // with every loop through draw()
+ * // the graphics object on the right doesn't automatically reset
+ * // so translate() is additive and it moves down the screen
+ * rect(0, 0, width / 2, 5);
+ * pg.rect(0, 0, width / 2, 5);
+ * translate(0, 5, 0);
+ * pg.translate(0, 5, 0);
+ * }
+ * function mouseClicked() {
+ * // if you click you will see that
+ * // reset() resets the translate back to the initial state
+ * // of the Graphics object
+ * pg.reset();
+ * }
+ *
+ *
+ * @alt
+ * A white line on a black background stays still on the top-left half.
+ * A black line animates from top to bottom on a white background on the right half.
+ * When clicked, the black line starts back over at the top.
+ *
+ */
+p5.Graphics.prototype.reset = function() {
+ this._renderer.resetMatrix();
+ if (this._renderer.isP3D) {
+ this._renderer._update();
+ }
+};
+
/**
* Removes a Graphics object from the page and frees any resources
* associated with it.
@@ -50351,7 +51199,7 @@ p5.Graphics.prototype = Object.create(p5.Element.prototype);
*
* @example
*
- * var bg;
+ * let bg;
* function setup() {
* bg = createCanvas(100, 100);
* bg.background(0);
@@ -50361,7 +51209,7 @@ p5.Graphics.prototype = Object.create(p5.Element.prototype);
*
*
*
- * var bg;
+ * let bg;
* function setup() {
* pixelDensity(1);
* createCanvas(100, 100);
@@ -50374,14 +51222,14 @@ p5.Graphics.prototype = Object.create(p5.Element.prototype);
* bg.ellipse(50, 50, 80, 80);
* }
* function draw() {
- * var t = millis() / 1000;
+ * let t = millis() / 1000;
* // draw the background
* if (bg) {
* image(bg, frameCount % 100, 0);
* image(bg, frameCount % 100 - 100, 0);
* }
* // draw the foreground
- * var p = p5.Vector.fromAngle(t, 35).add(50, 50);
+ * let p = p5.Vector.fromAngle(t, 35).add(50, 50);
* ellipse(p.x, p.y, 30);
* }
* function mouseClicked() {
@@ -50413,7 +51261,7 @@ p5.Graphics.prototype.remove = function() {
module.exports = p5.Graphics;
-},{"./constants":19,"./main":25}],28:[function(_dereq_,module,exports){
+},{"./constants":18,"./main":24}],27:[function(_dereq_,module,exports){
/**
* @module Rendering
* @submodule Rendering
@@ -50440,6 +51288,7 @@ var constants = _dereq_('../core/constants');
p5.Renderer = function(elt, pInst, isMainCanvas) {
p5.Element.call(this, elt, pInst);
this.canvas = elt;
+ this._pixelsState = pInst;
if (isMainCanvas) {
this._isMainCanvas = true;
// for pixel method sharing with pimage
@@ -50525,6 +51374,39 @@ p5.Renderer.prototype.resize = function(w, h) {
}
};
+p5.Renderer.prototype.get = function(x, y, w, h) {
+ var pixelsState = this._pixelsState;
+ var pd = pixelsState._pixelDensity;
+ var canvas = this.canvas;
+
+ if (typeof x === 'undefined' && typeof y === 'undefined') {
+ // get()
+ x = y = 0;
+ w = pixelsState.width;
+ h = pixelsState.height;
+ } else {
+ x *= pd;
+ y *= pd;
+
+ if (typeof w === 'undefined' && typeof h === 'undefined') {
+ // get(x,y)
+ if (x < 0 || y < 0 || x >= canvas.width || y >= canvas.height) {
+ return [0, 0, 0, 0];
+ }
+
+ return this._getPixel(x, y);
+ }
+ // get(x,y,w,h)
+ }
+
+ var region = new p5.Image(w, h);
+ region.canvas
+ .getContext('2d')
+ .drawImage(canvas, x, y, w * pd, h * pd, 0, 0, w, h);
+
+ return region;
+};
+
p5.Renderer.prototype.textLeading = function(l) {
if (typeof l === 'number') {
this._setProperty('_textLeading', l);
@@ -50549,7 +51431,8 @@ p5.Renderer.prototype.textStyle = function(s) {
if (
s === constants.NORMAL ||
s === constants.ITALIC ||
- s === constants.BOLD
+ s === constants.BOLD ||
+ s === constants.BOLDITALIC
) {
this._setProperty('_textStyle', s);
}
@@ -50787,7 +51670,7 @@ function calculateOffset(object) {
module.exports = p5.Renderer;
-},{"../core/constants":19,"./main":25}],29:[function(_dereq_,module,exports){
+},{"../core/constants":18,"./main":24}],28:[function(_dereq_,module,exports){
'use strict';
var p5 = _dereq_('./main');
@@ -50851,7 +51734,7 @@ p5.Renderer2D.prototype.background = function() {
}
this.drawingContext.restore();
- this._pInst._pixelsDirty = true;
+ this._pixelsState._pixelsDirty = true;
};
p5.Renderer2D.prototype.clear = function() {
@@ -50860,7 +51743,7 @@ p5.Renderer2D.prototype.clear = function() {
this.drawingContext.clearRect(0, 0, this.width, this.height);
this.drawingContext.restore();
- this._pInst._pixelsDirty = true;
+ this._pixelsState._pixelsDirty = true;
};
p5.Renderer2D.prototype.fill = function() {
@@ -50922,7 +51805,7 @@ p5.Renderer2D.prototype.image = function(
}
}
- this._pInst._pixelsDirty = true;
+ this._pixelsState._pixelsDirty = true;
};
p5.Renderer2D.prototype._getTintedImageCanvas = function(img) {
@@ -50955,8 +51838,30 @@ p5.Renderer2D.prototype._getTintedImageCanvas = function(img) {
//////////////////////////////////////////////
p5.Renderer2D.prototype.blendMode = function(mode) {
- this.drawingContext.globalCompositeOperation = mode;
+ if (mode === constants.SUBTRACT) {
+ console.warn('blendMode(SUBTRACT) only works in WEBGL mode.');
+ } else if (
+ mode === constants.BLEND ||
+ mode === constants.DARKEST ||
+ mode === constants.LIGHTEST ||
+ mode === constants.DIFFERENCE ||
+ mode === constants.MULTIPLY ||
+ mode === constants.EXCLUSION ||
+ mode === constants.SCREEN ||
+ mode === constants.REPLACE ||
+ mode === constants.OVERLAY ||
+ mode === constants.HARD_LIGHT ||
+ mode === constants.SOFT_LIGHT ||
+ mode === constants.DODGE ||
+ mode === constants.BURN ||
+ mode === constants.ADD
+ ) {
+ this.drawingContext.globalCompositeOperation = mode;
+ } else {
+ throw new Error('Mode ' + mode + ' not recognized.');
+ }
};
+
p5.Renderer2D.prototype.blend = function() {
var currBlend = this.drawingContext.globalCompositeOperation;
var blendMode = arguments[arguments.length - 1];
@@ -50999,7 +51904,7 @@ p5.Renderer2D.prototype.copy = function() {
}
p5.Renderer2D._copyHelper(this, srcImage, sx, sy, sw, sh, dx, dy, dw, dh);
- this._pInst._pixelsDirty = true;
+ this._pixelsState._pixelsDirty = true;
};
p5.Renderer2D._copyHelper = function(
@@ -51029,93 +51934,58 @@ p5.Renderer2D._copyHelper = function(
);
};
-p5.Renderer2D.prototype.get = function(x, y, w, h) {
- if (typeof w === 'undefined' && typeof h === 'undefined') {
- if (typeof x === 'undefined' && typeof y === 'undefined') {
- x = y = 0;
- w = this.width;
- h = this.height;
- } else {
- w = h = 1;
- }
- }
-
- // if the section does not overlap the canvas
- if (x + w < 0 || y + h < 0 || x >= this.width || y >= this.height) {
- // TODO: is this valid for w,h > 1 ?
- return [0, 0, 0, 255];
- }
-
- var ctx = this._pInst || this;
- var pd = ctx._pixelDensity;
+// p5.Renderer2D.prototype.get = p5.Renderer.prototype.get;
+// .get() is not overridden
- // round down to get integer numbers
- x = Math.floor(x);
- y = Math.floor(y);
- w = Math.floor(w);
- h = Math.floor(h);
-
- var sx = x * pd;
- var sy = y * pd;
- if (w === 1 && h === 1 && !(this instanceof p5.RendererGL)) {
- var imageData, index;
- if (ctx._pixelsDirty) {
- imageData = this.drawingContext.getImageData(sx, sy, 1, 1).data;
- index = 0;
- } else {
- imageData = ctx.pixels;
- index = (sx + sy * this.width * pd) * 4;
- }
- return [
- imageData[index + 0],
- imageData[index + 1],
- imageData[index + 2],
- imageData[index + 3]
- ];
+// x,y are canvas-relative (pre-scaled by _pixelDensity)
+p5.Renderer2D.prototype._getPixel = function(x, y) {
+ var pixelsState = this._pixelsState;
+ var imageData, index;
+ if (pixelsState._pixelsDirty) {
+ imageData = this.drawingContext.getImageData(x, y, 1, 1).data;
+ index = 0;
} else {
- //auto constrain the width and height to
- //dimensions of the source image
- var dw = Math.min(w, ctx.width);
- var dh = Math.min(h, ctx.height);
- var sw = dw * pd;
- var sh = dh * pd;
-
- var region = new p5.Image(dw, dh);
- region.canvas
- .getContext('2d')
- .drawImage(this.canvas, sx, sy, sw, sh, 0, 0, dw, dh);
-
- return region;
+ imageData = pixelsState.pixels;
+ index = (Math.floor(x) + Math.floor(y) * this.canvas.width) * 4;
}
+ return [
+ imageData[index + 0],
+ imageData[index + 1],
+ imageData[index + 2],
+ imageData[index + 3]
+ ];
};
p5.Renderer2D.prototype.loadPixels = function() {
- var ctx = this._pInst || this; // if called by p5.Image
- if (!ctx._pixelsDirty) return;
- ctx._pixelsDirty = false;
+ var pixelsState = this._pixelsState; // if called by p5.Image
+ if (!pixelsState._pixelsDirty) return;
+ pixelsState._pixelsDirty = false;
- var pd = ctx._pixelDensity;
+ var pd = pixelsState._pixelDensity;
var w = this.width * pd;
var h = this.height * pd;
var imageData = this.drawingContext.getImageData(0, 0, w, h);
// @todo this should actually set pixels per object, so diff buffers can
// have diff pixel arrays.
- ctx._setProperty('imageData', imageData);
- ctx._setProperty('pixels', imageData.data);
+ pixelsState._setProperty('imageData', imageData);
+ pixelsState._setProperty('pixels', imageData.data);
};
p5.Renderer2D.prototype.set = function(x, y, imgOrCol) {
// round down to get integer numbers
x = Math.floor(x);
y = Math.floor(y);
- var ctx = this._pInst || this;
+ var pixelsState = this._pixelsState;
if (imgOrCol instanceof p5.Image) {
this.drawingContext.save();
this.drawingContext.setTransform(1, 0, 0, 1, 0, 0);
- this.drawingContext.scale(ctx._pixelDensity, ctx._pixelDensity);
+ this.drawingContext.scale(
+ pixelsState._pixelDensity,
+ pixelsState._pixelDensity
+ );
this.drawingContext.drawImage(imgOrCol.canvas, x, y);
this.drawingContext.restore();
- ctx._pixelsDirty = true;
+ pixelsState._pixelsDirty = true;
} else {
var r = 0,
g = 0,
@@ -51123,13 +51993,15 @@ p5.Renderer2D.prototype.set = function(x, y, imgOrCol) {
a = 0;
var idx =
4 *
- (y * ctx._pixelDensity * (this.width * ctx._pixelDensity) +
- x * ctx._pixelDensity);
- if (!ctx.imageData || ctx._pixelsDirty) {
- ctx.loadPixels.call(ctx);
+ (y *
+ pixelsState._pixelDensity *
+ (this.width * pixelsState._pixelDensity) +
+ x * pixelsState._pixelDensity);
+ if (!pixelsState.imageData || pixelsState._pixelsDirty) {
+ pixelsState.loadPixels.call(pixelsState);
}
if (typeof imgOrCol === 'number') {
- if (idx < ctx.pixels.length) {
+ if (idx < pixelsState.pixels.length) {
r = imgOrCol;
g = imgOrCol;
b = imgOrCol;
@@ -51140,7 +52012,7 @@ p5.Renderer2D.prototype.set = function(x, y, imgOrCol) {
if (imgOrCol.length < 4) {
throw new Error('pixel array must be of the form [R, G, B, A]');
}
- if (idx < ctx.pixels.length) {
+ if (idx < pixelsState.pixels.length) {
r = imgOrCol[0];
g = imgOrCol[1];
b = imgOrCol[2];
@@ -51148,7 +52020,7 @@ p5.Renderer2D.prototype.set = function(x, y, imgOrCol) {
//this.updatePixels.call(this);
}
} else if (imgOrCol instanceof p5.Color) {
- if (idx < ctx.pixels.length) {
+ if (idx < pixelsState.pixels.length) {
r = imgOrCol.levels[0];
g = imgOrCol.levels[1];
b = imgOrCol.levels[2];
@@ -51157,25 +52029,27 @@ p5.Renderer2D.prototype.set = function(x, y, imgOrCol) {
}
}
// loop over pixelDensity * pixelDensity
- for (var i = 0; i < ctx._pixelDensity; i++) {
- for (var j = 0; j < ctx._pixelDensity; j++) {
+ for (var i = 0; i < pixelsState._pixelDensity; i++) {
+ for (var j = 0; j < pixelsState._pixelDensity; j++) {
// loop over
idx =
4 *
- ((y * ctx._pixelDensity + j) * this.width * ctx._pixelDensity +
- (x * ctx._pixelDensity + i));
- ctx.pixels[idx] = r;
- ctx.pixels[idx + 1] = g;
- ctx.pixels[idx + 2] = b;
- ctx.pixels[idx + 3] = a;
+ ((y * pixelsState._pixelDensity + j) *
+ this.width *
+ pixelsState._pixelDensity +
+ (x * pixelsState._pixelDensity + i));
+ pixelsState.pixels[idx] = r;
+ pixelsState.pixels[idx + 1] = g;
+ pixelsState.pixels[idx + 2] = b;
+ pixelsState.pixels[idx + 3] = a;
}
}
}
};
p5.Renderer2D.prototype.updatePixels = function(x, y, w, h) {
- var ctx = this._pInst || this;
- var pd = ctx._pixelDensity;
+ var pixelsState = this._pixelsState;
+ var pd = pixelsState._pixelDensity;
if (
x === undefined &&
y === undefined &&
@@ -51190,10 +52064,10 @@ p5.Renderer2D.prototype.updatePixels = function(x, y, w, h) {
w *= pd;
h *= pd;
- this.drawingContext.putImageData(ctx.imageData, x, y, 0, 0, w, h);
+ this.drawingContext.putImageData(pixelsState.imageData, x, y, 0, 0, w, h);
if (x !== 0 || y !== 0 || w !== this.width || h !== this.height) {
- ctx._pixelsDirty = true;
+ pixelsState._pixelsDirty = true;
}
};
@@ -51212,7 +52086,7 @@ p5.Renderer2D.prototype._acuteArcToBezier = function _acuteArcToBezier(
start,
size
) {
- // Evauate constants.
+ // Evaluate constants.
var alpha = size / 2.0,
cos_alpha = Math.cos(alpha),
sin_alpha = Math.sin(alpha),
@@ -51225,17 +52099,24 @@ p5.Renderer2D.prototype._acuteArcToBezier = function _acuteArcToBezier(
// Return rotated waypoints.
return {
- ax: Math.cos(start),
- ay: Math.sin(start),
- bx: lambda * cos_phi + mu * sin_phi,
- by: lambda * sin_phi - mu * cos_phi,
- cx: lambda * cos_phi - mu * sin_phi,
- cy: lambda * sin_phi + mu * cos_phi,
- dx: Math.cos(start + size),
- dy: Math.sin(start + size)
+ ax: Math.cos(start).toFixed(7),
+ ay: Math.sin(start).toFixed(7),
+ bx: (lambda * cos_phi + mu * sin_phi).toFixed(7),
+ by: (lambda * sin_phi - mu * cos_phi).toFixed(7),
+ cx: (lambda * cos_phi - mu * sin_phi).toFixed(7),
+ cy: (lambda * sin_phi + mu * cos_phi).toFixed(7),
+ dx: Math.cos(start + size).toFixed(7),
+ dy: Math.sin(start + size).toFixed(7)
};
};
+/*
+ * This function requires that:
+ *
+ * 0 <= start < TWO_PI
+ *
+ * start <= stop < start + TWO_PI
+ */
p5.Renderer2D.prototype.arc = function(x, y, w, h, start, stop, mode) {
var ctx = this.drawingContext;
var rx = w / 2.0;
@@ -51248,7 +52129,7 @@ p5.Renderer2D.prototype.arc = function(x, y, w, h, start, stop, mode) {
y += ry;
// Create curves
- while (stop - start > epsilon) {
+ while (stop - start >= epsilon) {
arcToDraw = Math.min(stop - start, constants.HALF_PI);
curves.push(this._acuteArcToBezier(start, arcToDraw));
start += arcToDraw;
@@ -51271,6 +52152,7 @@ p5.Renderer2D.prototype.arc = function(x, y, w, h, start, stop, mode) {
}
ctx.closePath();
ctx.fill();
+ this._pixelsState._pixelsDirty = true;
}
// Stroke curves
@@ -51292,6 +52174,7 @@ p5.Renderer2D.prototype.arc = function(x, y, w, h, start, stop, mode) {
ctx.closePath();
}
ctx.stroke();
+ this._pixelsState._pixelsDirty = true;
}
return this;
};
@@ -51329,9 +52212,11 @@ p5.Renderer2D.prototype.ellipse = function(args) {
ctx.closePath();
if (doFill) {
ctx.fill();
+ this._pixelsState._pixelsDirty = true;
}
if (doStroke) {
ctx.stroke();
+ this._pixelsState._pixelsDirty = true;
}
};
@@ -51342,17 +52227,11 @@ p5.Renderer2D.prototype.line = function(x1, y1, x2, y2) {
} else if (this._getStroke() === styleEmpty) {
return this;
}
- // Translate the line by (0.5, 0.5) to draw it crisp
- if (ctx.lineWidth % 2 === 1) {
- ctx.translate(0.5, 0.5);
- }
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
- if (ctx.lineWidth % 2 === 1) {
- ctx.translate(-0.5, -0.5);
- }
+ this._pixelsState._pixelsDirty = true;
return this;
};
@@ -51377,6 +52256,7 @@ p5.Renderer2D.prototype.point = function(x, y) {
ctx.fillRect(x, y, 1, 1);
}
this._setFill(f);
+ this._pixelsState._pixelsDirty = true;
};
p5.Renderer2D.prototype.quad = function(x1, y1, x2, y2, x3, y3, x4, y4) {
@@ -51404,6 +52284,7 @@ p5.Renderer2D.prototype.quad = function(x1, y1, x2, y2, x3, y3, x4, y4) {
if (doStroke) {
ctx.stroke();
}
+ this._pixelsState._pixelsDirty = true;
return this;
};
@@ -51428,10 +52309,6 @@ p5.Renderer2D.prototype.rect = function(args) {
return this;
}
}
- // Translate the line by (0.5, 0.5) to draw a crisp rectangle border
- if (this._doStroke && ctx.lineWidth % 2 === 1) {
- ctx.translate(0.5, 0.5);
- }
ctx.beginPath();
if (typeof tl === 'undefined') {
@@ -51494,9 +52371,7 @@ p5.Renderer2D.prototype.rect = function(args) {
if (this._doStroke) {
ctx.stroke();
}
- if (this._doStroke && ctx.lineWidth % 2 === 1) {
- ctx.translate(-0.5, -0.5);
- }
+ this._pixelsState._pixelsDirty = true;
return this;
};
@@ -51526,9 +52401,11 @@ p5.Renderer2D.prototype.triangle = function(args) {
ctx.closePath();
if (doFill) {
ctx.fill();
+ this._pixelsState._pixelsDirty = true;
}
if (doStroke) {
ctx.stroke();
+ this._pixelsState._pixelsDirty = true;
}
};
@@ -51585,7 +52462,7 @@ p5.Renderer2D.prototype.endShape = function(
if (closeShape) {
this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]);
}
- this._doFillStrokeClose();
+ this._doFillStrokeClose(closeShape);
}
} else if (
isBezier &&
@@ -51610,7 +52487,7 @@ p5.Renderer2D.prototype.endShape = function(
);
}
}
- this._doFillStrokeClose();
+ this._doFillStrokeClose(closeShape);
} else if (
isQuadratic &&
(shapeKind === constants.POLYGON || shapeKind === null)
@@ -51619,7 +52496,7 @@ p5.Renderer2D.prototype.endShape = function(
for (i = 0; i < numVerts; i++) {
if (vertices[i].isVert) {
if (vertices[i].moveTo) {
- this.drawingContext.moveTo([0], vertices[i][1]);
+ this.drawingContext.moveTo(vertices[i][0], vertices[i][1]);
} else {
this.drawingContext.lineTo(vertices[i][0], vertices[i][1]);
}
@@ -51632,7 +52509,7 @@ p5.Renderer2D.prototype.endShape = function(
);
}
}
- this._doFillStrokeClose();
+ this._doFillStrokeClose(closeShape);
} else {
if (shapeKind === constants.POINTS) {
for (i = 0; i < numVerts; i++) {
@@ -51688,7 +52565,7 @@ p5.Renderer2D.prototype.endShape = function(
this._pInst.fill(vertices[i + 2][5]);
}
}
- this._doFillStrokeClose();
+ this._doFillStrokeClose(closeShape);
}
} else if (shapeKind === constants.TRIANGLE_FAN) {
if (numVerts > 2) {
@@ -51722,7 +52599,7 @@ p5.Renderer2D.prototype.endShape = function(
}
}
}
- this._doFillStrokeClose();
+ this._doFillStrokeClose(closeShape);
}
} else if (shapeKind === constants.QUADS) {
for (i = 0; i + 3 < numVerts; i += 4) {
@@ -51739,7 +52616,7 @@ p5.Renderer2D.prototype.endShape = function(
if (this._doStroke) {
this._pInst.stroke(vertices[i + 3][6]);
}
- this._doFillStrokeClose();
+ this._doFillStrokeClose(closeShape);
}
} else if (shapeKind === constants.QUAD_STRIP) {
if (numVerts > 3) {
@@ -51761,7 +52638,7 @@ p5.Renderer2D.prototype.endShape = function(
this.drawingContext.moveTo(v[0], v[1]);
this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]);
}
- this._doFillStrokeClose();
+ this._doFillStrokeClose(closeShape);
}
}
} else {
@@ -51777,7 +52654,7 @@ p5.Renderer2D.prototype.endShape = function(
}
}
}
- this._doFillStrokeClose();
+ this._doFillStrokeClose(closeShape);
}
}
isCurve = false;
@@ -51788,27 +52665,13 @@ p5.Renderer2D.prototype.endShape = function(
vertices.pop();
}
- this._pInst._pixelsDirty = true;
+ this._pixelsState._pixelsDirty = true;
return this;
};
//////////////////////////////////////////////
// SHAPE | Attributes
//////////////////////////////////////////////
-p5.Renderer2D.prototype.noSmooth = function() {
- if ('imageSmoothingEnabled' in this.drawingContext) {
- this.drawingContext.imageSmoothingEnabled = false;
- }
- return this;
-};
-
-p5.Renderer2D.prototype.smooth = function() {
- if ('imageSmoothingEnabled' in this.drawingContext) {
- this.drawingContext.imageSmoothingEnabled = true;
- }
- return this;
-};
-
p5.Renderer2D.prototype.strokeCap = function(cap) {
if (
cap === constants.ROUND ||
@@ -51894,16 +52757,18 @@ p5.Renderer2D.prototype.curve = function(x1, y1, x2, y2, x3, y3, x4, y4) {
// SHAPE | Vertex
//////////////////////////////////////////////
-p5.Renderer2D.prototype._doFillStrokeClose = function() {
+p5.Renderer2D.prototype._doFillStrokeClose = function(closeShape) {
+ if (closeShape) {
+ this.drawingContext.closePath();
+ }
if (this._doFill) {
this.drawingContext.fill();
}
if (this._doStroke) {
this.drawingContext.stroke();
}
- this.drawingContext.closePath();
- this._pInst._pixelsDirty = true;
+ this._pixelsState._pixelsDirty = true;
};
//////////////////////////////////////////////
@@ -51932,16 +52797,6 @@ p5.Renderer2D.prototype.scale = function(x, y) {
return this;
};
-p5.Renderer2D.prototype.shearX = function(rad) {
- this.drawingContext.transform(1, 0, Math.tan(rad), 1, 0, 0);
- return this;
-};
-
-p5.Renderer2D.prototype.shearY = function(rad) {
- this.drawingContext.transform(1, Math.tan(rad), 0, 1, 0, 0);
- return this;
-};
-
p5.Renderer2D.prototype.translate = function(x, y) {
// support passing a vector as the 1st parameter
if (x instanceof p5.Vector) {
@@ -52011,7 +52866,7 @@ p5.Renderer2D.prototype._renderText = function(p, line, x, y, maxY) {
p.pop();
- this._pInst._pixelsDirty = true;
+ this._pixelsState._pixelsDirty = true;
return p;
};
@@ -52086,7 +52941,7 @@ p5.Renderer2D.prototype.pop = function(style) {
module.exports = p5.Renderer2D;
-},{"../image/filters":43,"./constants":19,"./main":25,"./p5.Renderer":28}],30:[function(_dereq_,module,exports){
+},{"../image/filters":42,"./constants":18,"./main":24,"./p5.Renderer":27}],29:[function(_dereq_,module,exports){
/**
* @module Rendering
* @submodule Rendering
@@ -52297,7 +53152,7 @@ p5.prototype.noCanvas = function() {
* @example
*
*
- * var pg;
+ * let pg;
* function setup() {
* createCanvas(100, 100);
* pg = createGraphics(100, 100);
@@ -52328,7 +53183,7 @@ p5.prototype.createGraphics = function(w, h, renderer) {
* with the ones of pixels already in the display window (B):
*
* BLEND
- linear interpolation of colours: C =
- * A\*factor + B. This is the default blending mode.
+ * A\*factor + B. This is the default blending mode.
* ADD
- sum of A and B
* DARKEST
- only the darkest colour succeeds: C =
* min(A\*factor, B).
@@ -52344,23 +53199,28 @@ p5.prototype.createGraphics = function(w, h, renderer) {
* REPLACE
- the pixels entirely replace the others and
* don't utilize alpha (transparency) values.
* OVERLAY
- mix of MULTIPLY
and SCREEN
- *
. Multiplies dark values, and screens light values.
+ *
. Multiplies dark values, and screens light values. (2D)
* HARD_LIGHT
- SCREEN
when greater than 50%
- * gray, MULTIPLY
when lower.
+ * gray, MULTIPLY
when lower. (2D)
* SOFT_LIGHT
- mix of DARKEST
and
- * LIGHTEST
. Works like OVERLAY
, but not as harsh.
+ * LIGHTEST
. Works like OVERLAY
, but not as harsh. (2D)
*
* DODGE
- lightens light tones and increases contrast,
- * ignores darks.
+ * ignores darks. (2D)
* BURN
- darker areas are applied, increasing contrast,
- * ignores lights.
+ * ignores lights. (2D)
+ * SUBTRACT
- remainder of A and B (3D)
*
+ *
+ * (2D) indicates that this blend mode only works in the 2D renderer.
+ * (3D) indicates that this blend mode only works in the WEBGL renderer.
+ *
*
* @method blendMode
* @param {Constant} mode blend mode to set for canvas.
* either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY,
* EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,
- * SOFT_LIGHT, DODGE, BURN, ADD or NORMAL
+ * SOFT_LIGHT, DODGE, BURN, ADD, or SUBTRACT
* @example
*
*
@@ -52389,32 +53249,19 @@ p5.prototype.createGraphics = function(w, h, renderer) {
*/
p5.prototype.blendMode = function(mode) {
p5._validateParameters('blendMode', arguments);
- if (
- mode === constants.BLEND ||
- mode === constants.DARKEST ||
- mode === constants.LIGHTEST ||
- mode === constants.DIFFERENCE ||
- mode === constants.MULTIPLY ||
- mode === constants.EXCLUSION ||
- mode === constants.SCREEN ||
- mode === constants.REPLACE ||
- mode === constants.OVERLAY ||
- mode === constants.HARD_LIGHT ||
- mode === constants.SOFT_LIGHT ||
- mode === constants.DODGE ||
- mode === constants.BURN ||
- mode === constants.ADD ||
- mode === constants.NORMAL
- ) {
- this._renderer.blendMode(mode);
- } else {
- throw new Error('Mode ' + mode + ' not recognized.');
+ if (mode === constants.NORMAL) {
+ // Warning added 3/26/19, can be deleted in future (1.0 release?)
+ console.warn(
+ 'NORMAL has been deprecated for use in blendMode. defaulting to BLEND instead.'
+ );
+ mode = constants.BLEND;
}
+ this._renderer.blendMode(mode);
};
module.exports = p5;
-},{"../webgl/p5.RendererGL":75,"./constants":19,"./main":25,"./p5.Graphics":27,"./p5.Renderer2D":29}],31:[function(_dereq_,module,exports){
+},{"../webgl/p5.RendererGL":74,"./constants":18,"./main":24,"./p5.Graphics":26,"./p5.Renderer2D":28}],30:[function(_dereq_,module,exports){
/**
* @module Shape
* @submodule 2D Primitives
@@ -52430,16 +53277,100 @@ var constants = _dereq_('../constants');
var canvas = _dereq_('../helpers');
_dereq_('../error_helpers');
+/**
+ * This function does 3 things:
+ *
+ * 1. Bounds the desired start/stop angles for an arc (in radians) so that:
+ *
+ * 0 <= start < TWO_PI ; start <= stop < start + TWO_PI
+ *
+ * This means that the arc rendering functions don't have to be concerned
+ * with what happens if stop is smaller than start, or if the arc 'goes
+ * round more than once', etc.: they can just start at start and increase
+ * until stop and the correct arc will be drawn.
+ *
+ * 2. Optionally adjusts the angles within each quadrant to counter the naive
+ * scaling of the underlying ellipse up from the unit circle. Without
+ * this, the angles become arbitrary when width != height: 45 degrees
+ * might be drawn at 5 degrees on a 'wide' ellipse, or at 85 degrees on
+ * a 'tall' ellipse.
+ *
+ * 3. Flags up when start and stop correspond to the same place on the
+ * underlying ellipse. This is useful if you want to do something special
+ * there (like rendering a whole ellipse instead).
+ */
+p5.prototype._normalizeArcAngles = function(
+ start,
+ stop,
+ width,
+ height,
+ correctForScaling
+) {
+ var epsilon = 0.00001; // Smallest visible angle on displays up to 4K.
+ var separation;
+
+ // The order of the steps is important here: each one builds upon the
+ // adjustments made in the steps that precede it.
+
+ // Constrain both start and stop to [0,TWO_PI).
+ start = start - constants.TWO_PI * Math.floor(start / constants.TWO_PI);
+ stop = stop - constants.TWO_PI * Math.floor(stop / constants.TWO_PI);
+
+ // Get the angular separation between the requested start and stop points.
+ //
+ // Technically this separation only matches what gets drawn if
+ // correctForScaling is enabled. We could add a more complicated calculation
+ // for when the scaling is uncorrected (in which case the drawn points could
+ // end up pushed together or pulled apart quite dramatically relative to what
+ // was requested), but it would make things more opaque for little practical
+ // benefit.
+ //
+ // (If you do disable correctForScaling and find that correspondToSamePoint
+ // is set too aggressively, the easiest thing to do is probably to just make
+ // epsilon smaller...)
+ separation = Math.min(
+ Math.abs(start - stop),
+ constants.TWO_PI - Math.abs(start - stop)
+ );
+
+ // Optionally adjust the angles to counter linear scaling.
+ if (correctForScaling) {
+ if (start <= constants.HALF_PI) {
+ start = Math.atan(width / height * Math.tan(start));
+ } else if (start > constants.HALF_PI && start <= 3 * constants.HALF_PI) {
+ start = Math.atan(width / height * Math.tan(start)) + constants.PI;
+ } else {
+ start = Math.atan(width / height * Math.tan(start)) + constants.TWO_PI;
+ }
+ if (stop <= constants.HALF_PI) {
+ stop = Math.atan(width / height * Math.tan(stop));
+ } else if (stop > constants.HALF_PI && stop <= 3 * constants.HALF_PI) {
+ stop = Math.atan(width / height * Math.tan(stop)) + constants.PI;
+ } else {
+ stop = Math.atan(width / height * Math.tan(stop)) + constants.TWO_PI;
+ }
+ }
+
+ // Ensure that start <= stop < start + TWO_PI.
+ if (start > stop) {
+ stop += constants.TWO_PI;
+ }
+
+ return {
+ start: start,
+ stop: stop,
+ correspondToSamePoint: separation < epsilon
+ };
+};
+
/**
* Draw an arc to the screen. If called with only x, y, w, h, start, and
* stop, the arc will be drawn and filled as an open pie segment. If a mode parameter is provided, the arc
* will be filled like an open semi-circle (OPEN) , a closed semi-circle (CHORD), or as a closed pie segment (PIE). The
* origin may be changed with the ellipseMode() function.
- * Note that drawing a full circle (ex: 0 to TWO_PI) will appear blank
- * because 0 and TWO_PI are the same position on the unit circle. The
- * best way to handle this is by using the ellipse() function instead
- * to create a closed ellipse, and to use the arc() function
- * only to draw parts of an ellipse.
+ * The arc is always drawn clockwise from wherever start falls to wherever stop falls on the ellipse.
+ * Adding or subtracting TWO_PI to either angle does not change where they fall.
+ * If both start and stop fall at the same place, a full ellipse will be drawn.
*
* @method arc
* @param {Number} x x-coordinate of the arc's ellipse
@@ -52510,55 +53441,32 @@ p5.prototype.arc = function(x, y, w, h, start, stop, mode, detail) {
start = this._toRadians(start);
stop = this._toRadians(stop);
- // Make all angles positive...
- while (start < 0) {
- start += constants.TWO_PI;
- }
- while (stop < 0) {
- stop += constants.TWO_PI;
- }
-
- if (typeof start !== 'undefined' && typeof stop !== 'undefined') {
- // don't display anything if the angles are same or they have a difference of 0 - TWO_PI
- if (
- stop.toFixed(10) === start.toFixed(10) ||
- Math.abs(stop - start) === constants.TWO_PI
- ) {
- start %= constants.TWO_PI;
- stop %= constants.TWO_PI;
- start += constants.TWO_PI;
- } else if (Math.abs(stop - start) > constants.TWO_PI) {
- // display a full circle if the difference between them is greater than 0 - TWO_PI
- start %= constants.TWO_PI;
- stop %= constants.TWO_PI;
- stop += constants.TWO_PI;
- }
- }
-
- //Adjust angles to counter linear scaling.
- if (start <= constants.HALF_PI) {
- start = Math.atan(w / h * Math.tan(start));
- } else if (start > constants.HALF_PI && start <= 3 * constants.HALF_PI) {
- start = Math.atan(w / h * Math.tan(start)) + constants.PI;
- }
- if (stop <= constants.HALF_PI) {
- stop = Math.atan(w / h * Math.tan(stop));
- } else if (stop > constants.HALF_PI && stop <= 3 * constants.HALF_PI) {
- stop = Math.atan(w / h * Math.tan(stop)) + constants.PI;
- }
-
- // Exceed the interval if necessary in order to preserve the size and
- // orientation of the arc.
- if (start > stop) {
- stop += constants.TWO_PI;
- }
-
// p5 supports negative width and heights for ellipses
w = Math.abs(w);
h = Math.abs(h);
var vals = canvas.modeAdjust(x, y, w, h, this._renderer._ellipseMode);
- this._renderer.arc(vals.x, vals.y, vals.w, vals.h, start, stop, mode, detail);
+ var angles = this._normalizeArcAngles(start, stop, vals.w, vals.h, true);
+
+ if (angles.correspondToSamePoint) {
+ // If the arc starts and ends at (near enough) the same place, we choose to
+ // draw an ellipse instead. This is preferable to faking an ellipse (by
+ // making stop ever-so-slightly less than start + TWO_PI) because the ends
+ // join up to each other rather than at a vertex at the centre (leaving
+ // an unwanted spike in the stroke/fill).
+ this._renderer.ellipse([vals.x, vals.y, vals.w, vals.h, detail]);
+ } else {
+ this._renderer.arc(
+ vals.x,
+ vals.y,
+ vals.w,
+ vals.h,
+ angles.start, // [0, TWO_PI)
+ angles.stop, // [start, start + TWO_PI)
+ mode,
+ detail
+ );
+ }
return this;
};
@@ -52594,7 +53502,7 @@ p5.prototype.arc = function(x, y, w, h, start, stop, mode, detail) {
* @param {Number} y
* @param {Number} w
* @param {Number} h
- * @param {Integer} detail number of radial sectors to draw
+ * @param {Integer} detail number of radial sectors to draw (for WebGL mode)
*/
p5.prototype.ellipse = function(x, y, w, h, detailX) {
p5._validateParameters('ellipse', arguments);
@@ -52622,6 +53530,37 @@ p5.prototype.ellipse = function(x, y, w, h, detailX) {
return this;
};
+
+/**
+ * Draws a circle to the screen. A circle is a simple closed shape.
+ * It is the set of all points in a plane that are at a given distance from a given point, the centre.
+ * This function is a special case of the ellipse() function, where the width and height of the ellipse are the same.
+ * Height and width of the ellipse correspond to the diameter of the circle.
+ * By default, the first two parameters set the location of the centre of the circle, the third sets the diameter of the circle.
+ *
+ * @method circle
+ * @param {Number} x x-coordinate of the centre of the circle.
+ * @param {Number} y y-coordinate of the centre of the circle.
+ * @param {Number} d diameter of the circle.
+ * @chainable
+ * @example
+ *
+ *
+ * // Draw a circle at location (30, 30) with a diameter of 20.
+ * circle(30, 30, 20);
+ *
+ *
+ *
+ * @alt
+ * white circle with black outline in mid of canvas that is 55x55.
+ */
+p5.prototype.circle = function() {
+ var args = Array.prototype.slice.call(arguments, 0, 2);
+ args.push(arguments[2]);
+ args.push(arguments[2]);
+ return this.ellipse.apply(this, args);
+};
+
/**
* Draws a line (a direct path between two points) to the screen. The version
* of line() with four parameters draws the line in 2D. To color a line, use
@@ -52687,7 +53626,7 @@ p5.prototype.line = function() {
* @method point
* @param {Number} x the x-coordinate
* @param {Number} y the y-coordinate
- * @param {Number} [z] the z-coordinate (for WEBGL mode)
+ * @param {Number} [z] the z-coordinate (for WebGL mode)
* @chainable
* @example
*
@@ -52719,6 +53658,8 @@ p5.prototype.point = function() {
* constrained to ninety degrees. The first pair of parameters (x1,y1)
* sets the first vertex and the subsequent pairs should proceed
* clockwise or counter-clockwise around the defined shape.
+ * z-arguments only work when quad() is used in WEBGL mode.
+ *
*
* @method quad
* @param {Number} x1 the x-coordinate of the first point
@@ -52761,7 +53702,18 @@ p5.prototype.quad = function() {
p5._validateParameters('quad', arguments);
if (this._renderer._doStroke || this._renderer._doFill) {
- this._renderer.quad.apply(this._renderer, arguments);
+ if (this._renderer.isP3D && arguments.length !== 12) {
+ // if 3D and we weren't passed 12 args, assume Z is 0
+ // prettier-ignore
+ this._renderer.quad.call(
+ this._renderer,
+ arguments[0], arguments[1], 0,
+ arguments[2], arguments[3], 0,
+ arguments[4], arguments[5], 0,
+ arguments[6], arguments[7], 0);
+ } else {
+ this._renderer.quad.apply(this._renderer, arguments);
+ }
}
return this;
@@ -52823,8 +53775,8 @@ p5.prototype.quad = function() {
* @param {Number} y
* @param {Number} w
* @param {Number} h
- * @param {Integer} [detailX] number of segments in the x-direction
- * @param {Integer} [detailY] number of segments in the y-direction
+ * @param {Integer} [detailX] number of segments in the x-direction (for WebGL mode)
+ * @param {Integer} [detailY] number of segments in the y-direction (for WebGL mode)
* @chainable
*/
p5.prototype.rect = function() {
@@ -52850,6 +53802,60 @@ p5.prototype.rect = function() {
return this;
};
+/**
+ * Draws a square to the screen. A square is a four-sided shape with
+ * every angle at ninety degrees, and equal side size.
+ * This function is a special case of the rect() function, where the width and height are the same, and the parameter is called "s" for side size.
+ * By default, the first two parameters set the location of the upper-left corner, the third sets the side size of the square.
+ * The way these parameters are interpreted, however,
+ * may be changed with the rectMode() function.
+ *
+ * The fourth, fifth, sixth and seventh parameters, if specified,
+ * determine corner radius for the top-left, top-right, lower-right and
+ * lower-left corners, respectively. An omitted corner radius parameter is set
+ * to the value of the previously specified radius value in the parameter list.
+ *
+ * @method square
+ * @param {Number} x x-coordinate of the square.
+ * @param {Number} y y-coordinate of the square.
+ * @param {Number} s side size of the square.
+ * @param {Number} [tl] optional radius of top-left corner.
+ * @param {Number} [tr] optional radius of top-right corner.
+ * @param {Number} [br] optional radius of bottom-right corner.
+ * @param {Number} [bl] optional radius of bottom-left corner.
+ * @chainable
+ * @example
+ *
+ *
+ * // Draw a square at location (30, 20) with a side size of 55.
+ * square(30, 20, 55);
+ *
+ *
+ *
+ *
+ *
+ * // Draw a square with rounded corners, each having a radius of 20.
+ * square(30, 20, 55, 20);
+ *
+ *
+ *
+ *
+ *
+ * // Draw a square with rounded corners having the following radii:
+ * // top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5.
+ * square(30, 20, 55, 20, 15, 10, 5);
+ *
+ *
+ *
+ * @alt
+ * 55x55 white square with black outline in mid-right of canvas.
+ * 55x55 white square with black outline and rounded edges in mid-right of canvas.
+ * 55x55 white square with black outline and rounded edges of different radii.
+ */
+p5.prototype.square = function(x, y, s, tl, tr, br, bl) {
+ return this.rect(x, y, s, s, tl, tr, br, bl);
+};
+
/**
* A triangle is a plane created by connecting three points. The first two
* arguments specify the first point, the middle two arguments specify the
@@ -52886,7 +53892,7 @@ p5.prototype.triangle = function() {
module.exports = p5;
-},{"../constants":19,"../error_helpers":21,"../helpers":22,"../main":25}],32:[function(_dereq_,module,exports){
+},{"../constants":18,"../error_helpers":20,"../helpers":21,"../main":24}],31:[function(_dereq_,module,exports){
/**
* @module Shape
* @submodule Attributes
@@ -52995,7 +54001,10 @@ p5.prototype.ellipseMode = function(m) {
*
*/
p5.prototype.noSmooth = function() {
- this._renderer.noSmooth();
+ this.setAttributes('antialias', false);
+ if ('imageSmoothingEnabled' in this.drawingContext) {
+ this.drawingContext.imageSmoothingEnabled = false;
+ }
return this;
};
@@ -53095,7 +54104,10 @@ p5.prototype.rectMode = function(m) {
*
*/
p5.prototype.smooth = function() {
- this._renderer.smooth();
+ this.setAttributes('antialias', true);
+ if ('imageSmoothingEnabled' in this.drawingContext) {
+ this.drawingContext.imageSmoothingEnabled = true;
+ }
return this;
};
@@ -53234,7 +54246,7 @@ p5.prototype.strokeWeight = function(w) {
module.exports = p5;
-},{"../constants":19,"../main":25}],33:[function(_dereq_,module,exports){
+},{"../constants":18,"../main":24}],32:[function(_dereq_,module,exports){
/**
* @module Shape
* @submodule Curves
@@ -53392,21 +54404,21 @@ p5.prototype.bezierDetail = function(d) {
*
*
* noFill();
- * var x1 = 85,
+ * let x1 = 85,
x2 = 10,
x3 = 90,
x4 = 15;
- * var y1 = 20,
+ * let y1 = 20,
y2 = 10,
y3 = 90,
y4 = 80;
* bezier(x1, y1, x2, y2, x3, y3, x4, y4);
* fill(255);
- * var steps = 10;
- * for (var i = 0; i <= steps; i++) {
- * var t = i / steps;
- * var x = bezierPoint(x1, x2, x3, x4, t);
- * var y = bezierPoint(y1, y2, y3, y4, t);
+ * let steps = 10;
+ * for (let i = 0; i <= steps; i++) {
+ * let t = i / steps;
+ * let x = bezierPoint(x1, x2, x3, x4, t);
+ * let y = bezierPoint(y1, y2, y3, y4, t);
* ellipse(x, y, 5, 5);
* }
*
@@ -53446,18 +54458,18 @@ p5.prototype.bezierPoint = function(a, b, c, d, t) {
*
* noFill();
* bezier(85, 20, 10, 10, 90, 90, 15, 80);
- * var steps = 6;
+ * let steps = 6;
* fill(255);
- * for (var i = 0; i <= steps; i++) {
- * var t = i / steps;
+ * for (let i = 0; i <= steps; i++) {
+ * let t = i / steps;
* // Get the location of the point
- * var x = bezierPoint(85, 10, 90, 15, t);
- * var y = bezierPoint(20, 10, 90, 80, t);
+ * let x = bezierPoint(85, 10, 90, 15, t);
+ * let y = bezierPoint(20, 10, 90, 80, t);
* // Get the tangent points
- * var tx = bezierTangent(85, 10, 90, 15, t);
- * var ty = bezierTangent(20, 10, 90, 80, t);
+ * let tx = bezierTangent(85, 10, 90, 15, t);
+ * let ty = bezierTangent(20, 10, 90, 80, t);
* // Calculate an angle from the tangent points
- * var a = atan2(ty, tx);
+ * let a = atan2(ty, tx);
* a += PI;
* stroke(255, 102, 0);
* line(x, y, cos(a) * 30 + x, sin(a) * 30 + y);
@@ -53475,14 +54487,14 @@ p5.prototype.bezierPoint = function(a, b, c, d, t) {
* noFill();
* bezier(85, 20, 10, 10, 90, 90, 15, 80);
* stroke(255, 102, 0);
- * var steps = 16;
- * for (var i = 0; i <= steps; i++) {
- * var t = i / steps;
- * var x = bezierPoint(85, 10, 90, 15, t);
- * var y = bezierPoint(20, 10, 90, 80, t);
- * var tx = bezierTangent(85, 10, 90, 15, t);
- * var ty = bezierTangent(20, 10, 90, 80, t);
- * var a = atan2(ty, tx);
+ * let steps = 16;
+ * for (let i = 0; i <= steps; i++) {
+ * let t = i / steps;
+ * let x = bezierPoint(85, 10, 90, 15, t);
+ * let y = bezierPoint(20, 10, 90, 80, t);
+ * let tx = bezierTangent(85, 10, 90, 15, t);
+ * let ty = bezierTangent(20, 10, 90, 80, t);
+ * let a = atan2(ty, tx);
* a -= HALF_PI;
* line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);
* }
@@ -53542,9 +54554,9 @@ p5.prototype.bezierTangent = function(a, b, c, d, t) {
*
*
* // Define the curve points as JavaScript objects
- * var p1 = { x: 5, y: 26 },
+ * let p1 = { x: 5, y: 26 },
p2 = { x: 73, y: 24 };
- * var p3 = { x: 73, y: 61 },
+ * let p3 = { x: 73, y: 61 },
p4 = { x: 15, y: 65 };
* noFill();
* stroke(255, 102, 0);
@@ -53608,7 +54620,7 @@ p5.prototype.curve = function() {
* information.
*
* @method curveDetail
- * @param {Number} resolution of the curves
+ * @param {Number} resolution resolution of the curves
* @chainable
* @example
*
@@ -53650,7 +54662,7 @@ p5.prototype.curveDetail = function(d) {
* increase in magnitude, they will continue to deform.
*
* @method curveTightness
- * @param {Number} amount of deformation from the original vertices
+ * @param {Number} amount amount of deformation from the original vertices
* @chainable
* @example
*
@@ -53664,7 +54676,7 @@ p5.prototype.curveDetail = function(d) {
*
* function draw() {
* background(204);
- * var t = map(mouseX, 0, width, -5, 5);
+ * let t = map(mouseX, 0, width, -5, 5);
* curveTightness(t);
* beginShape();
* curveVertex(10, 26);
@@ -53709,11 +54721,11 @@ p5.prototype.curveTightness = function(t) {
* curve(5, 26, 73, 24, 73, 61, 15, 65);
* fill(255);
* ellipseMode(CENTER);
- * var steps = 6;
- * for (var i = 0; i <= steps; i++) {
- * var t = i / steps;
- * var x = curvePoint(5, 5, 73, 73, t);
- * var y = curvePoint(26, 26, 24, 61, t);
+ * let steps = 6;
+ * for (let i = 0; i <= steps; i++) {
+ * let t = i / steps;
+ * let x = curvePoint(5, 5, 73, 73, t);
+ * let y = curvePoint(26, 26, 24, 61, t);
* ellipse(x, y, 5, 5);
* x = curvePoint(5, 73, 73, 15, t);
* y = curvePoint(26, 24, 61, 65, t);
@@ -53753,15 +54765,15 @@ p5.prototype.curvePoint = function(a, b, c, d, t) {
*
* noFill();
* curve(5, 26, 73, 24, 73, 61, 15, 65);
- * var steps = 6;
- * for (var i = 0; i <= steps; i++) {
- * var t = i / steps;
- * var x = curvePoint(5, 73, 73, 15, t);
- * var y = curvePoint(26, 24, 61, 65, t);
+ * let steps = 6;
+ * for (let i = 0; i <= steps; i++) {
+ * let t = i / steps;
+ * let x = curvePoint(5, 73, 73, 15, t);
+ * let y = curvePoint(26, 24, 61, 65, t);
* //ellipse(x, y, 5, 5);
- * var tx = curveTangent(5, 73, 73, 15, t);
- * var ty = curveTangent(26, 24, 61, 65, t);
- * var a = atan2(ty, tx);
+ * let tx = curveTangent(5, 73, 73, 15, t);
+ * let ty = curveTangent(26, 24, 61, 65, t);
+ * let a = atan2(ty, tx);
* a -= PI / 2.0;
* line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);
* }
@@ -53784,7 +54796,7 @@ p5.prototype.curveTangent = function(a, b, c, d, t) {
module.exports = p5;
-},{"../error_helpers":21,"../main":25}],34:[function(_dereq_,module,exports){
+},{"../error_helpers":20,"../main":24}],33:[function(_dereq_,module,exports){
/**
* @module Shape
* @submodule Vertex
@@ -54076,6 +55088,7 @@ p5.prototype.beginShape = function(kind) {
* @param {Number} x4 x-coordinate for the anchor point
* @param {Number} y4 y-coordinate for the anchor point
* @chainable
+ *
* @example
*
*
@@ -54087,6 +55100,10 @@ p5.prototype.beginShape = function(kind) {
*
*
*
+ * @alt
+ * crescent-shaped line in middle of canvas. Points facing left.
+ *
+ * @example
*
*
* beginShape();
@@ -54098,21 +55115,8 @@ p5.prototype.beginShape = function(kind) {
*
*
* @alt
- * crescent-shaped line in middle of canvas. Points facing left.
* white crescent shape in middle of canvas. Points facing left.
- */
-/**
- * @method bezierVertex
- * @param {Number} x2
- * @param {Number} y2
- * @param {Number} [z2] z-coordinate for the first control point (for WebGL mode)
- * @param {Number} x3
- * @param {Number} y3
- * @param {Number} [z3] z-coordinate for the second control point (for WebGL mode)
- * @param {Number} x4
- * @param {Number} y4
- * @param {Number} [z4] z-coordinate for the anchor point (for WebGL mode)
- * @chainable
+ *
* @example
*
*
@@ -54150,13 +55154,29 @@ p5.prototype.beginShape = function(kind) {
* crescent shape in middle of canvas with another crescent shape on positive z-axis.
*/
+/**
+ * @method bezierVertex
+ * @param {Number} x2
+ * @param {Number} y2
+ * @param {Number} z2 z-coordinate for the first control point (for WebGL mode)
+ * @param {Number} x3
+ * @param {Number} y3
+ * @param {Number} z3 z-coordinate for the second control point (for WebGL mode)
+ * @param {Number} x4
+ * @param {Number} y4
+ * @param {Number} z4 z-coordinate for the anchor point (for WebGL mode)
+ * @chainable
+ */
p5.prototype.bezierVertex = function() {
p5._validateParameters('bezierVertex', arguments);
if (this._renderer.isP3D) {
this._renderer.bezierVertex.apply(this._renderer, arguments);
} else {
if (vertices.length === 0) {
- throw 'vertex() must be used once before calling bezierVertex()';
+ p5._friendlyError(
+ 'vertex() must be used once before calling bezierVertex()',
+ 'bezierVertex'
+ );
} else {
isBezier = true;
var vert = [];
@@ -54450,6 +55470,7 @@ p5.prototype.endShape = function(mode) {
* @param {Number} x3 x-coordinate for the anchor point
* @param {Number} y3 y-coordinate for the anchor point
* @chainable
+ *
* @example
*
*
@@ -54492,16 +55513,19 @@ p5.prototype.endShape = function(mode) {
* @alt
* arched-shaped black line with 4 pixel thick stroke weight.
* backwards s-shaped black line with 4 pixel thick stroke weight.
+ *
*/
+
/**
* @method quadraticVertex
* @param {Number} cx
* @param {Number} cy
- * @param {Number} [cz] z-coordinate for the control point (for WebGL mode)
+ * @param {Number} cz z-coordinate for the control point (for WebGL mode)
* @param {Number} x3
* @param {Number} y3
- * @param {Number} [z3] z-coordinate for the anchor point (for WebGL mode)
+ * @param {Number} z3 z-coordinate for the anchor point (for WebGL mode)
* @chainable
+ *
* @example
*
*
@@ -54576,8 +55600,9 @@ p5.prototype.quadraticVertex = function() {
vertices.push(vert);
}
} else {
- throw new Error(
- 'vertex() must be used once before calling quadraticVertex()'
+ p5._friendlyError(
+ 'vertex() must be used once before calling quadraticVertex()',
+ 'quadraticVertex'
);
}
}
@@ -54711,7 +55736,7 @@ p5.prototype.vertex = function(x, y, moveTo, u, v) {
module.exports = p5;
-},{"../constants":19,"../main":25}],35:[function(_dereq_,module,exports){
+},{"../constants":18,"../main":24}],34:[function(_dereq_,module,exports){
'use strict';
// requestAnim shim layer by Paul Irish
@@ -54813,7 +55838,7 @@ window.requestAnimationFrame = (function() {
}
})();
-},{}],36:[function(_dereq_,module,exports){
+},{}],35:[function(_dereq_,module,exports){
/**
* @module Structure
* @submodule Structure
@@ -54856,7 +55881,7 @@ var p5 = _dereq_('./main');
*
*
*
- * var x = 0;
+ * let x = 0;
* function setup() {
* createCanvas(100, 100);
* }
@@ -54892,10 +55917,12 @@ p5.prototype.noLoop = function() {
* within it. However, the draw() loop may be stopped by calling noLoop().
* In that case, the draw() loop can be resumed with loop().
*
+ * Avoid calling loop() from inside setup().
+ *
* @method loop
* @example
*
- * var x = 0;
+ * let x = 0;
* function setup() {
* createCanvas(100, 100);
* noLoop();
@@ -54925,8 +55952,12 @@ p5.prototype.noLoop = function() {
*/
p5.prototype.loop = function() {
- this._loop = true;
- this._draw();
+ if (!this._loop) {
+ this._loop = true;
+ if (this._setupDone) {
+ this._draw();
+ }
+ }
};
/**
@@ -54942,7 +55973,11 @@ p5.prototype.loop = function() {
* and style settings controlled by the following functions: fill(),
* stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(),
* imageMode(), rectMode(), ellipseMode(), colorMode(), textAlign(),
- * textFont(), textMode(), textSize(), textLeading().
+ * textFont(), textSize(), textLeading().
+ *
+ * In WEBGL mode additional style settings are stored. These are controlled by the following functions: setCamera(), ambientLight(), directionalLight(),
+ * pointLight(), texture(), specularMaterial(), shininess(), normalMaterial()
+ * and shader().
*
* @method push
* @example
@@ -55007,7 +56042,11 @@ p5.prototype.push = function() {
* and style settings controlled by the following functions: fill(),
* stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(),
* imageMode(), rectMode(), ellipseMode(), colorMode(), textAlign(),
- * textFont(), textMode(), textSize(), textLeading().
+ * textFont(), textSize(), textLeading().
+ *
+ * In WEBGL mode additional style settings are stored. These are controlled by the following functions: setCamera(), ambientLight(), directionalLight(),
+ * pointLight(), texture(), specularMaterial(), shininess(), normalMaterial()
+ * and shader().
*
* @method pop
* @example
@@ -55081,7 +56120,7 @@ p5.prototype.pop = function() {
* @param {Integer} [n] Redraw for n-times. The default value is 1.
* @example
*
- * var x = 0;
+ * let x = 0;
*
* function setup() {
* createCanvas(100, 100);
@@ -55100,7 +56139,7 @@ p5.prototype.pop = function() {
*
*
*
- * var x = 0;
+ * let x = 0;
*
* function setup() {
* createCanvas(100, 100);
@@ -55124,6 +56163,10 @@ p5.prototype.pop = function() {
*
*/
p5.prototype.redraw = function(n) {
+ if (this._inUserDraw || !this._setupDone) {
+ return;
+ }
+
var numberOfRedraws = parseInt(n);
if (isNaN(numberOfRedraws) || numberOfRedraws < 1) {
numberOfRedraws = 1;
@@ -55146,7 +56189,12 @@ p5.prototype.redraw = function(n) {
}
context._setProperty('frameCount', context.frameCount + 1);
context._registeredMethods.pre.forEach(callMethod);
- userDraw();
+ this._inUserDraw = true;
+ try {
+ userDraw();
+ } finally {
+ this._inUserDraw = false;
+ }
context._registeredMethods.post.forEach(callMethod);
}
}
@@ -55154,7 +56202,7 @@ p5.prototype.redraw = function(n) {
module.exports = p5;
-},{"./main":25}],37:[function(_dereq_,module,exports){
+},{"./main":24}],36:[function(_dereq_,module,exports){
/**
* @module Transform
* @submodule Transform
@@ -55264,6 +56312,33 @@ var p5 = _dereq_('./main');
* }
*
*
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * noFill();
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * rotateY(PI / 6);
+ * stroke(153);
+ * box(35);
+ * var rad = millis() / 1000;
+ * // Set rotation angles
+ * var ct = cos(rad);
+ * var st = sin(rad);
+ * // Matrix for rotation around the Y axis
+ * // prettier-ignore
+ * applyMatrix( ct, 0.0, st, 0.0,
+ * 0.0, 1.0, 0.0, 0.0,
+ * -st, 0.0, ct, 0.0,
+ * 0.0, 0.0, 0.0, 1.0);
+ * stroke(255);
+ * box(50);
+ * }
+ *
+ *
*
* @alt
* A rectangle translating to the right
@@ -55273,22 +56348,10 @@ var p5 = _dereq_('./main');
*
*/
p5.prototype.applyMatrix = function(a, b, c, d, e, f) {
- this._renderer.applyMatrix(a, b, c, d, e, f);
+ this._renderer.applyMatrix.apply(this._renderer, arguments);
return this;
};
-p5.prototype.popMatrix = function() {
- throw new Error('popMatrix() not used, see pop()');
-};
-
-p5.prototype.printMatrix = function() {
- throw new Error('printMatrix() not implemented');
-};
-
-p5.prototype.pushMatrix = function() {
- throw new Error('pushMatrix() not used, see push()');
-};
-
/**
* Replaces the current matrix with the identity matrix.
*
@@ -55555,7 +56618,8 @@ p5.prototype.scale = function(x, y, z) {
*/
p5.prototype.shearX = function(angle) {
p5._validateParameters('shearX', arguments);
- this._renderer.shearX(this._toRadians(angle));
+ var rad = this._toRadians(angle);
+ this._renderer.applyMatrix(1, 0, Math.tan(rad), 1, 0, 0);
return this;
};
@@ -55594,7 +56658,8 @@ p5.prototype.shearX = function(angle) {
*/
p5.prototype.shearY = function(angle) {
p5._validateParameters('shearY', arguments);
- this._renderer.shearY(this._toRadians(angle));
+ var rad = this._toRadians(angle);
+ this._renderer.applyMatrix(1, Math.tan(rad), 0, 1, 0, 0);
return this;
};
@@ -55669,7 +56734,7 @@ p5.prototype.translate = function(x, y, z) {
module.exports = p5;
-},{"./main":25}],38:[function(_dereq_,module,exports){
+},{"./main":24}],37:[function(_dereq_,module,exports){
/**
* @module Data
* @submodule Dictionary
@@ -55700,10 +56765,10 @@ var p5 = _dereq_('../core/main');
*
*
* function setup() {
- * var myDictionary = createStringDict('p5', 'js');
+ * let myDictionary = createStringDict('p5', 'js');
* print(myDictionary.hasKey('p5')); // logs true to console
*
- * var anotherDictionary = createStringDict({ happy: 'coding' });
+ * let anotherDictionary = createStringDict({ happy: 'coding' });
* print(anotherDictionary.hasKey('happy')); // logs true to console
* }
*
@@ -55734,10 +56799,10 @@ p5.prototype.createStringDict = function(key, value) {
*
*
* function setup() {
- * var myDictionary = createNumberDict(100, 42);
+ * let myDictionary = createNumberDict(100, 42);
* print(myDictionary.hasKey(100)); // logs true to console
*
- * var anotherDictionary = createNumberDict({ 200: 84 });
+ * let anotherDictionary = createNumberDict({ 200: 84 });
* print(anotherDictionary.hasKey(200)); // logs true to console
* }
*
@@ -55782,7 +56847,7 @@ p5.TypedDict = function(key, value) {
*
*
* function setup() {
- * var myDictionary = createNumberDict(1, 10);
+ * let myDictionary = createNumberDict(1, 10);
* myDictionary.create(2, 20);
* myDictionary.create(3, 30);
* print(myDictionary.size()); // logs 3 to the console
@@ -55806,7 +56871,7 @@ p5.TypedDict.prototype.size = function() {
*
*
* function setup() {
- * var myDictionary = createStringDict('p5', 'js');
+ * let myDictionary = createStringDict('p5', 'js');
* print(myDictionary.hasKey('p5')); // logs true to console
* }
*
@@ -55828,8 +56893,8 @@ p5.TypedDict.prototype.hasKey = function(key) {
*
*
* function setup() {
- * var myDictionary = createStringDict('p5', 'js');
- * var myValue = myDictionary.get('p5');
+ * let myDictionary = createStringDict('p5', 'js');
+ * let myValue = myDictionary.get('p5');
* print(myValue === 'js'); // logs true to console
* }
*
@@ -55856,7 +56921,7 @@ p5.TypedDict.prototype.get = function(key) {
*
*
* function setup() {
- * var myDictionary = createStringDict('p5', 'js');
+ * let myDictionary = createStringDict('p5', 'js');
* myDictionary.set('p5', 'JS');
* myDictionary.print(); // logs "key: p5 - value: JS" to console
* }
@@ -55894,7 +56959,7 @@ p5.TypedDict.prototype._addObj = function(obj) {
*
*
* function setup() {
- * var myDictionary = createStringDict('p5', 'js');
+ * let myDictionary = createStringDict('p5', 'js');
* myDictionary.create('happy', 'coding');
* myDictionary.print();
* // above logs "key: p5 - value: js, key: happy - value: coding" to console
@@ -55927,7 +56992,7 @@ p5.TypedDict.prototype.create = function(key, value) {
*
*
* function setup() {
- * var myDictionary = createStringDict('p5', 'js');
+ * let myDictionary = createStringDict('p5', 'js');
* print(myDictionary.hasKey('p5')); // prints 'true'
* myDictionary.clear();
* print(myDictionary.hasKey('p5')); // prints 'false'
@@ -55950,7 +57015,7 @@ p5.TypedDict.prototype.clear = function() {
*
*
* function setup() {
- * var myDictionary = createStringDict('p5', 'js');
+ * let myDictionary = createStringDict('p5', 'js');
* myDictionary.create('happy', 'coding');
* myDictionary.print();
* // above logs "key: p5 - value: js, key: happy - value: coding" to console
@@ -55979,7 +57044,7 @@ p5.TypedDict.prototype.remove = function(key) {
*
*
* function setup() {
- * var myDictionary = createStringDict('p5', 'js');
+ * let myDictionary = createStringDict('p5', 'js');
* myDictionary.create('happy', 'coding');
* myDictionary.print();
* // above logs "key: p5 - value: js, key: happy - value: coding" to console
@@ -56001,16 +57066,22 @@ p5.TypedDict.prototype.print = function() {
* @example
*
*
- * createButton('save')
- * .position(10, 10)
- * .mousePressed(function() {
+ * function setup() {
+ * createCanvas(100, 100);
+ * background(200);
+ * text('click here to save', 10, 10, 70, 80);
+ * }
+ *
+ * function mousePressed() {
+ * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {
* createStringDict({
* john: 1940,
* paul: 1942,
* george: 1943,
* ringo: 1940
* }).saveTable('beatles');
- * });
+ * }
+ * }
*
*
*/
@@ -56033,16 +57104,22 @@ p5.TypedDict.prototype.saveTable = function(filename) {
* @example
*
*
- * createButton('save')
- * .position(10, 10)
- * .mousePressed(function() {
+ * function setup() {
+ * createCanvas(100, 100);
+ * background(200);
+ * text('click here to save', 10, 10, 70, 80);
+ * }
+ *
+ * function mousePressed() {
+ * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {
* createStringDict({
* john: 1940,
* paul: 1942,
* george: 1943,
* ringo: 1940
* }).saveJSON('beatles');
- * });
+ * }
+ * }
*
*
*/
@@ -56114,7 +57191,7 @@ p5.NumberDict.prototype._validate = function(value) {
*
*
* function setup() {
- * var myDictionary = createNumberDict(2, 5);
+ * let myDictionary = createNumberDict(2, 5);
* myDictionary.add(2, 2);
* print(myDictionary.get(2)); // logs 7 to console.
* }
@@ -56142,7 +57219,7 @@ p5.NumberDict.prototype.add = function(key, amount) {
*
*
* function setup() {
- * var myDictionary = createNumberDict(2, 5);
+ * let myDictionary = createNumberDict(2, 5);
* myDictionary.sub(2, 2);
* print(myDictionary.get(2)); // logs 3 to console.
* }
@@ -56166,7 +57243,7 @@ p5.NumberDict.prototype.sub = function(key, amount) {
*
*
* function setup() {
- * var myDictionary = createNumberDict(2, 4);
+ * let myDictionary = createNumberDict(2, 4);
* myDictionary.mult(2, 2);
* print(myDictionary.get(2)); // logs 8 to console.
* }
@@ -56194,7 +57271,7 @@ p5.NumberDict.prototype.mult = function(key, amount) {
*
*
* function setup() {
- * var myDictionary = createNumberDict(2, 8);
+ * let myDictionary = createNumberDict(2, 8);
* myDictionary.div(2, 2);
* print(myDictionary.get(2)); // logs 4 to console.
* }
@@ -56245,8 +57322,8 @@ p5.NumberDict.prototype._valueTest = function(flip) {
*
*
* function setup() {
- * var myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });
- * var lowestValue = myDictionary.minValue(); // value is -10
+ * let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });
+ * let lowestValue = myDictionary.minValue(); // value is -10
* print(lowestValue);
* }
*
@@ -56266,8 +57343,8 @@ p5.NumberDict.prototype.minValue = function() {
*
*
* function setup() {
- * var myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });
- * var highestValue = myDictionary.maxValue(); // value is 3
+ * let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });
+ * let highestValue = myDictionary.maxValue(); // value is 3
* print(highestValue);
* }
*
@@ -56310,8 +57387,8 @@ p5.NumberDict.prototype._keyTest = function(flip) {
*
*
* function setup() {
- * var myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });
- * var lowestKey = myDictionary.minKey(); // value is 1.2
+ * let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });
+ * let lowestKey = myDictionary.minKey(); // value is 1.2
* print(lowestKey);
* }
*
@@ -56331,8 +57408,8 @@ p5.NumberDict.prototype.minKey = function() {
*
*
* function setup() {
- * var myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });
- * var highestKey = myDictionary.maxKey(); // value is 4
+ * let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });
+ * let highestKey = myDictionary.maxKey(); // value is 4
* print(highestKey);
* }
*
@@ -56345,7 +57422,7 @@ p5.NumberDict.prototype.maxKey = function() {
module.exports = p5.TypedDict;
-},{"../core/main":25}],39:[function(_dereq_,module,exports){
+},{"../core/main":24}],38:[function(_dereq_,module,exports){
/**
* @module Events
* @submodule Acceleration
@@ -56374,6 +57451,20 @@ p5.prototype.deviceOrientation = undefined;
*
* @property {Number} accelerationX
* @readOnly
+ * @example
+ *
+ *
+ * // Move a touchscreen device to register
+ * // acceleration changes.
+ * function draw() {
+ * background(220, 50);
+ * fill('magenta');
+ * ellipse(width / 2, height / 2, accelerationX);
+ * }
+ *
+ *
+ * @alt
+ * Magnitude of device acceleration is displayed as ellipse size
*/
p5.prototype.accelerationX = 0;
@@ -56383,6 +57474,20 @@ p5.prototype.accelerationX = 0;
*
* @property {Number} accelerationY
* @readOnly
+ * @example
+ *
+ *
+ * // Move a touchscreen device to register
+ * // acceleration changes.
+ * function draw() {
+ * background(220, 50);
+ * fill('magenta');
+ * ellipse(width / 2, height / 2, accelerationY);
+ * }
+ *
+ *
+ * @alt
+ * Magnitude of device acceleration is displayed as ellipse size
*/
p5.prototype.accelerationY = 0;
@@ -56392,6 +57497,22 @@ p5.prototype.accelerationY = 0;
*
* @property {Number} accelerationZ
* @readOnly
+ *
+ * @example
+ *
+ *
+ * // Move a touchscreen device to register
+ * // acceleration changes.
+ * function draw() {
+ * background(220, 50);
+ * fill('magenta');
+ * ellipse(width / 2, height / 2, accelerationZ);
+ * }
+ *
+ *
+ *
+ * @alt
+ * Magnitude of device acceleration is displayed as ellipse size
*/
p5.prototype.accelerationZ = 0;
@@ -56444,6 +57565,8 @@ p5.prototype._updatePAccelerations = function() {
* together, it must be called in the order Z-X-Y or there might be
* unexpected behaviour.
*
+ * @property {Number} rotationX
+ * @readOnly
* @example
*
*
@@ -56460,13 +57583,8 @@ p5.prototype._updatePAccelerations = function() {
* }
*
*
- *
- * @property {Number} rotationX
- * @readOnly
- *
* @alt
* red horizontal line right, green vertical line bottom. black background.
- *
*/
p5.prototype.rotationX = 0;
@@ -56478,6 +57596,8 @@ p5.prototype.rotationX = 0;
* together, it must be called in the order Z-X-Y or there might be
* unexpected behaviour.
*
+ * @property {Number} rotationY
+ * @readOnly
* @example
*
*
@@ -56494,10 +57614,6 @@ p5.prototype.rotationX = 0;
* }
*
*
- *
- * @property {Number} rotationY
- * @readOnly
- *
* @alt
* red horizontal line right, green vertical line bottom. black background.
*/
@@ -56556,14 +57672,14 @@ p5.prototype.rotationZ = 0;
*
* // Some extra logic is needed to account for cases where
* // the angles wrap around.
- * var rotateDirection = 'clockwise';
+ * let rotateDirection = 'clockwise';
*
* // Simple range conversion to make things simpler.
* // This is not absolutely necessary but the logic
* // will be different in that case.
*
- * var rX = rotationX + 180;
- * var pRX = pRotationX + 180;
+ * let rX = rotationX + 180;
+ * let pRX = pRotationX + 180;
*
* if ((rX - pRX > 0 && rX - pRX < 270) || rX - pRX < -270) {
* rotateDirection = 'clockwise';
@@ -56601,14 +57717,14 @@ p5.prototype.pRotationX = 0;
*
* // Some extra logic is needed to account for cases where
* // the angles wrap around.
- * var rotateDirection = 'clockwise';
+ * let rotateDirection = 'clockwise';
*
* // Simple range conversion to make things simpler.
* // This is not absolutely necessary but the logic
* // will be different in that case.
*
- * var rY = rotationY + 180;
- * var pRY = pRotationY + 180;
+ * let rY = rotationY + 180;
+ * let pRY = pRotationY + 180;
*
* if ((rY - pRY > 0 && rY - pRY < 270) || rY - pRY < -270) {
* rotateDirection = 'clockwise';
@@ -56645,7 +57761,7 @@ p5.prototype.pRotationY = 0;
*
* // Some extra logic is needed to account for cases where
* // the angles wrap around.
- * var rotateDirection = 'clockwise';
+ * let rotateDirection = 'clockwise';
*
* if (
* (rotationZ - pRotationZ > 0 && rotationZ - pRotationZ < 270) ||
@@ -56687,8 +57803,38 @@ p5.prototype._updatePRotations = function() {
};
/**
+ * When a device is rotated, the axis that triggers the deviceTurned()
+ * method is stored in the turnAxis variable. The turnAxis variable is only defined within
+ * the scope of deviceTurned().
* @property {String} turnAxis
* @readOnly
+ * @example
+ *
+ *
+ * // Run this example on a mobile device
+ * // Rotate the device by 90 degrees in the
+ * // X-axis to change the value.
+ *
+ * var value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function deviceTurned() {
+ * if (turnAxis === 'X') {
+ * if (value === 0) {
+ * value = 255;
+ * } else if (value === 255) {
+ * value = 0;
+ * }
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect in center of canvas. turns white on mobile when device turns
+ * 50x50 black rect in center of canvas. turns white on mobile when x-axis turns
*/
p5.prototype.turnAxis = undefined;
@@ -56708,8 +57854,8 @@ var shake_threshold = 30;
* // You will need to move the device incrementally further
* // the closer the square's color gets to white in order to change the value.
*
- * var value = 0;
- * var threshold = 0.5;
+ * let value = 0;
+ * let threshold = 0.5;
* function setup() {
* setMoveThreshold(threshold);
* }
@@ -56751,8 +57897,8 @@ p5.prototype.setMoveThreshold = function(val) {
* // You will need to shake the device more firmly
* // the closer the box's fill gets to white in order to change the value.
*
- * var value = 0;
- * var threshold = 30;
+ * let value = 0;
+ * let threshold = 30;
* function setup() {
* setShakeThreshold(threshold);
* }
@@ -56784,8 +57930,9 @@ p5.prototype.setShakeThreshold = function(val) {
/**
* The deviceMoved() function is called when the device is moved by more than
- * the threshold value along X, Y or Z axis. The default threshold is set to
- * 0.5.
+ * the threshold value along X, Y or Z axis. The default threshold is set to 0.5.
+ * The threshold value can be changed using setMoveThreshold().
+ *
* @method deviceMoved
* @example
*
@@ -56794,7 +57941,7 @@ p5.prototype.setShakeThreshold = function(val) {
* // Move the device around
* // to change the value.
*
- * var value = 0;
+ * let value = 0;
* function draw() {
* fill(value);
* rect(25, 25, 50, 50);
@@ -56829,7 +57976,7 @@ p5.prototype.setShakeThreshold = function(val) {
* // Rotate the device by 90 degrees
* // to change the value.
*
- * var value = 0;
+ * let value = 0;
* function draw() {
* fill(value);
* rect(25, 25, 50, 50);
@@ -56849,7 +57996,7 @@ p5.prototype.setShakeThreshold = function(val) {
* // Rotate the device by 90 degrees in the
* // X-axis to change the value.
*
- * var value = 0;
+ * let value = 0;
* function draw() {
* fill(value);
* rect(25, 25, 50, 50);
@@ -56876,6 +58023,8 @@ p5.prototype.setShakeThreshold = function(val) {
* The deviceShaken() function is called when the device total acceleration
* changes of accelerationX and accelerationY values is more than
* the threshold value. The default threshold is set to 30.
+ * The threshold value can be changed using setShakeThreshold().
+ *
* @method deviceShaken
* @example
*
@@ -56883,7 +58032,7 @@ p5.prototype.setShakeThreshold = function(val) {
* // Run this example on a mobile device
* // Shake the device to change the value.
*
- * var value = 0;
+ * let value = 0;
* function draw() {
* fill(value);
* rect(25, 25, 50, 50);
@@ -57024,7 +58173,7 @@ p5.prototype._handleMotion = function() {
module.exports = p5;
-},{"../core/main":25}],40:[function(_dereq_,module,exports){
+},{"../core/main":24}],39:[function(_dereq_,module,exports){
/**
* @module Events
* @submodule Keyboard
@@ -57036,12 +58185,6 @@ module.exports = p5;
var p5 = _dereq_('../core/main');
-/**
- * Holds the key codes of currently pressed keys.
- * @private
- */
-var downKeys = {};
-
/**
* The boolean system variable keyIsPressed is true if any key is pressed
* and false if no keys are pressed.
@@ -57109,7 +58252,7 @@ p5.prototype.key = '';
* @readOnly
* @example
*
- * var fillVal = 126;
+ * let fillVal = 126;
* function draw() {
* fill(fillVal);
* rect(25, 25, 50, 50);
@@ -57124,10 +58267,18 @@ p5.prototype.key = '';
* return false; // prevent default
* }
*
- *
+ *
+ * function draw() {}
+ * function keyPressed() {
+ * background('yellow');
+ * text(`${key} ${keyCode}`, 10, 40);
+ * print(key, ' ', keyCode);
+ * return false; // prevent default
+ * }
+ *
* @alt
* Grey rect center. turns white when up arrow pressed and black when down
- *
+ * Display key pressed and its keyCode in a yellow box
*/
p5.prototype.keyCode = 0;
@@ -57139,7 +58290,7 @@ p5.prototype.keyCode = 0;
* equals BACKSPACE, DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL,
* OPTION, ALT, UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.
*
- * For ASCII keys that was pressed is stored in the key variable. However, it
+ * For ASCII keys, the key that was pressed is stored in the key variable. However, it
* does not distinguish between uppercase and lowercase. For this reason, it
* is recommended to use keyTyped() to read the key variable, in which the
* case of the variable will be distinguished.
@@ -57156,7 +58307,7 @@ p5.prototype.keyCode = 0;
* @example
*
*
- * var value = 0;
+ * let value = 0;
* function draw() {
* fill(value);
* rect(25, 25, 50, 50);
@@ -57172,7 +58323,7 @@ p5.prototype.keyCode = 0;
*
*
*
- * var value = 0;
+ * let value = 0;
* function draw() {
* fill(value);
* rect(25, 25, 50, 50);
@@ -57201,14 +58352,14 @@ p5.prototype.keyCode = 0;
*
*/
p5.prototype._onkeydown = function(e) {
- if (downKeys[e.which]) {
+ if (this._downKeys[e.which]) {
// prevent multiple firings
return;
}
this._setProperty('isKeyPressed', true);
this._setProperty('keyIsPressed', true);
this._setProperty('keyCode', e.which);
- downKeys[e.which] = true;
+ this._downKeys[e.which] = true;
this._setProperty('key', e.key || String.fromCharCode(e.which) || e.which);
var keyPressed = this.keyPressed || window.keyPressed;
if (typeof keyPressed === 'function' && !e.charCode) {
@@ -57229,7 +58380,7 @@ p5.prototype._onkeydown = function(e) {
* @example
*
*
- * var value = 0;
+ * let value = 0;
* function draw() {
* fill(value);
* rect(25, 25, 50, 50);
@@ -57251,9 +58402,9 @@ p5.prototype._onkeydown = function(e) {
*/
p5.prototype._onkeyup = function(e) {
var keyReleased = this.keyReleased || window.keyReleased;
- downKeys[e.which] = false;
+ this._downKeys[e.which] = false;
- if (!areDownKeys()) {
+ if (!this._areDownKeys()) {
this._setProperty('isKeyPressed', false);
this._setProperty('keyIsPressed', false);
}
@@ -57287,7 +58438,7 @@ p5.prototype._onkeyup = function(e) {
* @example
*
*
- * var value = 0;
+ * let value = 0;
* function draw() {
* fill(value);
* rect(25, 25, 50, 50);
@@ -57331,7 +58482,7 @@ p5.prototype._onkeypress = function(e) {
* been released.
*/
p5.prototype._onblur = function(e) {
- downKeys = {};
+ this._downKeys = {};
};
/**
@@ -57347,11 +58498,12 @@ p5.prototype._onblur = function(e) {
* @return {Boolean} whether key is down or not
* @example
*
- * var x = 100;
- * var y = 100;
+ * let x = 100;
+ * let y = 100;
*
* function setup() {
* createCanvas(512, 512);
+ * fill(255, 0, 0);
* }
*
* function draw() {
@@ -57372,13 +58524,12 @@ p5.prototype._onblur = function(e) {
* }
*
* clear();
- * fill(255, 0, 0);
* ellipse(x, y, 50, 50);
* }
*
*
*
- * var diameter = 50;
+ * let diameter = 50;
*
* function setup() {
* createCanvas(512, 512);
@@ -57408,30 +58559,30 @@ p5.prototype._onblur = function(e) {
*/
p5.prototype.keyIsDown = function(code) {
p5._validateParameters('keyIsDown', arguments);
- return downKeys[code];
+ return this._downKeys[code];
};
/**
- * The checkDownKeys function returns a boolean true if any keys pressed
+ * The _areDownKeys function returns a boolean true if any keys pressed
* and a false if no keys are currently pressed.
- * Helps avoid instances where a multiple keys are pressed simultaneously and
+ * Helps avoid instances where multiple keys are pressed simultaneously and
* releasing a single key will then switch the
* keyIsPressed property to true.
* @private
**/
-function areDownKeys() {
- for (var key in downKeys) {
- if (downKeys.hasOwnProperty(key) && downKeys[key] === true) {
+p5.prototype._areDownKeys = function() {
+ for (var key in this._downKeys) {
+ if (this._downKeys.hasOwnProperty(key) && this._downKeys[key] === true) {
return true;
}
}
return false;
-}
+};
module.exports = p5;
-},{"../core/main":25}],41:[function(_dereq_,module,exports){
+},{"../core/main":24}],40:[function(_dereq_,module,exports){
/**
* @module Events
* @submodule Mouse
@@ -57563,7 +58714,7 @@ p5.prototype.pmouseX = 0;
*
*
* @alt
- * 60x60 black rect center, fuschia background. rect flickers on mouse movement
+ * 60x60 black rect center, fuchsia background. rect flickers on mouse movement
*
*/
p5.prototype.pmouseY = 0;
@@ -57578,11 +58729,13 @@ p5.prototype.pmouseY = 0;
* @example
*
*
- * var myCanvas;
+ * let myCanvas;
*
* function setup() {
* //use a variable to store a pointer to the canvas
* myCanvas = createCanvas(100, 100);
+ * const body = document.getElementsByTagName('body')[0];
+ * myCanvas.parent(body);
* }
*
* function draw() {
@@ -57590,7 +58743,7 @@ p5.prototype.pmouseY = 0;
* fill(0);
*
* //move the canvas to the horizontal mouse position
- * //rela tive to the window
+ * //relative to the window
* myCanvas.position(winMouseX + 1, windowHeight / 2);
*
* //the y of the square is relative to the canvas
@@ -57600,7 +58753,7 @@ p5.prototype.pmouseY = 0;
*
*
* @alt
- * 60x60 black rect y moves with mouse y and fuschia canvas moves with mouse x
+ * 60x60 black rect y moves with mouse y and fuchsia canvas moves with mouse x
*
*/
p5.prototype.winMouseX = 0;
@@ -57615,11 +58768,13 @@ p5.prototype.winMouseX = 0;
* @example
*
*
- * var myCanvas;
+ * let myCanvas;
*
* function setup() {
* //use a variable to store a pointer to the canvas
* myCanvas = createCanvas(100, 100);
+ * const body = document.getElementsByTagName('body')[0];
+ * myCanvas.parent(body);
* }
*
* function draw() {
@@ -57627,7 +58782,7 @@ p5.prototype.winMouseX = 0;
* fill(0);
*
* //move the canvas to the vertical mouse position
- * //rel ative to the window
+ * //relative to the window
* myCanvas.position(windowWidth / 2, winMouseY + 1);
*
* //the x of the square is relative to the canvas
@@ -57637,7 +58792,7 @@ p5.prototype.winMouseX = 0;
*
*
* @alt
- * 60x60 black rect x moves with mouse x and fuschia canvas y moves with mouse y
+ * 60x60 black rect x moves with mouse x and fuchsia canvas y moves with mouse y
*
*/
p5.prototype.winMouseY = 0;
@@ -57654,7 +58809,7 @@ p5.prototype.winMouseY = 0;
* @example
*
*
- * var myCanvas;
+ * let myCanvas;
*
* function setup() {
* //use a variable to store a pointer to the canvas
@@ -57667,7 +58822,7 @@ p5.prototype.winMouseY = 0;
* clear();
* //the difference between previous and
* //current x position is the horizontal mouse speed
- * var speed = abs(winMouseX - pwinMouseX);
+ * let speed = abs(winMouseX - pwinMouseX);
* //change the size of the circle
* //according to the horizontal speed
* ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);
@@ -57678,7 +58833,7 @@ p5.prototype.winMouseY = 0;
*
*
* @alt
- * fuschia ellipse moves with mouse x and y. Grows and shrinks with mouse speed
+ * fuchsia ellipse moves with mouse x and y. Grows and shrinks with mouse speed
*
*/
p5.prototype.pwinMouseX = 0;
@@ -57696,7 +58851,7 @@ p5.prototype.pwinMouseX = 0;
* @example
*
*
- * var myCanvas;
+ * let myCanvas;
*
* function setup() {
* //use a variable to store a pointer to the canvas
@@ -57709,7 +58864,7 @@ p5.prototype.pwinMouseX = 0;
* clear();
* //the difference between previous and
* //current y position is the vertical mouse speed
- * var speed = abs(winMouseY - pwinMouseY);
+ * let speed = abs(winMouseY - pwinMouseY);
* //change the size of the circle
* //according to the vertical speed
* ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);
@@ -57720,7 +58875,7 @@ p5.prototype.pwinMouseX = 0;
*
*
* @alt
- * fuschia ellipse moves with mouse x and y. Grows and shrinks with mouse speed
+ * fuchsia ellipse moves with mouse x and y. Grows and shrinks with mouse speed
*
*/
p5.prototype.pwinMouseY = 0;
@@ -57759,7 +58914,7 @@ p5.prototype.pwinMouseY = 0;
*
*
* @alt
- * 50x50 black ellipse appears on center of fuschia canvas on mouse click/press.
+ * 50x50 black ellipse appears on center of fuchsia canvas on mouse click/press.
*
*/
p5.prototype.mouseButton = 0;
@@ -57790,7 +58945,7 @@ p5.prototype.mouseButton = 0;
*
*
* @alt
- * black 50x50 rect becomes ellipse with mouse click/press. fuschia background.
+ * black 50x50 rect becomes ellipse with mouse click/press. fuchsia background.
*
*/
p5.prototype.mouseIsPressed = false;
@@ -57863,13 +59018,14 @@ p5.prototype._setMouseButton = function(e) {
* behavior for this event, add "return false" to the end of the method.
*
* @method mouseMoved
+ * @param {Object} [event] optional MouseEvent callback argument.
* @example
*
*
* // Move the mouse across the page
* // to change its value
*
- * var value = 0;
+ * let value = 0;
* function draw() {
* fill(value);
* rect(25, 25, 50, 50);
@@ -57893,6 +59049,16 @@ p5.prototype._setMouseButton = function(e) {
*
*
*
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function mouseMoved(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
* @alt
* black 50x50 rect becomes lighter with mouse movements until white then resets
* no image displayed
@@ -57908,13 +59074,14 @@ p5.prototype._setMouseButton = function(e) {
* behavior for this event, add "return false" to the end of the method.
*
* @method mouseDragged
+ * @param {Object} [event] optional MouseEvent callback argument.
* @example
*
*
* // Drag the mouse across the page
* // to change its value
*
- * var value = 0;
+ * let value = 0;
* function draw() {
* fill(value);
* rect(25, 25, 50, 50);
@@ -57938,6 +59105,16 @@ p5.prototype._setMouseButton = function(e) {
*
*
*
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function mouseDragged(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
* @alt
* black 50x50 rect turns lighter with mouse click and drag until white, resets
* no image displayed
@@ -57980,13 +59157,14 @@ p5.prototype._onmousemove = function(e) {
* behavior for this event, add "return false" to the end of the method.
*
* @method mousePressed
+ * @param {Object} [event] optional MouseEvent callback argument.
* @example
*
*
* // Click within the image to change
* // the value of the rectangle
*
- * var value = 0;
+ * let value = 0;
* function draw() {
* fill(value);
* rect(25, 25, 50, 50);
@@ -58011,6 +59189,16 @@ p5.prototype._onmousemove = function(e) {
*
*
*
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function mousePressed(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
* @alt
* black 50x50 rect turns white with mouse click/press.
* no image displayed
@@ -58045,6 +59233,7 @@ p5.prototype._onmousedown = function(e) {
*
*
* @method mouseReleased
+ * @param {Object} [event] optional MouseEvent callback argument.
* @example
*
*
@@ -58052,7 +59241,7 @@ p5.prototype._onmousedown = function(e) {
* // the value of the rectangle
* // after the mouse has been clicked
*
- * var value = 0;
+ * let value = 0;
* function draw() {
* fill(value);
* rect(25, 25, 50, 50);
@@ -58077,6 +59266,16 @@ p5.prototype._onmousedown = function(e) {
*
*
*
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function mouseReleased(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
* @alt
* black 50x50 rect turns white with mouse click/press.
* no image displayed
@@ -58113,6 +59312,7 @@ p5.prototype._ondragover = p5.prototype._onmousemove;
* behavior for this event, add "return false" to the end of the method.
*
* @method mouseClicked
+ * @param {Object} [event] optional MouseEvent callback argument.
* @example
*
*
@@ -58120,7 +59320,7 @@ p5.prototype._ondragover = p5.prototype._onmousemove;
* // the value of the rectangle
* // after the mouse has been clicked
*
- * var value = 0;
+ * let value = 0;
* function draw() {
* fill(value);
* rect(25, 25, 50, 50);
@@ -58146,6 +59346,16 @@ p5.prototype._ondragover = p5.prototype._onmousemove;
*
*
*
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function mouseClicked(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
* @alt
* black 50x50 rect turns white with mouse click/press.
* no image displayed
@@ -58171,6 +59381,7 @@ p5.prototype._onclick = function(e) {
* https://developer.mozilla.org/en-US/docs/Web/Events/dblclick
*
* @method doubleClicked
+ * @param {Object} [event] optional MouseEvent callback argument.
* @example
*
*
@@ -58178,7 +59389,7 @@ p5.prototype._onclick = function(e) {
* // the value of the rectangle
* // after the mouse has been double clicked
*
- * var value = 0;
+ * let value = 0;
* function draw() {
* fill(value);
* rect(25, 25, 50, 50);
@@ -58204,6 +59415,16 @@ p5.prototype._onclick = function(e) {
*
*
*
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function doubleClicked(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
* @alt
* black 50x50 rect turns white with mouse doubleClick/press.
* no image displayed
@@ -58250,11 +59471,12 @@ p5.prototype._pmouseWheelDeltaY = 0;
* may only work as expected if "return false" is included while using Safari.
*
* @method mouseWheel
+ * @param {Object} [event] optional WheelEvent callback argument.
*
* @example
*
*
- * var pos = 25;
+ * let pos = 25;
*
* function draw() {
* background(237, 34, 93);
@@ -58273,7 +59495,7 @@ p5.prototype._pmouseWheelDeltaY = 0;
*
*
* @alt
- * black 50x50 rect moves up and down with vertical scroll. fuschia background
+ * black 50x50 rect moves up and down with vertical scroll. fuchsia background
*
*/
p5.prototype._onwheel = function(e) {
@@ -58290,7 +59512,7 @@ p5.prototype._onwheel = function(e) {
module.exports = p5;
-},{"../core/constants":19,"../core/main":25}],42:[function(_dereq_,module,exports){
+},{"../core/constants":18,"../core/main":24}],41:[function(_dereq_,module,exports){
/**
* @module Events
* @submodule Touch
@@ -58322,7 +59544,7 @@ var p5 = _dereq_('../core/main');
* // at the same time
* function draw() {
* clear();
- * var display = touches.length + ' touches';
+ * let display = touches.length + ' touches';
* text(display, 5, 10);
* }
*
@@ -58373,13 +59595,14 @@ function getTouchInfo(canvas, w, h, e, i) {
* to the end of the method.
*
* @method touchStarted
+ * @param {Object} [event] optional TouchEvent callback argument.
* @example
*
*
* // Touch within the image to change
* // the value of the rectangle
*
- * var value = 0;
+ * let value = 0;
* function draw() {
* fill(value);
* rect(25, 25, 50, 50);
@@ -58404,6 +59627,16 @@ function getTouchInfo(canvas, w, h, e, i) {
*
*
*
+ *
+ *
+ * // returns a TouchEvent object
+ * // as a callback argument
+ * function touchStarted(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
* @alt
* 50x50 black rect turns white with touch event.
* no image displayed
@@ -58437,13 +59670,14 @@ p5.prototype._ontouchstart = function(e) {
* to the end of the method.
*
* @method touchMoved
+ * @param {Object} [event] optional TouchEvent callback argument.
* @example
*
*
* // Move your finger across the page
* // to change its value
*
- * var value = 0;
+ * let value = 0;
* function draw() {
* fill(value);
* rect(25, 25, 50, 50);
@@ -58467,6 +59701,16 @@ p5.prototype._ontouchstart = function(e) {
*
*
*
+ *
+ *
+ * // returns a TouchEvent object
+ * // as a callback argument
+ * function touchMoved(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
* @alt
* 50x50 black rect turns lighter with touch until white. resets
* no image displayed
@@ -58499,13 +59743,14 @@ p5.prototype._ontouchmove = function(e) {
* to the end of the method.
*
* @method touchEnded
+ * @param {Object} [event] optional TouchEvent callback argument.
* @example
*
*
* // Release touch within the image to
* // change the value of the rectangle
*
- * var value = 0;
+ * let value = 0;
* function draw() {
* fill(value);
* rect(25, 25, 50, 50);
@@ -58530,6 +59775,16 @@ p5.prototype._ontouchmove = function(e) {
*
*
*
+ *
+ *
+ * // returns a TouchEvent object
+ * // as a callback argument
+ * function touchEnded(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
* @alt
* 50x50 black rect turns white with touch.
* no image displayed
@@ -58556,7 +59811,7 @@ p5.prototype._ontouchend = function(e) {
module.exports = p5;
-},{"../core/main":25}],43:[function(_dereq_,module,exports){
+},{"../core/main":24}],42:[function(_dereq_,module,exports){
/*global ImageData:false */
/**
@@ -58698,16 +59953,32 @@ Filters._createImageData = function(width, height) {
* @param {Object} filterParam [description]
*/
Filters.apply = function(canvas, func, filterParam) {
- var ctx = canvas.getContext('2d');
- var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ var pixelsState = canvas.getContext('2d');
+ var imageData = pixelsState.getImageData(0, 0, canvas.width, canvas.height);
//Filters can either return a new ImageData object, or just modify
//the one they received.
var newImageData = func(imageData, filterParam);
if (newImageData instanceof ImageData) {
- ctx.putImageData(newImageData, 0, 0, 0, 0, canvas.width, canvas.height);
+ pixelsState.putImageData(
+ newImageData,
+ 0,
+ 0,
+ 0,
+ 0,
+ canvas.width,
+ canvas.height
+ );
} else {
- ctx.putImageData(imageData, 0, 0, 0, 0, canvas.width, canvas.height);
+ pixelsState.putImageData(
+ imageData,
+ 0,
+ 0,
+ 0,
+ 0,
+ canvas.width,
+ canvas.height
+ );
}
};
@@ -59166,7 +60437,7 @@ Filters.blur = function(canvas, radius) {
module.exports = Filters;
-},{}],44:[function(_dereq_,module,exports){
+},{}],43:[function(_dereq_,module,exports){
/**
* @module Image
* @submodule Image
@@ -59212,10 +60483,10 @@ var p5 = _dereq_('../core/main');
* @example
*
*
- * var img = createImage(66, 66);
+ * let img = createImage(66, 66);
* img.loadPixels();
- * for (var i = 0; i < img.width; i++) {
- * for (var j = 0; j < img.height; j++) {
+ * for (let i = 0; i < img.width; i++) {
+ * for (let j = 0; j < img.height; j++) {
* img.set(i, j, color(0, 90, 102));
* }
* }
@@ -59226,10 +60497,10 @@ var p5 = _dereq_('../core/main');
*
*
*
- * var img = createImage(66, 66);
+ * let img = createImage(66, 66);
* img.loadPixels();
- * for (var i = 0; i < img.width; i++) {
- * for (var j = 0; j < img.height; j++) {
+ * for (let i = 0; i < img.width; i++) {
+ * for (let j = 0; j < img.height; j++) {
* img.set(i, j, color(0, 90, 102, (i % img.width) * 2));
* }
* }
@@ -59241,12 +60512,12 @@ var p5 = _dereq_('../core/main');
*
*
*
- * var pink = color(255, 102, 204);
- * var img = createImage(66, 66);
+ * let pink = color(255, 102, 204);
+ * let img = createImage(66, 66);
* img.loadPixels();
- * var d = pixelDensity();
- * var halfImage = 4 * (img.width * d) * (img.height / 2 * d);
- * for (var i = 0; i < halfImage; i += 4) {
+ * let d = pixelDensity();
+ * let halfImage = 4 * (img.width * d) * (img.height / 2 * d);
+ * for (let i = 0; i < halfImage; i += 4) {
* img.pixels[i] = red(pink);
* img.pixels[i + 1] = green(pink);
* img.pixels[i + 2] = blue(pink);
@@ -59281,7 +60552,7 @@ p5.prototype.createImage = function(width, height) {
* @example
*
* function setup() {
- * var c = createCanvas(100, 100);
+ * let c = createCanvas(100, 100);
* background(255, 0, 0);
* saveCanvas(c, 'myCanvas', 'jpg');
* }
@@ -59290,7 +60561,7 @@ p5.prototype.createImage = function(width, height) {
* // note that this example has the same result as above
* // if no canvas is specified, defaults to main canvas
* function setup() {
- * var c = createCanvas(100, 100);
+ * let c = createCanvas(100, 100);
* background(255, 0, 0);
* saveCanvas('myCanvas', 'jpg');
*
@@ -59394,7 +60665,7 @@ p5.prototype.saveCanvas = function() {
* }
*
* function mousePressed() {
- * saveFrames('out', 'png', 1, 25, function(data) {
+ * saveFrames('out', 'png', 1, 25, data => {
* print(data);
* });
* }
@@ -59474,7 +60745,7 @@ p5.prototype._makeFrame = function(filename, extension, _cnv) {
module.exports = p5;
-},{"../core/main":25}],45:[function(_dereq_,module,exports){
+},{"../core/main":24}],44:[function(_dereq_,module,exports){
/**
* @module Image
* @submodule Loading & Displaying
@@ -59515,7 +60786,7 @@ _dereq_('../core/error_helpers');
* @example
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/laDefense.jpg');
* }
@@ -59528,7 +60799,7 @@ _dereq_('../core/error_helpers');
*
* function setup() {
* // here we use a callback to display the image after loading
- * loadImage('assets/laDefense.jpg', function(img) {
+ * loadImage('assets/laDefense.jpg', img => {
* image(img, 0, 0);
* });
* }
@@ -59564,6 +60835,8 @@ p5.prototype.loadImage = function(path, successCallback, failureCallback) {
p5._friendlyFileLoadError(0, img.src);
if (typeof failureCallback === 'function') {
failureCallback(e);
+ } else {
+ console.error(e);
}
};
@@ -59625,7 +60898,7 @@ function _sAssign(sVal, iVal) {
* @example
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/laDefense.jpg');
* }
@@ -59638,7 +60911,7 @@ function _sAssign(sVal, iVal) {
*
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/laDefense.jpg');
* }
@@ -59654,7 +60927,7 @@ function _sAssign(sVal, iVal) {
*
* function setup() {
* // Here, we use a callback to display the image after loading
- * loadImage('assets/laDefense.jpg', function(img) {
+ * loadImage('assets/laDefense.jpg', img => {
* image(img, 0, 0);
* });
* }
@@ -59662,7 +60935,7 @@ function _sAssign(sVal, iVal) {
*
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/gradient.png');
* }
@@ -59796,7 +61069,7 @@ p5.prototype.image = function(
* @example
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/laDefense.jpg');
* }
@@ -59810,7 +61083,7 @@ p5.prototype.image = function(
*
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/laDefense.jpg');
* }
@@ -59824,7 +61097,7 @@ p5.prototype.image = function(
*
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/laDefense.jpg');
* }
@@ -59878,7 +61151,7 @@ p5.prototype.tint = function() {
* @example
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
@@ -59958,7 +61231,7 @@ p5.prototype._getTintedImageCanvas = function(img) {
*
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
@@ -59971,7 +61244,7 @@ p5.prototype._getTintedImageCanvas = function(img) {
*
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
@@ -59984,7 +61257,7 @@ p5.prototype._getTintedImageCanvas = function(img) {
*
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
@@ -60014,7 +61287,7 @@ p5.prototype.imageMode = function(m) {
module.exports = p5;
-},{"../core/constants":19,"../core/error_helpers":21,"../core/helpers":22,"../core/main":25,"./filters":43}],46:[function(_dereq_,module,exports){
+},{"../core/constants":18,"../core/error_helpers":20,"../core/helpers":21,"../core/main":24,"./filters":42}],45:[function(_dereq_,module,exports){
/**
* @module Image
* @submodule Image
@@ -60055,28 +61328,28 @@ var Filters = _dereq_('./filters');
* @example
*
* function setup() {
- * var img = createImage(100, 100); // same as new p5.Image(100, 100);
+ * let img = createImage(100, 100); // same as new p5.Image(100, 100);
* img.loadPixels();
* createCanvas(100, 100);
* background(0);
*
* // helper for writing color to array
* function writeColor(image, x, y, red, green, blue, alpha) {
- * var index = (x + y * width) * 4;
+ * let index = (x + y * width) * 4;
* image.pixels[index] = red;
* image.pixels[index + 1] = green;
* image.pixels[index + 2] = blue;
* image.pixels[index + 3] = alpha;
* }
*
- * var x, y;
+ * let x, y;
* // fill with random colors
* for (y = 0; y < img.height; y++) {
* for (x = 0; x < img.width; x++) {
- * var red = random(255);
- * var green = random(255);
- * var blue = random(255);
- * var alpha = 255;
+ * let red = random(255);
+ * let green = random(255);
+ * let blue = random(255);
+ * let alpha = 255;
* writeColor(img, x, y, red, green, blue, alpha);
* }
* }
@@ -60110,7 +61383,7 @@ p5.Image = function(width, height) {
* @readOnly
* @example
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/rockies.jpg');
* }
@@ -60118,8 +61391,8 @@ p5.Image = function(width, height) {
* function setup() {
* createCanvas(100, 100);
* image(img, 0, 0);
- * for (var i = 0; i < img.width; i++) {
- * var c = img.get(i, img.height / 2);
+ * for (let i = 0; i < img.width; i++) {
+ * let c = img.get(i, img.height / 2);
* stroke(c);
* line(i, height / 2, i, height);
* }
@@ -60137,7 +61410,7 @@ p5.Image = function(width, height) {
* @readOnly
* @example
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/rockies.jpg');
* }
@@ -60145,8 +61418,8 @@ p5.Image = function(width, height) {
* function setup() {
* createCanvas(100, 100);
* image(img, 0, 0);
- * for (var i = 0; i < img.height; i++) {
- * var c = img.get(img.width / 2, i);
+ * for (let i = 0; i < img.height; i++) {
+ * let c = img.get(img.width / 2, i);
* stroke(c);
* line(0, i, width / 2, i);
* }
@@ -60162,6 +61435,7 @@ p5.Image = function(width, height) {
this.canvas.width = this.width;
this.canvas.height = this.height;
this.drawingContext = this.canvas.getContext('2d');
+ this._pixelsState = this;
this._pixelDensity = 1;
//used for webgl texturing only
this._modified = false;
@@ -60181,15 +61455,15 @@ p5.Image = function(width, height) {
* values of the pixel at (1, 0). More generally, to set values for a pixel
* at (x, y):
* ```javascript
- * var d = pixelDensity();
- * for (var i = 0; i < d; i++) {
- * for (var j = 0; j < d; j++) {
+ * let d = pixelDensity();
+ * for (let i = 0; i < d; i++) {
+ * for (let j = 0; j < d; j++) {
* // loop over
- * idx = 4 * ((y * d + j) * width * d + (x * d + i));
- * pixels[idx] = r;
- * pixels[idx+1] = g;
- * pixels[idx+2] = b;
- * pixels[idx+3] = a;
+ * index = 4 * ((y * d + j) * width * d + (x * d + i));
+ * pixels[index] = r;
+ * pixels[index+1] = g;
+ * pixels[index+2] = b;
+ * pixels[index+3] = a;
* }
* }
* ```
@@ -60201,10 +61475,10 @@ p5.Image = function(width, height) {
* @example
*
*
- * var img = createImage(66, 66);
+ * let img = createImage(66, 66);
* img.loadPixels();
- * for (var i = 0; i < img.width; i++) {
- * for (var j = 0; j < img.height; j++) {
+ * for (let i = 0; i < img.width; i++) {
+ * for (let j = 0; j < img.height; j++) {
* img.set(i, j, color(0, 90, 102));
* }
* }
@@ -60214,10 +61488,10 @@ p5.Image = function(width, height) {
*
*
*
- * var pink = color(255, 102, 204);
- * var img = createImage(66, 66);
+ * let pink = color(255, 102, 204);
+ * let img = createImage(66, 66);
* img.loadPixels();
- * for (var i = 0; i < 4 * (width * height / 2); i += 4) {
+ * for (let i = 0; i < 4 * (width * height / 2); i += 4) {
* img.pixels[i] = red(pink);
* img.pixels[i + 1] = green(pink);
* img.pixels[i + 2] = blue(pink);
@@ -60251,8 +61525,8 @@ p5.Image.prototype._setProperty = function(prop, value) {
* @method loadPixels
* @example
*
- * var myImage;
- * var halfImage;
+ * let myImage;
+ * let halfImage;
*
* function preload() {
* myImage = loadImage('assets/rockies.jpg');
@@ -60260,15 +61534,15 @@ p5.Image.prototype._setProperty = function(prop, value) {
*
* function setup() {
* myImage.loadPixels();
- * halfImage = 4 * width * height / 2;
- * for (var i = 0; i < halfImage; i++) {
+ * halfImage = 4 * myImage.width * myImage.height / 2;
+ * for (let i = 0; i < halfImage; i++) {
* myImage.pixels[i + halfImage] = myImage.pixels[i];
* }
* myImage.updatePixels();
* }
*
* function draw() {
- * image(myImage, 0, 0);
+ * image(myImage, 0, 0, width, height);
* }
*
*
@@ -60296,8 +61570,8 @@ p5.Image.prototype.loadPixels = function() {
* underlying canvas
* @example
*
- * var myImage;
- * var halfImage;
+ * let myImage;
+ * let halfImage;
*
* function preload() {
* myImage = loadImage('assets/rockies.jpg');
@@ -60305,15 +61579,15 @@ p5.Image.prototype.loadPixels = function() {
*
* function setup() {
* myImage.loadPixels();
- * halfImage = 4 * width * height / 2;
- * for (var i = 0; i < halfImage; i++) {
+ * halfImage = 4 * myImage.width * myImage.height / 2;
+ * for (let i = 0; i < halfImage; i++) {
* myImage.pixels[i + halfImage] = myImage.pixels[i];
* }
* myImage.updatePixels();
* }
*
* function draw() {
- * image(myImage, 0, 0);
+ * image(myImage, 0, 0, width, height);
* }
*
*
@@ -60332,24 +61606,21 @@ p5.Image.prototype.updatePixels = function(x, y, w, h) {
/**
* Get a region of pixels from an image.
*
- * If no params are passed, those whole image is returned,
- * if x and y are the only params passed a single pixel is extracted
- * if all params are passed a rectangle region is extracted and a p5.Image
+ * If no params are passed, the whole image is returned.
+ * If x and y are the only params passed a single pixel is extracted.
+ * If all params are passed a rectangle region is extracted and a p5.Image
* is returned.
*
- * Returns undefined if the region is outside the bounds of the image
- *
* @method get
- * @param {Number} [x] x-coordinate of the pixel
- * @param {Number} [y] y-coordinate of the pixel
- * @param {Number} [w] width
- * @param {Number} [h] height
- * @return {Number[]|Color|p5.Image} color of pixel at x,y in array format
- * [R, G, B, A] or p5.Image
+ * @param {Number} x x-coordinate of the pixel
+ * @param {Number} y y-coordinate of the pixel
+ * @param {Number} w width
+ * @param {Number} h height
+ * @return {p5.Image} the rectangle p5.Image
* @example
*
- * var myImage;
- * var c;
+ * let myImage;
+ * let c;
*
* function preload() {
* myImage = loadImage('assets/rockies.jpg');
@@ -60370,10 +61641,23 @@ p5.Image.prototype.updatePixels = function(x, y, w, h) {
* image of rocky mountains with 50x50 green rect in front
*
*/
+/**
+ * @method get
+ * @return {p5.Image} the whole p5.Image
+ */
+/**
+ * @method get
+ * @param {Number} x
+ * @param {Number} y
+ * @return {Number[]} color of pixel at x,y in array format [R, G, B, A]
+ */
p5.Image.prototype.get = function(x, y, w, h) {
- return p5.Renderer2D.prototype.get.call(this, x, y, w, h);
+ p5._validateParameters('p5.Image.get', arguments);
+ return p5.Renderer2D.prototype.get.apply(this, arguments);
};
+p5.Image.prototype._getPixel = p5.Renderer2D.prototype._getPixel;
+
/**
* Set the color of a single pixel or write an image into
* this p5.Image.
@@ -60390,10 +61674,10 @@ p5.Image.prototype.get = function(x, y, w, h) {
* @example
*
*
- * var img = createImage(66, 66);
+ * let img = createImage(66, 66);
* img.loadPixels();
- * for (var i = 0; i < img.width; i++) {
- * for (var j = 0; j < img.height; j++) {
+ * for (let i = 0; i < img.width; i++) {
+ * for (let j = 0; j < img.height; j++) {
* img.set(i, j, color(0, 90, 102, (i % img.width) * 2));
* }
* }
@@ -60423,7 +61707,7 @@ p5.Image.prototype.set = function(x, y, imgOrCol) {
* @param {Number} height the resized image height
* @example
*
- * var img;
+ * let img;
*
* function preload() {
* img = loadImage('assets/rockies.jpg');
@@ -60516,10 +61800,10 @@ p5.Image.prototype.resize = function(width, height) {
* @param {Integer} dh destination image height
* @example
*
- * var photo;
- * var bricks;
- * var x;
- * var y;
+ * let photo;
+ * let bricks;
+ * let x;
+ * let y;
*
* function preload() {
* photo = loadImage('assets/rockies.jpg');
@@ -60587,7 +61871,7 @@ p5.Image.prototype.copy = function() {
* @param {p5.Image} srcImage source image
* @example
*
- * var photo, maskImage;
+ * let photo, maskImage;
* function preload() {
* photo = loadImage('assets/rockies.jpg');
* maskImage = loadImage('assets/mask2.png');
@@ -60653,8 +61937,8 @@ p5.Image.prototype.mask = function(p5Image) {
* to each filter, see above
* @example
*
- * var photo1;
- * var photo2;
+ * let photo1;
+ * let photo2;
*
* function preload() {
* photo1 = loadImage('assets/rockies.jpg');
@@ -60662,7 +61946,7 @@ p5.Image.prototype.mask = function(p5Image) {
* }
*
* function setup() {
- * photo2.filter('gray');
+ * photo2.filter(GRAY);
* image(photo1, 0, 0);
* image(photo2, width / 2, 0);
* }
@@ -60673,7 +61957,7 @@ p5.Image.prototype.mask = function(p5Image) {
*
*/
p5.Image.prototype.filter = function(operation, value) {
- Filters.apply(this.canvas, Filters[operation.toLowerCase()], value);
+ Filters.apply(this.canvas, Filters[operation], value);
this.setModified(true);
};
@@ -60705,8 +61989,8 @@ p5.Image.prototype.filter = function(operation, value) {
* http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/
* @example
*
- * var mountains;
- * var bricks;
+ * let mountains;
+ * let bricks;
*
* function preload() {
* mountains = loadImage('assets/rockies.jpg');
@@ -60720,8 +62004,8 @@ p5.Image.prototype.filter = function(operation, value) {
* }
*
*
- * var mountains;
- * var bricks;
+ * let mountains;
+ * let bricks;
*
* function preload() {
* mountains = loadImage('assets/rockies.jpg');
@@ -60735,8 +62019,8 @@ p5.Image.prototype.filter = function(operation, value) {
* }
*
*
- * var mountains;
- * var bricks;
+ * let mountains;
+ * let bricks;
*
* function preload() {
* mountains = loadImage('assets/rockies.jpg');
@@ -60809,7 +62093,7 @@ p5.Image.prototype.isModified = function() {
* @param {String} extension 'png' or 'jpg'
* @example
*
- * var photo;
+ * let photo;
*
* function preload() {
* photo = loadImage('assets/rockies.jpg');
@@ -60836,7 +62120,7 @@ p5.Image.prototype.save = function(filename, extension) {
module.exports = p5.Image;
-},{"../core/main":25,"./filters":43}],47:[function(_dereq_,module,exports){
+},{"../core/main":24,"./filters":42}],46:[function(_dereq_,module,exports){
/**
* @module Image
* @submodule Pixels
@@ -60868,15 +62152,15 @@ _dereq_('../color/p5.Color');
* contain the R, G, B, A values of the pixel at (1, 0). More generally, to
* set values for a pixel at (x, y):
* ```javascript
- * var d = pixelDensity();
- * for (var i = 0; i < d; i++) {
- * for (var j = 0; j < d; j++) {
+ * let d = pixelDensity();
+ * for (let i = 0; i < d; i++) {
+ * for (let j = 0; j < d; j++) {
* // loop over
- * idx = 4 * ((y * d + j) * width * d + (x * d + i));
- * pixels[idx] = r;
- * pixels[idx+1] = g;
- * pixels[idx+2] = b;
- * pixels[idx+3] = a;
+ * index = 4 * ((y * d + j) * width * d + (x * d + i));
+ * pixels[index] = r;
+ * pixels[index+1] = g;
+ * pixels[index+2] = b;
+ * pixels[index+3] = a;
* }
* }
* ```
@@ -60899,11 +62183,11 @@ _dereq_('../color/p5.Color');
* @example
*
*
- * var pink = color(255, 102, 204);
+ * let pink = color(255, 102, 204);
* loadPixels();
- * var d = pixelDensity();
- * var halfImage = 4 * (width * d) * (height / 2 * d);
- * for (var i = 0; i < halfImage; i += 4) {
+ * let d = pixelDensity();
+ * let halfImage = 4 * (width * d) * (height / 2 * d);
+ * for (let i = 0; i < halfImage; i += 4) {
* pixels[i] = red(pink);
* pixels[i + 1] = green(pink);
* pixels[i + 2] = blue(pink);
@@ -60940,8 +62224,8 @@ p5.prototype.pixels = [];
*
* @example
*
- * var img0;
- * var img1;
+ * let img0;
+ * let img1;
*
* function preload() {
* img0 = loadImage('assets/rockies.jpg');
@@ -60955,8 +62239,8 @@ p5.prototype.pixels = [];
* }
*
*
- * var img0;
- * var img1;
+ * let img0;
+ * let img1;
*
* function preload() {
* img0 = loadImage('assets/rockies.jpg');
@@ -60970,8 +62254,8 @@ p5.prototype.pixels = [];
* }
*
*
- * var img0;
- * var img1;
+ * let img0;
+ * let img1;
*
* function preload() {
* img0 = loadImage('assets/rockies.jpg');
@@ -61034,7 +62318,7 @@ p5.prototype.blend = function() {
*
* @example
*
- * var img;
+ * let img;
*
* function preload() {
* img = loadImage('assets/rockies.jpg');
@@ -61128,7 +62412,7 @@ p5.prototype.copy = function() {
* @example
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
@@ -61141,7 +62425,7 @@ p5.prototype.copy = function() {
*
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
@@ -61154,7 +62438,7 @@ p5.prototype.copy = function() {
*
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
@@ -61167,7 +62451,7 @@ p5.prototype.copy = function() {
*
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
@@ -61180,7 +62464,7 @@ p5.prototype.copy = function() {
*
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
@@ -61193,7 +62477,7 @@ p5.prototype.copy = function() {
*
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
@@ -61206,7 +62490,7 @@ p5.prototype.copy = function() {
*
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
@@ -61219,7 +62503,7 @@ p5.prototype.copy = function() {
*
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
@@ -61245,13 +62529,15 @@ p5.prototype.copy = function() {
p5.prototype.filter = function(operation, value) {
p5._validateParameters('filter', arguments);
if (this.canvas !== undefined) {
- Filters.apply(this.canvas, Filters[operation.toLowerCase()], value);
+ Filters.apply(this.canvas, Filters[operation], value);
} else {
- Filters.apply(this.elt, Filters[operation.toLowerCase()], value);
+ Filters.apply(this.elt, Filters[operation], value);
}
};
/**
+ * Get a region of pixels, or a single pixel, from the canvas.
+ *
* Returns an array of [R,G,B,A] values for any pixel or grabs a section of
* an image. If no parameters are specified, the entire image is returned.
* Use the x and y parameters to get the value of one pixel. Get a section of
@@ -61259,47 +62545,46 @@ p5.prototype.filter = function(operation, value) {
* getting an image, the x and y parameters define the coordinates for the
* upper-left corner of the image, regardless of the current imageMode().
*
- * If the pixel requested is outside of the image window, [0,0,0,255] is
- * returned. To get the numbers scaled according to the current color ranges
+ * To get the color components scaled according to the current color ranges
* and taking into account colorMode, use getColor instead of get.
*
* Getting the color of a single pixel with get(x, y) is easy, but not as fast
* as grabbing the data directly from pixels[]. The equivalent statement to
* get(x, y) using pixels[] with pixel density d is
- *
- * var x, y, d; // set these to the coordinates
- * var off = (y * width + x) * d * 4;
- * var components = [
+ * ```javascript
+ * let x, y, d; // set these to the coordinates
+ * let off = (y * width + x) * d * 4;
+ * let components = [
* pixels[off],
* pixels[off + 1],
* pixels[off + 2],
* pixels[off + 3]
* ];
* print(components);
- *
+ * ```
*
+ *
* See the reference for pixels[] for more information.
*
* If you want to extract an array of colors or a subimage from an p5.Image object,
* take a look at p5.Image.get()
*
* @method get
- * @param {Number} [x] x-coordinate of the pixel
- * @param {Number} [y] y-coordinate of the pixel
- * @param {Number} [w] width
- * @param {Number} [h] height
- * @return {Number[]|p5.Image} values of pixel at x,y in array format
- * [R, G, B, A] or p5.Image
+ * @param {Number} x x-coordinate of the pixel
+ * @param {Number} y y-coordinate of the pixel
+ * @param {Number} w width
+ * @param {Number} h height
+ * @return {p5.Image} the rectangle p5.Image
* @example
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/rockies.jpg');
* }
* function setup() {
* image(img, 0, 0);
- * var c = get();
+ * let c = get();
* image(c, width / 2, 0);
* }
*
@@ -61307,13 +62592,13 @@ p5.prototype.filter = function(operation, value) {
*
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/rockies.jpg');
* }
* function setup() {
* image(img, 0, 0);
- * var c = get(50, 90);
+ * let c = get(50, 90);
* fill(c);
* noStroke();
* rect(25, 25, 50, 50);
@@ -61326,8 +62611,19 @@ p5.prototype.filter = function(operation, value) {
* Image of the rocky mountains with 50x50 green rect in center of canvas
*
*/
+/**
+ * @method get
+ * @return {p5.Image} the whole p5.Image
+ */
+/**
+ * @method get
+ * @param {Number} x
+ * @param {Number} y
+ * @return {Number[]} color of pixel at x,y in array format [R, G, B, A]
+ */
p5.prototype.get = function(x, y, w, h) {
- return this._renderer.get(x, y, w, h);
+ p5._validateParameters('get', arguments);
+ return this._renderer.get.apply(this._renderer, arguments);
};
/**
@@ -61340,17 +62636,17 @@ p5.prototype.get = function(x, y, w, h) {
* @example
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/rockies.jpg');
* }
*
* function setup() {
- * image(img, 0, 0);
- * var d = pixelDensity();
- * var halfImage = 4 * (img.width * d) * (img.height * d / 2);
+ * image(img, 0, 0, width, height);
+ * let d = pixelDensity();
+ * let halfImage = 4 * (width * d) * (height * d / 2);
* loadPixels();
- * for (var i = 0; i < halfImage; i++) {
+ * for (let i = 0; i < halfImage; i++) {
* pixels[i + halfImage] = pixels[i];
* }
* updatePixels();
@@ -61396,7 +62692,7 @@ p5.prototype.loadPixels = function() {
* @example
*
*
- * var black = color(0);
+ * let black = color(0);
* set(30, 20, black);
* set(85, 20, black);
* set(85, 75, black);
@@ -61407,9 +62703,9 @@ p5.prototype.loadPixels = function() {
*
*
*
- * for (var i = 30; i < width - 15; i++) {
- * for (var j = 20; j < height - 25; j++) {
- * var c = color(204 - j, 153 - i, 0);
+ * for (let i = 30; i < width - 15; i++) {
+ * for (let j = 20; j < height - 25; j++) {
+ * let c = color(204 - j, 153 - i, 0);
* set(i, j, c);
* }
* }
@@ -61419,7 +62715,7 @@ p5.prototype.loadPixels = function() {
*
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/rockies.jpg');
* }
@@ -61459,17 +62755,17 @@ p5.prototype.set = function(x, y, imgOrCol) {
* @example
*
*
- * var img;
+ * let img;
* function preload() {
* img = loadImage('assets/rockies.jpg');
* }
*
* function setup() {
- * image(img, 0, 0);
- * var d = pixelDensity();
- * var halfImage = 4 * (img.width * d) * (img.height * d / 2);
+ * image(img, 0, 0, width, height);
+ * let d = pixelDensity();
+ * let halfImage = 4 * (width * d) * (height * d / 2);
* loadPixels();
- * for (var i = 0; i < halfImage; i++) {
+ * for (let i = 0; i < halfImage; i++) {
* pixels[i + halfImage] = pixels[i];
* }
* updatePixels();
@@ -61491,7 +62787,7 @@ p5.prototype.updatePixels = function(x, y, w, h) {
module.exports = p5;
-},{"../color/p5.Color":17,"../core/main":25,"./filters":43}],48:[function(_dereq_,module,exports){
+},{"../color/p5.Color":16,"../core/main":24,"./filters":42}],47:[function(_dereq_,module,exports){
/**
* @module IO
* @submodule Input
@@ -61541,10 +62837,10 @@ _dereq_('../core/error_helpers');
*
* // Examples use USGS Earthquake API:
* // https://earthquake.usgs.gov/fdsnws/event/1/#methods
- * var earthquakes;
+ * let earthquakes;
* function preload() {
* // Get the most recent earthquake in the database
- * var url =
+ * let url =
'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +
* 'summary/all_day.geojson';
* earthquakes = loadJSON(url);
@@ -61557,8 +62853,8 @@ _dereq_('../core/error_helpers');
* function draw() {
* background(200);
* // Get the magnitude and name of the earthquake out of the loaded JSON
- * var earthquakeMag = earthquakes.features[0].properties.mag;
- * var earthquakeName = earthquakes.features[0].properties.place;
+ * let earthquakeMag = earthquakes.features[0].properties.mag;
+ * let earthquakeName = earthquakes.features[0].properties.place;
* ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);
* textAlign(CENTER);
* text(earthquakeName, 0, height - 30, width, 30);
@@ -61571,7 +62867,7 @@ _dereq_('../core/error_helpers');
*
* function setup() {
* noLoop();
- * var url =
+ * let url =
'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +
* 'summary/all_day.geojson';
* loadJSON(url, drawEarthquake);
@@ -61583,8 +62879,8 @@ _dereq_('../core/error_helpers');
*
* function drawEarthquake(earthquakes) {
* // Get the magnitude and name of the earthquake out of the loaded JSON
- * var earthquakeMag = earthquakes.features[0].properties.mag;
- * var earthquakeName = earthquakes.features[0].properties.place;
+ * let earthquakeMag = earthquakes.features[0].properties.mag;
+ * let earthquakeName = earthquakes.features[0].properties.place;
* ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);
* textAlign(CENTER);
* text(earthquakeName, 0, height - 30, width, 30);
@@ -61700,14 +62996,14 @@ p5.prototype.loadJSON = function() {
* operation before