首页 > 解决方案 > 棋盘画布,循环并在 JS 画布中将一些棋子作为圆圈

问题描述

我正在努力如何在棋盘上创建多个检查器到目前为止我有这个 JS 代码:

<script>
  $(document).ready(function() {
      var gColor = "black";
      var c = $("#myCanvas")[0];
      var ctx = c.getContext("2d");

      ctx.lineWidth = 2;
      ctx.strokeStyle = "black";    //set the color, gradient, or pattern for stroke

      drawBoard();
      $("#color").click(function () {
          gColor = $("#color").val();
          if (gColor > "")
              drawBoard();
      });

    function drawBoard() {
      var x, y, step = 60, step2 = 120;
      ctx.rect(0,0,480,480);
      ctx.stroke();
      ctx.save();

      for (var k=0; k<2; k++)  {
          step2 -= step;
          ctx.translate(0, step*k);
          console.log("translate:("+0+","+step*k+")");
          for (var y=0; y<4; y++) {
              for (var i=0; i<4; i++)  {
        x = i * 2 * step + step2;
        ctx.fillStyle = gColor;
        ctx.fillRect(x,y*step*2,step,step);
                  console.log("fillRect: "+x+","+y*step*2+","+step+","+step+","+gColor);
              }
          }
      }
      ctx.restore();
    }

    var c = $("#myCanvas")[0];
    var ctx = c.getContext("2d");

    var rad = 90;
    for (var i=0; i<1; i++)  {
      switch (i)  {
        case 0:  ctx.fillStyle = "red";
        break;
      }
  ctx.beginPath();

  //  Draw circle (x, y, radius, starting angle, ending angle in radian)
  ctx.arc(30, 30, 30, 0, 2 * Math.PI);
  ctx.fill();
  ctx.stroke();

    }

  });

  </script>

我知道我需要做某种循环,但因为我只是在学习画布,所以我不知道从哪里开始。任何帮助或建议表示赞赏

标签: javascriptjquerycanvas

解决方案


for (var i=0; i<1; i++)  {
  switch (i)  {
    case 0:  ctx.fillStyle = "red";
    break;
  }


ctx.beginPath();

  //  Draw circle (x, y, radius, starting angle, ending angle in radian)
  ctx.arc(30, 30, 30, 0, 2 * Math.PI);
  ctx.fill();
  ctx.stroke();

您正在绘制的 Circle 位于 for 循环之外,并且硬编码值为 30 作为 x 和 30 作为 Y

您还需要使用与创建黑色方块相同的逻辑来创建圆圈

你的正方形是 60, 60 所以,

var size = 60;
var rows = 8;
var cols = 8;

for (let i=0; i < rows; i++) {
    for (let j=0; j < cols; j++) {
        // J is the column Identifier
        // I is the row identifier

        var x = j*size + (size/2); // j*size takes the center of cicle at the begining of current square + size/2 makes it at the exact center of square
        var y = i*size + (size/2); // i*size takes the center of circle at the top of current square, same to bring vertical center size/2 is added

        ctx.beginPath();
        //  Draw circle at (x, y, radius, starting angle, ending angle in radian)
        ctx.arc(x, y, (size/2), 0, 2 * Math.PI); // radius is half of square width
        ctx.fill();
        ctx.stroke();
    }
}

这将在每个正方形上绘制圆圈。

问题不在于画布,而在于迭代和计算圆的 x 和 y 位置的简单逻辑。我认为您应该阅读更多关于循环的内容,这将对您有所帮助。


推荐阅读