-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
126 lines (107 loc) · 2.45 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var SIZE = 256
ImageData.prototype.setPix = function(x, y, state){
this.data[(y*SIZE+x)*4 + 3] = state;
}
ImageData.prototype.getPix = function(x, y){
x = wrap(x);
y = wrap(y);
return this.data[(y*SIZE+x)*4 + 3];
}
ImageData.prototype.black = function(){
for(var i = 0; i < this.data.length; i++){
if(i%4 == 3){
if(Math.random() < .5){
this.data[i] = 255;
}else{
this.data[i] = 0;
}
}else{
this.data[i] = 0;
}
}
}
ImageData.prototype.count = function(x, y){
var c = 0;
for(var i = -1; i <= 1; i++){
for(var j = -1; j <= 1; j++){
if(j != 0 || i != 0)
if(this.getPix(x+i, y+j) == 255){
c++
}
}
}
return c
}
function wrap(n){
n = n%SIZE
if (n < 0){
n = SIZE - n
}
return n;
}
canvas = document.createElement( 'canvas' );
canvas.width = SIZE;
canvas.height = SIZE;
ctx = canvas.getContext('2d');
document.body.appendChild( canvas )
var a = ctx.createImageData(SIZE, SIZE);
var b = ctx.createImageData(SIZE, SIZE);
a.black();
//Any live cell with fewer than two live neighbours dies, as if caused by under-population.
//Any live cell with two or three live neighbours lives on to the next generation.
//Any live cell with more than three live neighbours dies, as if by overcrowding.
//Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element){
window.setTimeout(callback, 1000 / 60);
};
})();
// usage:
// instead of setInterval(render, 16) ....
function render(){
for(var i = 0; i < SIZE; i++){
for(var j = 0; j < SIZE; j++){
var c = a.count(i, j)
if(a.getPix(i, j) == 255){
if(c<2 || c>3){
b.setPix(i, j, 0)
//console.log(i,j,c,"died")
}
if(c == 2 || c == 3){
b.setPix(i, j, 255)
//console.log(i,j,c, "lived on")
}
}else{
if(c==3){
b.setPix(i, j, 255)
//console.log(i,j,c, "is alive!")
}else{
b.setPix(i, j, 0)
//console.log(i,j,c)
}
}
}
}
ctx.putImageData(b , 0, 0);
var temp = a;
a=b;
b=temp;
}
(function animloop(){
render();
requestAnimFrame(animloop);
})();
</script>
</body>
</html>