Two Guys Arguing

HTML 5 Game of Life – Canvas Tag

Posted in javascript by benjaminplee on 11.16.10
Screenshot of HTML5-GoL animation

Screenshot of HTML5-GoL animation

In a previous post I described how I created a simple version of John Conway’s Game of Life using HTML 5 Web Workers for multi-threaded matrix calculations: HTML5-GoL.  Once each new matrix is calculated, I needed to display it somewhere.  In order to keep rendering (and therefore UI thread overhead) at a minimum I decided to only pass back the delta from the previous matrix to the current one (those squares with new life and recently deceased).  The end result was a pretty fast implementation that could render fast enough for smooth transitions.

Canvas Tag – Simple 2D bitmap graphics

The Canvas tag was first introduced with Apple within Webkit and allows for a simple block area to render simple 2D bitmap graphics.  This differs from SVG implementations which render individual graphic primitive objects which can be re-rendered and modified as DOM elements.  Canvas tag graphics are simple drawing, composition, translation, and image manipulation.

In order to draw each Game of Life matrix, we first need the canvas area

<!DOCTYPE html>
<canvas id="gol_canvas" width="401" height="401"></canvas>

Next we need to get the 2D context from the canvas DOM element.

var context = document.getElementById('gol_canvas').getContext('2d')

Once we have the 2D context we can start drawing simple shapes (lines, blocks, circles, etc) or do any number of other 2D actions.  For this simple Game of Life example I created a new GoLCanvas object which would hold all of the GoL specific actions (e.g. create life at x,y, clear the board, etc).  Overall the drawing API is simple if not a bit archaic (reminds me of my CS course in computer graphics where we did very basic OpenGL commands in C++).

Taken from gol-canvas.js

var draw_background = function() {
context.clearRect(0, 0, size, size)
context.fillStyle = COLORS.BACKGROUND
context.fillRect(0, 0, size, size);
}

The canvas work was simple and effective; only touching the surface of what can be done. There are a ton of great tutorials on the canvas tag and what can be done with it.