Change Opacity in HSB Colormode

2.3k views Asked by At

I am trying to change the opacity of my strokes, but not sure how do it in HSB color mode. Or, if I switch to RGB mode how do I make the color change over time?

Here is my code: (Any help would be appreciated)

float rainbow=0;
int dir=1;

void setup() {
  size(600, 600);
  background(0);
  colorMode(HSB, 255);
 } 

void draw() {
  if ( rainbow < 255 && dir==1) {
     rainbow++;
  }

  if ( rainbow > 0 && dir==-1) {
    rainbow--;
  }

  if ( rainbow == 255) {
    dir*= -1;
  }

  if ( rainbow == 0) {
    dir*= -1;
  }

  stroke(rainbow, 255, 200);
  line(mouseX,mouseY,width/2,height/2); 

  if (mousePressed){
  stroke(rainbow, 255, 200);
  line(mouseX,mouseY,0,mouseX);
  }

  if (mousePressed){
  stroke(rainbow, 100, 200);
  line(mouseX,mouseY,600,mouseX);
  }
}
1

There are 1 answers

1
Kevin Workman On BEST ANSWER

You can give the stroke() or fill() functions a fourth parameter for the opacity. Here's an example:

void setup(){
  size(500, 500);
  colorMode(HSB, 255);
  background(255);
}

void draw(){
  fill(0, 255, 200, 100);
  ellipse(mouseX, mouseY, 20, 20);
}

Note that you can also use RGB mode and modify the R, G, and B arguments over time as well. This is going to be a little more complicated than cycling through HSB values, but you can create any pattern you want. Here's an example:

float r = 0;
float g = 0;
float b = 0;

float deltaR = 1;
float deltaG = 2;
float deltaB = 4;

void setup(){
  size(500, 500);
  background(255);
}

void draw(){
  
  r += deltaR;
  g += deltaG;
  b += deltaB;
  
  if(r < 0 || r > 255){
    deltaR *= -1;
    r = constrain(r, 0, 255);
  }
  
  if(g < 0 || g > 255){
   deltaG *= -1;
   g = constrain(g, 0, 255);
  }
  
  if(b < 0 || b > 255){
    deltaB *= -1;
    b = constrain(b, 0, 255);
  }
  
  fill(r, g, b);
  ellipse(mouseX, mouseY, 20, 20);
}