2017-10-20 105 views
2

我有我的數組,並且我想根據陣列中每個對象內部的內容來顯示數組。我有這裏的循環,但我似乎得到ctx.fillRect工作。我的循環會循環,但它不會顯示我想要的

var c = document.getElementById("can"); 
 
var ctx = c.getContext("2d"); 
 
var blocks = []; 
 

 
var rows = [0, 1, 2, 3]; 
 

 
function Block(h, w, x, y, c) { 
 
    this.h = h; 
 
    this.w = w; 
 
    this.x = x; 
 
    this.y = y; 
 
    this.c = c; 
 
} 
 
ctx.fillRect(900, 400, 10, 10) 
 
for (var i = 0, len = rows.length; i < len; i++) { 
 
    for (var j = 0; j < 10; j++) 
 
    blocks.push(new Block(10, 20, j * 30, i * 30, rows[i])) 
 
} 
 

 
function draw() { 
 
    ctx.fillStyle = "black"; 
 
    for (var i = 0, len = blocks.length; i < len; i++) { 
 

 
    for (var j = 0, len2 = blocks[i].length; j < len2; j++) { 
 

 
     ctx.fillRect(blocks[i][j].x, blocks[i][j].y, blocks[i][j].w, blocks[i][j].h); 
 

 
    } 
 
    } 
 
} 
 
setInterval(draw, 1000);
<canvas id="can" height="500" width="1000"></canvas>

+0

你嘗試檢查塊[I]。長度和其他屬性?這是未定義的.. – Optional

回答

5

blocks不是一個多維數組。

var c = document.getElementById("can"); 
 
var ctx = c.getContext("2d"); 
 
var blocks = []; 
 

 
var rows = [0, 1, 2, 3]; 
 

 
function Block(h, w, x, y, c) { 
 
    this.h = h; 
 
    this.w = w; 
 
    this.x = x; 
 
    this.y = y; 
 
    this.c = c; 
 
} 
 

 
for (var i = 0, len = rows.length; i < len; i++) { 
 
    for (var j = 0; j < 10; j++) 
 
    blocks.push(new Block(10, 20, j * 30, i * 30, rows[i])) 
 
} 
 

 
function draw() { 
 
    ctx.fillStyle = "#000000"; 
 
    for (var i = 0, len = blocks.length; i < len; i++) { 
 
     ctx.fillRect(blocks[i].x, blocks[i].y, blocks[i].w, blocks[i].h); 
 
    } 
 
} 
 
setInterval(draw, 1000);
<canvas id="can" height="500" width="1000"></canvas>

+1

謝謝。我沒有意識到這個陣列不是多維的。我想我只是沒有注意。 – Bestlogo56