In our blog today we will draw a simple chess board using HTML5 Canvas. We will draw simple black and white boxes to create it using canvas API of HTML5.
Canvas features
It is basically used to draw graphics on the webpage.
It acts as a container.
It has only two parameters namely height and width. Both are defined by user,if not set by user it automatically initialized as 300px wide and 150px height.
Lets get started
Step 1
Create you html page and define the title and head
<!DOCTYPE html> <html> <head> <title> Chess Board</title> </head>
Step 2
Define the canvas attributes
<body> <canvas id="myCanvas" width="560" height="560" style="border:2px solid #d3d3d3;"> Your browser does not support the HTML5 canvas tag.</canvas>
Step 3
Add the following script which draws the chess board using loops.
<script> var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); for(i=0;i<8;i++) {for(j=0;j<8;j++) {ctx.moveTo(0,70*j); ctx.lineTo(560,70*j); ctx.stroke(); ctx.moveTo(70*i,0); ctx.lineTo(70*i,560); ctx.stroke(); var left = 0; for(var a=0;a<8;a++) { for(var b=0; b<8;b+=2) { startX = b * 70; if(a%2==0) startX = (b+1) * 70; ctx.fillRect(startX + left,(a*70) ,70,70); }} }} </script> </body> </html>
In the code above we have taken a cell width to be 70 pixels and we are looping it 8 times to draw the content.