🚀 Setup Function
The setup() function runs once when your program starts. Use it to initialize your canvas and set initial values.
function setup() {
createCanvas(400, 400);
background(220);
}
Emphasize that setup() only runs ONCE at the beginning. Great for creating the canvas and setting initial states.
🎬 Draw Function
The draw() function runs continuously in a loop (default 60 times per second). This is where animation happens!
function draw() {
background(220);
circle(200, 200, 50);
}
Try changing the numbers in circle() to move it around the canvas!
📦 Variables
Variables store information that can change. Think of them as labeled boxes that hold values.
let x = 200;
let y = 200;
let diameter = 50;
function draw() {
background(220);
circle(x, y, diameter);
x = x + 1;
}
✅ Quick Check
What happens to the circle in this code?
It stays still
It moves to the right
It moves down
It gets bigger
⚙️ Creating Your Own Functions
Functions help organize your code and avoid repetition. They're like creating your own custom commands!
function drawSmileyFace(x, y) {
circle(x, y, 100);
circle(x - 20, y - 10, 10);
circle(x + 20, y - 10, 10);
arc(x, y + 10, 50, 30, 0, PI);
}
drawSmileyFace(100, 100);
drawSmileyFace(300, 100);
drawSmileyFace(200, 300);
Functions with parameters (x, y) make code flexible and reusable. This is a fundamental programming concept!
✅ Quick Check
How many smiley faces will this code draw?
🔀 If Statements
Conditionals let your program make decisions based on conditions.
let x = 200;
function draw() {
background(220);
if (x > 400) {
x = 0;
}
circle(x, 200, 50);
x = x + 2;
}
This creates a circle that wraps around! Try changing the condition or adding more if statements.
✅ Quick Check
When does the circle reset to the left side?
When x is less than 0
When x is greater than 400
When x equals 200
Never
🔄 For Loops
Loops help you repeat actions without writing the same code over and over.
function draw() {
background(220);
for (let i = 0; i < 8; i++) {
circle(i * 50 + 25, 200, 40);
}
}
Loops are powerful! This draws 8 circles with just 3 lines. Without a loop, we'd need 8 separate circle() commands.
✅ Quick Check
How many circles will this loop draw?