这篇文章主要介绍了p5.js入门教程之鼠标交互的示例,现在分享给大家,也给大家做个参考。
本文介绍了p5.js入门教程之鼠标交互的示例,分享给大家,具体如下:
一、鼠标交互常用关键词
p5.js提供了许多鼠标操作用的关键词与函数,常用的有:
mouseispressed:关键词,若鼠标按下则为true,反之为false
mousebutton:关键词,用来判断鼠标按下的是哪个键
案例如下:
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);
}
}
当鼠标按下左、中、右键时,分别会在屏幕上显示“left”、“center”、“right"。
查看效果:
http://alpha.editor.p5js.org/full/bkecwrdub
二、鼠标交互常用函数
鼠标操作常用函数如下,还有:
mouseclicked():函数,鼠标点击时触发一次
mousepressed():函数,鼠标按下时触发一次
mousereleased():函数,鼠标松开时触发一次
我们可以用这些函数控制何时在屏幕上显示图形,案例如下:
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
三、鼠标拖拽物体
灵活运用以上关键字和函数,可以做出许多功能,这里举一例,用鼠标拖拽物体。
代码如下:
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);
}
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
关于vuejs中v-if和v-show的区别及v-show不起作用问题
利用console来debug的10个高级技巧汇总
深入理解node module模块
以上就是p5.js入门教程之鼠标交互的示例的详细内容。
