code

The code property represents a physical key on the keyboard (as opposed to the character generated by pressing the key). In other words, this property returns a value that isn't altered by keyboard layout or the state of the modifier keys.

This property is useful when you want to handle keys based on their physical positions on the input device rather than the characters associated with those keys;

Unlike key, the code property differentiates between physical keys that generate the same character—for example, CtrlLeft and CtrlRight—so each can be handled independently. Here's the MDN docs for KeyboardEvent.code

Pressing the key physically labeled “A” always yields KeyA, regardless of the current keyboard layout (QWERTY, Dvorak, AZERTY, etc.) or the character that appears in a text field.

The code property returns a plain string (e.g., 'ArrowRight'). You can compare it directly with string literals:

if (keyIsDown(RIGHT_ARROW)) {
  // …
}
// The line above is equivalent to:
if (code === 'ArrowRight') {
  // …
}
if (key  === 'ArrowRight') { 
// …
}

The system variables BACKSPACE, DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL, OPTION, ALT, UP_ARROW, DOWN_ARROW, LEFT_ARROW, and RIGHT_ARROW are all helpful shorthands the key codes of special keys. These are simply shorthands for the same string values:

if (code === RIGHT_ARROW) {
// ..
}

The table below summarizes how the main keyboard-related system variables changed between p5.js 1.x and 2.x.

Variablep5.js 1.xp5.js 2.x
keyText string (e.g., "ArrowUp").Text string (e.g., "ArrowUp", "f" or "F").
codeNot supported.Text String (e.g., "ArrowUp", "KeyF").
keyCodeNumber (e.g., 70).Number (unchanged; e.g., 70).
System variables (BACKSPACE, UP_ARROW, …)NumberText String (e.g., "ArrowUp").

Ejemplos

Notice any errors or typos? Please let us know. Please feel free to edit src/events/keyboard.js and open a pull request!

Referencias Relacionadas