PHP Hex Map Graphics

This PHP code uses the GD functions to create hex map images (eg. for wargames).

Leland on GitHub


  • Shapes: rectangule, hexagonal (‘circle’), freeform (‘free’)
  • Variable hex sizes
  • shape() to calculate distance in hexes
  • highlight a hex
  • set a border on a hex
  • color a hex
  • add text to a hex
  • I swear it used to allow setting a background picture, but I don’t see that functionality so maybe I dreamed it or lost it when I misplaced this code for four years.

Known Issues

The code has ugly styling (tabs, odd spacing, no optional braces) – sorry, I was young(er) and stupid(er).

There’s a fair amount of temporal coupling in there – functions that you can’t call before other functions, etc. I hadn’t heard of the command pattern or closures yet.

There’s a bug in the ‘circle’ shape (that the following code exercises):

require 'class_hex_image.php';
$radius = 3;
$map = new Hex_image;
$map->set_color('bg', 255, 255, 255);
$map->set_shape('circle', $radius);
for($x = 1; $x <= $map->xsize; $x++) {
    for($y = 1; $y <= $map->ysize; $y++) {
        $map->text($x, $y, 'black', $map->steps($x, $y, $radius, $radius));
        // nice for getting a feel for coordinates
        //$map->text($x, $y, 'black', "$x,$y");
header('Content-Type: image.png');
$map->finish();       // calls imagepng()


One of the guys in #bbg on irc, is building a browser-based game with a hex map and I remembered this code was squirreled away somewhere on my hard drive. I have no plans to fix, improve, or in any way maintain this code. I figure I may as well release it so someone can do something with it.


I release this code to the public domain. You may use it for any purpose with or without attribution. It would be polite to mention my name and let me know you come up with, but it’s not at all required.

Want more? I'm not as good at forgetting to update @pushcx on Twitter.