- <!doctype html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>无标题文档</title>
- <link >
- </head>
- <body>
- <canvas id="mycanvas" width="500" height="500" onclick="mouseClick(event)"></canvas>
- <button onClick="start()">start</button>
- <button onclick="stop()">stop</button>
- <script type="text/javascript">
- var xOffset = 20;
- var yOffset = 20;
- var gridSize = 40;
- var size = 10;
- var myArray = new Array([1, 1 ,0, 0, 0, 0, 0, 0, 0, 0, 0],
- [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0],
- [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
- var myCanvas = document.getElementById("mycanvas");
- var ctxt = myCanvas.getContext("2d");
- ctxt.fillStyle = "#ff0000";
- paint();
- function paint(){
- ctxt.fillStyle = "#eeeeee";
- ctxt.fillRect(0, 0, 500, 500);
- ctxt.fillStyle = "#00ff00";
- for(var i = 0; i <= size; i++){
- ctxt.moveTo(xOffset, yOffset + i * gridSize);
- ctxt.lineTo(xOffset + gridSize*size, yOffset + i*gridSize);
- }
- for(var i = 0; i <= size; i++){
- ctxt.moveTo(xOffset + i*gridSize, yOffset);
- ctxt.lineTo(xOffset + i*gridSize, yOffset + gridSize*size);
- }
- ctxt.stroke();
- for(var x = 0; x<myArray.length; x++){
- for(var y = 0; y<myArray[x].length; y++){
- if(myArray[x][y]){
- ctxt.fillRect(xOffset + x*gridSize, yOffset + y*gridSize, gridSize -1, gridSize-1);
- }
- }
- }
- }
- <!--鼠标对canvas翻转>
- function mouseClick(event) {
- var x = parseInt((event.layerX - xOffset) / gridSize);
- var y = parseInt((event.layerY - yOffset) / gridSize);
- if(myArray[x][y]){
- myArray[x][y] = 0;
- }else{
- myArray[x][y] = 1;
- }
- paint();
- }
- <!--判定细胞的生死,引入aroundCount()方法>
- function reverse(){
- var copy = myArray;
- for(var i = 0; i < copy.length; i++){
- for(var j = 0; j < copy.length; j++){
- var count = aroundCount(i, j);
- if(count == 3){
- copy[i][j] = 1;
- }else if(count == 2){
- }else{
- copy[i][j] = 0;
- }
- }
- }
- myArray = copy;
- }
- <!--定义aroundCount判断除了该细胞周围的细胞个数>
- function aroundCount(x, y){
- var count = 0;
- for(var i = x - 1; i <= x+1; i++){
- for(var j = y - 1; j <= y + 1; j++){
- if(i<0 || i>=myArray.length || j < 0 || j>=myArray.length){
- continue;
- }
- if(myArray[i][j]){
- count++;
- }
- }
- }
- if(myArray[x][y]){
- count--;
- }
- return count;
- }
- function start(){
- timeID = setInterval(function(){
- reverse();
- paint();
- },1000);
- }
- function stop(){
- clearInterval(timeID);
- }
- </script>
- </body>
- </html>
- //该片段来自于http://www.codesnippet.cn/detail/3010201410840.html
来源: http://www.codesnippet.cn/detail/3010201410840.html