javascript3d_20070717.jpg

I wouldn’t have thought it possible, but here’s an extremely clever hack from the Useless Pickles blog that will render 3D objects at a usable frame rate using standard Javascript.

You might be familiar with another method in which you create a bunch of 1 pixel-high divs to draw each triangle with a series of horizontal slices. This becomes unbearably slow, however, as you need an awful lot of divs just to display a single triangle. Lot’s of divs = super slow frame rate.

The trick is to take advantage of the beveled edges on a div border to make right triangles. By setting the div height and width to 0px, then setting 3 borders to transparent and 1 border to an opaque color, you can make a right triangle of various sizes by adjusting the border widths.

Using some fancy geometry, you can then cut any type of triangle into a series of successively smaller right triangles. Now, in real life, the right triangles would get infinitely small (and numerous), but in the digital world, they only need to get as small as a single pixel before we don’t care anymore.

With this method of drawing a triangle, you might only need to use 10 divs to draw a 100 pixel tall triangle (which would have taken 100 divs in the scan line method).

With a reasonably fast (or should I say “not unbearably slow”) method for drawing triangles, you can now create a simple 3D engine to draw objects at any orientation. Obviously, you’ll want to limit the number of triangles your objects are composed of, but it works. As a demonstration, the author created a simple engine for rendering and rotating the polyhedron seen above.

References:
Javascript Triangles (and real-time 3d) – Link
Rotating 3D Polyhedron Demo – Link