Javascript Canvas, empty chess board

Short example of how to draw a empty chess grid using canvas and javascript.

Javascript Code, save as chessboard.js:

var chess={
 ctx: null,
 width: 402,
 height: 402,
 white: "#fff",
 lightGrey: "#000000",
 black: "#000000",
 squareWidth: 0,
 squareHeight: 0,
 graphDiv: "chessCanvas",

 initValues: function(){
   this.squareWidth = (this.width-2) / 8;
   this.squareHeight = (this.height-2) / 8;

 resetBackground: function(){
   this.ctx.canvas.width = this.width;
   this.ctx.canvas.height = this.height;
   this.ctx.fillStyle =;
   this.ctx.fillRect(0, 0, this.width, this.height);

 drawSquare: function(x, y){
   this.ctx.fillRect(x, y, this.squareWidth, this.squareHeight)
 drawGrid: function(){
   var x = 0;
   var y = 0;
   for (var row=0; row < 8; row++){
     for (var column=0; column < 8; column++){
       this.drawSquare(1+(row * this.squareWidth),1+(column * this.squareHeight));
 gradient: function(color){
   var gradient = this.ctx.createLinearGradient(0,0,0,this.squareHeight);
   gradient.addColorStop(1, color);
   gradient.addColorStop(1, "#ffffff");
   this.ctx.fillStyle = gradient;

 drawBoard: function(){
 initCanvas: function(){
   var s="#"+this.graphDiv;
   this.ctx = $( '<canvas />', {width:this.width, height:this.height} ).appendTo(s)[0   ].getContext('2d');

HTML code ex. chessboard.html :

<!DOCTYPE html>
  <title>Wonderfull Chess</title>
  <meta charset="UTF-8"/>
  <script src=""></script>
  <script src="chessboard.js"></script>
<body bgcolor="lightgrey">
  <div id="chessBoard">
    Welcome to the wonderfull chess game!
  <div id="chessCanvas"></div>

3 thoughts on “Javascript Canvas, empty chess board

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s