p5.js Starter Article 9

Keyboard Input

Detect key presses and use them to control colour, movement, and sketch behaviour.

⏱ 12 min read keyboard input events keyCode

The key variables

p5.js provides two variables for reading the current keyboard state:

Variable Description
key The character of the last key pressed, as a string (e.g. 'a', 'A', ' ')
keyCode The numeric key code of the last key pressed
keyIsPressed true while any key is held down

Reading key in draw()

Check keyIsPressed and key inside draw() for continuous movement:

let x = 300;
let y = 200;
const speed = 3;

function setup() {
  createCanvas(600, 400);
}

function draw() {
  background(20);

  if (keyIsPressed) {
    if (key === 'ArrowLeft'  || key === 'a') x -= speed;
    if (key === 'ArrowRight' || key === 'd') x += speed;
    if (key === 'ArrowUp'    || key === 'w') y -= speed;
    if (key === 'ArrowDown'  || key === 's') y += speed;
  }

  // Keep in bounds
  x = constrain(x, 20, width - 20);
  y = constrain(y, 20, height - 20);

  fill(100, 200, 255);
  noStroke();
  circle(x, y, 40);
}

keyPressed() and keyReleased()

For one-off actions rather than continuous movement, use the event functions:

function keyPressed() {
  // Called once each time a key is pressed
}

function keyReleased() {
  // Called once each time a key is released
}

function keyTyped() {
  // Called for printable characters — excludes Backspace, Enter, arrows, etc.
}

Example — change background colour on each key press:

let bgColor;

function setup() {
  createCanvas(600, 400);
  bgColor = color(20);
}

function draw() {
  background(bgColor);
  fill(255);
  textSize(18);
  textAlign(CENTER, CENTER);
  text('Press any key', width / 2, height / 2);
}

function keyPressed() {
  bgColor = color(random(255), random(255), random(255));
}

Special key codes

Arrow keys and modifier keys don’t have printable characters, so use keyCode instead:

function keyPressed() {
  if (keyCode === UP_ARROW)    { /* up */ }
  if (keyCode === DOWN_ARROW)  { /* down */ }
  if (keyCode === LEFT_ARROW)  { /* left */ }
  if (keyCode === RIGHT_ARROW) { /* right */ }
  if (keyCode === ENTER)       { /* enter */ }
  if (keyCode === BACKSPACE)   { /* backspace */ }
  if (keyCode === DELETE)      { /* delete */ }
  if (keyCode === ESCAPE)      { /* escape */ }
  if (keyCode === TAB)         { /* tab */ }
  if (keyCode === SHIFT)       { /* shift */ }
  if (keyCode === CONTROL)     { /* ctrl */ }
  if (keyCode === ALT)         { /* alt */ }
}

You can also compare raw numbers: keyCode === 32 is the space bar.

Toggling state with keys

A common pattern — press a key to toggle something on/off:

let showGrid = false;
let paused   = false;

function keyPressed() {
  if (key === 'g') showGrid = !showGrid;
  if (key === ' ') {
    paused = !paused;
    if (paused) noLoop();
    else        loop();
  }
}

A full example — interactive drawing tool

let brushSize  = 20;
let brushColor;
let drawing    = true;

function setup() {
  createCanvas(600, 400);
  background(245);
  brushColor = color(50, 100, 200);
  colorMode(HSB, 360, 100, 100);
}

function draw() {
  if (drawing && mouseIsPressed) {
    stroke(brushColor);
    strokeWeight(brushSize);
    strokeCap(ROUND);
    line(pmouseX, pmouseY, mouseX, mouseY);
  }

  // HUD
  fill(0, 0, 0, 120);
  noStroke();
  rect(0, height - 30, width, 30);
  fill(0, 0, 100);
  textSize(12);
  textAlign(LEFT, CENTER);
  text(`Size: ${brushSize}  |  C: clear  |  +/-: resize  |  H: hue shift`, 10, height - 15);
}

function keyPressed() {
  if (key === 'c' || key === 'C') background(245);

  if (key === '=' || key === '+') brushSize = min(brushSize + 5, 80);
  if (key === '-')                brushSize = max(brushSize - 5, 2);

  if (key === 'h' || key === 'H') {
    let h = hue(brushColor);
    brushColor = color((h + 30) % 360, 80, 90);
  }
}

Preventing default browser behaviour

Some keys (space, arrow keys) scroll the browser page by default. To prevent this, return false from keyPressed():

function keyPressed() {
  if (keyCode === UP_ARROW || keyCode === DOWN_ARROW ||
      keyCode === LEFT_ARROW || keyCode === RIGHT_ARROW ||
      keyCode === 32) {  // space
    return false;  // prevent page scroll
  }
}

Key takeaways

  • key holds the last key as a string; keyCode holds its numeric code
  • keyIsPressed is true while any key is held — useful for continuous movement
  • keyPressed() fires once per keypress — good for toggles and one-off actions
  • Use named constants (UP_ARROW, ENTER, etc.) instead of raw numbers
  • Return false from keyPressed() to stop arrow keys and space from scrolling the page