1. Basic Setup and Drawing
p5.js is a JavaScript library for creative coding, focusing on visual arts and interactive experiences. Every p5.js sketch requires two main functions: setup() and draw().
1.1. Including p5.js and Basic Structure
Include the p5.js library in your HTML file. Create a sketch.js file (or similar) and link it.
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.9.1/p5.min.js"></script>
<script src="sketch.js"></script>
</head>
<body></body>
</html>
// sketch.js
function setup() {
createCanvas(400, 400); // Create a 400x400 pixel canvas
}
function draw() {
background(220); // Set background color to light gray
}
The setup() function runs once at the beginning, while draw() runs repeatedly (usually 60 times per second).
1.2. Drawing Basic Shapes
You can draw various shapes using built-in functions.
function draw() {
background(220);
fill(255, 0, 0); // Set fill color to red
noStroke(); // Remove outline
ellipse(width / 2, height / 2, 50, 50); // Draw a circle in the center
stroke(0, 0, 255); // Set stroke color to blue
strokeWeight(4); // Set stroke thickness
rect(50, 50, 70, 70); // Draw a rectangle at (50, 50) with width/height 70
}
Use fill(), stroke(), noFill(), noStroke(), and strokeWeight() to control shape appearance.