【问题标题】:Using for loop to print grid in JavaScript在 JavaScript 中使用 for 循环打印网格
【发布时间】:2019-09-06 11:44:16
【问题描述】:

我正在尝试使用四个循环创建一个小网格来连接四个游戏。我已经为 X 和 Y 轴打印了圆圈,但我只能成功打印 1 行,我试图在画布上打印七次,但我创建的 for 循环似乎不起作用。

var x = 30;

var y = 30; 

function setup(){

createCanvas(300,300);
background(0);

for(i=0; i<=6; i++){
    for(i=0; i<=6; i++){
        x+=30;
        circle(x, y, 20);
            for(i=0; i<=6; i++){
                y+=30;
                circle(x, y, 20);
        }
    }   
}
    }
    setup();

我正在努力实现这一目标:

【问题讨论】:

  • 您是否对所有循环使用相同的变量??
  • 我对所有循环使用相同的 var x 和 var y 变量
  • 注意:您可以考虑为此使用模式,而不是 for 循环。

标签: javascript html css loops canvas


【解决方案1】:

也许这就是你需要的:

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let cw = (canvas.width = 300),
  cx = cw / 2;
let ch = (canvas.height = 300),
  cy = ch / 2;
//the circles radius
let ar = 30;
//the red and yellow clees index
let red = [10, 23, 30, 31, 37, 40];
let gold = [16, 17, 24, 32, 38, 39];

let n = 0;// a counter
let cellw = cw / 7;// the width of a cell

//the loop:

  for (let y = cellw / 2; y < ch; y += cellw) {
    for (let x = cellw / 2; x < cw; x += cellw) {
    ctx.beginPath();
    ctx.arc(x, y, ar / 2, 0, 2 * Math.PI);
    //set the color of the circles
    for (let i = 0; i < red.length; i++) {
      if (n == red[i]) {
        ctx.fillStyle = "red";
        break;
      } else if (n == gold[i]) {
        ctx.fillStyle = "gold";
        break;
      } else {
        ctx.fillStyle = "white";
      }
    }
    ctx.fill();
    n++;
  }
}
body {
  background-color: #222;
  overflow: hidden;
}
canvas {
  background-color: #000;
  display: block;
  position:absolute;
  margin: auto;
  top:0;bottom:0;left:0;right:0
}
&lt;canvas id="canvas"&gt;&lt;/canvas&gt;

【讨论】:

    【解决方案2】:

    是的,for 循环有问题。

    您只需要 2 个循环即可。

    for (let row = 0; row <= 6; row++) {
      for (let column = 0; column <= 6; column++) {
        circle(row * 30, column * 30, 20)
      } 
    }
    

    【讨论】:

      【解决方案3】:

      您确实有三个使用i 的循环,实际上所有循环都将在相同的数字上运行,因此内部循环将循环 6 次,而不是所有三个循环都结束。由于您的目标是遍历 x 和 y,因此只需使用它们:

        for(let x = 1; x < 6; x++) { // always declare variables with let!
          for(let y = 1; y < 6; y++) {
             circle(x * 30, y * 30, 20); // just keep as many varoables as necessary, the position can easily be derived from the index
          }
       }
      

      【讨论】:

        【解决方案4】:

        更改循环结构 - 迭代 7 次并在每次迭代结束时增加 y,并在渲染圆圈的循环内迭代,并增加 x

        for (let i = 0; i < 6; i++) {
            x = 30;
            for (let j = 0; j < 7; j++) {
                circle(x, y, 20);
                x += 30;
            }
            y += 30;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-12-25
          • 2013-02-20
          • 2012-04-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-12-23
          相关资源
          最近更新 更多