一、鼠標(biāo)交互常用關(guān)鍵詞
p5.js提供了許多鼠標(biāo)操作用的關(guān)鍵詞與函數(shù),常用的有:
mouseIsPressed:關(guān)鍵詞,若鼠標(biāo)按下則為true,反之為false
mouseButton:關(guān)鍵詞,用來判斷鼠標(biāo)按下的是哪個(gè)鍵
案例如下:
function setup() { createCanvas(400, 400); } function draw() { background(220); if (mouseIsPressed) { textAlign(CENTER); textSize(30); if (mouseButton == LEFT) text("LEFT",200,height/2); if (mouseButton == RIGHT) text("RIGHT",200,height/2); if (mouseButton == CENTER) text("CENTER",200,height/2); } }
當(dāng)鼠標(biāo)按下左、中、右鍵時(shí),分別會(huì)在屏幕上顯示“LEFT”、“CENTER”、“RIGHT"。
二、鼠標(biāo)交互常用函數(shù)
鼠標(biāo)操作常用函數(shù)如下,還有:
mouseClicked():函數(shù),鼠標(biāo)點(diǎn)擊時(shí)觸發(fā)一次
mousePressed():函數(shù),鼠標(biāo)按下時(shí)觸發(fā)一次
mouseReleased():函數(shù),鼠標(biāo)松開時(shí)觸發(fā)一次
我們可以用這些函數(shù)控制何時(shí)在屏幕上顯示圖形,案例如下:
var showEllipse=false; var showRect=false; function setup() { createCanvas(400, 400); } function draw() { background(220); if (mouseIsPressed){ ellipse(50, height/2, 50, 50); } if(showEllipse){ ellipse(200, height/2, 50, 50); } if(showRect){ rectMode(CENTER); rect(350,height/2,50,50); } } function mouseClicked(){ showEllipse=!showEllipse; } function mousePressed(){ showRect=true; } function mouseReleased(){ showRect=false; }
三、鼠標(biāo)拖拽物體
靈活運(yùn)用以上關(guān)鍵字和函數(shù),可以做出許多功能,這里舉一例,用鼠標(biāo)拖拽物體。
代碼如下:
var x=200; var y=200 var r=50; function setup() { createCanvas(400, 400); } function draw() { background(220); if(mouseIsPressed&&dist(mouseX,mouseY,x,y)<r){ x=mouseX; y=mouseY; } ellipse(x,y,r,r); }
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com