📜  p5.js | keyPressed()函数

📅  最后修改于: 2022-05-13 01:56:27.469000             🧑  作者: Mango

p5.js | keyPressed()函数

每当按下某个键时,都会调用keyPressed()函数。最近键入的 ASCII 密钥存储在 'key' 变量中,但它不区分大小写字符。可以在“keyCode”变量中使用它们各自的名称访问非 ASCII字符代码。
按住一个键可能会导致多次 keyPressed() 调用。这是由于操作系统如何处理按键并取决于计算机的配置方式。浏览器可能有自己的默认行为附加到各种键。这可以通过在方法末尾添加“return false”来防止。
句法:

keyPressed()

参数:此方法不接受任何参数。
以下示例说明了 p5.js 中的keyPressed()函数
示例 1:

javascript
function setup() {
  createCanvas(600, 200);
  textSize(20);
  text("Press any key to display it "
          + "on the screen", 10, 20);
}
 
function keyPressed() {
  clear();
  textSize(20);
  text("Press any key to display it "
          + "on the screen", 10, 20);
  textSize(100);
  text(key, 100, 150);
}


javascript
let opac = 128;
 
function setup() {
  createCanvas(700, 200);
  background(0, 128, 0, opac);
  textSize(22);
  text("Press the left and right arrow"
        + " keys to change the opacity"
        + " of the color.", 10, 20);
}
 
function keyPressed() {
  clear();
 
  textSize(50);
  text("Pressing: " + key, 100, 150);
 
  // Reduce opacity if the left arrow is pressed
  if (key == "ArrowLeft" && opac > 0)
    opac -= 20;
  // Increase opacity if the left arrow is pressed
  else if (key == "ArrowRight" && opac < 255)
    opac += 20;
 
  // Set the new background color
  background(0, 128, 0, opac);
 
  textSize(22);
  text("Press the left and right arrow"
        + " keys to change the opacity"
        + " of the color.", 10, 20);
}


输出:

显示按下

示例 2:

javascript

let opac = 128;
 
function setup() {
  createCanvas(700, 200);
  background(0, 128, 0, opac);
  textSize(22);
  text("Press the left and right arrow"
        + " keys to change the opacity"
        + " of the color.", 10, 20);
}
 
function keyPressed() {
  clear();
 
  textSize(50);
  text("Pressing: " + key, 100, 150);
 
  // Reduce opacity if the left arrow is pressed
  if (key == "ArrowLeft" && opac > 0)
    opac -= 20;
  // Increase opacity if the left arrow is pressed
  else if (key == "ArrowRight" && opac < 255)
    opac += 20;
 
  // Set the new background color
  background(0, 128, 0, opac);
 
  textSize(22);
  text("Press the left and right arrow"
        + " keys to change the opacity"
        + " of the color.", 10, 20);
}

输出:

改变不透明度

在线编辑器: https://editor.p5js.org/
环境设置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
参考: https://p5js.org/reference/#/p5/keyPressed