Book
Submodule 17.1: Events
Submodule 17.1: Events
Completion requirements
View
- Introduction to p5.js events
- mouseX and mouseY
- mouseClicked()
- mouseIsPressed
mouseClicked()
The mouseClicked()
function is called everytime the left mouse button is clicked.
In our code, we place this function outside the draw().
The syntax is:
function mouseClicked(){
//your code
}
Example
Here is an example code which will be drawn an ellipse in the position where we point our mouse, everytime we click the left mouse button:
let xPos, yPos;
function setup() {
createCanvas(800, 500);
// set background color
background('#D66761');
}
function draw() {
fill(241, 213, 145);
// an ellipse will be drawn everytime the xPos, yPos are defined
ellipse(xPos, yPos, 50);
}
// everytime the mouse is clicked
function mouseClicked(){
// the x position will take the value of the horizontal mouse position
xPos=mouseX;
// the y position will take the value of the vertical mouse position
yPos = mouseY;
}
You can see the result of the above code, click here.
Exercise
- Open your Visual Studio editor and the
p5yourName
folder. - Open the file
ex812.js
in your editor and save it asex913.js
- Open the file
ex812.html
in your editor and save it asex913.html
- In the
ex913.html
file, update the link toex913.js
from exersice812.js - Go to the
index.html
file and create, underModule 9
, alink
to theex913.html
file with the title "mouseClicked()".
Modify the ex913.js
file to create an ellipse which will change its color from white to red, everytime the user clicks inside it.If the user clicks outside the ellipse, change its color back to white. You can see here an example.
let i = 'white';
function setup() {
createCanvas(800, 500);
// set background color
background('#D66761');
}
function draw() {
fill(i);
// create an ellipse
ellipse(400, 250, 50);
}
// everytime the mouse is clicked
function mouseClicked(){
// if the mouse x and y position is inside the ellipse
if (mouseX >=350 && mouseX <=450 && mouseY >=200 && mouseY <=300){
//change its color to red
i = 'red';
}
// else change the color to white
else {
i = 'white';
}
}
Do a Git commit with the message "mouseClicked() ".
- See more about the mouseClicked() function