Clearing background on demand in Processing

In older versions of Processing, you could modify the canvas outside of the draw() function. In Processing 3 and above, this is no longer possible, due to a more logical and organized codebase. Therefore if you want to do something like clear the background when a serial event indicates a button was pressed, this no longer works:

 

void draw() {
   // your code...
}

void serialEvent() {
   // interpet serial data...
   // ...some code here to set buttonPressed variable...

   if (buttonPressed) {
      clearBackground();
   }
}

void clearBackground() {
   // erase screen with black
   background(0);
   // but this doesn't work outside of draw()!
}

 

So one way to fix it is to set a flag variable and check it inside draw, every loop. Whenever it is true, clear the background and reset the flag:

// flag variable to check when it's time to clear screen:
boolean clearBG = false;

void draw() {
   if (clearBG) {
      background(0);
      clearBG = false;
   }
   
   // your code...
}

void serialEvent() {
   // interpet serial data...
   // ...some code here to set buttonPressed variable...
   if (buttonPressed) {
      clearBG = true;
   }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: