代码之家  ›  专栏  ›  技术社区  ›  Perraco

如何用GLSL渲染圆形渐晕图

  •  2
  • Perraco  · 技术社区  · 7 年前

    我试图实现一个圆形渐晕与GLSL,但结果是椭圆时,纹理是矩形的。什么是正确的方法,使其正方形的纹理大小无关?输入纹理大小(分辨率)可以是矩形或正方形。 我试着用 丢弃 方法,但这不适合我的要求,因为我需要使用 获得渐变边。

    当前结果:

    enter image description here

    varying vec2 v_texcoord;
    uniform sampler2D u_texture;
    uniform vec2 u_resolution;
    
    vec4 applyVignette(vec4 color)
    {
        vec2 position = (gl_FragCoord.xy / u_resolution) - vec2(0.5);           
        float dist = length(position);
    
        float radius = 0.5;
        float softness = 0.02;
        float vignette = smoothstep(radius, radius - softness, dist);
    
        color.rgb = color.rgb - (1.0 - vignette);
    
        return color;
    }
    
    void main()
    {
        vec4 color = texture2D(u_texture, v_texcoord);
        color = applyVignette(color);
        gl_FragColor = color;
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Rabbid76    7 年前

    计算到圆形视图中心点的距离时,必须考虑纵横比:

    float dist = length(position * vec2(u_resolution.x/u_resolution.y, 1.0));
    

    注意,如果您有一个矩形视口,其中宽度大于高度,那么当坐标从视图空间转换到规范化设备空间时,一个完美的圆在其左右两侧被压缩为椭圆。