A chessboard using javascript and html5 canvas

Jun 1, 2014 • val antonini

A chessboard using HTML5 canvas. The number of row/columns is configurable and the tiles autosize to fill the canvas minus padding.

chessboard
(click the image to see the example)

The Javascript:

var gridWidth = 400;
var gridHeight = 400;
var gridPadding = 10

var tilesWide = 8;
var tilesHigh = 8;

var tileWidth = (gridWidth / tilesWide);

var tileHeight = ( gridHeight / tilesHigh );

var canvasWidth = gridWidth + (2 * gridPadding);
var canvasHeight = gridHeight + (2 * gridPadding);

var canvas = $('<canvas></canvas>').attr({
    width: canvasWidth,
    height: canvasHeight
}).appendTo('#chessboard');

var context = canvas.get(0).getContext("2d");

drawBoard();

function drawBoard() {

    drawBackground();

    for (var row = 0; row <= tilesHigh - 1; row++) {

        var y = (row * tileHeight) + gridPadding;

        for (var column = 0; column <= tilesWide - 1; column++) {

            var x = (column * tileWidth) + gridPadding;

            if (isAlternate(row, column)) {
                drawFilledSquare(x, y);
            }
            else {
                drawEmptySquare(x, y);
            }
        }
    }

    context.strokeStyle = "black";
    context.stroke();
}

function drawBackground() {
    context.fillStyle = "#ffffff";
    context.fillRect(0, 0, canvasWidth, canvasHeight);
}

function drawEmptySquare(x, y) {
    context.rect(x, y, tileWidth, tileHeight);
}

function drawFilledSquare(x, y) {
    context.fillStyle = "#000000";
    context.fillRect(x, y, tileWidth, tileHeight);
    drawEmptySquare(x, y);
}

function isAlternate(row, column) {
    return (isEven(row) && !isEven(column)) ||
            (!isEven(row) && isEven(column))
}

function isEven(num) {
    return num == 0 || num % 2 == 0;
}

The css:

body {
    background-color: gray;
}

canvas {
    margin: 50 auto;
    display: block;
}

The markup:

<div id="chessboard"></div>