如何在片段着色器中将径向渐变叠加在线性渐变上?

How to overlay a radial gradient over a linear gradient within a fragment shader?

我被片段着色器困住了。我设法从上到下显示线性渐变(左图)。目标是将径向白色渐变叠加到此线性渐变上(在左图中显示为黑色虚线 => 右图说明了目标)。

我知道我必须以某种方式组合 x 和 y 坐标,但到目前为止所有试验都失败了 - 我认为我的数学太差了 :-/ 我也不知道如何混合蓝色颜色以获得白色阴影。

有人可以帮我提示一下吗?

这是给出左图结果的当前着色器(取决于颜色制服):

// Precision
precision highp float;
// Uniforms
uniform vec2 uResolution;
// Colors
uniform vec3 uColor1;
uniform vec3 uColor2;

void main(void) {
    vec2 position = gl_FragCoord.xy/uResolution;
    vec3 color = vec3(uColor2.x+(uColor1.x-uColor2.x)*position.y, uColor2.y+(uColor1.y-uColor2.y)*position.y, uColor2.z+(uColor1.z-uColor2.z)*position.y);
    gl_FragColor = vec4(color.x, color.y, color.z, 1.);
}

这里有一些代码可以满足您的需要:

// Precision
precision highp float;
// Uniforms
uniform vec2 uResolution;
// Colors
uniform vec3 uColor1;
uniform vec3 uColor2;

// parameters of the radial gradient
uniform vec2  uRadialFxCenter; // this should be in [0-1], so normalized screen coords
uniform float uRadialFxRadius; // this should be in [0-1], so normalized screen coords
uniform vec3 uRadialFxColor;    // should be white
uniform float uRadialFxOpacity; // between [0-1]

void main(void) {
    vec2 position = gl_FragCoord.xy/uResolution;
    vec3 color = vec3(uColor2.x+(uColor1.x-uColor2.x)*position.y, 
                      uColor2.y+(uColor1.y-uColor2.y)*position.y, 
                      uColor2.z+(uColor1.z-uColor2.z)*position.y);

    // compute radial fx opacity => alpha
    vec2 posToRadialFxCenter = uRadialFxCenter - position;
    float distToCenterNormalized = min((length(posToRadialFxCenter)/uRadialFxRadius), 1.0);
    float alpha = (1.0-distToCenterNormalized) * uRadialFxOpacity;

    // alpha blending radialFxColor / color 
    color = color * (1.0-alpha) + uRadialFxColor * alpha;

    //
    gl_FragColor = vec4(color.x, color.y, color.z, 1.);
}

您还可以通过添加如下内容来控制径向渐变逐渐消失的 "slope":

distToCenterNormalized = pow(distToCenterNormalized, slope);