Skip to content

Instantly share code, notes, and snippets.

@fallengiants
Created March 30, 2020 16:41
Show Gist options
  • Select an option

  • Save fallengiants/d188926a322f37fa055972155859f32b to your computer and use it in GitHub Desktop.

Select an option

Save fallengiants/d188926a322f37fa055972155859f32b to your computer and use it in GitHub Desktop.
Hexes in Canvas
const $canvas = document.getElementById('art')
const ctx = $canvas.getContext('2d')
const $dump = document.getElementById('dump')
const debug = (c) => $dump.value = JSON.stringify(c)
const deg2rad = (angle) => angle * Math.PI / -180
class Hex {
constructor (x,y,r=10){
this.r = r
this.cx = x
this.cy = y
}
distanceToNeighbor() { return this.r * 1.73205080757 }
xOffsetForAngle (a) { return Math.sin(deg2rad(a)) }
yOffsetForAngle (a) { return Math.cos(deg2rad(a)) }
calculateVertices(){
let points = []
for (let a=0; a<360; a+=60){
let x = this.cx + this.xOffsetForAngle(a) * this.r
let y = this.cy + this.yOffsetForAngle(a) * this.r
points.push({x: x, y: y})
}
return points;
}
draw(){
let moved = false;
ctx.beginPath();
this.calculateVertices().forEach(function (pt) {
ctx[moved&&'lineTo'||'moveTo'](pt.x, pt.y)
moved = true
})
ctx.closePath()
ctx.stroke()
}
}
hex1 = new Hex(100,100)
hex1.draw()
hex2 = new Hex(100+hex1.distanceToNeighbor(),100)
hex2.draw()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment