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

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

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

Answer:

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