Assume a tree of objects that need to be rendered, each with their own x/y coordinates.

Now let's say I could crawl through the tree and give each element a "z" coordinate, before rendering.

Is there a technique to allow the tree to be rendered out-of-order, yet still have the appropriate layering?

In other words, it makes no difference whether parent is drawn before child, or child before parent, the parent will always be drawn before the child (or the other way around, but it will be consistent).

I'm just getting started with WebGL, but I'm thinking that with some sort of orthographic projection, this would work?


OpenGL (including WebGL) by default uses the z coordinate of a fragment when it needs to decide if the current fragment should override the one already present on the screen if depth testing is enabled (gl.enable(gl.DEPTH_TEST) at the beginning of the code).

But you'll need some sort of projection anyways (ortographic in this case) to make sure a unit horizontally is the same length, as a unit vertically (OpenGL's coordinate system goes from -1 to 1 on the x and y axis, it doesn't care about the aspect ratio).

  • \$\begingroup\$ If you're calculating everything in screenspace you could also traverse the tree, queue all render objects, sort them on z and then render the sorted queue rather than the tree. It's a bit more elaborate but doesn't require a depth buffer. \$\endgroup\$ – Sidar Oct 23 '17 at 3:42

Most 2D games have transparent assets. As such it's more typical that if you have a tree structure you walk the tree and generate a list of things to draw. You then sort the list of things to draw by Z and draw back to front.

If you have no transparency then you can rely on the z-buffer and draw out of order.

If you have only on/off transparency (0 or 1) then you can discard in your fragment shader


if (color.a <= alphaThreshold) { // where alphaThreshold is close to 0
   discard;   // don't draw this pixel and therefore don't update the z-buffer
gl_FragColor = color;


And then you can still draw out of order

As for "orthographic projection" neither WebGL nor OpenGL require any kind of projection. Projection is a term left over from the old fixed function pipeline that is not part of modern OpenGL or WebGL.

Of course it's still common to use a projection and use math like

 gl_Position = projection * view * model * vertexPosition;

But since it's up to you to write that code you're free to write something else.

You might consider these tutorials helpful


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.