15

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?

1 Answer 1

20

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.