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

Odd number of columns #1

Closed mirimCZ closed 2 years ago

mirimCZ commented 3 years ago

Hi,

there is a bug if it ends up rendering odd number of columns - to reproduce just try <canvas id="canvas" width="1048" height="1048"/> in your codepen.

Otherwise great job, many thanks :)

eperezcosano commented 3 years ago

Thanks for letting me know, i will try to fix it as soon as i can :)

ryanherford commented 2 years ago

For future travelers - I ended up solving this by adding the offset height back on every odd loop

Like so:

 for (let y = radius; y + radius * Math.sin(angle) < height; y += radius * Math.sin(angle)) {
        let j = 1;
        for (let x = radius; x + radius * (1 + Math.cos(angle)) < width; x += radius * (1 + Math.cos(angle)), y += (-1) ** j * radius * Math.sin(angle)) {
            j++ 
            drawHexagon(canvas, ctx, x, y)
        }
        y += j % 2 *radius * Math.sin(angle);
      }
eperezcosano commented 2 years ago

Changes added. Thanks!

eperezcosano commented 2 years ago

Hi,

there is a bug if it ends up rendering odd number of columns - to reproduce just try <canvas id="canvas" width="1048" height="1048"/> in your codepen.

Otherwise great job, many thanks :)

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);
    }
  }
}