These control the flow of your program. setup() runs once at the start, draw() runs over and over to animate things, and the rest help you set up your canvas.
A function YOU write. It runs once when your program starts. Use it to set the canvas size and do any one-time setup.
function setup() {
size(400, 300);
background("skyblue");
}
function draw() {
fill("white");
circle(200, 150, 50);
}A function YOU write. It runs about 60 times per second, creating animation! Everything you draw in here gets redrawn each frame.
function setup() {
size(400, 300);
}
function draw() {
background("white");
fill("tomato");
circle(mouseX, mouseY, 30);
}A function YOU write. It runs once each time a key is pressed down. Check the 'key' variable to see which key it was.
let message = "Press any key!";
function setup() {
size(400, 200);
}
function draw() {
background("white");
fill("black");
textSize(24);
text(message, 80, 90);
}
function keyPressed() {
message = "You pressed: " + key;
}A function YOU write. It runs once each time a key is released (lifted up). Useful for toggling things on and off.
let color = "dodgerblue";
function setup() {
size(400, 200);
}
function draw() {
background("white");
fill(color);
circle(200, 100, 60);
}
function keyReleased() {
color = color === "dodgerblue" ? "tomato" : "dodgerblue";
}Sets the width and height of your canvas in pixels. Call this inside setup(). Call with no arguments to fill the entire window β great for fullscreen games!
| Parameter | Type | Description |
|---|---|---|
woptional | number | Width in pixels (leave empty to fill window) |
hoptional | number | Height in pixels (leave empty to fill window) |
function setup() {
size(600, 400);
}
function draw() {
background("lavender");
fill("black");
textSize(20);
text("600 x 400 canvas!", 200, 190);
}Fills the entire canvas with a color. Call this at the start of draw() to clear the screen each frame.
| Parameter | Type | Description |
|---|---|---|
color | color | A color name like "white", a hex code like "#ff0000", or a number 0β255 for gray |
function setup() {
size(400, 200);
}
function draw() {
background("midnightblue");
fill("gold");
textSize(28);
text("Dark background!", 80, 85);
}A variable (not a function!) that holds the current canvas width. Handy for centering things.
Returns: number
function setup() {
size(400, 300);
}
function draw() {
background("white");
fill("dodgerblue");
circle(width / 2, height / 2, 50);
}A variable that holds the current canvas height.
Returns: number
function setup() {
size(400, 300);
}
function draw() {
background("white");
stroke("tomato");
strokeWeight(2);
noFill();
rect(10, 10, width - 20, height - 20);
}A variable that counts how many frames have been drawn since the program started. Great for animation!
Returns: number
function setup() {
size(400, 200);
}
function draw() {
background("white");
fill("black");
textSize(20);
text("Frames: " + frameCount, 130, 90);
}