Open In App

p5.js erase() Function

The erase() function in p5.js is used to subtract all the drawings that would be done after the use of this function. The subtracted drawing area would reveal the webpage below the canvas. The effect of this function can be canceled by using the noErase() function.

It does not affect the drawings done by the image() and background() functions.



Syntax:

erase( [strengthFill], [strengthStroke] )

Parameters: This function accept two parameters as mentioned above and described below.



Below examples illustrate the erase() function in p5.js:

Example 1:




function setup() {
  createCanvas(600, 400);
  textSize(20);
  
  fill('black');
  text("Move the slider below to change fill strength", 20, 30);
  
  fillStrengthSlider = createSlider(0, 255, 128, 1);
  fillStrengthSlider.position(30, 50);
  
  text("Move the slider below to change stroke strength", 20, 100);
  
  strokeStrengthSlider = createSlider(0, 255, 128, 1);
  strokeStrengthSlider.position(30, 120);
}
  
function draw() {
  fill('red');
  rect(50, 200, 200, 200);
  
  erase(fillStrengthSlider.value(), strokeStrengthSlider.value());
  circle(100, 300, 200);
  noErase();
  
}

Output:

Example 2:




let eraseEnable = false;
  
function setup() {
  createCanvas(600, 400);
  textSize(20);
  
  fill('black');
  text("Click the button to see the effects of"
         + " the erase() function", 20, 30);
  
  toggleBtn = createButton("Toggle erase");
  toggleBtn.position(30, 60);
  toggleBtn.mouseClicked(toggleErase);
}
  
function toggleErase() {
  if (eraseEnable) {
    noErase();
    eraseEnable = false;
  }
  else {
    erase();
    eraseEnable = true;
  }
}
  
function mouseMoved() {
  fill('red');
  noStroke();
  circle(mouseX, mouseY, 50);
}

Output:

Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/amp/

Reference: https://p5js.org/reference/#/p5/erase


Article Tags :