Συνάρτηση redraw

Η redraw() ίναι μια συνάρτηση p5.js, η οποία καθιστά τον κώδικα εντός της  draw() function να εκτελείται μόνο μία φορά όταν είναι απαραίτητο

Αυτή η συνάρτηση χρησιμοποιείται μέσα στα γεγονότα - events.

Example 

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

// create a variable to control the direction of the ellipse
let control = false;
// make ellipse starting from the left end of the canvas
let i=30;
function setup() {
  // create canvas
  createCanvas(800,500);
  noLoop();
}
function draw () {
  // set background color
  background('#31bc33');
  // when ellipse is in the left edge, control would be/become false
  if (i==30) {
    control = false;
  }
  ellipse(i,height/2,60);
}
function mousePressed() {
  if (i<(width-30) && control==false){
    i=i+20;
  }
  else {
    // else control will change to true
    control = true;
    // decrease its x position (ellipse moves in the left direction)
    i=i-20;
  }
  // use redraw to update the position of ellipse
   redraw();
 }

Μπορείτε να δείτε το αποτέλεσμα του παραπάνω κώδικα 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 ex922.js
  3. Open the file ex812.html in your editor and save it as ex922.html
  4. In the ex922.html file, update the link to ex922.js  from exersice812.js
  5. Go to the index.html file and create, under Module 9, a link to the ex922.html  file with the title "redraw".

Modify the ex922.jsfile to use redraw() to create an ellipse which will change its size every time the mouse is pressed. The size of the ellipse should not exceed the canvas height. When it reaches the maximum point it should start decreasing its size until it reaches 30 px. You can see here an example.

Answer:

// create a variable to control the size of the ellipse
let control = false;
// make ellipse starting from the left end of the canvas
let i=30;
function setup() {
  // create canvas
  createCanvas(800,500);
  noLoop();
}
function draw () {
  // set background color
  background('#31bc33');
  // when ellipse is 30px change the control to false
  if (i==30) {
    control = false;
  }
  ellipse(width/2,height/2,i);
}
function mousePressed() {
  // if the ellipse size do no exceed the canvas height
  if (i<(height-30) && control ==false){
    // increase the size of the ellipse
    i=i+20;
  }
  else {
    // else control will change to true
    control = true;
    // decrease the size of the ellipse
    i=i-20;
  }
  // use redraw to update the size of ellipse
   redraw();
 }

Κάντε μια  Git commit με το μήνυμα "redraw".

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