aboutsummaryrefslogtreecommitdiff
path: root/utils/sierpinski_triangle/script.js
blob: c4d7efe43c8f8bdcafb2d16c3f4453345a975286 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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 - 200)
    canvas.width  = canvas_size
    canvas.height = canvas_size
    context.strokeStyle = "#DDDDDD"
    context.lineWidth = 0.7
    draw()
}

window.addEventListener("resize", updateCanvas)
updateCanvas()