一、鼠標(biāo)交互常用關(guān)鍵詞
p5.js提供了許多鼠標(biāo)操作用的關(guān)鍵詞與函數(shù),常用的有:
mouseIsPressed:關(guān)鍵詞,若鼠標(biāo)按下則為true,反之為false
mouseButton:關(guān)鍵詞,用來判斷鼠標(biāo)按下的是哪個鍵
案例如下:
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)按下左、中、右鍵時,分別會在屏幕上顯示“LEFT”、“CENTER”、“RIGHT"。
查看效果:
http://alpha.editor.p5js.org/full/BkEcwrdUb
二、鼠標(biāo)交互常用函數(shù)
鼠標(biāo)操作常用函數(shù)如下,還有:
mouseClicked():函數(shù),鼠標(biāo)點擊時觸發(fā)一次
mousePressed():函數(shù),鼠標(biāo)按下時觸發(fā)一次
mouseReleased():函數(shù),鼠標(biāo)松開時觸發(fā)一次
我們可以用這些函數(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; }
查看效果:http://alpha.editor.p5js.org/full/BkHEY8OUZ
三、鼠標(biāo)拖拽物體
靈活運用以上關(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); }
相信看了本文案例你已經(jīng)掌握了方法,更多精彩請關(guān)注Gxl網(wǎng)其它相關(guān)文章!
推薦閱讀:
vue+Echarts實現(xiàn)點擊高亮(附代碼)
echarts鼠標(biāo)覆蓋高亮顯示節(jié)點關(guān)系數(shù)實現(xiàn)步驟
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com