JSFiddle - React, Tailwind, and code Playground
by timgilbert
HTML
<div id="hexmap"></div>
<div id="tooltip"><a href="http://timgilbert.wordpress.com/2012/02/24/javascript-hexmap-display/">some explanation, plus github</a></div>
<!-- templates -->
<div id="templates" class="hidden">
<h1>Templates</h1>
<div class="tiles desert">
<img src="http://img716.imageshack.us/img716/6569/desertt.png" width="72" height="72"/>
</div>
<div class="tiles ocean">
<img src="http://img577.imageshack.us/img577/5797/oceanb.png" width="72" height="72"/>
</div>
</div>
CSS
html, body {
margin:0;
padding: 0;
height: 100%;
}
div#tooltip {
position: absolute;
margin: 0px auto;
bottom: 0;
width:13em;
height: 60px;
}
div#hexmap {
position: relative;
}
div.hidden {
display: none;
}
JavaScript
/*
Return a list of lists of strings. The top-level list
represents columns, and each column list is a series of
strings where the string value corresponds to the name
of a tile in the templates div.
*/
function getHexMap(bounds) {
var columns = [];
for (var c = 0; c < bounds; c++) {
var row = [];
for (var r = 0; r < bounds; r++) {
row.push(randomTile());
}
columns.push(row);
}
return columns;
}
// For testing - return a random tile, 66% desert, 33% ocean
function randomTile() {
if (Math.floor(Math.random() * 3) == 0) {
return "ocean";
}
return "desert";
}
/*
Given a 2d array like that returned from getHexMap(),
iterate through it and position the named tiles in
their proper places in the hexmap div
*/
function populate(hexmap) {
for (var x = 0; x < hexmap.length; x++) {
var column = hexmap[x];
for (var y = 0; y < column.length; y++) {
// clone the tile and place it
var tile = placeTile(column[y], x, y);
// Add some event handling
tile.bind("mouseover", function(event) {
var message = "Hex position ("
+ $(this).data("row") + ", "
+ $(this).data("column") + ")";
$('#tooltip').text(message);
});
}
}
}
/*
Given a tile name and row/column numbers, make a clone
of the tile and place it in the hexmap.
*/
function placeTile(name, x, y) {
var tile = $("." + name, "#templates").children().clone();
tile.hexMapPosition(x, y).appendTo($('#hexmap'));
return tile;
}
/*
jQuery extension to place a tile based on row and column data
attached to the element set
*/
(function($) {
$.fn.hexMapPosition = function(row, column) {
// We store the row and column in the tile for
// use in the tooltip stuff
this.data({"row": row, "column": column});
var tile_width = this.attr("width");
var tile_height = this.attr("height");
// Haven't done the math to check these but...