99 lines
2.4 KiB
HTML
99 lines
2.4 KiB
HTML
|
<!DOCTYPE html>
|
||
|
<html>
|
||
|
<head>
|
||
|
<meta charset="utf-8">
|
||
|
<title>Game of QR</title>
|
||
|
</head>
|
||
|
<body>
|
||
|
<canvas id="canvas"></canvas>
|
||
|
<script>
|
||
|
const canvas = document.getElementById('canvas');
|
||
|
|
||
|
function get(data, x, y) {
|
||
|
if (x < 0) x = data.width + x;
|
||
|
if (y < 0) y = data.height + y;
|
||
|
if (x >= data.width) x %= data.width;
|
||
|
if (y >= data.height) y %= data.height;
|
||
|
|
||
|
return data.data[y * data.width * 4 + x * 4] === 0 ? 1 : 0;
|
||
|
}
|
||
|
|
||
|
class GameOfQR {
|
||
|
init(src) {
|
||
|
if (this.interval) {
|
||
|
clearInterval(this.interval);
|
||
|
}
|
||
|
|
||
|
canvas.width = src.width * 16;
|
||
|
canvas.height = src.height * 16;
|
||
|
|
||
|
const tmp = new OffscreenCanvas(src.width, src.height);
|
||
|
const tmpCtx = tmp.getContext('2d');
|
||
|
tmpCtx.drawImage(src, 0, 0);
|
||
|
this.data = tmpCtx.getImageData(0, 0, tmp.width, tmp.height);
|
||
|
|
||
|
this.ctx = canvas.getContext('2d');
|
||
|
this.ctx.imageSmoothingEnabled = false;
|
||
|
this.ctx.drawImage(tmp, 0, 0, src.width, src.height, 0, 0, canvas.width, canvas.height);
|
||
|
|
||
|
setTimeout(() => {
|
||
|
setInterval(() => {
|
||
|
this.step();
|
||
|
}, 100);
|
||
|
}, 5000);
|
||
|
}
|
||
|
|
||
|
step() {
|
||
|
const prev = this.ctx.createImageData(this.data);
|
||
|
for (let i = 0; i < this.data.data.length; ++i) {
|
||
|
prev.data[i] = this.data.data[i];
|
||
|
}
|
||
|
|
||
|
for (let i = 0; i < this.data.height; ++i) {
|
||
|
for (let j = 0; j < this.data.width; ++j) {
|
||
|
const liveNeighbors = [
|
||
|
[ 1, 0],
|
||
|
[ 1, -1],
|
||
|
[ 0, -1],
|
||
|
[-1, -1],
|
||
|
[-1, 0],
|
||
|
[-1, 1],
|
||
|
[ 0, 1],
|
||
|
[ 1, 1]
|
||
|
].reduce((acc, [dx, dy]) => acc + get(prev, j+dx, i+dy), 0);
|
||
|
|
||
|
const k = i * this.data.width * 4 + j * 4;
|
||
|
const state = liveNeighbors > 3 || liveNeighbors < 2 ? 0 : liveNeighbors === 3 ? 1 : prev.data[k] === 0 ? 1 : 0;
|
||
|
this.data.data[k ] = (1-state) * 255;
|
||
|
this.data.data[k+1] = (1-state) * 255;
|
||
|
this.data.data[k+2] = (1-state) * 255;
|
||
|
this.data.data[k+3] = 255;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
const tmp = new OffscreenCanvas(this.data.width, this.data.height);
|
||
|
const tmpCtx = tmp.getContext('2d');
|
||
|
tmpCtx.putImageData(this.data, 0, 0);
|
||
|
|
||
|
this.ctx.drawImage(tmp, 0, 0, this.data.width, this.data.height, 0, 0, canvas.width, canvas.height);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
const app = new GameOfQR();
|
||
|
|
||
|
function hashchange() {
|
||
|
if (window.location.hash) {
|
||
|
const src = document.createElement('img');
|
||
|
src.src = window.location.hash.substring(1);
|
||
|
src.decode().then(() => {
|
||
|
app.init(src);
|
||
|
});
|
||
|
}
|
||
|
}
|
||
|
|
||
|
window.addEventListener('hashchange', hashchange);
|
||
|
hashchange();
|
||
|
</script>
|
||
|
</body>
|
||
|
</html>
|