Skip to content

Instantly share code, notes, and snippets.

@carrotflakes
Created September 9, 2022 02:43
Show Gist options
  • Save carrotflakes/ab21c13b4f3bce6c45ef33a324756d58 to your computer and use it in GitHub Desktop.
Save carrotflakes/ab21c13b4f3bce6c45ef33a324756d58 to your computer and use it in GitHub Desktop.
fractal
<body>
<canvas id="canvas" width="800" height="800" />
<script>
const el = document.getElementById("canvas")
const ctx = el.getContext("2d")
ctx.lineWidth = 2
function line(x1, y1, x2, y2) {
ctx.beginPath()
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.stroke()
}
function g(x1, y1, x2, y2, n=1) {
if (n === 0) {
line(x1, y1, x2, y2)
return
}
const x3 = (x1 + x2) / 2 + (y2 - y1) / 2
const y3 = (y1 + y2) / 2 - (x2 - x1) / 2
g(x1, y1, x3, y3, n-1)
g(x3, y3, x2, y2, n-1)
}
for (let i = 0; i < 8; ++i) {
ctx.strokeStyle = `hsl(${i * 40}, 50%, 50%)`
g(100 * 2, 100 * 2, 200 * 2, 100 * 2, i + 1)
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment