Submodule 17.1: Events
mouseIsPressed
mouseIsPressed
is a boolean variable which changes from false to true when the mouse is pressed.
This variable stays true as long as the mouse is pressed, and when it is released it changes back to false.
Example
Here is an example code which draws an ellipse in the position where the mouse is pointing, as long as the mouse is pressed:
function setup() {
createCanvas(800, 500);
}
function draw() {
// set background inside draw so that the ellipse will not leave traces
background('#D66761');
fill(241, 213, 145);
// if the mouse is pressed
if (mouseIsPressed){
// an ellipse will be drawn in the position where the mouse is pointing
ellipse(mouseX, mouseY, 50);
}
}
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 asex914.js
- Open the file
ex812.html
in your editor and save it asex914.html
- In the
ex914.html
file, update the link toex914.js
from exersice812.js - Go to the
index.html
file and create, underModule 9
, alink
to theex914.html
file with the title "mouseIsPressed".
Modify the ex914.js
file to create a drawing tool which will be drawing ellipses as long as the mouse is pressed. Also, include two other ellipses, a red and a green one. Make the drawing tool change the color of the ellipses it is drawing to red, if the user clicks inside the red ellipse and to green if the user clicks inside the green ellipse. You can see here an example.
let mycolor = 'white';
function setup() {
createCanvas(800, 500);
background('#D66761');
}
function draw() {
// this color will change every time the mouse clikcs the red or green ellipse
fill(mycolor);
// if the mouse is pressed
if (mouseIsPressed){
// an ellipse will be drawn in the position where the mouse is pointing
ellipse(mouseX, mouseY, 20);
}
fill ('red');
ellipse (600,250,50);
fill('green');
ellipse (600,350,50);
}
// everytime the mouse is clicked
function mouseClicked(){
// if the mouse x and y position is inside the red ellipse
if (mouseX >=550 && mouseX <=650 && mouseY >=200 && mouseY <=300){
//change its color to red
mycolor = 'red';
}
// if the mouse x and y position is inside the green ellipse
if (mouseX >=550 && mouseX <=650 && mouseY >=300 && mouseY <=400){
//change its color to green
mycolor = 'green';
}
}
Do a Git commit with the message "mouseIsPressed".
- See more about the mouseIsPressed event