Search code examples
javascriptglslshaderwebgl

How to find current output pixel position in clip-space coordinates in WebGL?


So, in my vertex shader I'm doing something like this:

void main() {
  gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1);
}

But now I'm in my fragment shader and I would like to access that location. That is, I'm looking for a variable to access the current location of the pixel being drawn, but in clip-space coordinates. The reason for this is that I am looking to blend that pixel with a pixel at the same location in a texture.

It looks like gl_FragCoord is similar to what I want, but it's in window-space. I think I would be able to convert it like so:

vec2 what_i_want = vec2(gl_FragCoord.x / 1920., gl_FragCoord.y / 1080.);

But then I need to know my canvas size. I could pass in the canvas size as a uniform, but that seems like a bit much. Is there no way to just access this value somehow in the fragment shader?


Solution

  • You are on the right track. You must set the size of the viewport (canvas) in a uniform variable. There is no other option. That's what everyone does in WebGL as in OpenGL.

    uniform vec2 u_resolution;
    
    void main()
    {
        vec2 uv = gl_FragCoord.xy / u_resolution;
    
        // [...]
    }