Skip to content

Instantly share code, notes, and snippets.

@shadda
Created July 13, 2013 18:20
Show Gist options
  • Save shadda/5991654 to your computer and use it in GitHub Desktop.
Save shadda/5991654 to your computer and use it in GitHub Desktop.
(function()
{
HexMap = function(rows, columns, hexsize)
{
this.rows = rows;
this.columns = columns;
this.$_hexsize = hexsize;
this.$_half_hexsize= hexsize / 2;
this.$_x_offset = 30;
this.$_y_offset = 30;
this.$_radius = 27;
}
HexMap.prototype.drawGrid = function(canvas)
{
var posX;
var posY;
var coord;
var self = this;
for(var row = 0; row < this.rows; row++)
{
for(var col = 0; col < this.columns; col++)
{
posY = this.$_y_offset + row * this.$_radius;
posX = (row & 1) * (this.$_hexsize * 1.5) + this.$_x_offset + 2 * col * (this.$_hexsize * 1.5);
this.drawHex(canvas, [posX, posY], [col, row]);
}
}
}
HexMap.prototype.findHex = function(position)
{
var mX = position[0];
var mY =position[1];
var vCol = parseInt(mX / (this.$_hexsize * 1.5));
var tCol = parseInt(vCol / 2);
var vRow = parseInt((mY + this.$_radius * (~vCol & 1)) / this.$_radius);
var tRow;
if(vCol & 1)
{
tRow = vRow - 1;
}
else
{
tRow = vRow - 2;
}
//Woof.
posY = this.$_y_offset + this.$_radius * (vCol & 1) - this.$_radius * (vCol & 1) + tRow * this.$_radius;
posX = (tRow & 1) * (this.$_hexsize * 1.5) + this.$_x_offset + 2 * tCol * (this.$_hexsize * 1.5);
if((vCol <= this.columns) && (tRow <= this.rows))
{
return [posX, posY];
}
return false;
}
HexMap.prototype.drawHex = function(canvas, position, options)
{
var defaults = {
strokeStyle: 'black',
strokeWidth: 1,
x: position[0] , y: position[1],
radius: this.$_radius,
sides: 6
};
var options = $.extend(defaults, options);
canvas.drawPolygon(options);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment