mouseClicked()

Η συνάρτηση  mouseClicked() καλείται κάθε φορά που γίνεται κλικ στο αριστερό πλήκτρο του ποντικιού.

Στον κώδικα μας, τοποθετούμε αυτή τη λειτουργία εκτός της draw().

Η σύνταξη είναι:

 function mouseClicked(){
//your code
}

Παράδειγμα
Εδώ είναι ένα παράδειγμα κώδικα που θα σχεδιαστεί έλλειψη στη θέση όπου δείχνουμε το ποντίκι μας, κάθε φορά που κάνουμε κλικ στο αριστερό πλήκτρο του ποντικιού:

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;
}

Μπορείτε να δείτε το αποτέλεσμα του παραπάνω κώδικα, 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';
  }
}

Κάντε μια  Git commit με το μήνυμα  "mouseClicked() ".

  • Δείτε περισσότερα για τη mouseClicked() function