§3.3 - User Events
KM
bykarutt
2024-12-31
User Events
User events are actions performed by users on a web page. For example, mouse clicks, keyboard inputs, and scrolling are all user events. In this section, we will learn about common user events in p5.js.
Triggering Actions on the Computer
We mainly use two devices to trigger actions on a computer:
- Mouse
- Keyboard
For example, when you press a button on a web page, you use the mouse to click it. When you enter text in a search box, you use the keyboard to type.
p5.js provides functions to detect actions from these devices. In programming, actions triggered by users on a computer are called events.
Mouse Events
Let's consider what happens when you click on a circle.
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
circle(200, 200, 100);
}
function mouseClicked() {
if (dist(mouseX, mouseY, 200, 200) < 50) {
fill(255, 0, 0);
}
}