The key variable in p5.js always contains the value of the key which is recently pressed. To get the proper capitalisation, it is best to use it within keyTyped(). Use the keyCode variable For non-ASCII keys.
Syntax:
key
Below program illustrates the key variable in p5.js:
Example-1:
let valueX;
let valueY;
function setup() {
createCanvas(1000, 500);
}
function draw() {
background(200);
fill( 'green' );
textSize(25);
text(
'Press Any Key to change the text within circle'
, 30, 30);
if (keyIsPressed) {
ellipse(mouseX, mouseY, 115, 115);
fill( 'red' );
text( "Key Is Pressed" , 100, 300);
textSize(100);
text(key, mouseX, mouseY);
}
else {
rect(mouseX / 2, mouseY / 2, 300, 200);
text(key, mouseX, mouseY);
}
}
|
Output:

Example-2:
let valueX;
let valueY;
function setup() {
createCanvas(500, 500);
}
function draw() {
background(200);
fill( 'green' );
textSize(100);
text(key, height / 2, width / 2);
if (keyIsPressed) {
textSize(40);
text( "is pressed" , height / 7, width - 50);
}
}
|
Output:

Reference: https://p5js.org/reference/#/p5/key
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
18 Aug, 2023
Like Article
Save Article