2013-05-25 76 views
2

Connect4 - Game 我想提出一個connect4遊戲,當我回到畫布對象的數組:的Javascript的getElementsByTagName()怪異的行爲

var canvas = document.getElementsByTagName('canvas'); 

它返回前18個對象的罰款。 Chrome的JavaScript控制檯(console.log(canvas [id]);)打印出html標籤。但在18以上,它只是寫出畫布#+ ID。 因爲這個,當我點擊底部的框來繪製一個圓時,我會收到錯誤。

function create_circle(index) { 

    if (start==0) { 
     color = 'red'; 
     start++; 
    } else if (start==1) { 
     color = 'black'; 
     start--; 
    } else { 
     color = 'white'; 
    } 

    var circle = document.canvas[index].getContext('2d'); // IT SHOWS THE ERROR HERE 

    circle.beginPath(); 
    circle.arc(40, 40, 40, 0, 2 * Math.PI, false); 
    circle.fillStyle = color; 
    circle.fill(); 
} 
+0

它應該是'document.getElementsByTagName('canvas')',錯字? –

+2

無論如何,在該頁面上記錄'document.getElementsByTagName('canvas')'輸出的所有canvas元素都非常好,而不是前18個! –

+0

你真的應該在這裏發佈代碼,而不是全部;只是表現出你不瞭解的行爲的部分。奇怪的是,你使用jQuery,但你也想使用基本的DOM例程。 – Pointy

回答

2

您正在使用document.canvas而不是您的canvas變量。瀏覽器不存在這樣的集合。

// remove---------v 
var circle = /*document.*/canvas[index].getContext('2d'); 
+0

感謝您的幫助! –

+0

不客氣。 – 2013-05-25 13:54:42