2017-02-19 334 views
1

我有新的項目: 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); 
    } 
} 
+2

爲什麼你25次做同樣的事情? –

+0

兩個循環內的代碼應該依賴'i'和'j'。 –

+2

這是內循環中缺失的大括號。投票結束作爲印刷錯誤。 – lonesomeday

回答

1

你失蹤在你內心的大括號。循環的代碼和你不動的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>