2013-03-21 23 views
1

當我按Ctrl + A突出顯示我繪製的所有畫布,最後一行似乎是空白或全部組合。我正在嘗試製作一個4x4的油畫網格。我的邏輯錯誤是什麼?4x4畫布繪圖中的邏輯錯誤

var count = 0; 
while (count < 16) { 
    if (count % 4 == 0) 
     document.write("<br><canvas id = \"canvas_ \" + count + \" width = \"50\" height = \"  50\"></canvas>"); 
    else 
     document.write("<canvas id = \"canvas_ \" + count + \" width = \"50\" height = \" 50\"></canvas>"); 
    count++; 
} 

回答

1

我已經重寫你的代碼位:

var count = 0; 
while (count < 16) { 
    if (count % 4 == 0) 
     document.write('<br>'); 
    document.write('<canvas id="canvas_' + count + '" width="50" height="50"></canvas>'); 
    count++; 
} 
document.write('<br>'); 

其他不僅僅是提高了編碼風格的方式(例如,使用這兩種引號的),我增加了一個<br>在結束,因爲這是導致最後一行不被選中的原因。

添加canvas { border: 1px solid #000 }使它看起來像這樣:

a

+0

如果我計數<= 16,那麼在底部繪製另外一個圖案 – Kelvin 2013-03-21 17:15:59

+0

@Kelvin我已經更新了我的答案。 – 2013-03-21 17:39:02

0

你的代碼是好的,但是當你按下CTRL +一個元素<br/>接縫它沒有選擇該畫布元素。它將在最後添加一個<br/>時起作用。而且你的代碼計數中的錯誤也在字符串內。

var count = 0; 
document.write("<br>"); 
while (count < 16) { 
    document.write("<canvas id=\"canvas_" + count + "\" width=\"50\" height=\"50\"></canvas>"); 
    count++; 
    if (count % 4 == 0) { 
     document.write("<br>"); 
    } 
} 
+0

謝謝!它的作品,你是一個拯救生命的人。 – Kelvin 2013-03-21 17:29:00

+0

一件事,當我有這樣的代碼跟上面你貼,它說,畫布的一個是空..... 而(計數<16){ \t \t變數名稱=「canvas_」 +計數; \t \t var canv = document.getElementById(name); \t \t \t var ctx = canv.getContext(「2d」); \t \t \t如果(計數%2 == 0){ \t \t \t \t ctx.fillStyle = 「#FF0000」; \t \t \t \t}否則{ \t \t \t \t ctx.fillStyle = 「#00FF00」; \t \t \t \t} \t \t \t \t ctx.fillRect(0,0,50,50); \t \t \t \t count ++; \t \t \t \t} – Kelvin 2013-03-21 17:31:31

+0

@Kelvin作爲一個猜測,這是因爲' 2013-03-21 17:37:06