My goal is to create a 20×20 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!
You can clear the whole screen to one of your colours. You can then step through two loops (one for y and another for x) Instead of drawing every single square, maintain a counter and just draw every second one. This way, all of the squares of 1 colour will be drawn with a single call and a counter that’s odd or even is the shortest way I can think of to colour the rest. You might need to be careful to begin and close paths if you’re using stroke to draw lines.