javascript p5 js

javascript p5 js is the p5.js library. It is a JavaScript library for drawing in the browser. Lauren Lee McCarthy created it in 2013 as an interpretation of Processing for the web, and the Processing Foundation supports it. Processing is the desktop software Ben Fry and Casey Reas started in 2001. You download Processing and run it on Mac, Windows, or Linux. A p5.js sketch runs in a web page.

p5.js creates the canvas for you and gives you functions such as circle() and background(). The same page can still use ordinary JavaScript, HTML, and CSS. Sound is a separate library, p5.sound. Buttons, sliders, and the other HTML helpers below are part of p5.js itself.

Adding the library

The current file on the p5.js download page is:

https://cdn.jsdelivr.net/npm/p5@2.4.0/lib/p5.min.js

That page also lists https://cdn.jsdelivr.net/npm/p5@2/lib/p5.min.js for the latest 2.x release, and separate downloads of p5.js and p5.min.js. The npm package name is p5. If a sketch needs sound, add a current p5.sound script as well. The download page says to skip an old p5.sound.js file that may be sitting in the complete-library download, because that copy does not work with p5.js 2.

This page loads the pinned 2.4.0 build, then a sketch.js file. The page has no <canvas> tag. createCanvas() inserts the canvas.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>sketch</title>
  </head>
  <body>
    <script src="https://cdn.jsdelivr.net/npm/p5@2.4.0/lib/p5.min.js"></script>
    <script src="sketch.js"></script>
  </body>
</html>

The p5.js Web Editor is the other way to start. A new editor project already has index.html, style.css, and sketch.js, and Play runs the sketch in the preview. Saving needs an account. File, then Share, gives an embed link, a fullscreen link, and a link that opens the code.

setup and draw

setup() runs once when the sketch starts. draw() runs after that, in a loop. By default, draw() tries to run 60 times a second. frameRate(30) asks for 30 frames a second. The machine may not hit that target. frameRate() with no argument returns an approximate current rate.

frameCount is 0 inside setup(). It goes up by 1 each time draw() finishes.

function setup() {
  createCanvas(200, 100);
}

function draw() {
  background(220);
  circle(frameCount, 50, 20);
}

createCanvas(200, 100) makes a canvas 200 pixels wide and 100 pixels tall. Call createCanvas() once. Calling it again makes the sketch behave unpredictably. If you omit the width and height, both default to 100. The renderer defaults to P2D.

background(220) paints the canvas gray at the start of every frame, so the previous circle is covered. Leave background() out of draw() and the circles stay, which is how a trail is drawn. The canvas background is transparent until something paints it. background(255, 204, 0) is yellow in the default RGB mode. background("aqua") uses a CSS color name.

noLoop() stops draw() from repeating. loop() starts it again. redraw() runs draw() once.

The canvas

resizeCanvas(300, 500) changes the canvas to 300 by 500 and clears it. By default it also calls redraw(). Pass true as the third argument to skip that redraw.

windowWidth and windowHeight are the browser viewport, in pixels. This sketch starts at that size and follows the window:

function setup() {
  createCanvas(windowWidth, windowHeight);
}

function draw() {
  background(220);
  circle(width / 2, height / 2, 40);
}

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
}

width and height are the canvas size. After resizeCanvas(300, 500), width is 300 and height is 500.

To put the canvas inside an existing element, select it and call parent() with that element’s id:

function setup() {
  createCanvas(200, 200);
  select("canvas").parent("holder");
}

select("canvas") returns the first canvas as a p5 element, or null if it finds nothing. parent("holder") moves that element under the element whose id is holder.

Coordinates

In 2D mode the origin, (0, 0), is the top-left corner of the canvas. x grows to the right. y grows downward. circle(200, 200, 100) puts the center 200 pixels from the left edge and 200 pixels from the top, with a diameter of 100.

translate(50, 50) moves the origin to (50, 50). Everything drawn after that uses the new origin. rotate(QUARTER_PI) turns the axes clockwise by one eighth of a turn. Angles are radians until you call angleMode(DEGREES), and then rotate(45) is the same eighth of a turn. scale(2) stretches every axis by 2. scale(2, 0.5) stretches x by 2 and y by 0.5.

Transforms add up inside the current frame, and they reset when the next draw() starts. rotate(0.01) on every frame does not spin a shape, because each frame starts from the original axes. Increase the angle with frameCount if you want a spin. push() and pop() keep a transform, or a fill, inside one group.

function setup() {
  createCanvas(100, 100);
}

function draw() {
  background(200);
  circle(25, 50, 20);
  push();
  translate(50, 50);
  rotate(QUARTER_PI);
  fill("orange");
  rect(-20, -10, 40, 20);
  pop();
  circle(75, 50, 20);
}

The two circles use the original origin. The rectangle is drawn around (50, 50), turned one eighth of a turn, and filled orange. pop() drops that origin, that rotation, and that fill before the second circle.

In WebGL mode the origin starts at the center of the canvas, not the top-left.

Shapes and color

The default color mode is RGB, the same as colorMode(RGB, 255). Each channel runs from 0 to 255.

function setup() {
  createCanvas(120, 80);
  background(200);
  fill(255, 0, 0, 128);
  stroke(0, 0, 255);
  strokeWeight(4);
  rect(20, 20, 60, 40);
}

rect(20, 20, 60, 40) draws a rectangle whose top-left corner is (20, 20), 60 pixels wide and 40 pixels tall. That corner anchor is rectMode(CORNER), the default. rectMode(CENTER) reads the first two numbers as the center. rectMode(CORNERS) reads them as opposite corners. rectMode(RADIUS) also uses the center, and the next two numbers are half the width and half the height.

fill(255, 0, 0, 128) is semi-transparent red. The fourth number is alpha. In this default mode, 0 is transparent and 255 is opaque. stroke(0, 0, 255) is a blue outline. strokeWeight(4) makes that outline 4 pixels wide. A line’s default width is 1 pixel. noFill() turns the fill off, and noStroke() turns the outline off. A call to both draws nothing.

ellipse(x, y, w, h) is an oval. With one size, ellipse(50, 50, 80), the height matches the width. The default ellipseMode(CENTER) treats x and y as the center. line(x1, y1, x2, y2) draws a straight line. Fill does not color a line. triangle(x1, y1, x2, y2, x3, y3) uses three points. quad(x1, y1, x2, y2, x3, y3, x4, y4) uses four, in order around the shape. point(x, y) is a single point, colored by stroke().

colorMode(HSB) switches the channels. fill(0, 100, 100) is pure red in that mode.

beginShape() starts a custom outline, vertex(x, y) adds a corner, and endShape(CLOSE) connects the last point back to the first. Without CLOSE, the shape stays open.

function setup() {
  createCanvas(100, 100);
  background(200);
  beginShape();
  vertex(30, 20);
  vertex(85, 20);
  vertex(85, 75);
  vertex(30, 75);
  endShape(CLOSE);
}

That draws a white square from (30, 20) to (85, 75). bezierVertex() adds a Bézier segment inside the same shape. splineVertex() connects points with a spline. translate(), rotate(), and scale() do not apply between beginShape() and endShape().

Animation

Declare a variable outside setup() and draw() if the next frame needs the value.

let x = 0;

function setup() {
  createCanvas(200, 100);
}

function draw() {
  background(220);
  circle(x, 50, 20);
  x += 1;
  if (x > width) {
    x = 0;
  }
}

The circle’s center starts at x of 0. Each frame adds 1. When the center moves past the right edge, x returns to 0.

lerp(start, stop, amt) returns a number on the way from start to stop. lerp(20, 80, 0.5) is 50. lerp(0, 10, 1.5) is 15, past the end. This is the usual easing step, moving x a fraction of the way toward targetX on every frame:

x = lerp(x, targetX, 0.05);

map(value, start1, stop1, start2, stop2) remaps a number. map(2, 0, 10, 0, 100) returns 20. Values outside the first range still map, so map(11, 0, 10, 0, 100) returns 110. Pass true as the sixth argument to clamp the result to the second range. dist(x1, y1, x2, y2) is the distance between two points. dist(10, 50, 90, 50) is 80.

Mouse and keyboard

mouseX and mouseY are the mouse position measured from the top-left of the canvas. On a touch screen, mouseX is the x of the latest touch. pmouseX and pmouseY are those positions from the previous frame. mouseIsPressed is true while a button is down.

function setup() {
  createCanvas(200, 200);
}

function draw() {
  background(220);
  if (mouseIsPressed === true) {
    fill(0);
  } else {
    fill(255);
  }
  circle(mouseX, mouseY, 40);
}

The circle follows the pointer. It is white until a mouse button is down, and then the fill is black.

mousePressed() runs once when a button goes down. mouseReleased() runs when it comes up. mouseClicked() runs just after that release. mouseMoved() runs when the pointer moves, and mouseDragged() runs when it moves while a button is held. mousePressed() also runs when a touch starts. return false at the end of mousePressed() cancels the browser’s default action for that event.

mouseButton is an object with left, right, and center. Each one is true while that button is pressed. Browsers do not all report the buttons the same way.

keyIsPressed is true while any key is down. key is the last character typed, so key === "a" checks that letter. key does not update for arrow keys or Enter. keyIsDown(LEFT_ARROW) is true while the left arrow is held, and it can see more than one key at once. keyIsDown("ArrowLeft") is the same check. In p5.js 2, keyIsDown() does not take a numeric key code. keyPressed() runs once when a key goes down, and keyReleased() runs when it comes up.

let x = 100;
let y = 100;

function setup() {
  createCanvas(200, 200);
}

function draw() {
  background(220);
  if (keyIsDown(LEFT_ARROW)) {
    x -= 1;
  }
  if (keyIsDown(RIGHT_ARROW)) {
    x += 1;
  }
  if (keyIsDown(UP_ARROW)) {
    y -= 1;
  }
  if (keyIsDown(DOWN_ARROW)) {
    y += 1;
  }
  circle(x, y, 20);
}

Each held arrow moves the circle by 1 pixel on that frame. Up decreases y because the y-axis points down.

Touch

touches is an array of the current touch points. It is empty until a finger is on the screen. Each point has x and y relative to the canvas, winX and winY relative to the browser, and an id.

function setup() {
  createCanvas(200, 200);
}

function draw() {
  background(220);
  for (let touch of touches) {
    circle(touch.x, touch.y, 40);
  }
}

One circle is drawn for each finger on the canvas.

Text and images

text("hi", 50, 50) draws that string. By default the point is the bottom-left of the text box. textAlign(CENTER, CENTER) uses the center instead. The horizontal value is LEFT, CENTER, or RIGHT. The vertical value is TOP, BOTTOM, CENTER, or BASELINE. textSize(32) sets the size in pixels. fill() sets the text color, and stroke() sets an outline in 2D mode. In WebGL mode, stroke() does not affect text, and the font has to be one loaded with loadFont().

loadFont() reads a .otf or .ttf file and returns a promise of a p5.Font. In 2D mode the path can also be a CSS file or a CSS @font-face string. Pass the font to textFont().

let font;

async function setup() {
  font = await loadFont("inconsolata.otf");
  createCanvas(200, 100);
  textFont(font);
  textSize(32);
  textAlign(CENTER, CENTER);
  background(255);
  fill("deeppink");
  text("p5.js", width / 2, height / 2);
}

setup is async, so it waits at await until the font file has loaded. draw() starts after setup() finishes.

loadImage("photo.jpg") works the same way. The path is relative for a local file. A full URL can be blocked by the browser. The function returns a promise of a p5.Image.

let img;

async function setup() {
  img = await loadImage("photo.jpg");
  createCanvas(img.width, img.height);
}

function draw() {
  image(img, 0, 0);
}

image(img, 0, 0) draws the image with its top-left at the origin, at the file’s own size. image(img, 0, 0, 50, 50) draws it 50 by 50. That top-left anchor is imageMode(CORNER), the default. imageMode(CENTER) uses the center. tint(255, 0, 0) tints later images red. tint(255, 128) keeps the image and makes it partly transparent.

get(50, 90) returns the pixel at that point as [R, G, B, A]. get(0, 0, 50, 50) returns that rectangle as a p5.Image. set(30, 20, 0) writes a black pixel, and the change shows up after updatePixels(). set() is the slow way to write many pixels. The pixels array is the faster one.

p5.js 1 loaded files in preload(), which ran before setup(). p5.js 2 does not use preload(). The wait is the await inside async function setup(). The Web Editor has a preload compatibility add-on for old sketches.

saveCanvas("drawing", "jpg") saves drawing.jpg. The extension is png, webp, or jpg. With no arguments, the file is untitled.png. The browser downloads it or asks you first.

random and noise

random() with no arguments returns a number from 0 up to, but not including, 1. random(5) returns a number from 0 up to, but not including, 5. random(-5, 10.2) uses that range, and the upper bound is still excluded. random(["red", "green", "blue"]) returns one of those three strings. Each run of the sketch gets a new sequence unless you call randomSeed(99) first.

noise(x), noise(x, y), and noise(x, y, z) return a number from 0 to 1. Nearby inputs produce nearby outputs, which is the useful difference from random(). noiseSeed(99) keeps the same pattern on the next run. Smaller steps in the input make a smoother change.

function setup() {
  createCanvas(100, 100);
  noiseSeed(99);
  noLoop();
}

function draw() {
  for (let x = 0; x < width; x += 1) {
    for (let y = 0; y < height; y += 1) {
      let shade = noise(x * 0.05, y * 0.05) * 255;
      set(x, y, shade);
    }
  }
  updatePixels();
}

Each pixel’s gray comes from noise() at that pixel’s coordinates. Multiplying by 0.05 keeps neighboring pixels close together in noise space, so the field changes gradually. updatePixels() copies the set() calls onto the canvas. noLoop() stops the sketch after that one frame.

Classes

A sketch is JavaScript, so a class is an ordinary class. This one stores a position, a velocity, and an alpha, then draws itself.

class Particle {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.vx = random(-1, 1);
    this.vy = random(-1, 1);
    this.life = 255;
  }

  update() {
    this.x += this.vx;
    this.y += this.vy;
    this.life -= 1;
  }

  show() {
    noStroke();
    fill(0, 0, 0, this.life);
    circle(this.x, this.y, 8);
  }
}

let particles = [];

function setup() {
  createCanvas(200, 200);
}

function draw() {
  background(255);
  particles.push(new Particle(mouseX, mouseY));
  for (let i = particles.length - 1; i >= 0; i -= 1) {
    let p = particles[i];
    p.update();
    p.show();
    if (p.life <= 0) {
      particles.splice(i, 1);
    }
  }
}

Every frame adds a particle at the mouse. update() moves it by vx and vy and lowers life. show() draws an 8-pixel black circle whose alpha is life. The loop walks backward so splice() does not skip the next particle. At life of 0 the particle is removed.

WebGL

createCanvas(200, 200, WEBGL) uses a WebGL canvas. The browser uses WebGL2 when it has it. box(), sphere(), cylinder(), cone(), and torus() are 3D shapes, and box() only works in this mode. box(60) is a cube 60 pixels on a side, drawn at the origin, which is the center of the canvas. orbitControl() rotates the view when you drag.

function setup() {
  createCanvas(200, 200, WEBGL);
}

function draw() {
  background(200);
  orbitControl();
  box(60);
}

camera(), perspective(), and ortho() set the view. ambientLight(), directionalLight(), and pointLight() add light. A loaded image can be passed to texture() on a 3D shape. The reference pages for those functions list the arguments.

HTML elements

createButton("click me") adds a button. createSlider(0, 255, 128) adds a slider from 0 to 255 that starts at 128. An optional fourth argument is the step. A step of 0 lets the slider move continuously. createInput() adds a text field. selectAll(".label") returns every match, where select() returns the first.

let slider;

function setup() {
  createCanvas(200, 200);
  slider = createSlider(0, 255, 128);
  slider.position(10, 210);
}

function draw() {
  background(slider.value());
}

slider.value() is the current number, and background() uses it as a gray level. position(10, 210) places the slider 10 pixels from the left of the page and 210 pixels from the top, just under a canvas that is 200 pixels tall.

If this article was helpful, tweet it!