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 - 200) canvas.width = canvas_size canvas.height = canvas_size context.strokeStyle = "#DDDDDD" context.lineWidth = 0.7 draw() } window.addEventListener("resize", updateCanvas) updateCanvas()