glslshaderfragment-shaderperspective

Using GLSL, how to create a perspective bending like effect


I'm trying to make a perspective bending GLSL shader similar to this.

Original:

Perspective Bending:

void mainImage( out vec4 fragColor, in vec2 fragCoord ){

    vec2 uv = fragCoord.xy/iResolution.xy;
    if (uv.x + uv.y < 1.0) uv = 1.0 - vec2(uv.y, uv.x);
    fragColor = texture(iChannel0, uv);

}

The code above does not achieve exactly what I want; your help is appreciated!

enter image description here


Solution

  • The reason why the line is not at a 45° angle and doesn't end where it should is that by dividing fragCoord.xy by iResolution.xy, you scale the x and y axes by different amounts. In your situation, since the image is wider than it is tall, uv will be stretched horizontally. To avoid that, I suggest you to do the scaling after the mirror transformation :

    void mainImage( out vec4 fragColor, in vec2 fragCoord ){
    
        vec2 uv = fragCoord.xy;
        if (uv.x + uv.y < iResolution.y) uv = iResolution.y - vec2(uv.y, uv.x);
        uv /= iResolution.xy;
        fragColor = texture(iChannel0, uv);
    
    }
    

    Note that I replaced the 1.0s by iResolution.y since in this coordinate system, that is the height of your image.