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.
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.
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.
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.
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>
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
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.
We will use Mootools to execute our drawing code after the webpage is created.
Edit 17/09/2014 : You don’t have to use Mootools for this, it is not the only solution, browsers natively implement events to execute a code after page finishes loading (window.onload), there’s also jquery’s $(document).ready(). I used Mootools to introduce the concept because I kinda like this framework, it has nice OOP support for beginners. However, it comes at a cost, don’t get me started on that here, I’ll talk about it in a full article maybe.