Loading...
Logo
Processing Forum

clear image

in Programming Questions  •  1 year ago  
How can I continually clear the canvas?  I essentially want to make sure the entire screen is cleared at the end of each draw().  This is the code I have, which doesn't work.

Thanks!

Copy code
  1. void setup() {
  2.   size(200, 200);
  3. }

  4. void draw() {
  5.   fill(255);
  6.   ellipseMode(CENTER);
  7.   ellipse(width/2, height/2,width/2,height/2);
  8.   delay(1000);
  9.   
  10.   fill(0);
  11.   rect(0,0,width,height);
  12.   delay(1000);
  13. }

Replies(1)

Re: clear image

1 year ago
Call background( your_favorite_color ) as the very first line in draw function. It will clear the window with color provided and then you draw the rest on top of it.

BTW: I think your code could be written a little bit different:

Copy code
  1. void setup() {
  2.   size(200, 200);
  3.   smooth();           // just to make things look nice
  4.   frameRate( 1 );   // run the draw function once a second (frames per second or fps)
  5. }

  6. void draw() {
  7.   background( 90 );
  8.   if( frameCount % 2 == 0 ) {  // if it's even frame, draw the circle
  9.     fill(255);
  10.     ellipseMode(CENTER);
  11.     ellipse(width/2, height/2,width/2,height/2);
  12.   }
  13.   else {  // otherwise, draw the square
  14.     fill(0);
  15.     rect(0,0,width,height);
  16.   }
  17. }

This code make use of a few nice features:
  1. frameRate( fps ) is a function that sets the speed of animation, that is how often the draw function is run. it this case 1 time a second. the Processing default is 60.
  2. smooth() makes shapes look better using so called antialiasing
  3. instead of delays the function draw makes a decision what to draw based on wether the frame currently played is odd or even. the if statement reads the frameCount (i.e. number of animation frames from the begining of the program, i.e. the numer of times the draw function was executed) and makes a modulo division by 2. The modulo division gives you the remainder of the division of two numbers. So 1 % 2 == 1 (0, reminder 1), 2 % 2 == 0 (1, reminder 0), 3 % 2 == 1 (1, reminder 1) and so on. So the x % 2 == 0 means that the number x is even and x % 2 == 1 means it's odd. That's why the code inside if/else will run one after another.