webgl 颜色和 alpha [英] webgl colors and alpha

查看:67
本文介绍了webgl 颜色和 alpha的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 webgl 中遇到颜色和 alpha 问题.

我的 JavaScript 程序的一部分:

gl.clearColor(0.0, 0.0, 0.0, 1.0);gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

还有我的片段着色器:

precision highp float;无效主(无效){浮动 c = 0.5;浮动 a = 0.7;if(gl_FragCoord.x <310.0)//左颜色gl_FragColor = vec4(c, c, c, 1.0);else if(gl_FragCoord.x > 330.0)//正确的颜色gl_FragColor = vec4(c, c, c, a);否则 gl_FragColor = vec4(c/a, c/a, c/a, 1.0);//中间色}

我正在渲染一个立方体.

但不幸的是,立方体以 3 种不同的颜色呈现.结果:

图片参见

默认的混合方程为:

blendColor = sourceColor + destinationColor * (1 - sourceAlpha)

所以在白色背景下,sourceColor = c = 0.5,sourceAlpha = a = 0.7,destinationColor = white = 1.0,所以 blendColor = 0.8

在这种情况下,除以 alpha 没有多大意义.要匹配中间区域,您可以复制上面的混合过程:

else gl_FragColor = vec4(vec3(c) + vec3(1.0) * (1.0 - a), 1.0);//中间色

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.

解决方案

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

这篇关于webgl 颜色和 alpha的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆