Question

I'm reading through learningwebgl.com and what confuses me is that it draws the first buffer I bound as last element?

http://jsfiddle.net/Cx8gG/1/

red triangle
green square
blue square

I expected to see only the blue square because everything else gets overdrawn, the output seems to be in reverse order?

I've also read about stencil buffers, so what I tried to do is create a mask (red) and then there should be a green triangle on the blue square.

the mask works ( http://jsfiddle.net/D3QNg/3/ ) but I don't know if it's right or if I'm just lucky.

Would appreciate some help.

Was it helpful?

Solution

It does this because you enabled the depth buffer at line 203

gl.enable(gl.DEPTH_TEST);

The depth buffer holds the depth for each pixel drawn. In the default mode, when trying to draw a pixel WebGL will check the depth of the pixel already there, only if the new pixel's depth is LESS then the previous pixel will the new pixel be drawn.

Since all your shapes have a depth of 0.0 the first one fills in the depth buffer for those pixels with 0.0. The next shape you draw also has a depth of 0.0 for each pixel which is not LESS than the 0.0 already there so those pixels do not get overwritten

If you comment out the line that enables depth testing you'll get the results you were expecting.

Note, with depth testing enabled you can set the comparison WebGL uses to decide whether or not to draw the pixel by calling the function gl.depthFunc (docs)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top