【问题标题】:How can I make the FragColor work with alpha?如何使 FragColor 与 alpha 一起使用?
【发布时间】:2021-04-24 23:01:57
【问题描述】:

我对 OGL 很陌生。 我试图让片段着色器显示一个具有透明度的 png 图像。 到目前为止,我已经设法将图像中的透明背景变为黑色,然后 alpha 通道以黑色显示,但是如何使 alpha 通道真正透明呢?

我已经尽力自己解决了,但没有成功。 请帮忙?

这是我的代码:

      const fragment = `
                    precision highp float;
                    precision highp int;
                    uniform sampler2D tWater;
                    uniform sampler2D tFlow;
                    uniform float uTime;
                    varying vec2 vUv;
                    uniform vec4 res;

                    void main() {

                            vec3 flow = texture2D(tFlow, vUv).rgb;

                            vec2 uv = .5 * gl_FragCoord.xy / res.xy ;
                            vec2 myUV = (uv - vec2(0.5))*res.zw + vec2(0.5);
                            myUV -= flow.xy * (0.15 * 0.7);

                            vec3 tex = texture2D(tWater, myUV).rgb;

              gl_FragColor = vec4(tex.r, tex.g, tex.b, 1.0);
                    }
            `;
    {

【问题讨论】:

    标签: javascript alpha fragment-shader ogl


    【解决方案1】:

    您当前在着色器中将 alpha 定义为 1.0,使输出颜色不透明。如此变化

    vec3 tex = texture2D(tWater, myUV).rgb;
    gl_FragColor = vec4(tex.r, tex.g, tex.b, 1.0);
    

    vec4 tex = texture2D(tWater, myUV).rgba;
    gl_FragColor = vec4(tex.r, tex.g, tex.b, tex.a);
    

    还将设置 alpha 值以匹配您的纹理。

    现在您正在输出 alpha 值,您还需要确保您已告知 WebGL 使用混合:

    const program = new Program(gl, {
        vertex,
        fragment,
        transparent: true, // this property does that
        ...
    };
    

    而且,如果您还希望 WebGL 画布对其后面的 HTML 页面的其余部分透明,则需要通知上下文它应该处理 alpha:

    const renderer = new Renderer({alpha: true});
    

    最后,为了让您的clearColor(即renderer 在每次渲染时重置为的颜色)不会使画布不透明,请确保它具有0 的alpha 值:

    gl.clearColor(0, 0, 0, 0); // the fourth 0 is alpha
    

    另请参阅this similar question 以获取另一个示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-02
      • 2016-08-27
      • 2016-05-29
      • 1970-01-01
      • 2016-08-30
      • 2021-01-28
      • 2020-06-03
      • 1970-01-01
      相关资源
      最近更新 更多