background() alpha in PGraphics

edited June 2015 in How To...

Hey everybody. I ran into an strange issue when using transparency in a PGraphics element, and I'd like to understand if it's a bug or a design decision. According to the docs:

Unlike the main drawing surface which is completely opaque, surfaces created with createGraphics() can have transparency. This makes it possible to draw into a graphics and maintain the alpha channel.

So, from my understanding, if I draw something into a PGraphics, then give it a background i.e. background(255, 30);, it should still show the drawing from the previous frame, which would slowly disappear as the background gets repainted every frame, correct? But when I tried, what happend is that setting a background behaves like calling clear() and then setting the background color. The following code illustrates this behaviour:

PGraphics canvas;

void setup() 
  size(512, 512);

  canvas = createGraphics(512, 512);


void draw()
  //canvas.background(255, 10);  // this clears the PGraphics, and then sets the semitransparent background

  canvas.ellipse(mouseX, mouseY, 10, 10);

  image(canvas, 0, 0);

I can only see my fading trail if I comment the first statement on the draw() method, not painting the main background, but it may not always be desired. I also can work around this issue by drawing a semitransparent rectangle over the PGraphics instead of calling the background(), but it doesn't seem to me that it should be necessary. So, is this the expected behaviour and I missed something from the docs, or is it a bug?

Thanks in advance.


  • edited June 2015 Answer ✓

    AFAIK, both background() & set() modify the canvas w/o taking into consideration what was there before.
    Although I thought the same as you that background() applied over a PGraphics instead of the main canvas would end up respecting its alpha property.
    Seems like rect(0, 0, width, height) is the only option left then... 8-X

  • Thanks @GoToLoop. Good to know it wasn't my fault! :) Do you think it would be worth to mention it as an issue over at github to be discussed wether it should behave differently on the PGraphics?

  • Good idea requesting a diff. background()'s behavior for PGraphics.
    Although chances are slim... [-O<

Sign In or Register to comment.