Interaction
Add interactivity to your p5.js sketch with mouse and keyboard functions.
StartKey Concepts
Review core concepts you need to learn to master this subject
mouseX
and mouseY
The mouseIsPressed
Variable
The mousePressed()
Function
The dist()
Function
The key
Variable
The keyCode
Variable
Key Events
The keyTyped()
Function
mouseX
and mouseY
mouseX
and mouseY
function draw() {
// The ellipse's x and y positions follow the mouse
ellipse(mouseX, mouseY, 100, 100);
}
The mouseX
and mouseY
variables always store the current x and y coordinates of the mouse relative to the origin of the canvas. So if the mouse was currently at the x position of 150 pixels and the y position of 200 pixels, the value of the mouseX
variable would be 150 and the value of the mouseY
variable would be 200.
- 1Say we wanted to create a browser-based version of the classic arcade game Asteroids, where the mouse position controlled the movement of the game’s spaceship and the blaster was triggered by press…
- 2p5.js makes it easy for us to use the mouse position with the built-in variables mouseX and mouseY. These two variables allow for a variety of mappings to visual elements in a p5.js sketch. The mo…
- 3p5.js also provides us with functions that trigger when specific mouse events are detected. Some examples of mouse events include pressing the mouse, pressing and releasing the mouse, and detecti…
- 4The dist() function is a powerful tool for calculating the distance between two points, stationary or dynamic. This function is oftentimes used in conjunction with mouse events. Understanding how a…
- 5The p5.js library has the ability to store data from the keyboard input for a variety of uses. For example, suppose we wanted to know when a certain key was typed and have that key trigger a unique…
- 6Similar to how we can use mouse input to perform actions in our p5.js sketches, we can also use key events for interaction! These key events are used with general key input or for detecting speci…
What you'll create
Portfolio projects that showcase your new skills
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory