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>
Reblogged this on Ancien Hippie.
LikeLiked by 1 person
Excellent article. I will be dealing with some of
these issues as well..
LikeLike
I am always up for a match of chess: http://andreasmoser.wordpress.com/2012/04/07/wasting-time-chess/
LikeLike