Skip to content

Instantly share code, notes, and snippets.

@lot224
Last active September 9, 2015 03:04
Show Gist options
  • Save lot224/8e1b57be99c20f1eafdd to your computer and use it in GitHub Desktop.
Save lot224/8e1b57be99c20f1eafdd to your computer and use it in GitHub Desktop.
Generate Hexagon Points
var horizontalHexagonPoints = function (canvas, radius) {
var size = {
width: radius * 2,
height: (radius / 2 * Math.sqrt(3)) * 2
};
var rows = Math.ceil(canvas.height / size.height) + 1;
var columns = Math.ceil(canvas.width / (radius / 2 * 3)) + 1;
var offset = {
// (width - ((diameter * columns) - (((columns - 1) * radius) / 2))) / 2
x: (canvas.width - ((size.width * columns) - (((columns - 1) * radius) / 2))) / 2,
// (height - (innerDiameter * radius)) / 2
y: (canvas.height - (size.height * rows)) / 2
};
var points = [];
var y;
for (var row = 0; row < rows; row++) {
for (var col = 0; col < columns; col++) {
y = col % 2 == 0 ? 0 : size.height / 2;
points.push({
x: offset.x + ((size.width - (radius / 2)) * col) + (size.width / 2),
y: (offset.y + y) + (size.height * row) + (size.height / 2)
})
}
}
return points;
};
var verticalHexagonPoints = function (canvas, radius) {
var size = {
width: (radius / 2 * Math.sqrt(3)) * 2,
height: radius * 2
};
var rows = Math.ceil(canvas.height / (radius / 2 * 3)) + 1;
var columns = Math.ceil(canvas.width / size.width) + 1;
var offset = {
x: (canvas.width - (size.width * columns)) / 2,
y: (canvas.height - ((size.height * rows) - (((rows - 1) * radius) / 2))) / 2
};
var points = []; // these are the centroid points for the hexagon.
var x;
for (var row = 0; row < rows; row++) {
for (var col = 0; col < columns; col++) {
x = row % 2 == 0 ? 0 : size.width / 2;
points.push({
// (width - (innerDiameter * columns)) / 2
x: (offset.x + x) + (size.width * col) + (size.width / 2),
// (height - ((diameter * rows) - (((rows - 1) * radius) / 2))) / 2
y: offset.y + ((size.height - (radius / 2)) * row) + (size.height / 2)
})
}
}
return points;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment