Sebastian Haiduk
Sebastian Haiduk

Reputation: 13

How to draw pgraphics with different opacity out of an array?

i am trying to draw this 5 rectangles with an array but they have all the same opacity... But they should have different but i dont now why? Does someone can help me? Thank you in advance :) Sebastian

PGraphics[] pgArray = new PGraphics[5];

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

  for (int i = 0; i<pgArray.length; i++) {
    pgArray[i] = createGraphics(500, 500);
  }
}

void draw() {

  for (int i = 0; i < pgArray.length; i++) {
    pgArray[i].beginDraw();
    pgArray[i].fill(0, (255/pgArray.length)*i+1);
    pgArray[i].rect(20*i, 20*i, 50, 50);
    pgArray[i].endDraw();
  }

  for(int i = 0; i < pgArray.length; i++){
    image(pgArray[i],0,0);
  } 
}

Upvotes: 1

Views: 108

Answers (1)

micycle
micycle

Reputation: 3810

There are two problems: Your code does not clear the stage between frames and nor does it clear the PGraphics objects between frames. As opacity is additive, the rectangles would each reach full opacity within a few frames since you are drawing them on top of each other.

First, to refresh the background each frame:

  • Insert a call to background(255); at the top of the draw() loop.

Then, to clear the PGraphics objects you can either:

  • Move your rectangle drawing loop into setup(), so it runs once only.

Or

  • Insert a call to pgArray[i].clear(); after pgArray[i].beginDraw();.

Result:

enter image description here

Upvotes: 1

Related Questions