Finding the pixel color in a specific coordinate from a sampler2D using GLSL

18,017

The fragment shader has a built-in value called gl_FragCoord that supplies the pixel coordinates of the target fragment. You must divide this by the width and height of the viewport to get the texture coordinates for lookup. Here's a short example:

uniform vec2 resolution;
uniform sampler2D backbuffer;

void main( void ) {
    vec2 position = ( gl_FragCoord.xy / resolution.xy );
    vec4 color = texture2D(backbuffer, position);
    // ... do something with it ...
}

For a complete working example, try this in a WebGL-capable browser:

http://glslsandbox.com/e#375.15

Share:
18,017

Related videos on Youtube

Luke B.
Author by

Luke B.

Updated on June 08, 2022

Comments

  • Luke B.
    Luke B. almost 2 years

    I have a 3D object in my scene and the fragment shader for this object receives a texture that has the same size of the screen. I want to get the coordinates from the current fragment and find the color information on the image in the same position. Is this possible? Can someone point me to the right direction?

  • Luke B.
    Luke B. about 12 years
    I can't believe it was so easy, thanks a lot @emackey, I've been trying to do this for days.