-
Notifications
You must be signed in to change notification settings - Fork 0
/
cg.html
103 lines (86 loc) · 2.66 KB
/
cg.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
<!--May want to look at https://stackoverflow.com/a/12886479/1474521 if there are multiple canvases-->
<style>
p {
font-size: 16px;
}
canvas {
border: 1px solid black;
}
#auto-draw {
margin: 10px;
padding: 10px;
font-size: 18px;
}
</style>
<h1>Chaos Game<h1>
<p>
Click in the box to draw the next point. <br>
Press any key to start the auto draw. <br>
Press any key again to pause the auto draw. <br>
Each time you start the auto draw, it draws quicker. <br>
For mobile, you may want to click -> <button id="auto-draw">Start Auto Draw</button>
</p>
<canvas id="chaos-game" width="700" height="540"></canvas>
<p>Inspired by:</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/kbKtFN71Lfs" frameborder="0" allowfullscreen></iframe>
<br>
<br>
<a href="/">Back to home</a>
<script>
var interval = null
var intervalSpeed = 60
var autoDrawButton = document.getElementById('auto-draw')
var canvas = document.getElementById('chaos-game')
var ctx = canvas.getContext('2d')
canvas.addEventListener('click', drawNextPoint)
document.addEventListener('keydown', quickDrawNextPoint)
autoDrawButton.addEventListener('click', quickDrawNextPoint)
var dotSize = 2
var pointA = [350, 50]
var pointB = [50, 490]
var pointC = [650, 490]
var currPoint = [getRandomInt(1,700), getRandomInt(1,500)]
var points = [pointA, pointB, pointC]
drawPoint(pointA)
drawPoint(pointB)
drawPoint(pointC)
drawPoint(currPoint)
ctx.font = '20px serif'
ctx.fillStyle = 'black';
ctx.fillText('A', 346, 40);
ctx.fillText('B', 36, 515);
ctx.fillText('C', 654, 515);
function drawPoint(p) {
ctx.fillStyle = getRandomColour()
ctx.fillRect(p[0],p[1],dotSize,dotSize)
}
function drawNextPoint() {
currPoint = getMidPoint(currPoint, points[getRandomInt(0,3)])
drawPoint(currPoint)
}
function quickDrawNextPoint() {
if (interval === null) {
intervalSpeed *= 0.6
interval = setInterval(function() {
drawNextPoint()
}, intervalSpeed)
autoDrawButton.textContent = "Pause Auto Draw"
} else {
clearInterval(interval)
interval = null
autoDrawButton.textContent = "Start Auto Draw"
}
}
function getMidPoint(p1, p2) {
return [(p1[0]+p2[0])/2, (p1[1]+p2[1])/2]
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
//The maximum is exclusive and the minimum is inclusive
}
function getRandomColour(min, max) {
return 'rgb( ' + getRandomInt(0,256) + ', ' + getRandomInt(0,256) + ', ' + getRandomInt(0,256) + ')'
}
</script>