How to Draw a Chessboard in HTML Canvas Using JavaScript

The canvas HTML element provides a bitmap area for graphics drawing. The canvas was standardized across various browsers in the HTML5 specification. Using JavaScript, we can draw 2D/3D images and animation on a canvas. Almost all modern browsers support canvas. With a hardware accelerated browser, Canvas can produce fast 2D graphics.

The following tutorial is intended as an introduction to Canvas 2D drawing using JavaScript. We will draw a chess board using some of the basic drawing primitives available on the canvas element. See the Mozilla canvas tutorial for a detailed look at the canvas API.

Let us create a simple HTML file(index.html) which contains the canvas element. Using the script tag, we will import the the JavaScript file(chess.js) containing the drawing commands for chessboard. When the HTML file is opened in a browser, the onload event on the body tag is triggered. This in turn calls the JavaScript method drawChessboard() defined in the script tag of the HTML page. The full source code of the index.html is given below.

    <meta charset="UTF-8">
    <title>Draw Chess Board</title>
    <script src="chess.js"></script>
  <body onload="drawChessboard()">
    <canvas id="canvasChessboard" width="800px" height="500px"></canvas>

Let us now create chess.js which contains the JavaScript code for drawing the chessboard. Ensure that you have chess.js and index.html in the same folder. The full source code of chess.js is given below,

function drawChessboard() {
  // size of each chess square
  const squareSize = 50;
  // position of board's top left
  const boardTopx = 50;
  const boardTopy = 50;
  let canvas = document.getElementById("canvasChessboard");
  context = canvas.getContext("2d");
  for(let i=0; i<8; i++) {
    for(let j=0; j<8; j++) {
      context.fillStyle = ((i+j)%2==0) ? "white":"black";
      let xOffset = boardTopx + j*squareSize;
      let yOffset = boardTopy + i*squareSize;
      context.fillRect(xOffset, yOffset, squareSize, squareSize);
  // draw the border around the chessboard
  context.strokeStyle = "black";
  context.strokeRect(boardTopx, boardTopy, squareSize*8, squareSize*8)

The drawChessboard() method gets a reference to the canvas element using the getElementById() method. We then create a 2d drawing context using the getContext() method of canvas object. Finally a nested loop draws all the 64 squares of the chess board. The squares are drawn using white or black color depending on the position of the square in the board.

The final output of the chessboard drawing JavaScript code is given below,
chessboard in javascript