Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

NOTE: This article is 3 years or older so its information may no longer be relevant. Read on at your own discretion! Comments for this article have automatically been locked, refer to the FAQ for more details.
When I first started looking into the HTML5 side of things for my game one of the key requirements for me was the ability to work with hexagonal grids and to be able to interact with the cells in this grid. KineticJS seemed to have the right features to do this, but I soon discovered that large grids simply did not perform, so after playing around a bit I found another solution.

The problem as it appears to me is that when you generate a grid with many cells, the browser simply cannot perform well and keep track of every single one. The solution is to generate the grid in an off-screen layer, convert it to an image, remove all the hexagons that are not needed any more and simply draw the generated image.

I created a jsFiddle to show the concept, it's available here: http://jsfiddle.net/jy7G2/

When using a grid of 80x80 hexagons and dragging it around, the lag is very noticeable. However when converted to an image, this grid can be dragged around very quickly.

This is all the code to get it running:
// hexagon dimensions
var radius = 16;
var height = (radius * Math.sqrt(3));
var side = radius * 3 / 2;
// grid size
var gridWidth = 80;
var gridHeight = 80;
// set up stage and layer
var stage = new Kinetic.Stage({
container: 'container',
x: 0,
y: 0,
width: 512,
height: 512,
draggable: true
var layer = new Kinetic.Layer();
// position polygons
for (var i = 0; i < gridWidth; i++) {
for (var j = 0; j < gridHeight; j++) {
mX = radius + (i * side);
mY = radius + (height * (2 * j + (i % 2)) / 2);
hexagon = new Kinetic.RegularPolygon({
x: mX,
y: mY,
sides: 6,
radius: radius,
fill: 'red',
stroke: 'black',
strokeWidth: 1,
rotationDeg: 90
// generate an image from the current layer
width: (gridWidth * side) + radius,
height: (gridHeight * height) + radius,
callback: function (img) {
var image = new Kinetic.Image({
image: img,
x: 0,
y: 0,
// remove all the hexagon nodes
// add image to layer and draw the stage

Next time I will show how to position things on top of this grid and snap to the grid.


Hope you found this post useful...

...so please read on! I love writing articles that provide beneficial information, tips and examples to my readers. All information on my blog is provided free of charge and I encourage you to share it as you wish. There is a small favour I ask in return however - engage in comments below, provide feedback, and if you see mistakes let me know.

If you want to show additional support and help me pay for web hosting and domain name registration, donations, no matter how small, are always welcome!

Use of any information contained in this blog post/article is subject to this disclaimer.
comments powered by Disqus
Other posts you may like...