In GLSL (WebGL), how can I get the screen pixel X position in the fragment shader?

Initially I was using just gl_FragCoord.x which works great up to a point. However the range of gl_FragCoord.xy is between 0.5 and 1023.5, so after 1023.5 x just returns the same value.

I have a uniform with the actual canvas size.

    uniform vec2 resolution;

    void main(void) {
         float pixelXPos = ?
    }

Assuming the width is 1800, how can I get the actual pixel screen X position in the fragment shader for pixels above 1023.5?

For context, I have a single square that covers the entire canvas. I want to the shader to print a pattern on that square, so I need to know the x and y coordinate (in screen space) in order to know what to paint each pixel to.

Thanks!

>Solution :

You have to use the highp precision qualifiers for pixelXPos:

highp float pixelXPos = gl_FragCoord.x;

The integer range for mediump is only guaranteed to be at least [-2e10, 2e10] ([-1024, 1024]). See OpenGL ES Shading Language 1.00 – 4.5 Precision and Precision Qualifiers.

Leave a Reply