For some time I have been interested in the new HTML5 features primarily Canvas and WebGL. For this reason I looked at implementing a very simple RPG in HTML5. Five years ago the idea of doing so would have been ludicrous. An HTML implementation would have been clunky, the obvious choice would have been flash. Fortunately most people are using up to date browsers with decent Canvas support.

My initial goal was to implement a hex grid. I looked around to see if anyone had implemented a nice hex grid library but those that did exist did not fit my requirements.

Primarily I wanted flat top hexagons, and the ability to select a specific cell via mouse click or touch. Hence Hexagon.js a library that does exactly that.

You can download Hexagon.js from the GitHub repository, or you can try the demo on this page.

Hexagon.js has no dependencies, though it does require a modern browser. The code is licensed under an MIT license. At the moment it only supports flat topped Hexagons, but I plan to eventually generalize it to support flat sided hexagons.

This code owes a great to debt to Ruslans whose well diagrammed explanations of the mathematics of hexagons proved invaluable.

To get started you simply need to embed the following in your page:

The constructor takes the ID of the canvas element along with the radius of the hexagons that will be drawn.

You then call hexagonGrid.drawHexGrid() passing it the number of rows and columns and the amount of off set. The offset is where ON the canvas the grid will be drawn. This allows you to have a single canvas for say a game where the grid itself will be drawn in the middle, while UI components will be drawn around it. Finally there is a debug flag. When enabled this draws the cells coordinates at the bottom of each hex.

Other functions that may be of interest are:

hexagonGrid.drawHexAtColRow(): Draws a hexagon at a particular row and column with a given colour.

hexagonGrid.drawHex() Draws a hex at an arbitrary x and y coordinate with an arbitrary colour.

If this was interesting you may also be interested in my Mandelbrot implementation JS.