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.
Variable | p5.js 1.x | p5.js 2.x |
---|---|---|
key | Text string (e.g., "ArrowUp" ). | Text string (e.g., "ArrowUp" , "f" or "F" ). |
code | Not supported. | Text String (e.g., "ArrowUp" , "KeyF" ). |
keyCode | Number (e.g., 70 ). | Number (unchanged; e.g., 70 ). |
System variables (BACKSPACE , UP_ARROW , …) | Number | Text String (e.g., "ArrowUp" ). |
Ejemplos
Referencias Relacionadas
key
Una variable del sistema String que contiene el valor de la última tecla pulsada.
keyCode
Una variable de sistema Number que contiene el código de la última tecla presionada.
keyIsDown
Devuelve true si la tecla que se está comprobando está presionada y false si no lo está.
keyIsPressed
Una variable de sistema Boolean que es true si se está presionando alguna tecla y false si no se está presionando ninguna tecla.