Game of Life on an HTML5 Canvas

by Patrick Horgan

(Back to canvas tutorials)

An implementation of John Conway's Game of Life

(click any cell to toggle)

The buttons are colorful because I was redesigning them and wanted to see how they looked in different colors so I could get the gradients right. They are drawn on the canvas and implemented using my event manager that's discussed in the article HTML5 Canvas Event Delegation. Tutorial on them in the works.

(Back to canvas tutorials)

You can paste RLE files here

RLE (Run Length Encoding) is a common way to share interesting set ups for Life. If you go on the internet and search for them there's a lot. I recommend that you make the cells as small as possible, then paste a few in and see all the cool stuff. First paste into the text box, then click on the Paste It button to put it into the application above. If the set up is too large (that's why I recommend a small cell size, you can fit a lot more), it will tell you it won't fit. Then, when you click Start it will begin to evolve. Enjoy!

Paste RLE stuff here to see it run

How Life Works

The complexity of the behavior comes from a few simple rules. At each generation:

If you want to learn more, including some interesting patterns you can try out for yourself by clearing the grid and drawing with your mouse, look at the wikipedia article about Conway's Game of Life

The javascript--you can add it to your own page!

The code that runs it is a javascript class called gameOfLife(acanvas); To use it, you can add a canvas to your page, include the appropriate scripts and then invoke the draw method of the object one time.

<!DOCTYPE html> <!-- Copyright 2011 Patrick Horgan patrick at dbp-consulting dot com all rights reserved. --> <html> <head> <title>Game of Life</title> <meta charset='utf-8'> </head> <body> <canvas id='gol' width=1200px height=600px></canvas> </body> <script type='text/javascript' src='../../scripts/utilities.js'></script> <script type='text/javascript' src='../../scripts/canvasutilities.js'></script> <script type='text/javascript' src='scripts/life.js'></script> <script> var gol=new gameOfLife('gol'); gol.draw(); </script> </html>

It uses

Feel free to use any of the code/css/html you want, as long as it notes my copyright. Notice that I use relative links. If you put stuff in different places then you will have to adjust as appropriate.

If you want you can just use explicit links to my site for those three things and then your page will become quite simple.

It will adjust quite a bit to larger and smaller canvas sizes within reason. If you get it too small there's no room for the buttons. If you get it too large it really slows down.