Skip to content
On this page

Point → hex

Translating a point (e.g. screen pixel) to the corresponding hex in a grid is possible with Grid's pointToHex() method. It also works with irregularly shaped hexes.

pointToHex() accepts a second argument to indicate what to do when a point corresponds to a hex outside the grid. By default it creates the hex and returns that.

typescript
import { defineHex, Grid, rectangle } from 'honeycomb-grid'

const WideHex = defineHex({
  dimensions: { xRadius: 50, yRadius: 30 }, // wide hexes
})
const grid = new Grid(WideHex, rectangle({ width: 5, height: 5 }))

document.addEventListener('click', ({ offsetX, offsetY }) => {
  const hex = grid.pointToHex(
    { x: offsetX, y: offsetY },
    { allowOutside: false }
  )
  console.log(hex)
})

Click somewhere below

0,01,02,03,04,00,11,12,13,14,1-1,20,21,22,23,2-1,30,31,32,33,3-2,4-1,40,41,42,4

Released under the MIT License.