Keyboard

key variable

p5.js provides the key variable, which stores the most recently pressed key as a string. This allows us to track user input dynamically. The example below displays the last pressed key in the center of the canvas.

Code Explanation
let lastKey = '';  

function setup() {  
  createCanvas(200, 200);  
  textAlign(CENTER, CENTER);  
  textSize(32);  
}  

function draw() {  
  background(220);  
  text(lastKey, width / 2, height / 2);  
}  

function keyPressed() {  
  // Store the last pressed key
  lastKey = key;  
}  
ℹ️
  • key: Stores the most recently pressed key as a string.
  • text(string, x, y): Displays text at a specified position on the canvas.

Key Presses

The keyPressed() function runs once whenever a key is pressed. In the example below, pressing 'r', 'g', or 'b' changes the background color to red, green, or blue.

Code Explanation
let bgColor = 220;  

function setup() {  
  createCanvas(200, 200);  
}  

function draw() {  
  background(bgColor);  
}  

function keyPressed() {  
  // Change background color based on key press
  if (key === 'r') {  
    bgColor = color(255, 0, 0);  
  }
  if (key === 'g') {  
    bgColor = color(0, 255, 0);  
  } 
  if (key === 'b') {  
    bgColor = color(0, 0, 255);  
  }  
}  
ℹ️
  • keyPressed: Runs when any key is pressed.
  • color(r, g, b): Creates an RGB color value.

Further Reading

📌 p5.js Keyboard – Learn more about handling keyboard input.
📌 keyCode variable – Used for detecting special keys (e.g., arrow keys, Enter, Backspace).
📌 keyIsDown() – Checks if a specific key is currently being held down.