Interaction: Keyboard

Use keyboard input to move and transform graphics.

Example 1: Arrow + WASD Move

Code

let px = 200;
let py = 200;
const speed = 3;

function setup() {
  createCanvas(400, 400);
  rectMode(CENTER);
}

function draw() {
  background(248);

  if (keyIsDown(LEFT_ARROW) || keyIsDown(65)) px -= speed;
  if (keyIsDown(RIGHT_ARROW) || keyIsDown(68)) px += speed;
  if (keyIsDown(UP_ARROW) || keyIsDown(87)) py -= speed;
  if (keyIsDown(DOWN_ARROW) || keyIsDown(83)) py += speed;

  px = constrain(px, 20, width - 20);
  py = constrain(py, 20, height - 20);

  fill(255, 50, 140);
  noStroke();
  rect(px, py, 40, 40, 8);
}

Try this: Clamp movement to the canvas edges.

Open sketch in new tab

Example 2: Key Trail

Code

let marks = [];

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

function draw() {
  background(255, 255, 255, 30);
  noStroke();
  for (let i = marks.length - 1; i >= 0; i--) {
    const m = marks[i];
    fill(255, 45, 140, m.life);
    circle(m.x, m.y, m.size);
    m.life -= 4;
    if (m.life <= 0) marks.splice(i, 1);
  }
}

function keyPressed() {
  marks.push({
    x: random(width),
    y: random(height),
    size: map(keyCode, 32, 126, 10, 80, true),
    life: 255
  });
}

Try this: Map different keys to different shapes instead of circles.

Open sketch in new tab

Resources