-
Notifications
You must be signed in to change notification settings - Fork 0
/
sandpiles.html
105 lines (95 loc) · 3.29 KB
/
sandpiles.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
105
<html>
<head>
<style>
body{
padding:0px;
margin: 0px;
display: flex;
align-items: center;
justify-content: center;
}
canvas{
border: 1px solid black;
background-color: #000;
}
</style>
</head>
<body>
<canvas></canvas>
</body>
<script>
var canvas=document.querySelector("canvas");
canvas.width=501;
canvas.height=501;
canvas.style.height=window.innerHeight;
var c= canvas.getContext('2d');
var sandpiles=[]
for(var i=0; i<canvas.width; i++){
var tmp=[];
for(var j=0; j<canvas.width; j++){
tmp.push(0);
}
sandpiles.push(tmp);
}
sandpiles[Math.ceil(sandpiles.length/2)][Math.ceil(sandpiles.length/2)]=1000000;
limit=6;
function animate(){
for(var p=0; p<1000; p++){
for(var i=0; i<sandpiles.length; i++){
for(var j=0; j<sandpiles[i].length; j++){
if(sandpiles[i][j]>limit){
sandpiles[i][j]-=4;
if(i>0)sandpiles[i-1][j]++;
if(i<sandpiles.length)sandpiles[i+1][j]++;
if(j>0)sandpiles[i][j-1]++;
if(j<sandpiles.length)sandpiles[i][j+1]++;
}
}
}
}
var imagedata=c.createImageData(canvas.width, canvas.height);
var data=imagedata.data;
for(var i=0; i<sandpiles.length; i++){
for(var j=0; j<sandpiles[i].length; j++){
var color = [];
if(sandpiles[i][j]<limit)color=hslToRgb(1/limit*sandpiles[i][j],0.5,0.5)
else color=hslToRgb(1,0.5,0.5)
data[(i*sandpiles.length + j)*4] = color[0];
data[(i*sandpiles.length + j)*4 +1] = color[1];
data[(i*sandpiles.length + j)*4 +2] = color[2];
data[(i*sandpiles.length + j)*4 +3] = 255;
/*
data[(i*sandpiles.length + j)*4] = 255/(limit+1)*sandpiles[i][j];
data[(i*sandpiles.length + j)*4 +1] = 255/(limit+1)*sandpiles[i][j];
data[(i*sandpiles.length + j)*4 +2] = 255/(limit+1)*sandpiles[i][j];
data[(i*sandpiles.length + j)*4 +3] = 255;
*/
}
}
c.putImageData(imagedata, 0, 0);
requestAnimationFrame(animate);
}
animate();
function hslToRgb(h, s, l) {
var r, g, b;
if (s == 0) {
r = g = b = l; // achromatic
} else {
function hue2rgb(p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1/6) return p + (q - p) * 6 * t;
if (t < 1/2) return q;
if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
}
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return [ r * 255, g * 255, b * 255 ];
}
</script>
</html>