2013-10-12 74 views
0

HTML5, JavaScript and drawing multiple rectangles in a canvas矩形的HTML5打印陣列錯誤

所以我花了2小時以來百思不得其解自己,爲什麼這不會工作,我遵循了上述問題的所有代碼,但尚未對我來說仍然不會工作我是什麼做錯了?

我在一個正方形添加,以確保它是越來越向線和實際工作

http://jsfiddle.net/Wh5YX/

function Shape(a,b,w,h,fill){ 

    this.a = a; 
    this.b = b; 
    this.w = w; 
    this.h = h; 
    this.fill = fill; 

} 

var canvas = document.getElementById("canvas"); 
if (canvas.getContext){ 
var myRect = []; 

    myRect.push(new Shape(100, 0, 25, 25, "#333")); 
    myRect.push(new Shape(0, 40, 39, 25, "#333")); 
    myRect.push(new Shape(0, 80, 100, 25, "#333")); 

ctx = canvas.getContext("2d"); 
for (i in myRect) { 
    oblock = myRect[i]; 
    ctx.fillStyle = oblock.fill; 
    ctx.fillRect(oblock.x,oblock.y,oblock.w,oblock.h); 
    ctx.fillStyle="#CC00FF"; 
ctx.fillRect(100,100,20,20); 
} 
} 

回答

1

這似乎是在Shape對象一個簡單的拼寫錯誤:

function Shape(a,b,w,h,fill){ 

    this.x = a; /// change to this.x 
    this.y = b; /// change to this.y 

    this.w = w; 
    this.h = h; 
    this.fill = fill; 
} 

Updated fiddle here

,或者你可以通過提供恰當的變量名,例如減少錯別字,如本的風險(一般):

function Shape(x, y, w, h, fill){ 

    this.x = x; /// now we see the link more clearly 
    this.y = y; 

    this.w = w; 
    this.h = h; 
    this.fill = fill; 
} 
+0

非常感謝!深夜頭累了! JavaScript的新功能,所以只是使用它!再次感謝男人! – Bawn