Learn P5JS with Real Code Examples
Updated Nov 26, 2025
Code Sample Descriptions
1
Hello World in p5.js
function setup() {
createCanvas(400, 200);
background(255);
fill(0);
textSize(32);
text("Hello World", 100, 100);
}
A simple p5.js sketch that displays 'Hello World' in the browser canvas.
2
Moving Circle
let x = 0;
function setup() {
createCanvas(400, 200);
}
function draw() {
background(255);
ellipse(x, 100, 50, 50);
x += 2;
if(x > width) x = 0;
}
A circle moving horizontally across the canvas.
3
Bouncing Ball
let x = 200, y = 100;
let xspeed = 3, yspeed = 2;
function setup() {
createCanvas(400, 200);
}
function draw() {
background(255);
x += xspeed;
y += yspeed;
if(x > width || x < 0) xspeed *= -1;
if(y > height || y < 0) yspeed *= -1;
ellipse(x, y, 50, 50);
}
A ball bouncing off the edges of the canvas.
4
Colorful Rectangles
function setup() {
createCanvas(400, 200);
noLoop();
}
function draw() {
for(let i=0; i<10; i++) {
fill(random(255), random(255), random(255));
rect(i*40, 50, 30, 100);
}
}
Draws a series of colored rectangles.
5
Mouse Follow Circle
function setup() {
createCanvas(400, 200);
}
function draw() {
background(255);
fill(0, 100, 255);
ellipse(mouseX, mouseY, 50, 50);
}
A circle that follows the mouse cursor.
6
Random Stars
function setup() {
createCanvas(400, 200);
background(0);
}
function draw() {
fill(255);
ellipse(random(width), random(height), 2, 2);
}
Draws random stars on the canvas every frame.
7
Growing Circle
let r = 10;
function setup() {
createCanvas(400, 200);
}
function draw() {
background(255);
ellipse(width/2, height/2, r, r);
r += 1;
if(r > width) r = 10;
}
A circle that grows in size over time.
8
Rotating Line
let angle = 0;
function setup() {
createCanvas(400, 200);
}
function draw() {
background(255);
translate(width/2, height/2);
line(0, 0, 100*cos(angle), 100*sin(angle));
angle += 0.05;
}
A line rotating around the center of the canvas.
9
Random Walk
let x, y;
function setup() {
createCanvas(400, 200);
x = width/2;
y = height/2;
background(255);
}
function draw() {
stroke(0);
x += random(-5, 5);
y += random(-5, 5);
point(x, y);
}
A point performing a random walk across the canvas.
10
Interactive Rectangle
function setup() {
createCanvas(400, 200);
}
function draw() {
background(255);
if(mouseIsPressed) {
rect(150, 50, 100, 100);
} else {
rect(150, 50, 50, 50);
}
}
Rectangle width changes when mouse is pressed.