Cyrill
Cyrill

Reputation: 833

PGraphics with background(); in Processing

I am trying to draw ellipses from an array list onto a PGraphics layer. This works so far. However, I need to give the PGraphics layer a white background. The moment I add the background, I can't add any more ellipses by mouse click. I have already tried to draw the ellipses without background on a PGraphics layer, and this again on a second PGraphics layer with background. But this still leads to the problem that the ellipses become pixelated as they are drawn over and over again. How can I make it so that the ellipses are gradually added from the array list to the one and only PGrpahics layer?

PGraphics pg;
ArrayList<Circle> circles;
void setup () {
  size(500, 500);
  circles = new ArrayList<Circle>();
  circles.add(new Circle());
  pg = createGraphics(width, height);
}

void draw() {
  background(255);
  image(pg, 0, 0);
  for (int i = circles.size()-1; i >= 0; i--) {
    Circle circle = circles.get(i);
    circle.display();
  }
}
void mousePressed() {
  circles.add(new Circle());
}

And this part… I commented the background function out…

  class Circle {
  int x = int(random(width));
  int y = int(random(height));
  int size;

  Circle() {
  }
  void display() {
    pg.beginDraw();
    //pg.background(255);
    pg.ellipse(x, y, 20, 20);
    pg.endDraw();
  }
}

Upvotes: 1

Views: 172

Answers (2)

Michael Zaminer
Michael Zaminer

Reputation: 1

Maybe try putting the background in the setup, so the background doesn't overwrite all the ellipses. Hope it works

Upvotes: 0

Cyrill
Cyrill

Reputation: 833

I think I found the solution. I found out that there are methods on my object that accepts a PGraphics as parameter:

PGraphics pg;
ArrayList<Circle> circles;
void setup () {
  size(500, 500);
  circles = new ArrayList<Circle>();
  circles.add(new Circle());

  pg = createGraphics(width, height);

}

void draw() {

  pg.beginDraw();
  pg.background(255);

  for (int i = circles.size()-1; i >= 0; i--) {
   
    Circle circle = circles.get(i);
    circle.display(pg);
  }
  pg.endDraw();
    //image(pg, 0, 0);
 
}
void mousePressed() {
  circles.add(new Circle());
}

class Circle {
  int x = mouseX;
  int y = mouseY;
  int size;

  Circle() {
  }
  void display(PGraphics pg) {

    pg.fill(0);
    pg.ellipse(x, y, 20, 20);

  }
}

Upvotes: 1

Related Questions