2017-10-20 38 views
2

J'ai mon tableau, et je veux afficher le tableau basé sur ce qui est à l'intérieur de chaque objet dans le tableau. J'ai les boucles ici mais je peux sembler obtenir le ctx.fillRect pour fonctionner.Ma boucle sera en boucle, mais elle ne montrera pas ce que je veux

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

Avez-vous essayé de vérifier les blocs [i] .length et d'autres propriétés? C'est indéfini .. – Optional

Répondre

5

blocks n'est pas un tableau multidimensionnel.

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

Merci. Je n'ai pas réalisé que le tableau n'était pas multidimensionnel. Je suppose que je ne faisais pas attention. – Bestlogo56