-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
104 lines (89 loc) · 3 KB
/
index.html
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<!doctype html>
<html>
<head>
<title>Sierpinky Triangle</title>
<meta name="author" content="Avritt Rohwer">
<meta charset="utf-8">
<style>
body {
margin: 0;
padding: 0;
font-family: sans-serif;
display: flex;
flex-direction: column;
justify-content: space-around;
padding: 20px;
}
canvas {
display: block;
}
</style>
</head>
<body>
<h1>Welcome to the Sierpinsky Triangle generator!</h1>
<p>I've always been interested in chaos theory and decided to make this visualizer because I was bored one afternoon.</p>
<p>This animation is generated by playing the <a href="https://en.wikipedia.org/wiki/Chaos_game">chaos game</a>.</p>
<div>
<button type="button" id="start">Start</button>
<button type="button" id="stop">Stop</button>
<button type="reset" id="reset">Reset</button>
</div>
<canvas></canvas>
<script>
// givePoint generates points that, when plotted, will draw a sierpinski triangle.
// domain: [0, 1]
// range: [0, Math.sqrt(3) / 2]
function* givePoint() {
const rootThreeOver2 = Math.sqrt(3) / 2 // tired of writing this out
const vertices = [
{x: 0, y: rootThreeOver2},
{x: 1, y: rootThreeOver2},
{x: 0.5, y: 0},
]
let point = {x: Math.random(), y: Math.random() * rootThreeOver2}
yield point
while (true) {
const vertex = vertices[Math.floor(Math.random() * 3)]
point.x = (point.x + vertex.x) / 2
point.y = (point.y + vertex.y) / 2
yield point
}
}
// set up canvas
const $canvas = document.querySelector('canvas')
const ctx = $canvas.getContext('2d')
// get minimum dimension, make canvas a square
const minDimen = innerHeight < innerWidth ? innerHeight : innerWidth
$canvas.width = $canvas.height = minDimen
// play / pause flag
let animateEh = false
// set up buttons
document.querySelector('#start').addEventListener('click', _ => {
animateEh = true
for (let i = 0; i < 666; i++) { // makes it draw faster
draw()
}
})
document.querySelector('#stop').addEventListener('click', _ => {
animateEh = false
})
document.querySelector('#reset').addEventListener('click', _ => {
animateEh = false
ctx.clearRect(0, 0, minDimen, minDimen)
})
// set up generator function
const gen = givePoint()
// get a new point, scale it, then draw it to the canvas
function draw() {
if (!animateEh) return
const point = gen.next().value
const x = Math.floor(point.x * minDimen)
const y = Math.floor(point.y * minDimen)
const pixel = ctx.getImageData(x, y, 1, 1)
pixel.data[3] = 255
ctx.putImageData(pixel, x, y)
requestAnimationFrame(draw)
}
</script>
</body>
</html>