Skip to content

gojko/hexgridwidget

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 

Repository files navigation

A simple jQuery Hex Grid Widget

A simple jQuery Hex grid Widget, implemented using SVG, for prototyping hex-grid based games.

  • Just plain DOM, works in all browsers, easy to manipulate
  • Does not force any styling (so you can style it any way you want, using normal CSS)
  • Fields can are clickable, and the grid has dispatches an event with row and column position for easy click handling
  • Fields have DOM attributes attached to signal row and column position, so you can easily select them using jQuery or DOM selectors.
  • Fields have jQuery meta-data attached to point to the center of the field, so you can easily put other objects on them and position relative to the grid

Demo

See http://gojko.github.io/hexgridwidget/

Usage

Initialise the grid by calling hexGridWidget:

$('#container').hexGridWidget(radius, columns, rows, cssClass)
  • radius is the length (in pixels) of the side of a single hexagon (effectively the radius of the circle in which the hex field will be inscribed.
  • columns is the number of columns of the hex grid (horizontal hex count)
  • rows is the number of rows (vertical hex count)
  • cssClass is the css class that will be set on the hex polygons, for easy styling

##Selecting individual hex elements

Use the hex-row and hex-column DOM attributes to select an individual hex in the grid. For example:

$('#container [hex-row=2][hex-column=3]')

##Capturing clicks

There are two ways to capture clicks. The first one is to listen to a hexclick event on the grid container DOM element.

$('#container').hexGridWidget(radius, columns, rows, cssClass).on('hexclick', 
		function (e) { 
			console.log('clicked [' + e.column + ',' + e.row +']' +
			' hex with center at [' + e.center.x + ',' + e.center.y + ']');
		}
	);

This event will have the following properties:

  • column: hex grid column clicked
  • row: hex grid row clicked
  • center: object with {x, y} containing the center position of the clicked hex field, relative to the grid container

The second option is to assign a normal click handler to individual hex field, or even a group of hexfields.

$('#container .hexfield').click(function () {
  this.classList.toggle('clicked');
});

The hexclick event is particularly useful if you plan to resize grids dynamically after creation, because the individual hexes will be destroyed after resizing.

##Styling

Just pass a CSS class name as the fourth argument of the widget initialisation function, and style as you would any other DOM SVG element.

The individual hex fields are SVG polygons, so any CSS styles that work on polygons will also work on the grid.

About

jQuery Hex Grid Widget

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published