Javascript drawing board with columns of alternating colors using ctx

167 views Asked by At

I would like to write a javascript code such that the boards appears as it is in this image: 1
This is my code so far:

function draw() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x, y;

    for (y=0; y<100; y+=10) {
        for (x=0; x<100; x+=5) {
            if ((x+y)%10 == 0) {
                    ctx.fillStyle = "black";
                                } 
                else {
                     ctx.fillStyle = "white";
                        }
                     ctx.fillRect(x, y, 10, 10);
                                }
                            }
}

As of now, it only displays vertical lines. What changes do I need to make, in order for it to appear like the image?

2

There are 2 answers

1
Kaiido On BEST ANSWER

You should divide your x value by the increment (10) and check its modulo 2 :

function draw() {
  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');

  for (var y = 0; y < 100; y += 10) {
    for (var x = 0; x < 100; x += 10) {
      if ((x/10) % 2 == 0) {
        ctx.fillStyle = "black";
      } else {
        ctx.fillStyle = "red";
      }
      ctx.fillRect(x, y, 7, 7);
    }
  }
}
draw()
<canvas id="canvas" height="100" width="100"></canvas>

2
FlavorScape On

I prefer to have my loops always increment by 1 and multiply by desired size. It helps you keep your bearings better in a complex application. Then I simply modulo on 2 because it's easier to read than dividing by an increment.That also allows for clearer configuration of your gridsize.

function draw() {
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    var x, y;


    var xWidth = 10;
    var yWidth = 10;

    for (x=0; x<10; x++) {

        if( x % 2 === 0)
        {
            ctx.fillStyle = "white";
        } else {
            ctx.fillStyle = "black";
        }

       for( y = 0; y < 10 ; y++)
       {
           ctx.fillRect(x * xWidth, y * yWidth, 10, 10);
       }

    }

}