2017-02-19 29 views
1

私は新しいプロジェクトを持っています: 15コードをfillRect()関数に書き留めるように5行のボックスを描画します。 (例えば3つの正方形の3行目).Whyあなたは、あなたの内側の周りにカーリー・ブレースが欠落した:(forループのJavascriptで

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

2つのループ内のコードは '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>