clear

clear() is a p5.js function which when called, clears everything that is inside the canvas.

This function does not actually delete the elements. It clears them by making them transparent.

Example 

Here is an example code which clears the canvas every time the mouse is pressed : 

function setup() {
  createCanvas(windowWidth, windowHeight);
  // set background color in the setup so sketches will leave traces
  background('white');
}
function draw() {
  noStroke();
  fill(0, 0, 0, 30);
  // ellipse will change according to the mouseX and mouseY position
  ellipse(mouseX, mouseY, 30, 30);
}
// clear the canvas every time the user presses the mouse
function mousePressed() {
  clear();
}


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 ex923.js
  3. Open the file ex812.html in your editor and save it as ex923.html
  4. In the ex923.html file, update the link to ex923.js  from exersice812.js
  5. Go to the index.html file and create, under Module 9, a link to the ex923.html  file with the title "clear".

Modify the ex923.jsfile to create a drawing program which will be draw ellipses in the mouseX and mouseY position every time the user presses the mouse. Clear the sketch every time the user presses a key using the information from here. You can see here an example.

Answer:

function setup() {
  createCanvas(windowWidth, windowHeight);
  // set background color
  background('white');
}
function draw() {
   noStroke();
  fill(0, 0, 0, 30);
  if (mouseIsPressed) {
    // ellipse will be drawn to the mouseX and mouseY position
    ellipse(mouseX, mouseY, 30, 30);
  }
}
// clear the canvas every time the user presses a key
function keyPressed() {
  clear();
}

Do a Git commit with the message "clear".

  • See more about the clear() function