Skip to content

Instantly share code, notes, and snippets.

@phuwn
Created May 17, 2022 05:11
Show Gist options
  • Save phuwn/6ce5632f8729525e857db9b96326325e to your computer and use it in GitHub Desktop.
Save phuwn/6ce5632f8729525e857db9b96326325e to your computer and use it in GitHub Desktop.
function drawHexagon(
ctx: CanvasRenderingContext2D,
cx: number,
cy: number,
color = "white"
) {
strokeRoundedPath(ctx, cx, cy, hexagon, 15, color, 4, 7 / 20)
}
interface Point {
x: number
y: number
}
function polygon(sides: number, rad: number, rot = 0): Point[] {
let i = 0
const step = (Math.PI * 2) / sides
const path = []
while (i < sides) {
path.push({
x: Math.cos(i * step + rot) * rad,
y: Math.sin(i++ * step + rot) * rad
} as Point)
}
return path
}
const hexagon = polygon(6, 100)
const octagon = polygon(8, 100)
function strokeRoundedPath(
ctx: CanvasRenderingContext2D,
cx: number,
cy: number,
path: Point[],
radius: number,
style: string,
width: number,
ratio = 1
) {
ctx.setTransform(1, 0, 0, 1, cx, cy)
let i = 0
const len = path.length
let p1 = path[i++],
p2 = path[i]
ctx.lineWidth = width
ctx.lineCap = "round"
ctx.strokeStyle = style
ctx.beginPath()
ctx.lineTo(((p1.x + p2.x) / 2) * ratio, ((p1.y + p2.y) / 2) * ratio)
while (i <= len) {
p1 = p2
p2 = path[++i % len]
ctx.arcTo(
p1.x * ratio,
p1.y * ratio,
((p1.x + p2.x) / 2) * ratio,
((p1.y + p2.y) / 2) * ratio,
radius
)
}
ctx.closePath()
ctx.stroke()
ctx.setTransform(1, 0, 0, 1, 0, 0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment