p5.js online editor

Write, Run & Share p5.js code online using OneCompiler's p5.js online editor for free. The editor opens with a small sample sketch when you pick 'p5.js' as the language, and the preview updates as you type, so you can try ideas without installing anything.

About p5.js

p5.js is a JavaScript library for creative coding, built by the Processing Foundation. You write a setup() function that runs once and a draw() function that runs every frame, and p5 gives you simple functions for shapes, color, input, sound and more. Artists, designers, teachers and beginners use it to sketch interactive graphics in the browser.

Syntax help

Setup

Load p5.js from a CDN in index.html, then put your sketch in script.js. p5 looks for global setup and draw functions and calls them for you.

<script src="https://cdn.jsdelivr.net/npm/p5@2/lib/p5.min.js"></script>
<script src="script.js"></script>

setup() and draw()

setup() runs once when the sketch starts. draw() runs about 60 times a second until you call noLoop().

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

function draw() {
  background(220);
  circle(200, 200, 100);
}

Shapes

Positions are in pixels from the top-left corner of the canvas.

rect(20, 20, 100, 60);       // x, y, width, height
ellipse(200, 100, 80, 40);   // x, y, width, height
circle(300, 300, 50);        // x, y, diameter
line(0, 0, width, height);
triangle(50, 350, 100, 250, 150, 350);

Color

fill() sets the inside color of shapes, stroke() sets the outline. Call noFill() or noStroke() to turn either off.

background(30);           // grayscale
fill(255, 0, 100);        // red, green, blue
stroke('#00c2ff');        // CSS color strings work too
strokeWeight(4);

colorMode(HSB);           // switch to hue, saturation, brightness
fill(200, 80, 100);

Mouse and keyboard

mouseX and mouseY always hold the current pointer position. Define event functions to react to clicks and key presses.

function draw() {
  background(240);
  circle(mouseX, mouseY, 30);
}

function mousePressed() {
  console.log('clicked at', mouseX, mouseY);
}

function keyPressed() {
  if (key === 's') saveCanvas('sketch', 'png');
}

Animation

Change a value a little on every frame to make things move. frameCount counts frames since the sketch started.

let x = 0;

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

Full-window canvas

Use windowWidth and windowHeight for a canvas that fills the preview, and resize it when the window changes.

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

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