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

  1. Open your Visual Studio editor and the p5yourName folder.
  2. Open the file ex812.js in your editor and save it as ex914.js
  3. Open the file ex812.html in your editor and save it as ex914.html
  4. In the ex914.html file, update the link to ex914.js  from exersice812.js
  5. Go to the index.html file and create, under Module 9, a link to the ex914.html  file with the title "mouseIsPressed".

Modify the ex914.jsfile 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.

Answer:

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".