I am drawing a hexagonal grid using javascript and svg. The grid needs to have a fixed width (let’s say, of 1000px). The dimensions of the grid can differ, but I have that information (the columns and rows). I have written a function that given a hexagons ‘bounding box’ width (the height is a factor 0.8660254
of the width), will calculate all 6 points and draw a polygon between them. I am staggering the x
coordinate such that the polygons neatly connect.
However, the part I am stuck on currently is: How do I figure out the width of the polygons such that they take up the most available space on the canvas? I cannot simply do width of the canvas / number of columns
because that doesn’t take into account the staggering (see the image below)
How can I figure out how to stretch the hexagons such that they all fit and take up as much space as they can?
Advertisement
Answer
If you have C
columns and hexagon side size (unknown yet) is x
, we can write inequality:
x/2 + C*x*3/2 <= width x*(1+3*C)>=2*width x <= 2*width / (1+3*C)
So calculate the right part and get floored integer (if you need integer side)
For height with R
rows:
x*sqrt(3)/2 + R*x*sqrt(3)/2 <= height x <= 2*height / (sqrt(3) + R*sqrt(3))
Get min value from calculated sizes to fit both width and height