0

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)

hexagonal grid

How can I figure out how to stretch the hexagons such that they all fit and take up as much space as they can?

spassvogel
  • 3,479
  • 2
  • 18
  • 23

2 Answers2

1

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

MBo
  • 77,366
  • 5
  • 53
  • 86
0

You need some trigonometry

Each Hexigon neighbor is at an increment of 60 degrees (pi/3) angle. Use cos (pi/3) * radius for the x location adjustment, and +/- sin (pi/3) * radius for height adjustment.

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • 2
    Please note that cos(pi/3) is exactly 1/2. Don't use javascript's cos function for this. – Stef Sep 16 '22 at 08:51