PApplet: Fill all but shape

edited February 2014 in How To...

Hey all,

This is more of a logical issue I'm having, but it pertains to the PApplet. Instead of drawing a simple shape, such as a rectangle or a polygon, and filling it, how would I fill the entire PApplet, except a simple shape. For example, fill the entire applet, and do not fill a shape in the applet.

Thanks for your help.

Tagged:

Answers

  • It depends on what you mean. If you just want to fill the background with one color and the shape with another (white for example), then you do just that: draw the background and then draw the shape.

    However, if you want to see previous drawings "through" the shape, then that's a little more involved. One way would be to create a "mask" image the same size as your PApplet that is white except where the shape is, which is black. Create another "buffer" image that you draw to. When you want to draw the background minus the shape, you have to go through the pixels on the mask image, find their positions, and get the corresponding pixels from your buffer image. Save those pixels, then draw the background in your buffer image, then draw those pixels back to your buffer image. In the draw() method, all you do is draw the buffer image to the PApplet.

    There might be a simpler way, but that's the first approach that occurred to me.

  • In addition to both solutions presented above, you could also use contours in a PShape.

    Code Example

    void setup() {
      size(800, 800, P2D);
    }
    
    void draw() {
      background(125);
      drawLines(10);
      createAndDrawCutoutShape(200);
    }
    
    void drawLines(int numLines) {
      noStroke();
      fill(255);
      float w = (float) width / numLines;
      for (int i=-1; i<numLines; i++) {
        rect(w*i + (frameCount % w), 0, 20, height);
      }
    }
    
    void createAndDrawCutoutShape(float dim) {
      PShape s = createShape();
      s.beginShape();
      s.stroke(0);
      s.strokeWeight(2);
      s.fill(255);
      s.vertex(0, 0);
      s.vertex(width, 0);
      s.vertex(width, height);
      s.vertex(0, height);
      s.beginContour();
      s.vertex(mouseX-dim, mouseY-dim);
      s.vertex(mouseX+dim, mouseY-dim);
      s.vertex(mouseX+dim, mouseY+dim);
      s.vertex(mouseX-dim, mouseY+dim);
      s.endContour();
      s.endShape(CLOSE);
      shape(s);
    }
    
  • edited February 2014

    [Removed after edit]

Sign In or Register to comment.