### Basic p5.js Example with setup() Source: https://github.com/processing/p5.js/blob/main/contributor_docs/contributing_to_the_p5js_reference.md A standard p5.js example that includes a setup() function to create a canvas, set the background, draw a shape, and describe the visual output. ```javascript * @example * function setup() { * createCanvas(100, 100); * * background(200); * * // A CSS named color. * fill('red'); * square(20, 20, 60); * * describe('A red square with a black outline.'); * }; ``` -------------------------------- ### p5.js Setup with RequireJS Source: https://github.com/processing/p5.js/blob/main/test/manual-test-examples/module.html Demonstrates how to set up a p5.js sketch using RequireJS for module loading. This example initializes a p5 instance and draws a red rectangle in the setup function. ```javascript require.config({ paths: { reqwest: '../node_modules/reqwest/reqwest' } }); require(['app'], function( p5 ) { new p5(function( p ) { p.setup = function() { p.fill('red'); p.rect(0,0,10,10); }; }, null, true); }); ``` -------------------------------- ### Processing.js Global Mode Setup Examples Source: https://github.com/processing/p5.js/wiki/Archived-Content Illustrates various ways to structure Processing.js sketches in global mode, including automatic and explicit canvas creation, and the use of setup() and draw() functions. Use these examples to understand basic sketch initialization. ```javascript // API preload(): runs once, first setup(): runs once, second draw(): loops, indefinitely createCanvas(w, h): creates a canvas element at the 0,0 with input size // CASE 1 // Only setup(). // setup() runs once and createCanvas() gets called automatically with defaults. function setup() { background(255, 0, 0); noStroke(); ellipse(0, 0, 50, 50); } ``` ```javascript // CASE 2 // Only setup() and createCanvas(). // setup() runs once and createCanvas() returns a pointer to the canvas created // with the input size, at 0,0. Holding the pointer is optional. function setup() { createCanvas(400, 400); background(255, 0, 0); noStroke(); ellipse(0, 0, 50, 50); } ``` ```javascript // CASE 3 // Only draw(). // createCanvas() is called automatically with defaults. function draw() { ellipse(random(0, 400), random(0, 400), 50, 50); } ``` ```javascript // CASE 4 // setup() and draw() without createCanvas(). // createCanvas() is called automatically with defaults. function setup() { background(255, 0, 0); } function draw() { ellipse(random(0, 400), random(0, 400), 50, 50); } ``` ```javascript // CASE 5 // setup() and draw() with createCanvas(). function setup() { createCanvas(400, 400); background(255, 255, 0); } function draw() { ellipse(random(0, 400), random(0, 400), 50, 50); } ``` ```javascript // CASE 6 // setup() and draw() with createCanvas(), holding pointer var canvas; function setup() { canvas = createCanvas(400, 400); canvas.position(100, 50); // allows you to set position, id, etc background(255, 255, 0); } function draw() { ellipse(random(0, 400), random(0, 400), 50, 50); } ``` ```javascript // CASE 7 // holding pointer, calling methods explicitly on that object function setup() { var cnv = createCanvas(400, 400); cnv.background(255, 0, 0); cnv.noStroke(); cnv.ellipse(0, 0, 50, 50); } ``` -------------------------------- ### Convert Processing Bezier Example to p5.js Source: https://github.com/processing/p5.js/wiki/Transitioning-from-Processing Demonstrates converting Processing's `void setup()` to `function setup()`, `size()` to `createCanvas()`, and `int` to `let`. Useful for basic sketch structure. ```javascript /** * This example can be found in the Processing examples package * that comes with the Processing PDE.v * Processing > Examples > Basics > Form > Bezier * Adapted by Evelyn Eastmond */ function setup() { // **change** void setup() to function setup() createCanvas(640, 360); // **change** size() to createCanvas() stroke(255); // stroke() is the same noFill(); // noFill() is the same } function draw() { // **change** void draw() to function draw() background(0); // background() is the same for (let i = 0; i < 200; i += 20) { // **change** int i to let i bezier(mouseX-(i/2.0), 40+i, 410, 20, 440, 300, 240-(i/16.0), 300+(i/8.0)); // bezier() is the same } } ``` -------------------------------- ### P5.js Basic Geometry and Material Setup Source: https://github.com/processing/p5.js/blob/main/preview/index.html Defines basic geometry using `buildGeometry` and applies materials with lighting. Includes examples of `box` and `sphere` with texture mapping. ```javascript instance = p.buildGeometry(() => p.sphere(5)); circleGeometry = p.buildGeometry(() => p.sphere(RADIUS)); // ... inside draw loop ... p.push(); p.imageLight(env); p.shader(sh); p.ambientLight(10); //p.directionalLight(100, 100, 100, 0, 1, -1); //p.pointLight(155, 155, 155, 0, -200, 500); p.specularMaterial(255); p.shininess(50); p.metalness(100); //p.stroke('white'); p.noStroke(); for (const [i, c] of ['red', 'gray', 'blue'].entries()) { p.push(); p.fill(c); p.translate( p.width/3 * p.sin(t + i * Math.E), 0, p.width/3 * p.sin(t * 1.2 + i * Math.E + 0.3), ) if (i % 2 === 0) { if (i === 0) { p.texture(fbo) } p.box(30); } else { p.sphere(30); } p.pop(); } p.pop(); p.push(); p.shader(sh2); p.noStroke(); p.fill('red'); p.model(instance, 10); p.pop(); ``` -------------------------------- ### Instantiation Case 1: Only setup() Source: https://github.com/processing/p5.js/wiki/Archived-Content Demonstrates using only the setup() function, where createCanvas() is called automatically with default dimensions. ```APIDOC ## Instantiation Case 1: Only setup() ### Description This case shows the minimal setup where only the `setup()` function is defined. `createCanvas()` is invoked automatically with default parameters. ### Code ```javascript function setup() { background(255, 0, 0); noStroke(); ellipse(0, 0, 50, 50); } ``` ``` -------------------------------- ### Convert Processing Bezier Example to p5.js Source: https://github.com/processing/p5.js/wiki/Processing-transition Demonstrates converting Processing's `void setup()` and `void draw()` to `function setup()` and `function draw()`, and `size()` to `createCanvas()`. Also shows changing `int i` to `var i`. ```javascript /** * This example can be found in the Processing examples package * that comes with the Processing PDE.v * Processing > Examples > Basics > Form > Bezier * Adapted by Evelyn Eastmond */ function setup() { // **change** void setup() to function setup() createCanvas(640, 360); // **change** size() to createCanvas() stroke(255); // stroke() is the same noFill(); // noFill() is the same } function draw() { // **change** void draw() to function draw() background(0); // background() is the same for (var i = 0; i < 200; i += 20) { // **change** int i to var i bezier(mouseX-(i/2.0), 40+i, 410, 20, 440, 300, 240-(i/16.0), 300+(i/8.0)); // bezier() is the same } } ``` -------------------------------- ### Instantiation Case 5: setup() and draw() with createCanvas() Source: https://github.com/processing/p5.js/wiki/Archived-Content Demonstrates using setup() and draw() with an explicitly defined canvas size via createCanvas(). ```APIDOC ## Instantiation Case 5: setup() and draw() with createCanvas() ### Description This case uses both `setup()` and `draw()`, with `createCanvas()` explicitly called to define the canvas dimensions. The `draw()` function will loop after `setup()` completes. ### Code ```javascript function setup() { createCanvas(400, 400); background(255, 255, 0); } function draw() { ellipse(random(0, 400), random(0, 400), 50, 50); } ``` ``` -------------------------------- ### Basic p5.js Setup with a Line Source: https://github.com/processing/p5.js/wiki/p5.js-overview This is a minimal p5.js program that draws a single line. The setup() function runs once for initialization. ```javascript function setup() { line(15, 25, 70, 90); } ``` -------------------------------- ### Run Python 2 SimpleHTTPServer Source: https://github.com/processing/p5.js/wiki/Local-server Use this command to start a simple HTTP server from any directory using Python 2. Ensure Python is installed. ```bash python -m SimpleHTTPServer ``` -------------------------------- ### Run Python 3 http.server Source: https://github.com/processing/p5.js/wiki/Local-server Use this command to start a simple HTTP server from any directory using Python 3. Ensure Python 3 is installed. ```bash python -m http.server ``` -------------------------------- ### Basic p5.js Sketch Setup and Drawing Source: https://github.com/processing/p5.js/blob/main/README.md This snippet demonstrates the fundamental setup() and draw() functions in p5.js. Use setup() for initial canvas creation and background setting, and draw() for continuous rendering of elements like circles based on mouse position. ```javascript function setup() { createCanvas(400, 400); background(255); } function draw() { circle(mouseX, mouseY, 80); } ``` -------------------------------- ### Instantiation Case 2: Only setup() and createCanvas() Source: https://github.com/processing/p5.js/wiki/Archived-Content Shows using setup() along with explicitly calling createCanvas() to define canvas dimensions. ```APIDOC ## Instantiation Case 2: Only setup() and createCanvas() ### Description This case utilizes both `setup()` and `createCanvas()`. `createCanvas()` is called explicitly to set the canvas dimensions, and its return value (a pointer to the canvas) can optionally be held. ### Code ```javascript function setup() { createCanvas(400, 400); background(255, 0, 0); noStroke(); ellipse(0, 0, 50, 50); } ``` ``` -------------------------------- ### Multiple p5.js Examples for createCanvas() Source: https://github.com/processing/p5.js/blob/main/contributor_docs/contributing_to_the_p5js_reference.md Demonstrates how to provide multiple distinct examples for a single p5.js function, separated by blank lines and new @example tags. The first example uses the default 2D renderer, while the second uses the WEBGL renderer. ```javascript * @example * function setup() { * createCanvas(100, 50); * * background(200); * * // Draw a diagonal line. * line(0, 0, width, height); * * describe('A diagonal line drawn from top-left to bottom-right on a gray background.'); * } * * @example * // Use WebGL mode. * function setup() { * createCanvas(100, 100, WEBGL); * * background(200); * * // Draw a diagonal line. * line(-width / 2, -height / 2, width / 2, height / 2); * * describe('A diagonal line drawn from top-left to bottom-right on a gray background.'); * } ``` -------------------------------- ### Basic Sketch Setup: Processing vs p5.js Source: https://github.com/processing/p5.js/wiki/Transitioning-from-Processing Illustrates the fundamental `setup()` and `draw()` function structure in both Processing (Java) and p5.js (JavaScript). ```java void setup() { // setup stuff } void draw() { // draw stuff } ``` ```javascript function setup() { // setup stuff } function draw() { // draw stuff } ``` -------------------------------- ### Basic P5.js Setup and Draw Loop Source: https://github.com/processing/p5.js/blob/main/lib/index.html Demonstrates the fundamental setup and draw functions in P5.js for creating a 200x200 WEBGL canvas and drawing a background with a circle. ```javascript body{ margin:0; overflow: hidden; } function setup(){ createCanvas(200, 200, WEBGL); } function draw(){ background(200); circle(100, 100, 50); } ``` -------------------------------- ### Basic p5.js Sketch Setup Source: https://github.com/processing/p5.js/wiki/Processing-transition The equivalent basic structure for a p5.js sketch, using JavaScript syntax for setup() and draw() functions. ```javascript function setup() { // setup stuff } function draw() { // draw stuff } ``` -------------------------------- ### Instantiation Case 4: setup() and draw() without createCanvas() Source: https://github.com/processing/p5.js/wiki/Archived-Content Shows setup() and draw() used together, with createCanvas() being automatically called. ```APIDOC ## Instantiation Case 4: setup() and draw() without createCanvas() ### Description This case combines `setup()` and `draw()`. `createCanvas()` is automatically invoked with default parameters, and `draw()` will execute repeatedly. ### Code ```javascript function setup() { background(255, 0, 0); } function draw() { ellipse(random(0, 400), random(0, 400), 50, 50); } ``` ``` -------------------------------- ### Setup p5.js Instance for Testing Source: https://github.com/processing/p5.js/blob/main/contributor_docs/unit_testing.md Set up a p5.js instance in instance mode within the `setup` function for testing. This makes the p5 instance accessible via the `myp5` variable. ```javascript let myp5; setup(function(done) { new p5(function(p) { p.setup = function() { myp5 = p; done(); }; }); }); ``` -------------------------------- ### Example Local Preview Command Source: https://github.com/processing/p5.js/blob/main/contributor_docs/working_with_contributor_documents.md An example of the local preview command, assuming your p5.js repository is in a sibling folder named 'p5.js' and your branch is 'my-amazing-branch'. ```sh P5_REPO_URL=../p5.js P5_BRANCH=my-amazing-branch npm run build:contributor-docs && npm run dev ``` -------------------------------- ### Basic Processing Sketch Setup Source: https://github.com/processing/p5.js/wiki/Processing-transition The fundamental structure for a Processing sketch, including setup() and draw() functions. ```java void setup() { // setup stuff } void draw() { // draw stuff } ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/processing/p5.js/blob/main/contributor_docs/contributor_guidelines.md Install all necessary dependencies for the p5.js project using npm. ```bash npm ci ``` -------------------------------- ### Documenting Multiple Function Signatures (Example 2) Source: https://github.com/processing/p5.js/blob/main/contributor_docs/contributing_to_the_p5js_reference.md This example shows a subsequent signature for the background() function, demonstrating how to document different parameter sets for the same method. ```javascript /** * @method background * @param {Number} gray specifies a value * between white and black * @param {Number} [a] */ ``` -------------------------------- ### Attaching Setup Function in Instance Mode Source: https://github.com/processing/p5.js/wiki/Global-and-instance-mode In instance mode, the setup function is attached as a property of the sketch object passed into the seed function. ```javascript const s = ( sketch ) => { sketch.setup = () => { }; }; ``` -------------------------------- ### Basic p5.js Sketch Setup Source: https://github.com/processing/p5.js/wiki/Positioning-your-canvas This is a minimal HTML and JavaScript setup for a p5.js sketch. It includes the necessary script tags to load the p5.js library and your sketch file. ```html My Sketch ``` -------------------------------- ### p5.js preload function example Source: https://github.com/processing/p5.js/blob/main/contributor_docs/fes_contribution_guide.md Example of using the `preload()` function in p5.js. FES will flag `preLoad` as a typo. ```javascript function preload() { loadImage('myimage.png'); } ``` -------------------------------- ### Examples of Concise First Sentences for Function Descriptions Source: https://github.com/processing/p5.js/blob/main/contributor_docs/contributing_to_the_p5js_reference.md These examples demonstrate how to write a brief, summarizing first sentence for function descriptions in the p5.js reference. ```javascript Creates a canvas element on the web page. Sets the color used to draw points, lines, and the outlines of shapes. Stops the code in draw() from running repeatedly. Creates a new p5.Element object. Creates a p5.Graphics object. Translates the coordinate system. Draws an image to the canvas. Applies an image filter to the canvas. A function that's called once when any key is pressed. Calculates the distance between two points. Calculates the magnitude, or length, of a vector. Re-maps a number from one range to another. Returns a random number or a random element from an array. Sets or gets the current text size. Sets the position and orientation of the current camera in a 3D sketch. Creates a new 2D unit vector with a random heading. Multiplies a vector by a scalar and returns a new vector. ``` -------------------------------- ### Install http-server globally Source: https://github.com/processing/p5.js/wiki/Local-server Install the http-server package globally using npm. This command requires administrative privileges on some systems. ```bash npm install -g http-server ``` -------------------------------- ### Install browser-sync globally Source: https://github.com/processing/p5.js/wiki/Local-server Install the browser-sync package globally using npm. This tool provides live reloading for web projects. ```bash npm install -g browser-sync ``` -------------------------------- ### Documenting Multiple Function Signatures (Example 1) Source: https://github.com/processing/p5.js/blob/main/contributor_docs/contributing_to_the_p5js_reference.md For functions with multiple parameter options, document each signature separately. This example shows the first signature for the background() function. ```javascript /** * @method background * @param {String} colorstring color string, * possible formats include: integer rgb() * or rgba(), percentage rgb() or rgba(), * 3-digit hex, 6-digit hex * @param {Number} [a] alpha value */ ``` -------------------------------- ### p5.js Text Style Example Source: https://github.com/processing/p5.js/blob/main/test/manual-test-examples/type/index.html Demonstrates how to set the text style using p.textStyle(). This example displays text in normal, italic, and bold styles. ```javascript let textStyleSketch = function (p) { p.setup = function () { p.createCanvas(240, 160); p.fill(0); p.strokeWeight(0); p.textSize(12); p.textStyle(p.NORMAL); p.text('Font Style Normal', 10, 30); p.textStyle(p.ITALIC); p.text('Font Style Italic', 10, 60); p.textStyle(p.BOLD); p.text('Font Style Bold', 10, 90); p.loadImage('img/p5v2.jpg').then(img => p.image(img, p.width - 20, 0)); }; }; ``` -------------------------------- ### Start PHP built-in web server Source: https://github.com/processing/p5.js/wiki/Local-server Start PHP's built-in web server to serve files from the current directory on localhost:8000. This is useful for testing P5.js sketches. ```bash php -S localhost:8000 ``` -------------------------------- ### P5.js Setup with WebGPU and Addons Source: https://github.com/processing/p5.js/blob/main/preview/index.html Initializes P5.js with the WebGPU renderer and loads necessary addons. Ensure the canvas is created with the 'p.WEBGPU' option. ```javascript import p5 from '../src/app.js'; import rendererWebGPU from '../src/webgpu/p5.RendererWebGPU.js'; p5.registerAddon(rendererWebGPU); const sketch = function (p) { // ... sketch code ... p.setup = async function () { await p.createCanvas(400, 400, p.WEBGPU); // ... rest of setup ... }; // ... rest of sketch ... }; ``` -------------------------------- ### p5.js Text Width Example Source: https://github.com/processing/p5.js/blob/main/test/manual-test-examples/type/index.html Illustrates how to get the width of a text string using p.fontWidth(). It draws a rectangle below the text to visually represent its calculated width. ```javascript let textWidthSketch = function (p) { p.setup = function () { p.createCanvas(240, 160); p.fill(0); p.strokeWeight(0); p.textSize(12); let s = "What's the width of this line?"; let tw = p.fontWidth(s), x = 10, y = 30; p.text(s, x, y); p.rect(x, y, tw, 2); p.text('width: ' + tw, x, y + 20); p.loadImage('img/p5v2.jpg').then(img => p.image(img, p.width - 20, 0)); }; }; ``` -------------------------------- ### Load Image using preload() in p5.js Source: https://github.com/processing/p5.js/wiki/p5.js-overview Loads an image in the preload() function, making it available in setup() and draw(). This is the recommended way to load assets before the sketch starts. ```javascript let img; function preload() { img = loadImage('cat.jpg'); } function setup() { createCanvas(400, 240); image(img, 0, 0); } ``` -------------------------------- ### JavaScript Code Style Example Source: https://github.com/processing/p5.js/wiki/Archived-Content Follow this style guide for consistent code formatting across the project. It covers variable declarations, loop structures, and conditional statements. ```javascript var i = 0, length = 100; for ( ; i < length; i++ ) { // statements } if ( true ) { // statements } else { // statements } ``` -------------------------------- ### Example p5.js Sketch for Scope Error Source: https://github.com/processing/p5.js/blob/main/contributor_docs/project_wrapups/akshaypadte_gsoc_2020.md This sketch demonstrates a common beginner mistake related to variable scope. The 'draw' function attempts to access variable 'a' which is defined only within the 'setup' function, leading to a reference error. ```javascript function setup() { let a = 5; } function draw() { let b = a + 5; } ``` -------------------------------- ### p5.js Dynamic Object Example Source: https://github.com/processing/p5.js/wiki/JavaScript-basics This p5.js sketch demonstrates object-oriented programming concepts using dynamic objects. It creates multiple shapes that follow the mouse and change color over time. The setup function initializes the canvas and shapes, while the draw function updates and displays them. ```javascript const numShapes = 30; const baseRadius = 5; let shapes = []; // Declare array to hold shape objects function setup() { // Runs once at beginning of app createCanvas(800, 600); // Use HSB colors in our app, so we can get easy changes of just color (hue). colorMode(HSB, 100); // H,S,B will be in range 0 - 100 // Create each object for (let i = 0; i < numShapes; i++) { let x = random(1, width - 2); // Centre our circle randomly somewhere in the window let y = random(1, height - 2); shapes[i] = new Shape( x, y ); } } function draw() { background(0, 0, 5, 10); // Dark grey with a small alpha value, this achieves a blurring effect. noStroke(); // No outline of shapes // Update some controls for our shapes. let cycle = 200; // Change the shapes appearance over a cycle of n frames let percent = (frameCount % cycle) / cycle; // 0.0 to 0.999 let percent2 = percent; if (percent > 0.5 ) { percent2 = 1 - percent } // 0.0 to 0.5, then back down let radius = baseRadius + 30 * (percent2); // Grow and shrink the radius // Update and display each shape in the array for (let i = 0; i < shapes.length; i++) { shapes[i].setRadius(radius); shapes[i].followMouse(0.008); // rate to follow mouse at shapes[i].setColor(percent); // change hue as well shapes[i].display(); // draw it } } function Shape(xpos, ypos) { // Set initial values for properties, as supplied in the constructor, ie the New() call this.xpos = xpos; this.ypos = ypos; this.hue = 0; // value not important, just good practice to init to something // Some methods to operate on an instance of Shape // Method to set the radius this.setRadius = function(rad) { this.radius = rad; } // Method to move the shape's position towards the cursor position. // Don't move if closer than a certain distance. this.followMouse = function(fraction) { let xdiff = mouseX - this.xpos; let ydiff = mouseY - this.ypos; let dist = Math.sqrt(xdiff * xdiff + ydiff * ydiff); if ( dist > 100 ) { this.xpos += xdiff * fraction; this.ypos += ydiff * fraction; } } // Method to reposition the shapes randomly. This is only because our simple // follow-the-cursor code eventually clumps all the shapes together :=( this.resetPos = function () { this.xpos = random(1, width - 2); this.ypos = random(1, height - 2); } // Method to set color of the shape. Use the HSB system, and vary hue from 0.0 to 1.0 this.setColor = function(hue) { this.hue = 100 * hue; } // Method to draw the shape to the screen. This is it! draw those pixels. this.display = function() { fill(this.hue, 100, 100); ellipse(this.xpos, this.ypos, this.radius, this.radius ); // a solid circle } } // Separate callback function for user keystrokes. // Allow any key to reset the app. function keyTyped() { for (let i = 0; i < numShapes; i++) { shapes[i].resetPos(); } } ``` -------------------------------- ### Prevent Example Execution with norender Source: https://github.com/processing/p5.js/blob/main/contributor_docs/contributing_to_the_p5js_reference.md Use `// META:norender` after the `@example` tag to prevent the example code from running and only display the code itself. ```javascript * @example * // META:norender * arc(50, 50, 80, 80, 0, PI + QUARTER_PI, OPEN); * describe('ellipse created using arc with its top right open'); ``` -------------------------------- ### Example p5.js Reference Comment for circle() Source: https://github.com/processing/p5.js/blob/main/contributor_docs/contributing_to_the_p5js_reference.md This is an example of a reference comment block for the `circle()` function, demonstrating the JSDoc format with method, parameter, and example tags. ```javascript /** * Draws a circle. * * A much longer description normally goes here * * @method circle * @param {Number} x x-coordinate of centre. * @param {Number} y y-coordinate of centre. * @param {Number} diameter Diameter of circle. * * @example * function setup() { * createCanvas(100, 100); * //Draw circle at (50, 0) with diameter 70. * circle(50, 0, 70); * } */ ``` -------------------------------- ### Check Node.js Installation Source: https://github.com/processing/p5.js/blob/main/contributor_docs/contributor_guidelines.md Verify that Node.js is installed on your machine by checking its version. ```bash node -v ``` -------------------------------- ### Call loadCSV in Setup (Initial) Source: https://github.com/processing/p5.js/blob/main/contributor_docs/creating_libraries.md Demonstrates a basic call to the `loadCSV` function within the p5.js `setup` function. Note that this initial call will return a Promise due to the asynchronous nature of `loadCSV`. ```javascript function setup(){ createCanvas(400, 400); let myCSV = loadCSV('data.csv'); print(myCSV); } ``` -------------------------------- ### XML Data Structure Example Source: https://github.com/processing/p5.js/wiki/Loading-external-files:-AJAX,-XML,-JSON An example of an XML document structure, used for data representation. ```xml Belgian Waffles $5.95 Two of our famous Belgian Waffles with plenty of real maple syrup 650 Strawberry Belgian Waffles $7.95 Light Belgian waffles covered with strawberries and whipped cream 900 French Toast $4.50 Thick slices made from our homemade sourdough bread 600 ``` -------------------------------- ### Embedded p5.js Example within Description Source: https://github.com/processing/p5.js/blob/main/contributor_docs/contributing_to_the_p5js_reference.md An example of embedding a runnable p5.js code snippet directly within the documentation's description section using a fenced markdown code block with the 'js example' annotation. ```javascript ```js example function setup(){ fill('orange'); circle(0, 30, 10); } ``` ``` -------------------------------- ### Start browser-sync server Source: https://github.com/processing/p5.js/wiki/Local-server Launch browser-sync to serve files from the current directory and watch for changes. The server will be available at http://localhost:3000. ```bash browser-sync start --server -f -w ``` -------------------------------- ### Run Custom Development Preview Source: https://github.com/processing/p5.js/blob/main/contributor_docs/contributing_to_the_p5js_reference.md Builds the local website reference pages from your p5.js branch and starts a development preview. Use this to test changes in your local p5.js repository. ```shell npm run custom:dev path/to/YOUR/local/repo#yourBranch ``` -------------------------------- ### Optional Parameter Example: rect() Source: https://github.com/processing/p5.js/blob/main/contributor_docs/contributing_to_the_p5js_reference.md Example of an optional parameter ('tl') for the rect() function, specifying radius. ```javascript @param {Number} [tl] optional radius of top-left corner. ``` -------------------------------- ### FES Interpolation Example Source: https://github.com/processing/p5.js/blob/main/contributor_docs/friendly_error_system.md An example from FES's fileLoadError demonstrating interpolation for dynamic error messages. ```json "image": "It looks like there was a problem loading your image. {{suggestion}}" ``` -------------------------------- ### JSON Data Structure Example Source: https://github.com/processing/p5.js/wiki/Loading-external-files:-AJAX,-XML,-JSON An example of a JSON object structure, commonly used for data exchange. ```json { "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021" }, "phoneNumber": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ], "gender":{ "type":"male" } } ``` -------------------------------- ### Basic Test Setup and Teardown Source: https://github.com/processing/p5.js/blob/main/contributor_docs/unit_testing.md This snippet shows the basic structure for setting up and tearing down a p5.js instance for unit testing. It's used to create a canvas and make it available for tests. ```javascript suite('module_name', function() { let myp5; let myID = 'myCanvasID'; setup(function(done) { new p5(function(p) { p.setup = function() { let cnv = p.createCanvas(100, 100); cnv.id(myID); myp5 = p; done(); }; }); }); teardown(function() { myp5.remove(); }); }); ``` -------------------------------- ### Run Custom Development Preview with Local Repo Source: https://github.com/processing/p5.js/blob/main/contributor_docs/contributing_to_the_p5js_reference.md Example of running the custom development preview using a local p5.js repository located in a sibling directory. ```shell npm run custom:dev ../p5.js#my-amazing-branch ``` -------------------------------- ### Install Socket.IO Module Source: https://github.com/processing/p5.js/wiki/p5.js,-node.js,-socket.io Install the socket.io module using npm to enable WebSocket functionality for your Node.js server. ```bash $ npm install socket.io ``` -------------------------------- ### Creating and Registering a Custom Renderer Source: https://github.com/processing/p5.js/blob/main/rfc_p5js_2.md Example of how an addon library can define a new renderer by inheriting from p5.Renderer and registering it. ```javascript (function(p5){ class MyRenderer extends p5.Renderer { ellipse(x, y, w, h) { // ... } // ... } p5.registerAddon((p5, fn, lifecycles) => { p5.renderers.myRenderer = MyRenderer; }); })(p5); ``` -------------------------------- ### Node.js Server Setup with Socket.IO Source: https://github.com/processing/p5.js/wiki/p5.js,-node.js,-socket.io Set up a basic Node.js HTTP server and integrate Socket.IO to listen for incoming client connections. ```javascript let server = http.createServer(handleRequest); server.listen(8080); let io = require('socket.io').listen(server); ```