Skip to content

Instantly share code, notes, and snippets.

@Pan-Maciek
Created December 31, 2018 22:41
Show Gist options
  • Save Pan-Maciek/3c428520a57f0ba938f22bae34044ea9 to your computer and use it in GitHub Desktop.
Save Pan-Maciek/3c428520a57f0ba938f22bae34044ea9 to your computer and use it in GitHub Desktop.
const { min, cos, sin, PI, sqrt, ceil } = Math
const canvas = document.createElement('canvas')
const sqrt3 = sqrt(3)
const size = min(document.body.clientWidth, document.body.clientHeight * 1.5 / sqrt3) * 4 / 5
canvas.width = size
canvas.height = ceil(size * 2 * sqrt3 / 3)
document.body.appendChild(canvas)
const c = canvas.getContext('2d')
c.strokeStyle = '#fff'
let segments = [
[[0, sqrt3 / 2 * size], [size / 2, 0]],
[[size / 2, 0], [size, sqrt3 / 2 * size]],
[[size, sqrt3 / 2 * size], [0, sqrt3 / 2 * size]]
]
const length = ([[x1, y1], [x2, y2]]) => Math.hypot(x1 - x2, y1 - y2)
const drawSegment = ([[x1, y1], [x2, y2]]) => {
c.beginPath()
c.lineTo(x1, y1)
c.lineTo(x2, y2)
c.stroke()
}
const split = ([[x1, y1], [x2, y2]]) => {
const [vx, vy] = [(x2 - x1) / 3, (y2 - y1) / 3]
const [rvx, rvy] = [vx * cos(-PI / 3) - vy * sin(-PI / 3), vx * sin(-PI / 3) + vy * cos(-PI / 3)]
const a = [x1 + vx, y1 + vy], b = [x1 + rvx + vx, y1 + rvy + vy], c = [x2 - vx, y2 - vy]
return [[[x1, y1], a], [a, b], [b, c], [c, [x2, y2]]]
}
segments.forEach(drawSegment)
const update = () => {
c.clearRect(0, 0, canvas.width, canvas.height)
segments = segments.reduce((acc, x) => [...acc, ...split(x)], [])
segments.forEach(drawSegment)
}
setInterval(() => length(segments[0]) > 1 ? update() : null, 500)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="theme-color" content="#000">
<title>Snowflake</title>
</head>
<body style="display: flex; justify-content: center; align-items: center; margin: 0;background-color: #000;height: 100vh">
<script src="main.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment