diff options
| author | Charles Cabergs <me@cacharle.xyz> | 2020-11-03 12:54:23 +0100 |
|---|---|---|
| committer | Charles Cabergs <me@cacharle.xyz> | 2020-11-03 12:54:23 +0100 |
| commit | 0bf460197e9d5a477f8ec5072e482203530bcba9 (patch) | |
| tree | c6e742454a81719ffb2838bf3c77d291d0114670 /utils/sierpinski_triangle/script.js | |
| parent | 6f14e8ee1281b2384c926ebfabaa4da57c509b96 (diff) | |
| download | cacharle.xyz-0bf460197e9d5a477f8ec5072e482203530bcba9.tar.gz cacharle.xyz-0bf460197e9d5a477f8ec5072e482203530bcba9.tar.bz2 cacharle.xyz-0bf460197e9d5a477f8ec5072e482203530bcba9.zip | |
Added sierpinski triangle
Diffstat (limited to 'utils/sierpinski_triangle/script.js')
| -rw-r--r-- | utils/sierpinski_triangle/script.js | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/utils/sierpinski_triangle/script.js b/utils/sierpinski_triangle/script.js new file mode 100644 index 0000000..6194413 --- /dev/null +++ b/utils/sierpinski_triangle/script.js @@ -0,0 +1,52 @@ +const canvas = document.getElementById("sierpinski-triangle") +const context = canvas.getContext("2d") + +function triangle(width, height, n) { + if (n === 0) + return + context.beginPath() + context.moveTo(width / 2, 0) + context.lineTo(width, height) + context.lineTo(0, height) + context.closePath() + context.stroke() + + // top + context.save() + context.translate(width / 4, 0) + triangle(width / 2, height / 2, n - 1) + context.restore() + + // bottom left + context.save() + context.translate(0, height / 2) + triangle(width / 2, height / 2, n - 1) + context.restore() + + // bottom right + context.save() + context.translate(width / 2, height / 2) + triangle(width / 2, height / 2, n - 1) + context.restore() +} + +const depth_input = document.getElementById("depth") + +function draw() { + context.clearRect(0, 0, canvas.width, canvas.height) + triangle(canvas.width - 1, canvas.height - 1, parseInt(depth_input.value)) +} + +depth_input.addEventListener("input", draw) + +function updateCanvas() { + const canvas_size = Math.min(window.innerWidth, window.innerHeight - 250) + canvas.width = canvas_size + canvas.height = canvas_size + context.strokeStyle = "#DDDDDD" + context.lineWidth = 0.7 + draw() +} + +window.addEventListener("resize", updateCanvas) +updateCanvas() |
