redraw

redraw() is a p5.js function which makes the code inside draw() function to be executed only one time when necessary.

This function is used inside events.

Example 

Here is an example code which makes the ellipse moving every time the user presses the mouse: 

// 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();
 }

You can see the result of the above code 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();
 }

Do a Git commit with the message "redraw".