191 Building a 3D Maze with CSS and JavaScript
Well also need a floor plan for our maze, and a handful of methods for dynamically converting
that floor plan into the polygons that represent the walls of our maze.
Making Triangles
If an element has a very thick border (say 50px), and adjacent borders have different colors, the in-
tersection of those borders creates a diagonal line, as Figure 6.2 illustrates.
Figure 6.2. Making diagonal lines from CSS borders
That example is simply a div element to which the following CSS rules are applied:
width: 200px;
height: 200px;
border: 50px solid #900;
border-color: #009 #900;
To render a triangle, we dont actually need the contents of that divwe only need its borders. So
lets remove the text, and reduce the width and height values to zero. What were left with is the
image shown in Figure 6.3.
Figure 6.3. Making triangles from CSS borders
Heres the CSS that achieves that effect:
width: 0;
border: 50px solid #900;
border-color: #009 #900;
The Art & Science Of JavaScript192
If we were to vary the relative border widths (applying, say, 50px on the left border and 25px on
the top), we could create triangles with various angles. By setting the color of one of the borders to
transparent, the diagonal line from the solid border stands alone, as Figure 6.4 reveals.
Figure 6.4. Creating diagonal lines using transparent adjacent borders
Now, if we wrap a second div element around the first, well be able to extract a single, discreet
triangle. We can achieve this by:
1. applying position: relative to the outer container
2. applying position: absolute to the inner element
3. clipping the inner element
Clipped elements are required to have absolute positioning,
so the relative positioning on the
container provides a positioning context for the inner element, as Figure 6.5 shows.
Figure 6.5. Extracting a single triangle using CSS clip
The code that produces Figure 6.5 is still very simple. Heres the HTML:
<div id="triangle">
And heres the CSS:
border: 2px solid #999;
position: relative;
width: 50px;
height: 25px;
#triangle > div
border-style: solid;
border-color: transparent #900;
border-width: 25px 50px;
position: absolute;
left: 0;

Get The Art & Science of JavaScript now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.