For循环在Javascript中的for循环
问题描述:
我有新的项目: 15用5行绘制一个框,以便一旦你写下你的代码fillRect()函数。 对应于当前行号的每一行是正方形(例如,第三排的三个方格中)。为什么不工作:(For循环在Javascript中的for循环
var c= document.getElementById('myCanvas').getContext('2d');
var a= 10;
var b= 10;
var cw= 40;
var ch= 40;
for(i=1; i<= 5; i++){
for(j=1; j<= 5; j++){
c.fillStyle= '#fff947';
c.fillRect(a,b,cw,ch);
}
}
答
你失踪在你内心的大括号。循环的代码和你不动的X,Y值时,额外的箱子需要在额外的行所做的
看评论内嵌的详细信息:
var can = document.getElementById('myCanvas');
can.style.width = "500px";
can.style.height = "500px";
var ctx = can.getContext('2d');
var x = 10;
var y = 10;
var w = 10;
var h = 10;
// Need to keep track of a horizontal indentation amount
// on rows where more than one box should be drawn.
var offsetX = 0;
for(i = 1; i < 6; i++){
// Each new row should have the default indentaion
offsetX = 10;
// This loop needs to execute the amount of times that the
// outer loop has run (i.e. when i is 1, j should be 2
// so that this loop will run once. This loop also needs
// curly braces around its code.
for(j = 1; j < i + 1; j++){
ctx.fillStyle = '#fff947';
ctx.strokeRect(x + offsetX, y, w, h);
ctx.fillRect(x + offsetX, y, w, h);
// On a given row, after making a box, increase the horizontal offset
// by the width of one box.
offsetX += w;
}
// After a row has been made, increase the vertical offset so that the
// next boxes go below the previous ones. Change the y value to be the
// old y value plus the height of a box plus 5 pixels just for a margin
// between rows.
y += (h + 5);
}
<canvas id="myCanvas"></canvas>
为什么你25次做同样的事情? –
两个循环内的代码应该依赖'i'和'j'。 –
这是内循环中缺失的大括号。投票结束作为印刷错误。 – lonesomeday