Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptp5.js Keyboard keyIsPressed

p5.js Keyboard keyIsPressed

The keyIsPressed variable in p5.js is true if any key is pressed and false if no keys are pressed

Syntax:

keyIsPressed

The below program illustrates the key is pressed variable in p5.js.

Example-1: 

javascript




let valueX;
let valueY;
  
function setup() {
    // Create Canvas of size 500*500
    createCanvas(1000, 500);
}
  
function draw() {
    
    // set background color
    background(200);
    fill('green');
    
    // set text and text size
    textSize(25);
    
    text('Press Key to change the figure '+
         'from Circle To Keyboard', 30, 30);
    
    // use of keyIsPressed Variable
    if (keyIsPressed) {
        // draw ellipse  
        ellipse(mouseX, mouseY, 115, 115);
        fill('red');
        text("Key Is Pressed", 100, 300);
    } else {
        rect(mouseX / 2, mouseY / 2, 300, 200);
    }
  
};


Output: 

Before: 

After: 

 Example-2: 

javascript




let valueX;
let valueY;
  
function setup() {
    
    // Create Canvas of size 500*500
    createCanvas(500, 500);
}
  
function draw() {
    
    // set background color
    background(200);
    
    fill('green');
    
    // set text and text size
    textSize(25);
    text('Click to flip the figure', 30, 30);
    
    // use of KeyIsPressed
    if (keyIsPressed) {
        fill(valueX, 255 - valueY, 255 - valueX);
        
        // draw rectangle 
        rect(mouseX, mouseY, 115, 115);
        fill(valueY, 255 - valueX, 255 - valueX);
  
        rect(mouseX, mouseY + 115, 115, 115);
        fill(255 - valueY, 255 - valueX, 255 - valueY);
    } else {
        rect(mouseX - 115, mouseY, 115, 115);
        fill(255 - valueY, 255 - valueY, 255 - valueY);
  
        rect(mouseX - 115, mouseY + 115, 115, 115);
    }
};


Output: Before: 

 After: 

Reference: https://p5js.org/reference/#/p5/keyIsPressed

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen 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!

RELATED ARTICLES

Most Popular

Recent Comments