ben tedder : code things

Create a hexagon in javascript

This was a fun little method to write. The requirements were to create a hexagon around a point, with the ability to rotate it at any angle. Fair warning, I've used typescript in all code samples.

First step, a hexagon is nothing but 6 triangles emanating from a center point. So, once you have the origin point, you just need to put a point in space a certain number of pixels (the radius) away in a certain direction. Let's define a few of those things:

  • Angle of each triangle: 60˚
  • Radius of the hexagon: 5
  • Rotation of 15˚

So, if you have Point A, and you want to create Point B one radius distance away at a 15˚ angle, what do you do?

  • Point A is at { x: 0, y: 0 }
  • Point B is at { x: ?, y: ? }

We need to do some fairly simple trigonometry:

  • Point B's x is the addition of Point A's x value with the product of the radius and the Cosine of the angle in radians, or (a.x + (radius * Math.cos(θ))).
  • Point B's y is similar. It is the addition of Point A's y value with the product of the radius and the Sine of the angle in radians, or (a.x + (radius * Math.sin(θ))).

To get the angle, here's the trick. Cosine isn't something you pass the 15˚ degree measurement to. You instead pass the "radian" of the angle. To get the radian of an angle, you simply multiple the degrees by (π / 180). I created a little helper method to handle that:

const toRadians = (angle: number): number => angle * (Math.PI / 180)

Once you have the ability to convert degrees to radians, all that's left to do is loop around your origin in 60˚ increments (degrees NOT radians) and create all the vertices of your hexagon:

interface Point {
    x: number;
    y: number;
}
const findHexagon = (p: Point, rotation: number, radius: number): Point[] => {
    const hexagon: Point[] = []
    for (let i = 0; i < 360; i += 60) {
        hexagon.push({
            x: (p.x + radius * Math.cos(toRadians(i + rotation))),
            y: (p.y + radius * Math.sin(toRadians(i + rotation))),
        })
    }
    return hexagon
}

And now you have an array of all the vertices of a hexagon!

Protip: All you need to do is convert that 60 into a variable and you can use this method to create any normal polygon.