4

Using a javascript framework called p5, I'm trying to animate a circle that moves across the screen, however old frames don't delete, and this causes a line to show across the canvas.

var xPos = 0;

function setup() {
    createCanvas(400, 200)
    background(123);
}

function draw() {
    ellipse(xPos, height/2, 30, 30); //Draws the circle
    fill(255);
    xPos++; //Moves the circle a pixel over
    if(xPos > width){xPos = 0;} //resets the circle when it reaches the edge of the canvas
}
<script src="http://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.5/p5.js"></script>
Travis
  • 1,274
  • 1
  • 16
  • 33

1 Answers1

7

That's because you only call the background() function once, right at the beginning of the program.

Then every time the draw() function is called, you draw another circle- without clearing out any old frames.

If you want to clear out old frames every frame, call the background() function at the beginning of your draw() function.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
  • 1
    Fixed. Thanks so much, I got stuck here and can't believe I didn't think of that. – Travis Dec 26 '16 at 23:33
  • 1
    this also works if you misplace the image() method. If it's on setup(), you will have the same behavior. Thanks for this! – Octanic Jun 25 '20 at 18:42