How do I alter my code to generate a checkered board in javascript?

Viewed 55

My goal is to create a 20x20 grid, each block 30 pixels wide and have the grid colored in a checkered pattern of white and light gray.

function draw(){

    for(y = 0; y < 20; y++){
        for(x = 0; x < 20; x++){
         rect = ctx.rect(x*30, y*30, 30, 30)
            
        }
    }
   
    ctx.strokeStyle = "black";
    ctx.lineWidth = 0.75;
    ctx.stroke();  
 

    for(y = 0; y < 20; y+=2){
        for(x = 0; x < 20; x+=2){
         rect = ctx.rect(x*30, y*30, 30, 30)
         ctx.fillStyle="gray";
         ctx.fillRect(x*size, y*size, size, size);
        }
    }
    
}   
    draw();

When I run this code,I get a 20 by 20 grid and every other row fills in every other block with the color gray. I would appreciate some tips on how to modify this, so I can get a checkered pattern. Thank you!

1 Answers

Solution

let canvas = document.querySelector(".canvas");
let ctx = canvas.getContext("2d");
let size = 30;
function draw() {
  for (y = 1; y <= 20; y++) {
    for (x = 1; x <= 20; x++) {
     let rect = ctx.rect(x * size, y * size, size, size);
     let isEven = y%2==0;

     if (x % 2 === 0) {
        ctx.fillStyle = isEven? "gray":"white";
      } else {
        ctx.fillStyle = isEven?"white":"gray";
      }
      ctx.fillRect(x*size, y*size, size, size);
    }
  }
  ctx.strokeStyle = "black";
  ctx.lineWidth = 0.75;
  ctx.stroke();
}
draw();
<canvas class="canvas" height="1000px" width="1000px"></canvas>

Related