var gridHeight = 400;
var gridWidth = 400;
var theGrid = createArray(gridWidth);
var mirrorGrid = createArray(gridWidth);
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
fillRandom(); //create the starting state for the grid by filling it with random cells
tick(); //call main loop
//functions
function tick() { //main loop
console.time("loop");
drawGrid();
updateGrid();
console.timeEnd("loop");
requestAnimationFrame(tick);
}
function createArray(rows) { //creates a 2 dimensional array of required height
var arr = [];
for (var i = 0; i < rows; i++) {
arr[i] = [];
}
return arr;
}
function fillRandom() { //fill the grid randomly
for (var j = 100; j < gridHeight - 100; j++) { //iterate through rows
for (var k = 100; k < gridWidth - 100; k++) { //iterate through columns
theGrid[j][k] = Math.round(Math.random());
}
}
}
function drawGrid() { //draw the contents of the grid onto a canvas
var liveCount = 0;
ctx.clearRect(0, 0, gridHeight, gridWidth); //this should clear the canvas ahead of each redraw
for (var j = 1; j < gridHeight; j++) { //iterate through rows
for (var k = 1; k < gridWidth; k++) { //iterate through columns
if (theGrid[j][k] === 1) {
ctx.fillRect(j, k, 1, 1);
liveCount++;
}
}
}
console.log(liveCount/100);
}
function updateGrid() { //perform one iteration of grid update
for (var j = 1; j < gridHeight - 1; j++) { //iterate through rows
for (var k = 1; k < gridWidth - 1; k++) { //iterate through columns
var totalCells = 0;
//add up the total values for the surrounding cells
totalCells += theGrid[j - 1][k - 1]; //top left
totalCells += theGrid[j - 1][k]; //top center
totalCells +=...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.