aboutsummaryrefslogtreecommitdiff
path: root/utils/fractal_tree/script.js
blob: 21a3d26a5950d83e2636d0e5116f1463854a528b (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
53
54
55
const canvas  = document.getElementById("tree-canvas")
const context = canvas.getContext("2d")

let angle = undefined

function tree(length, n) {
    if (n === 0)
        return
    context.beginPath()
    context.moveTo(0, 0)
    context.lineTo(0, -length)
    context.stroke()

    context.save()
    context.translate(0, -length)

    context.save()
    context.rotate(angle)
    tree(length / 2, n - 1)
    context.restore()

    context.save()
    context.rotate(-angle)
    tree(length / 2, n - 1)
    context.restore()

    context.restore()
}

const depth_input = document.getElementById("depth")
const angle_input = document.getElementById("angle")

function draw() {
    context.clearRect(0, 0, canvas.width, canvas.height)
    context.save()
    context.translate(canvas.width / 2, canvas.height)
    angle = 2 * Math.PI * (parseInt(angle_input.value) / 360)
    tree(canvas.height / 2, parseInt(depth_input.value))
    context.restore()
}

depth_input.addEventListener("input", draw)
angle_input.addEventListener("input", draw)

function updateCanvas() {
    const canvas_size = Math.min(window.innerWidth, window.innerHeight - 255)
    canvas.width  = canvas_size
    canvas.height = canvas_size
    context.strokeStyle = "#DDDDDD"
    context.lineWidth = 0.7
    draw()
}

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