Search code examples
javascriptcanvasprocessingp5.js

P5.js does not clear the canvas automatically


In P5.js, Somehow, when I'm drawing any shape and moving it, the shape leaves sort of like a trail.

Tried with an ellipseenter image description here

Testing code:

function draw() {
    if (times < 100) {
        fill(255);
        ellipse(times, times, 10, 10);
        times++
    }
}

I tried adding erase() and it does seem to do the trick coupled with re-rendering the background, but it would clear the canvas at each frame which is not what I want.


Solution

  • You need to call background() to clear the canvas. background() fills the entire canvas with the specified color.

    For instance:

    function draw() {
        if (times < 100) {
    
            background(255, 255, 255);
    
            fill(255);
            ellipse(times, times, 10, 10);
            times++
        }
    }