Differences in alpha visualization between OpenGL and WebGL

I am reproducing the same scene using the exact same C ++ code, once on my own OpenGL on windows and once using Emscripten in WebGL. Everything in the scene looks exactly the same, except when I show something with alpha! = 1.0. The difference looks like this: enter image description here

Blue Cube Color (0.0, 0.0, 1.0, 0.5)
The shader used to render the cube does nothing but paint color.
On the right, what it looks like with OpenGL and is the expected result, just blue and a half transparency. On the left is how it looks with Emscripten + WebGL. It looks like the color that is displayed is actually (0.5, 0.5, 1.0, 0.5)

The blend function I use is standard:

 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); 

Is there any difference with alpha in WebGL? What could be the reason for this?

+7
c ++ opengl webgl emscripten
source share
1 answer

Did you find that the canvas doesn't really matter?

 gl = someCanvas.getContext("webgl", { premultipliedAlpha: false }); 

The default value for WebGL is true. By default, most OpenGL applications are set to false.

In addition, WebGL is linked to the rest of the page. At a minimum, the background color of the canvas or something inside it (the body of your document).

To make sure this is a problem, try setting the canvas background color to purple or something that will stick out

 <canvas ... style="background-color: #F0F;"></canvas> 

or in css

 canvas { background-color: #F0F; } 

OpenGL applications rarely compose on anything where WebGL applications effectively ALWAYS link.

Some solutions

  • Disable alpha

    If you don’t need alpha at your destination, you can turn it off

     gl = someCanvas.getContext("webgl", { alpha: false }); 

    Now alpha will be effective 1

  • Set alpha to 1 at the end of the frame

     // clear only the alpha channel to 1 gl.clearColor(1, 1, 1, 1); gl.colorMask(false, false, false, true); gl.clear(gl.COLOR_BUFFER_BIT); 

    don't forget to set the color mask back to all true if you need to clear the color buffer later

  • Set the canvas background color to black

     canvas { background-color: #000; } 

If possible, I would choose to disable alpha. The reason this is alpha is disabled, the browser may disable blending when drawing the canvas in the browser. This may be an increase in speed of 10-20% or more, depending on the GPU. There is no guarantee that any browser does this optimization, only that it is possible, while with the other 2 solutions it is impossible or at least much less likely

+11
source share

All Articles