2012-11-24 80 views
-1

我使用下面的代碼來嘗試一下canvas元素HTML5畫布陣列創建錯誤

Shape = function(x,y){ 
     this.x = x; 
     this.y = y; 
    }; 

    shapes = new array(); 

    shapes.push(new Shape(50,50,10,10)); 
    shapes.push(new Shape(100,100,10,10)); 
    shapes.push(new Shape(150,150,10,10)); 

    function animate(){ 
     context.clearRect(0,0, canvas.width(),canvas.height()); 
     var shapesLength = shapes.length; 
     for(var i = 0; i < shapesLength; i++){ 
      var tmpShape = shapes[i]; 
      tmpShape.x++; 
      context.fillRect(tmpShape.x,thmpShape.y,10,10); 
     } 
     context.fillStyle = 'yellow'; 
     context.fill(); 
     if(playAnimation){ 
      setTimeout(animate, 1) 
     } 
    } 

然而,當我在瀏覽器中我碰到下面的錯誤運行此 -

ReferenceError: array is not defined  

shapes = new array(); 

我試圖使它成爲一個全局和局部變量我只是不知道我要去哪裏錯了?

回答

3

array應該大寫,因爲這是構造函數的名稱:

shapes = new Array(); 

此外,最好用方括號創建一個數組。就像這樣:

shapes = []; 
+0

爲什麼我總是問題愚蠢的簡單的事情!謝謝! –

+0

@RoryStandley這是一個簡單的錯誤,是真的;但你所能做的就是從中吸取教訓。 – 0x499602D2

+1

+1此外,該數組可以在飛行中填充,如'shapes = [new Shape(...),...]'。 – pimvdb