Pages

Wednesday, 28 November 2012

Creating Chess Board Layout Using Pixel Manipulation in HTML5 Canvas

The canvas element in HTML5 can be used to render any graphical content. Shapes, paths, text and even images can be drawn on canvas. Canvas doesn’t support animations, but animations can be created by writing some additional JavaScript code.

Using the pixel manipulation feature of canvas, we can draw images or change colours of existing images. To manipulate pixels, we have to follow the following steps:

Create an image data object to draw on the canvas context

Loop through each pixel in the area to be drawn

Set RGBA values to current position inside the loop

Put the image on the canvas context

To draw something specific, we have to logically divide the area to be drawn and manipulate carefully. With this understanding, let’s start drawing a chess board layout.

This is the entire HTML needed for this demo. To draw image on it, we have to write some JavaScript code. Following operations have to be performed inside the JavaScript code:

Obtain JavaScript object of the canvas element

Get the canvas context

Follow steps to draw image

Canvas element will be ready to operate once the entire page is loaded. So, above operations have to be performed once the page is loaded. Following script gets the canvas object and object of the 2-dimensional context:

To draw on the canvas, we have to get an image data object. Canvas context has a function createImageData that returns the object we need, but it is not supported on all browsers. Following snippet shows different ways of obtaining an object using which we can draw some colors on the canvas:

Now that we have the object using which we can achieve what we have to do, let’s think about the logic to draw a chess board layout.

As we all know, a chess board has alternate arrangement of white and black colors. On observing a bit, we can say that the color of last cell on a row is repeated on first cell of next row. Keeping this point in mind and calculating pixels on which we have to draw, I came up with the following logic:

About Me

I am a software developer working on and passionate about Microsoft Technologies and anything new in the Web world. Lately, spending a lot of time with JavaScript and finding it much deeper than what I knew for past few years. I enjoy writing code and writing about code. My contribution to community earned me a Microsoft MVP award (ASP.NET/IIS) and a DZone MVB award. When not in front of computers, like to spend time with melodious Hindi and Telugu tunes or watching Cricket