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.black;
   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.gradient(((row+column)%2===0)?this.lightGrey:this.white);
       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(){
   this.resetBackground();
 },
 initCanvas: function(){
   var s="#"+this.graphDiv;
   this.ctx = $( '<canvas />', {width:this.width, height:this.height} ).appendTo(s)[0   ].getContext('2d');
  },
 };
$(document).ready(function(){
   chess.initCanvas();
   chess.initValues();
   chess.resetBackground();
   chess.drawGrid();
});

HTML code ex. chessboard.html :


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

3 thoughts on “Javascript Canvas, empty chess board

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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