How can I change the fill colors of each box for a chessboard in JS, using Canvas?

Viewed 901

I just had a quick thought in mind of drawing a chessboard using JS and Canvas, and I have this code that draws the boxes alright with for loops.

canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");

var x, y,
  boxWidth = 30,
  boxHeight = 30;

for (x = 0; x < canvas.width; x += boxWidth) {
  for (y = 0; y < canvas.height; y += boxHeight) {
    ctx.beginPath();
    ctx.rect(x, y, boxWidth, boxHeight);
    ctx.stroke();
    ctx.closePath();
  }
}
<canvas id="canvas" width="240" height="240"></canvas>

Now I'm wondering how I can access each odd box on the axes to change their fill colors (e.g. black, white, black, white, and so on).

I know using global variables isn't the best way, but this is a very small project and I just want to get some logic on how I can alternate the colors of the chessboard. Your help is very much appreciated!

5 Answers
Related