Hello Processing Community,
I’ve encountered a challenging issue while working with the P2D renderer in Processing, specifically when trying to layer semi-transparent shapes over a white background. The expected result is a lighter color where the semi-transparent shape overlays the background. However, the actual result is a greyish shape, suggesting an issue with how alpha blending is being handled in P2D (probably related to pre-multiplication?)
Here’s the minimal code that reproduces the problem:
PGraphics backgroundLayer;
PGraphics shapeLayer;
void setup() {
size(400, 400, P2D);
// Initialize the background layer with white opaque background
backgroundLayer = createGraphics(width, height, P2D);
backgroundLayer.beginDraw();
backgroundLayer.background(255);
backgroundLayer.endDraw();
// Initialize the shape layer with a transparent background
shapeLayer = createGraphics(width, height, P2D);
shapeLayer.beginDraw();
shapeLayer.clear();
shapeLayer.endDraw();
}
void draw() {
// Draw a semi-transparent rectangle on the shape layer
shapeLayer.beginDraw();
shapeLayer.clear(); // Clear previous frame
shapeLayer.fill(255, 127); // Set color to white with half opacity
shapeLayer.noStroke();
shapeLayer.rectMode(CENTER);
shapeLayer.rect(width/2, height/2, width/2, height/2);
shapeLayer.endDraw();
// Draw the background layer
image(backgroundLayer, 0, 0);
// Set the blend mode for drawing the shape layer
blendMode(BLEND);
// Draw the shape layer
image(shapeLayer, 0, 0);
}
Here are the steps and attempts I have made to resolve this issue:
- Explicitly setting the blend mode to
BLEND
before drawing the shape layer. - Clearing the shape layer with
clear()
to ensure no residual pixels from the previous frame. - Using the default renderer, which resolved the issue but is not compatible with the Syphon library that I intend to use.
The goal is to work with the Syphon library, which requires P2D, and thus finding a solution with P2D is imperative.
I’m reaching out for help to understand if there’s something I’m missing or if there’s a known workaround for this issue. Any insight, suggestions, or guidance would be greatly appreciated.
Thank you for your time and assistance!