Hexagons have six equal sides. If we imagine our starting point as the center of the hexagon, we can move around this point six times, joining each point as we go to make the sides.

Let’s start off by creating a <canvas> with a 2d drawing context. We’ll fix the size of the canvas to 400 x 200 pixels for this example and set the center point as (200, 100).

<canvas></canvas>
const canvas = document.querySelector("canvas");
canvas.width = 400;
canvas.height = 200; const ctx = canvas.getContext("2d");
const cx = 200;
const cy = 100;

Now we need to figure out the x (horizontal) and y (vertical) position of points around the center, which when joined with a line, will make six equal sides. For this, we use the measurement from the center to the point (we’ll call this the radius) and the angle of direction from the center.

As there are 360 degrees in a full rotation and six points we want to create, we can divide 360/6 and know we’ll make a point every 60 degrees. However, there’s a tiny caveat to this – JavaScript works with radians rather than degrees. One thing I always remember is that the value pi in radians is 180 degrees, or half a circle. So (Math.PI*2)/6 would give us each rotation in radians or even simpler Math.PI/3.

Next we need to add a bit of trigonometry to find the x and y position of each point. For the x position, we can use the sum radius multiplied by cos(angle) and for the y position radius multiplied by sin(angle). Let’s put it all together, adding to our JavaScript code above:


const radius = 50; ctx.translate(cx, cy); for (let i = 0; i < 6; i++) { const rotation = (Math.PI / 3) * i; if (i === 0) { ctx.moveTo(radius * Math.cos(rotation), radius * Math.sin(rotation)); } else { ctx.lineTo(radius * Math.cos(rotation), radius * Math.sin(rotation)); }
} ctx.closePath();
ctx.stroke();

Similar Posts