Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn 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

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 2. ChapterΒ 2

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

bookMouse and Keyboard Input

Swipe to show menu

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

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 2. ChapterΒ 2
some-alt