diff options
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() |
