WebGL: How do I get the position of every pixel in fragment shader?

12,452
vec2 gl_FragCoord

It will return you position of the fragment on the screen in pixels. If you pass uniform vec2 screenResolution then you could play with that two values to determine where exactly on the screen is pixel, in which part and such.

This is a built-in variable, so you can use it whenever you want in fragment shader.

Here's one example of usage just to demonstrate: http://goo.gl/AG7UO

If you want woorld coordinate of the fragment, then you should use varying variable.

Vertex shader:

varying vec3 vPos;
attribute vec3 aVertexCoord;
uniform mat4 uMVMat;
uniform mat4 uProjMat;

void main() {
    vPos = uMVMat * aVertexPos;
    gl_Position = uProjMat * vPos;
}

Fragment shader:

varying vec3 vPos;
void main() {
    // do something
}

Hope this helps.

Share:
12,452

Related videos on Youtube

WoooHaaaa
Author by

WoooHaaaa

Updated on July 03, 2022

Comments

  • WoooHaaaa
    WoooHaaaa almost 2 years

    I know I could use gl_Position to get every vertex's position, but if it's possible to get every pixel's position in fragment shader ?

    I want to change the alpha value of some pixel area.