Home >Web Front-end >JS Tutorial >How to implement and use p5.js mouse interaction
This time I will show you how to implement and use p5.js mouse interaction. What are the precautions for implementing and using p5.js mouse interaction. Here are practical cases, let’s take a look.
1. Commonly used keywords for mouse interaction
p5.js provides many keywords and functions for mouse operations. Commonly used keywords are:
mouseIsPressed: Keyword, if the mouse is pressed, it is true, otherwise it is false
mouseButton: Keyword, used to determine which key is pressed by the mouse
Case As follows:
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); } }
When the left, middle, and right buttons of the mouse are pressed, "LEFT", "CENTER", and "RIGHT" will be displayed on the screen respectively.
View the effect:
http://alpha.editor.p5js.org/full/BkEcwrdUb
##2. Mouse interactionCommonly used Function
Commonly used functions for mouse operations are as follows, as well as: mouseClicked(): function, which is triggered once when the mouse is clickedmousePressed(): function , triggered once when the mouse is pressed
mouseReleased(): function, triggered once when the mouse is released
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; }View the effect: http://alpha.editor.p5js.org/full/BkHEY8OUZ
3. Mouse dragging objects
Flexible use of the above keywords and functions can create many functions. Here is an example of dragging objects with the mouse. The code is as follows: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); }I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! Recommended reading:
vue Echarts implements click highlighting (with code)
echarts mouse overlay highlights nodes Steps to implement relational numbers
The above is the detailed content of How to implement and use p5.js mouse interaction. For more information, please follow other related articles on the PHP Chinese website!