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


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


鼠標單擊文檔時,p5.js中的mousePressed()函數起作用。 mouseButton變量用於指定按下哪個按鈕。如果未定義mousePressed()函數,則使用touchStarted()函數代替mousePressed()函數。

用法:

mousePressed(Event)

以下程序說明了p5.js中的mousePressed()函數:


範例1:本示例使用mousePressed()函數。

function setup() { 
      
    // Create Canvas 
    createCanvas(500, 500); 
} 
   
let value = 0; 
  
function draw() { 
      
    // Set background color 
    background(200); 
      
    // Fill the color 
    fill(value, value-50, value-100); 
      
    // Create rectangle 
    rect(25, 25, 460, 440); 
      
    // Set the color of text 
    fill('lightgreen'); 
      
    // Set font size 
    textSize(15); 
      
    // Display content 
    text('Keep on Clicking the Mouse Across'
        + 'the page \nto change Canvas Color.', 
            windowHeight/10, windowWidth/4); 
} 
  
function mousePressed() { 
      
    value = value + 5; 
      
    if (value > 255) { 
        value = 0; 
    } 
}

輸出:

範例2:

let valueX; 
let valueY; 
  
function setup() { 
    
    // Create Canvas 
    createCanvas(500, 500); 
} 
   
function draw() { 
      
    // Set background color 
    background(200);  
      
    // Set the text color 
    fill('green'); 
      
    // Set text size 
    textSize(25); 
      
    text('Drag mouse to change color', 30, 30); 
      
    // Fill color according to mouseMoved()  
    fill(valueX, 255-valueY, 255-valueX); 
      
    // Draw ellipse   
    ellipse(mouseX, mouseY, 115, 115); 
} 
  
function mousePressed() { 
    valueX = mouseX%255; 
    valueY = mouseY%255; 
}

輸出:

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



相關用法


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