Triangles in Javascript

This is demonstration of rendering arbitrary triangles (relatively fast) with javascript/DOM/css (no images, flash, canvas tags or java applets). This page is fugly in IE6 because it does not render transparent borders properly, but it does work in the latest versions of IE7, Firefox and Opera. This was hacked together in 2 evenings, so there are some glitches and the code is not great; it's just a proof of concept. This demo brought to you by www.uselesspickles.com.

Yes, that is a 3D object being rotated and rendered in real-time! Use the following keys to rotate the shape:

How It Works

The technique used here is different than other Javascript drawing libraries. Usually, triangles are constructed by stacking several 1-pixel tall DIVs of varying widths on top of each other. A 100-pixel tall triangle would need 100 DIVs! My method uses many fewer DIVs, and here's how...

It's All About Borders

Let's render a DIV with very thick borders of differing colors:
Look at my borders!

See that nice diagonal line in each corner? What if we only use two adjacent borders, and set the color of one to "transparent"?
Look at my borders!

Now let's make the DIV have a width and height of zero:

We've got ourselves a right triangle! Varying the widths of the adjacent borders yields right triangles of different sizes and proportions. Different orientations can be achieved by carefully selecting which two adjacent borders to use.

But What Good is a Right Triangle?

So a right triangle is nice to have, but we want triangles of ANY shape and size. The following image shows how an arbitrary triangle can be broken into several right triangles:

As you can see, this 256-pixel tall triangle only requires about 10 DIVs, as opposed to 256 DIVs. This reduction in DIVs to be rendered by the browser greatly increases the speed of triangle rendering.