Mouse & Keyboard

Make your sketches interactive with mouse and keyboard input.

Mouse Position

Use mouseX and mouseY to get the current mouse position:

fn setup() { size(300, 200) } fn draw() { background(rgb(30, 30, 40)) fill(coral) circle(mouseX, mouseY, 30) }

Mouse Pressed

Check if the mouse button is held down with mousePressed:

fn setup() { size(300, 200) } fn draw() { background(rgb(30, 30, 40)) if mousePressed { fill(coral) circle(mouseX, mouseY, 50) } else { fill(gray) circle(mouseX, mouseY, 30) } }

Click Events

Define mouseClicked() to respond to clicks:

let clicks = 0 fn setup() { size(300, 200) } fn draw() { background(rgb(30, 30, 40)) fill(white) text("Clicks: " + clicks, 20, 30) fill(coral) circle(150, 110, 40) } fn mouseClicked() { clicks = clicks + 1 }

Keyboard Input

Check if a key is pressed with keyPressed and key:

let x = 150 let y = 100 fn setup() { size(300, 200) } fn draw() { background(rgb(30, 30, 40)) // Arrow keys move the circle if keyPressed { if key == "ArrowUp" { y = y - 3 } if key == "ArrowDown" { y = y + 3 } if key == "ArrowLeft" { x = x - 3 } if key == "ArrowRight" { x = x + 3 } } fill(cyan) circle(x, y, 25) fill(white) text("Use arrow keys", 100, 180) }

Common Keys