HomeBooks

En

Chapter 1
Getting Ready to Write Programs
Chapter 3
Programming Syntax
§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:

  1. Mouse
  2. 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);
    }
}
Prev
§3.2 - for Loop (Repetition Processing)