Keyboard interaction allows users to manipulate or control the application using their keyboard. p5.js has built-in functions that allow for such interactions.
p5.js has a built-in keyPressed()
function, which is called whenever any keyboard key is pressed. We can then access the global key
variable, which stores which key is pressed.
In this example, we can see a dash in the output. To interact with it, click on the screen and press any key. The pressed key will show up on the output.
Lines 1–6: The setup()
function is called once before the application runs. This function sets up the application canvas with the size and the text properties such as size and alignment.
Lines 8–14: The showKey
variable stores which key we are displaying at the moment. The draw()
function is called once every frame. In this function the background is being reset, and the text is being displayed.
From lines 16–20: The keyPressed()
function is called once whenever any key is pressed. In this function, the showKey
variable is updated.
In this example, we can see an ellipse in the output. To interact with it, click on the screen and use "a" and "d" to move left and right, and use "w" and "s" for vertical movement.
Lines 1–7: The code begins by declaring several variables:
x
and y
: These variables store the current position of the circle on the canvas.
moveSpeed
: This variable defines the rate at which the circle moves.
movementInterval
: This variable will store the interval ID for the movement timer.
isMovingLeft
, isMovingRight
, isMovingUp
and isMovingDown
: These boolean variables track whether the respective movement key (arrow keys or WASD keys) is currently being held down.
Lines 9–13: In the setup()
function, The x
and y
variables are set to the center of the screen.
Lines 15–32: In the draw()
function, the circle is filled with a pink color using fill()
and then displayed using ellipse()
.
Lines 34–62: In the keyPressed()
function, the position x
and y
of the circle are updated, depending on what key is pressed. For example, if the key "a" or "ArrowLeft" is pressed, move the circle left.
Lines 34–62: The keyReleased()
function is triggered when a key is released. It clears the movement interval using clearInterval
to stop the continuous movement. Also, it sets all the boolean variables (isMovingLeft
, isMovingRight
, isMovingUp
, isMovingDown
) to false
, indicating that the respective movement key is no longer being held down.
p5.js allows it's users to make creative coding applications in a simple manner. Adding keyboard input to a p5.js application is intuitive and easy to implement.
Free Resources