Icy4614 Icy4614 - 3 years ago 112
Java Question

What's the best way to implement a color cycling background?

What's the best way to cycle the color of a background smoothly (as well as other things) using cos or sin in java, without using more than one file? I've tried using randomness and increasing each individual r, g, and b value separately to make this look kind of normal, but it's jittery, not smooth, and the colors are horrid. Right now, it's just plain white. I included only the necessary code, and I am using Processing 3.

int bg1 = 255; //r
int bg2 = 255; //g
int bg3 = 255; //b

void draw() {

Answer Source

You've got the general idea down. It's a three-step process:

  • Step 1: Declare variables at the top of your sketch.
  • Step 2: Use those variables to draw your scene.
  • Step 3: Change those variables over time.

This is the basic approach to create any animation in Processing. Here is a tutorial with more information.

Here is a small example that shows a window that cycles between white and black:

float c = 0;

float cChange = 1;

void draw(){


  c += cChange;
  if(c < 0 || c > 255){
    cChange *= -1;

You would need to do something similar, but with 3 color values instead of 1. Note that I'm only changing the color by a small amount each time, which makes it appear smooth instead of jittery.

If you're still having trouble, please post an updated MCVE in a new question and we'll go from there. Good luck.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download