2015-09-20 57 views
0

我想要做的是用随机颜色的32x32块填充myCanvas。我正在使用循环来创建块并为它们分配颜色。我已经想出了在循环继续时如何让线在Y轴上下降,但是我无法将我的头围绕在正确的X轴上。JavaScript Loop在画布上创建网格

如果你让画布变大,你会看到20块长方块向右走。

var c=document.getElementById("myCanvas"); 
     var ctx=c.getContext("2d"); 
     for (i = 0; i < 400; i++) { 
      var X = i * 32; 
      var Y = Math.floor(i/20) * 32; 
      ctx.fillStyle='#'+Math.floor(Math.random()*16777215).toString(16); 
      ctx.fillRect(X, Y, 32, 32); 
      console.log('X:' + X); 
      console.log('Y:' + Y); 
     } 

我使用模这样的尝试:

if(i % 20 == 0){ 
X = 0; 
} 

但它仅仅修复它,当我得到20的倍数所以只有在画布的左侧将充满块。我的问题是在包含完成这个任务的数学方面。对不起,我很累了,新在这个:(

小提琴:http://jsfiddle.net/orwfo7re/

回答

1

你已经非常接近与模量的建议不过! ,你if语句只被执行i % 20 == 0,东西,比如是不是真实i=21

的SOLUT离子只是在你的算法中使用var x = (i % 20) * 32作为var x。所以:

var c=document.getElementById("myCanvas"); 
var ctx=c.getContext("2d"); 
for (i = 0; i < 400; i++) { 
    var X = (i % 20) * 32; 
    var Y = Math.floor(i/20) * 32; 
    ctx.fillStyle='#'+Math.floor(Math.random()*16777215).toString(16); 
    ctx.fillRect(X, Y, 32, 32); 
} 

小提琴:https://jsfiddle.net/MartyB/ur9vug0x/2/

+0

非常感谢您! – Cancler

1

你的意思是做这样的事情:

var c=document.getElementById("myCanvas"); 
      var ctx=c.getContext("2d"); 
      var width = 640; 
      var height = 640; 

      for (y=0; y< height; y=y+32) { 
       for (x=0; x < width; x=x+32) { 
       ctx.fillStyle='#'+Math.floor(Math.random()*16777215).toString(16); 
       ctx.fillRect(x, y, 32, 32); 
       } 
      } 
+0

感谢我居然看着嵌套循环一点点,它修复了,希望我能让他们两个答案:( – Cancler