2017-02-19 12 views
1

У меня есть новый проект: 15 Нарисуйте ящик с 5 строками, чтобы после того, как вы запишите свой код для функции fillRect(). Каждая строка, соответствующая номер текущей строки квадратная (например, в третьем ряду из трех квадратов) .Why не работает :(Для цикла в цикле в 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

Код внутри двух циклов должен зависеть от 'i' и' j'. –

+2

Это недостающие фигурные скобки на внутренней петле. Голосование закрывается как типографская ошибка. – lonesomeday

ответ

1

Вы отсутствовали в фигурных скобках вокруг вашего внутреннего . код цикла и не перемещались х, у значения, когда дополнительные ящики должны быть сделаны на дополнительных строках

Смотреть комментарии рядных подробностей:

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>

Смежные вопросы