Javascript 使用 ctx 的带有交替颜色列的绘图板

Javascript drawing board with columns of alternating colors using ctx

我想编写一个 javascript 代码,使电路板显示为这张图片中的样子: 1
到目前为止,这是我的代码:

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);
                                }
                            }
}

截至目前,它只显示垂直线。我需要做哪些更改才能使其看起来像图像?

您应该将 x 值除以增量 (10) 并检查其模数 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>

我更喜欢让我的循环总是递增 1 并乘以所需的大小。它可以帮助您在复杂的应用中更好地保​​持轴承。然后我简单地对 2 求模,因为它比除以 increment.That 更容易阅读,也允许更清晰地配置你的网格大小。

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);
       }

    }

}