User Input
p5.js includes an event-driven system for responding to mouse and keyboard input, along with a number of global variables for querying the state of the mouse and keyboard.
Table of Contents
- Mouse Position
- Mouse Events
- Mapping Mouse Input
- Constraining Mouse Input
- Map and Constrain Example
- Keyboard Variables
- Is a Key being Held Down?
Mouse Position
The current x/y location of the mouse can be retrieved using the special π mouseX and π mouseY variables:
circle(mouseX, mouseY, 50);
The state of the mouse buttons is available via π mouseIsPressed and π mouseButton.
In p5.js mouseButton is an object with left, right, and center Boolean properties:
if (mouseIsPressed) {
if (mouseButton.left) {
circle(50, 50, 50);
}
}
Because each button has its own Boolean property, multiple mouse buttons can be detected at the same time.
There are also:
- π
pmouseXand πpmouseY- Previous positions of the mouse in the last frame. - π
movedXand πmovedY- Pixel distance moved since the last frame. - π
winMouseXand πwinMouseY- Mouse position in the entire browser window, not just the p5 canvas. - π
pwinMouseXand πpwinMouseY- Previous browser window positions.
Mouse Events
There are a number of functions you can define that will be called for particular mouse events:
- π
mouseMoved()- Called anytime the mouse moves. - π
mouseDragged()- Called anytime the mouse moves while a button is pressed. - π
mousePressed()- Called when any mouse button is pressed. - π
mouseReleased()- Called when any mouse button is released. - π
mouseClicked()- Called after a mouse button has been pressed and then released.
Resources
- π° Conditionals and Interactivity Tutorial
- π Variables in p5.js - mouseX and mouseY - Coding Train Video (12m23s)
- π Mouse Interaction with Objects - Coding Train Video (14m57s)
- π·οΈ Drawing Lines Example
- π·οΈ Animation with Events Example
- π·οΈ Circle Clicker Example
Mapping Mouse Input
When using positional mouse values, we often wish to map the screen positions to a range of values that are more useful for our sketch. For example, imagine a sketch where the mouse position controls the background color, with the red component of the color controlled by mouseX and the blue component of the color controlled by mouseY.
A naive approach would be:
function draw() {
background(mouseX, 0, mouseY);
}
Because the color components need to be in the range of 0 to 255, this would only work as intended for a sketch with a 255x255 canvas. This is where the π map() function comes into play. With map() we can re-map a number from one range of values to another:
let redValue = map(mouseX, 0, width, 0, 255);
The first argument is the value being remapped, the next two arguments are the initial range (in our case mouseX goes from 0 to the width of the canvas), and the final two arguments are the range we want to map to (in our case 0 to 255).
Resources
- π The Map() Function - Coding Train Video
- π·οΈ Map Example
Constraining Mouse Input
The mouse can move outside the canvas, so mouseX and mouseY can return values outside the canvas dimensions. We can use the π constrain() function to set minimum and maximum limits:
let xPos = constrain(mouseX, 0, width); // Constrain xPos to the canvas width.
let redValue = map(xPos, 0, width, 0, 255); // Map xPos to the 0 to 255 range.
map() also supports an optional sixth argument that can constrain the mapped result to its target range. For example:
let redValue = map(mouseX, 0, width, 0, 255, true);
Resources
Map and Constrain Example
The map() and constrain() functions are useful beyond just mouse position, but hereβs a full demo of using them with the mouse:
function setup() {
createCanvas(200, 300);
textSize(32);
fill(255);
}
function draw() {
let xPos = constrain(mouseX, 0, width); // Constrain xPos to 0 to 200.
let redValue = map(xPos, 0, width, 0, 255); // Map xPos to 0 to 255 range.
let yPos = constrain(mouseY, 0, height); // Constrain yPos to 0 to 300.
let blueValue = map(yPos, 0, height, 0, 255); // Map yPos to 0 to 255 range.
background(redValue, 0, blueValue);
text(`red: ${redValue}\nblue: ${blueValue}`, 10, 40);
}
The Result:
Keyboard Variables
There are several variables related to the state of keys pressed on the keyboard:
- π
keyIsPressed- Boolean that istrueif any key is currently pressed. - π
key- String containing the value of the most recently typed key. This is most useful for printable characters. - π
keyCode- Numeric code for the last key pressed. - π
keyIsDown()- Check if a particular is is being held down.
p5.js also provides constants for common special keys, including BACKSPACE, DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL, OPTION, ALT, UP_ARROW, DOWN_ARROW, LEFT_ARROW, and RIGHT_ARROW.
Is a Key being Held Down?
We use keyIsDown() to test if I key is currently being held down.
if (keyIsDown(UP_ARROW)) { // returns true if the UP Arrow is being held down.
// Move up.
}
This also makes it easy to check for multiple keys at the same time:
if (keyIsDown(LEFT_ARROW) && keyIsDown(UP_ARROW)) {
// Move diagonally up and left.
}
We can also check for all other keyboard keys using a search argument:
if (keyIsDown("q")) {
// User is holding down the q key.
}
Keyboard Events
Like with the mouse, there are special functions you can define to respond to keyboard events:
- π
keyPressed()- Called when any key is pressed. - π
keyReleased()- Called when any key is released. - π
keyTyped()- Called when a key that produces a printable character is pressed.
For continuous input, such as moving a game character while a key is held down, use π keyIsDown() as shown above.