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

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/
hexgridfiddle1.png




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
});
layer.add(hexagon);
}
}
// generate an image from the current layer
layer.toImage({
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
layer.removeChildren();
// add image to layer and draw the stage
layer.add(image);
stage.add(layer);
stage.draw();
}
});


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

-i

A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.