當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


p5.js keyPressed()用法及代碼示例

每當按鍵時,都會調用keyPressed()函數。最新輸入的ASCII key 存儲在“ key”變量中,但是不能區分大小寫字符。非ASCII字符代碼及其相應名稱可以在“ keyCode”變量中訪問。

按住一個鍵可能會導致多個keyPressed()調用。這是由於操作係統如何處理按鍵並取決於計算機的配置方式。瀏覽器可能將自己的默認行為附加到各種鍵上。可以通過在方法末尾添加“return false”來防止這種情況。

用法:



keyPressed()

參數:此方法不接受任何參數。

以下示例說明了p5.js中的keyPressed()函數:

範例1:

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); 
}

輸出:
display-pressed

範例2:

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); 
}

輸出:
change-opacity

在線編輯: https://editor.p5js.org/

環境設置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/

參考: https://p5js.org/reference/#/p5/keyPressed




相關用法


注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 p5.js | keyPressed() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。