使用for循环在JavaScript中打印网格

时间:2019-04-16 11:24:24

标签: javascript html css loops canvas

我正在尝试创建一个小的网格,以使用四个循环连接四个游戏。我已经为X和Y轴打印了圆圈,但是我只能成功打印1行,我试图在画布上打印7次,但是我创建的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();

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

https://cdn-images-1.medium.com/max/1600/1*A5b630g96x9PrhwB9Mvf1w.png

4 个答案:

答案 0 :(得分:1)

更改循环结构-迭代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;
}

答案 1 :(得分: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
}
<canvas id="canvas"></canvas>

答案 2 :(得分:0)

您确实有三个使用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
    }
 }

答案 3 :(得分:0)

是的,for循环中有问题。

您只需要进行2次循环即可。

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