Rendering hexagonal grids on websites

June 21, 2020


These notes iteratively build up to the dynamic rendering of a portion of a grid of regular hexagons using HTML, CSS, and Javascript.

To view the implementation at any stage in the process, just right click on the desired element and inspect it.

Single SVG hexagon (HTML+CSS)

We are using the HTML SVG tag to render this hexagon. The SVG tag has a polygon child which actually defines the hexagon. The SVG viewBox attribute is set to have a width of \(2\) and a height of \(2 \cdot sin\left(\frac{2\pi}{6}\right)\). The polygon is rendered by translating the \(x\)- and \(y\)-coordinates of each of the points $$\left(cos(2\pi i/6), sin(2\pi i/6)\right),\ i = 0, 1, \ldots, 5$$ to the appropriate coordinates in the SVG view box.

Grid of SVG hexagons (HTML+CSS)

This grid is hard coded as an SVG object consisting of one group per row, with each row rendering hexagons whose centroids lie on the same horizontal line.

We set the polygon.interactive:hover style to fill polygons of the interactive class that we hover over with the mouse cursor with the color #A0000F.

Dynamic grid of SVG hexagons (HTML+CSS+Javascript)

Now we define a Javascript function which renders each row of the grid for us - imaginatively named renderHexGrid. We define a wrapper called setHexGridParameters which reads the parameters specified in a form and updates the grid accordingly.

We creatively define the number of rows on a hexagonal grid to be the number of distinct horizontal lines along which the centroids of the hexagons in the grid lie. Similarly we define the number of columns as the number of distinct vertical lines along which the centroids lie.

Rows: Columns: