eperezcosano / hexagonal-grid

How to get a perfect hexagon grid using JavaScript to draw on a HTML canvas.
https://eperezcosano.github.io/hex-grid/
MIT License
23 stars 1 forks source link

Changing the Radius #2

Closed Julian-Cole closed 2 years ago

Julian-Cole commented 2 years ago

When you change the radius to say 100 in order to make the Hexagons appear bigger there is an issue. (see below)

image

On Line 13 if you change

for (let y = r; y + r * Math.sin(a) < height; y += r * Math.sin(a)) {

to

for (var y=r; y + r * Math.sin(a) < height; y += 2 * r * Math.sin(a) ) {

it should appear correctly with any radius value?

Julian-Cole commented 2 years ago

After some more tests this is releated to the "Odd number of columns" issue already reported, and the code above doesn't fix the issue for all radius sizes.

eperezcosano commented 2 years ago

After some more tests this is releated to the "Odd number of columns" issue already reported, and the code above doesn't fix the issue for all radius sizes.

Resolved. The bug was depending how many hexagons can fit in a row. If is odd we have to add rsin(a) or 2rsin(a) if is even.

function drawGrid(width, height) {
  for (let y = r, j = 0; y + r * Math.sin(a) < height; y += 2 ** ((j + 1) % 2) * r * Math.sin(a), j = 0) {
    for (let x = r; x + r * (1 + Math.cos(a)) < width; x += r * (1 + Math.cos(a)), y += (-1) ** j++ * r * Math.sin(a)) {
      drawHexagon(x, y);
    }
  }
}