Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Mouse and Keyboard Input | Transformations and Interactivity
Generative Art with JavaScript and P5.js

bookMouse and Keyboard Input

index.html

index.html

copy

You can make your P5.js sketches interactive by responding to mouse and keyboard events. Two built-in variables, mouseX and mouseY, always contain the current position of the mouse cursor within the canvas. These variables update automatically as the mouse moves, allowing you to draw shapes that follow the mouse or react to its position.

To respond to keyboard input, P5.js provides special functions like keyPressed(). This function is called automatically whenever you press any key. By placing code inside keyPressed(), you can change colors, move objects, or trigger any behavior you want in response to a key press.

This style of programming, where your code reacts to user actions such as moving the mouse or pressing a key, is called event-driven programming. Instead of following a fixed sequence, your sketch waits for events and responds to them, making your art interactive and engaging.

question mark

Which variables in P5.js provide the current position of the mouse?

Select the correct answer

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 2. Kapitel 2

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

bookMouse and Keyboard Input

Stryg for at vise menuen

index.html

index.html

copy

You can make your P5.js sketches interactive by responding to mouse and keyboard events. Two built-in variables, mouseX and mouseY, always contain the current position of the mouse cursor within the canvas. These variables update automatically as the mouse moves, allowing you to draw shapes that follow the mouse or react to its position.

To respond to keyboard input, P5.js provides special functions like keyPressed(). This function is called automatically whenever you press any key. By placing code inside keyPressed(), you can change colors, move objects, or trigger any behavior you want in response to a key press.

This style of programming, where your code reacts to user actions such as moving the mouse or pressing a key, is called event-driven programming. Instead of following a fixed sequence, your sketch waits for events and responds to them, making your art interactive and engaging.

question mark

Which variables in P5.js provide the current position of the mouse?

Select the correct answer

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 2. Kapitel 2
some-alt