How can I read the depth buffer in WebGL?

Kevin Reid picture Kevin Reid · Sep 7, 2011 · Viewed 8.8k times · Source

Using the WebGL API, how can I get a value from the depth buffer, or in any other way determine 3D coordinates from screen coordinates (i.e. to find a location clicked on), other than by performing my own raycasting?

Answer

Markus picture Markus · Sep 7, 2011

I don't know if it's possible to directly access the depth buffer but if you want depth information in a texture, you'll have to create a rgba texture, attach it as a colour attachment to an frame buffer object and render depth information into the texture, using a fragment shader that writes the depth value into gl_FragColor.

For more information, see the answers to one of my older questions: WebGL - render depth to fbo texture does not work

If you google for opengl es and shadow mapping or depth, you'll find more explanations and example source code.