问题
I have a problem with colors and alpha in webgl.
A part of my JavaScript-Program:
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
And my fragment-shader:
precision highp float;
void main(void)
{
float c = 0.5;
float a = 0.7;
if(gl_FragCoord.x < 310.0) // left color
gl_FragColor = vec4(c, c, c, 1.0);
else if(gl_FragCoord.x > 330.0) // right color
gl_FragColor = vec4(c, c , c , a);
else gl_FragColor = vec4(c / a, c / a, c / a, 1.0); // middle color
}
I am rendering a cube.
But unfortunatelly the cube is rendered in 3 different colors. The result:
image see http://fs5.directupload.net/images/160301/hcrpgyc9.png
The first gl_FragColor-command has an alpha = 1.0. The color is rendered as expected.
The second gl_FragColor-command has an alpha-value of 0.7.
The last parameter of the third gl_FragColor-command is again 1.0. r, g and b are divided by the alpha-value of 0.7. But I would like, that this command produces the same color as the second gl_FragColor-command. It seems, that my calculations are wrong. What can I do, to get the same color?
Tested with chrome and firefox, both on windows.
回答1:
The result you get is because the browser blends in the background color behind the canvas. Try setting the background-color, and you get something like this:
The blending equation by default is:
blendedColor = sourceColor + destinationColor * (1 - sourceAlpha)
So with a white background, sourceColor = c = 0.5, sourceAlpha = a = 0.7, destinationColor = white = 1.0, so blendedColor = 0.8
In this context dividing by alpha doesn't make much sense. To match the middle region, you could replicate the blending process above:
else gl_FragColor = vec4(vec3(c) + vec3(1.0) * (1.0 - a), 1.0); // middle color
来源:https://stackoverflow.com/questions/35724317/webgl-colors-and-alpha