Keyboard Interaction

Like the mouse events we covered in our first lessons on interaction, we can also use events in JavaScript to detect user interaction with the keyboard.

We can detect whether the user has pressed a key down, released a key and determine which key was pressed, using p5 environment variables and boolean logic.

keyIsPressed

The following example will simply display whether or not a user is pressing any key on the keyboard using the keyIsPressed environment variable.

This is a boolean value, a key is either being pressed or not, so keyIsPressed is either true or false.

function draw() { background('white'); if (keyIsPressed) { background("plum"); } // display keyIsPressed value textSize(40); textAlign(CENTER, CENTER); text(keyIsPressed, width/2, height/2); }

key

Once we have determined that a key is being pressed, we may need to know which key is being pressed.

The key variable saves the value of whichever key was most recently pressed, like the mouseX variable saves the most recent x position of the mouse.

function draw() { background('white'); if (keyIsPressed) { if (key == 'b') { background("blue"); } if (key == 'g') { background('green'); } } // display key value textSize(40); textAlign(CENTER, CENTER); text(key, width/2, height/2); }

Notice that this code has one if statement inside of another. We are testing two different sets of conditions.

Be careful to make the curly brackets match here. Use Beautify in Brackets if it doesn't look right.

keyCode

p5 doesn't have values for all of the keys. To test for any key on the keyboard, we can use the ASCII value of the key which is stored by the keyCode variable. Use keycode.info to test which key is which keyCode.

function draw() { background('white'); if (keyIsPressed) { if (keyCode == 13) { // Enter key background("blue"); } if (keyCode == 32) { // Space bar background('green'); } } // display key value textSize(40); textAlign(CENTER, CENTER); text(keyCode, width/2, height/2); }

keyPressed

Like the mousePressed function, we can use keyPressed in cases where we just want to react to a key press with a function.

Since we covered sound earlier this week, let's use a key press to trigger a sound file.

This example will trigger a recording of chickens I found on FreeSound.org.

var chickens; function preload() { chickens = loadSound('chickens.mp3'); } function setup() { createCanvas(640, 200); } function draw() { if (chickens.isPlaying()) { background('yellow'); } else { background(0) } } function keyPressed() { if (keyCode == 32) { // Space bar chickens.play(); } }

There are other functions like keyReleased for other keyboard related events.

Make sure to check out the p5 documentation for all the keyboard events: Events