How to Draw a Checker Board Using HTML5 Canvas

In this tutorial, we will see how to draw a checker board using Canvas.

We’ll dive into Canvas drawing step by step.

You’ll discover how to setup a simple web page, draw a rectangle on canvas and finally implement an algorithm for drawing a checker board.

End Result

The image below is a screenshot of what you’ll be able to do after following this tutorial. Click here¬†or on the image to see the live demo.

Checker Board Drawing using HTML5 Canvas

Requirements

Let’s state some requirements for our little project. These will keep us focused on what needs to be done.

We will create a checker board that that has a size of 400×400 pixels.

We will basically create a grid that has 8 rows and 8 columns.

Each cell will have a size of 50×50 pixels. And of course, each cell will be either black or white.

Set Up

We will be working with an HTML file linked to a Javascript file.

The HTML file will define the webpage’s layout while the Javascript file will contain drawing code.

Open up your favorite text editor and create a text file named “index.html”. Copy and past the code below into it :

<!DOCTYPE html>
<html>
	<head>
		<title>Checker Board</title>
	</head>

	<body>
	</body>
</html>

 

Create another text file named “checkerboard.js” in the same folder. You can leave it blank for now.

Importing Javascript Files

To be able to use “checkerboard.js” inside “index.html”, we need to add a script tag to head :

<!DOCTYPE html>
<html>
	<head>
		<title>Checker Board</title>

		<script src="checkerboard.js"></script>
	</head>

	<body>
	</body>
</html>

 

Creating Canvas

Canvas is created by adding a canvas tag to body :

<!DOCTYPE html>
<html>
	<head>
		<title>Checker Board</title>

		<script src="checkerboard.js"></script>
	</head>

	<body>
		<canvas id="checkerboard" width="400" height="400">
		</canvas>	
	</body>
</html>

 

2D Rendering Context : Our Drawing Tool

To draw 2D shapes like rectangles, we need the 2D rendering context of Canvas. This is done in Javascript.

First get an object representing our canvas by using document.getElementById. Then call getContext to get a 2D rendering context object.

Copy and past the following code into “checkerboard.js” :

var canvas = document.getElementById("checkerboard");
var context2D = canvas.getContext("2d");

context2D.fillStyle = "black";
context2D.fillRect(0, 0, 50, 50);

 

Nothing happens !

The code above is supposed to get the 2D rendering context and draw a black rectangle.

Open “index.html” in a web browser. You should see a blank page, our drawing code didn’t work properly.

The problem is that our Javascript code is executed before canvas is created by the browser. When you use document.getElementById, no element is found and you get an error.

We will use Mootools to execute our drawing code after the webpage is created.

Mootools to the rescue

In “index.html”, import Mootools using a script tag :

<!DOCTYPE html>
<html>
	<head>
		<title>Checker Board</title>

		<script src="//ajax.googleapis.com/ajax/libs/mootools/1.4.5/mootools-yui-compressed.js"></script>
		<script src="checkerboard.js"></script>
	</head>

	<body>
		<canvas id="checkerboard" width="400" height="400">
		</canvas>	
	</body>
</html>

 

Tip: If you want to work offline, consider downloading Mootools. Simply put “mootools.js” (or whatever you name it) in the same folder as index.html. Then change the src attribute of the script tag to “mootools.js”.

Go back to “checkerboard.js”.

Put the Javascript code in an anonymous function and pass it to window.addEvent(“domready”, …) as a second argument :

window.addEvent("domready", function()
{
	var canvas = document.getElementById("checkerboard");
	var context2D = canvas.getContext("2d");

	context2D.fillStyle = "black";
	context2D.fillRect(0, 0, 50, 50);
});

 

Rectangle Drawing – a Closer Look

To draw a rectangle, use fillRect, a method of 2D context.

fillRect takes 4 arguments :

  1. x coordinate of the top-left corner
  2. y coordinate of the top-left corner
  3. width
  4. height

fillRect draws with black. To change fill color, set the fillStyle attribute before calling fillRect.

// drawing a red 50x200 rectangle at (20, 30)
context2D.fillStyle = "red";
context2D.fillRect(20, 30, 50, 200);

// drawing a green rectangle 
// color is a hexadecimal value
context2D.fillStyle = "#00FF00"; 
context2D.fillRect(40, 100, 60, 20);

 

Checker Board Drawing Loop

Now that you know how to draw a rectangle of any color, let’s draw a checker board.

We need to draw a grid where each cell is – alternatively – a black or white rectangle (square to be precise :) ).

Drawing a grid

Let’s keep it simple and stupid : let’s draw a grid where every cell is black. We’ll figure out how to alternate colors later.

To draw a grid, iterate over every row and draw a new cell for every column in that row.

In code, this translates to a for loop nested inside another for loop.

window.addEvent("domready", function()
{
	var canvas = document.getElementById("checkerboard");
	var context2D = canvas.getContext("2d");

	for (var row = 0; row < 8; row ++)
	{
		for (var column = 0; column < 8; column ++)
		{
			// coordinates of the top-left corner
			var x = column * 50;
			var y = row * 50;

			context2D.fillStyle = "black";
			context2D.fillRect(x, y, 50, 50);
		}
	}
});

 

x and y coordinates of a cell’s top-left corner are the cell’s column and row indices times the rectangle’s width and height.

Open “index.html” in a web browser, you should see a 400×400 black rectangle.

Alternating black and white

Alternating colors can be done using the following algorithm :

  • In even rows, cells in even columns are black and those in odd columns are white.
  • In odd rows, cells in even columns are white and those in odd columns are black.

We’ll implement this algorithm using if/else statements :

window.addEvent("domready", function()
{
	var canvas = document.getElementById("checkerboard");
	var context2D = canvas.getContext("2d");

	for (var row = 0; row < 8; row ++)
	{
		for (var column = 0; column < 8; column ++)
		{
			// coordinates of the top-left corner
			var x = column * 50;
			var y = row * 50;

			if (row%2 == 0)
			{
				if (column%2 == 0)
				{
					context2D.fillStyle = "black";
				}
				else
				{
					context2D.fillStyle = "white";
				}
			}
			else
			{
				if (column%2 == 0)
				{
					context2D.fillStyle = "white";
				}
				else
				{
					context2D.fillStyle = "black";
				}
			}

			context2D.fillRect(x, y, 50, 50);
		}
	}

});

 

We used the fact that if a number modulus 2 equals zero, then the number is even.

Open “index.html” in a web browser and look at your beautiful 8×8 checker board.

Final Touch

As a final touch, let’s draw a border around the checker board.

We can do this easily using CSS, let’s get back to “index.css” and add a border to canvas :

<!DOCTYPE html>
<html>
	<head>
		<title>Checker Board</title>

		<script src="mootools-1.4.5.js"></script>
		<script src="checkerboard.js"></script>

		<style>
			#checkerboard {
				border: 1px solid black;
			}
		</style>
	</head>

	<body>
		<canvas id="checkerboard" width="400" height="400">
		</canvas>	
	</body>
</html>

 

The checker board looks nicer with a border around it, don’t you think ?

Open “index.html” in a web browser and see for yourself.

Conclusion

In this article, we learned how to draw rectangles of any color using HTML5 Canvas. Then we applied this knowledge to a more complex example :  drawing a checker board.

There’s a lot of amazing things you can do with canvas that are not covered by this tutorial.

Have a look at Mozilla’s Developer Network for more informations. You can also check Canvas From Scratch tutorials at nettuts.

Keep in touch !