Keyboard

key variable

p5.js provides the key variable, which stores the most recently pressed key as a string. The sketch below shows the last pressed key at the canvas center.

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: holds the most recently pressed key as a string.
  • text(string, x, y): draws text at (x, y).

Key presses

keyPressed() runs once whenever a key is pressed. Pressing 'r', 'g', or 'b' below changes the background color.

Code Explanation
let bgColor = 220;

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

function draw() {
  background(bgColor);
}

function keyPressed() {
  // Traditional conditionals
  if (key === 'r') {
    bgColor = color(255, 0, 0);
  }
  if (key === 'g') {
    bgColor = color(0, 255, 0);
  }
  // Short-circuit alternative
  key === 'b' && (bgColor = color(0, 0, 255));
}
ℹ️
  • keyPressed: fires when any key is pressed.
  • color(r, g, b): creates an RGB color.
  • key === 'b' && ... uses short-circuiting: the right side runs only if the left side is true.

String templates (`...`)

String templates let you embed variables directly in text using ${value} syntax. This makes dynamic messages a bit simpler than manual concatenation.

The example below displays the last pressed key and the total number of key presses.

Code Explanation
let lastKey = '';
let pressCount = 0;

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

function draw() {
  background(220);
  // Interpolates both variables into the display text
  text(`You pressed '${lastKey}' (${pressCount} times)`, width / 2, height / 2);
}

function keyPressed() {
  lastKey = key;
  pressCount++;
}
ℹ️
Quotes in JS: Single '...' and double "..." quotes work the same for strings. Book style: single quotes '...' are used throughout, except for string templates which require backticks `...` for interpolation with ${...}.

Further reading

📌 p5.js Keyboard – Keyboard handling overview
📌 keyCode variable – Detect special keys (arrows, Enter, Backspace)
📌 keyIsDown() – Check if a specific key is currently held down