Skip to content

Instantly share code, notes, and snippets.

@ikr7
Created May 19, 2016 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ikr7/3fabaf2b32d3e937fe0c4ac44eb8a751 to your computer and use it in GitHub Desktop.
Save ikr7/3fabaf2b32d3e937fe0c4ac44eb8a751 to your computer and use it in GitHub Desktop.
細胞
<!DOCTYPE html>
<html>
<head>
</head>
<body style="margin:0;overflow:hidden">
<canvas></canvas>
<script>
'use strict';
const W = Math.max(
document.body.clientWidth,
document.body.scrollWidth,
document.documentElement.scrollWidth,
document.documentElement.clientWidth
);
const H = Math.max(
document.body.clientHeight,
document.body.scrollHeight,
document.documentElement.scrollHeight,
document.documentElement.clientHeight
);
const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');
const groups = 'red, green, blue, cyan, magenta, yellow, pink, lime, skyblue, black, gray, white'.split(', ');
const cellSize = 10;
const fieldSizeX = Math.ceil(W / cellSize);
const fieldSizeY = Math.ceil(H / cellSize);
canvas.width = cellSize * fieldSizeX;
canvas.height = cellSize * fieldSizeY;
let cells = [];
for (let i = 0; i < fieldSizeX * fieldSizeY; i++) {
cells[i] = Math.floor(Math.random() * groups.length);
}
const step = function () {
cells = cells.map((cell, i) => {
if ([
cells[i - 1],
cells[i + 1],
cells[i - fieldSizeX],
cells[i + fieldSizeX]
].filter((neighbor) => {
return neighbor !== undefined;
}).some((neighbor) => {
return neighbor === (cell + 1) % groups.length;
})) {
return (cell + 1) % groups.length;
} else {
return cell;
}
});
};
const draw = function () {
step();
for (let y = 0; y < fieldSizeY; y++) {
for (let x = 0; x < fieldSizeX; x++) {
context.fillStyle = groups[cells[y * fieldSizeX + x]];
context.fillRect(x * cellSize, y * cellSize, cellSize, cellSize);
}
}
setTimeout(draw, 100);
// requestAnimationFrame(draw);
};
draw();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment