如何使用 javascript 为 canvas 坐标网格的背景着色?

How to color the background of a canvas coordinate grid on click using javascript?

如何 select 多个方块并在 canvas 和 javascript 上单击更改它们的背景颜色?

到目前为止,我可以“绘制”canvas 和坐标网格。我无法弄清楚的部分是如何更改 selected 方块的背景颜色以及如何对多个方块做同样的事情(select 用鼠标对它们进行操作)?

function draw() {

      var canvas = document.getElementById('canvas');
      if (canvas.getContext) {
        var context = canvas.getContext('2d');

        for(var x=0.5;x<500;x+=10) {
          context.moveTo(x,0);
          context.lineTo(x,500);
        }

        for(var y=0.5; y<500; y+=10) {
          context.moveTo(0,y);
          context.lineTo(500,y);

      }

      context.strokeStyle='grey';
      context.stroke();

  }
}

function color(event) {
    var x = event.clientX - 10;
    var y = event.clientY - 10;
    
    console.log(x + ' ' + y);
    // how to color the selected squares?
  }
#canvas { border: 1px solid black;}
<body onload='draw()'>
    <div id=container>
      <canvas id='canvas' width='500' height='500' onclick="color(event)"></canvas>
    </div>
</body>

保持状态是个好主意。在这里,我开始创建一个包含对象的二维数组(数组的数组)。对象状态可以selected=true|false.

在 draw() 函数中,我迭代数组并根据对象的状态设置 fillStyle。

在 color() 函数中,我计算了对象的索引并将选定的 属性 设置为 true。然后我再次绘制 canvas。

var squares = [...new Array(50)].map((a,i) => [...new Array(50)].map((a,i) => {return {selected: false};}));

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
function draw() {
  if (canvas.getContext) {
    context.fillStyle = 'black';
    context.fillRect(0, 0, 501, 501);
    squares.forEach((line, i) => {
      line.forEach((square, j) => {
        context.fillStyle = (square.selected) ? 'red' : 'white';
        context.fillRect(10*j+1, 10*i+1, 9, 9);
      });
    });
  }
}

function color(event) {
  var x = Math.floor((event.clientX - 10) / 10);
  var y = Math.floor((event.clientY - 10) / 10);
  squares[y][x].selected = true;
  draw();
}
#canvas {
  /*border: 1px solid black;*/
}
<body onload='draw()'>
  <div id=container>
    <canvas id='canvas' width='501' height='501' onclick="color(event)"></canvas>
  </div>
</body>