SVG 3D Boxes

This page use JavaScript to render the below SVG image of a number of 3D stacked boxes. The project was inspired by a question posted to stackoverflow about how to render a stack of boxes in JavaScript. The question asks to render a stack of boxes in a 3D format by use of a client-side script in a browser, without using as yet not widely supported technologies such as WebGL.

I surmised that it would be possible to create such an image in SVG, computed by a client-side JavaScript implementation. SVG is a technology that is widely supported among current browsers, however, with the notable exception of IE, IE9 should be introducing SVG support.

The code uses a homogeneous coordinate system to do the 3D coordinate transformations and projections. This is heavily based on the way OpenGL uses homogeneous coordinates and providing similar translate(), rotate() and scale() calls. To do the rendering a project() call is provided, which maps a given (x, y, z) coordinate onto the (x, y) viewport.

It should be noted that the code does not do any z buffering, nor any back-face culling, as such all faces and objects need to be drawn in a back to front order to create a good image. In this code only the three faces of the box that the viewer can see are rendered, which needs to be adapted if rotations other than [0..90] about the x and y axis are used. Additionally the for loops ensure the boxes are drawn in a back to front ordering. In the case the boxes are given as an unordered list, additional code would be needed to sort the boxes back to front before rendering them.

This code has been tested and found working under the following platforms: