2013-03-26 41 views
5

我花了一些可用的基本傍代碼在互聯網上,並嘗試添加按鍵,該代碼是在這裏:http://cssdeck.com/labs/ping-pong-game-tutorial-with-html5-canvas-and-sounds的addEventListener KEYDOWN不工作

我加了這一點:

canvas.addEventListener("keydown", handlekeydown, true); 

這個現有的代碼之後:

canvas.addEventListener("mousemove", trackPosition, true); 
canvas.addEventListener("mousedown", btnClick, true); 

而且我還添加了這一點:

function handlekeydown(e) { 
    console.log("debug"); 
    console.log("keycode: "+e.keyCode); 
} 

但是,即使我嘗試按各種按鍵,該功能也不會被調用。爲什麼是這樣?我很確定畫布是關注焦點。

+0

可能重複(http://stackoverflow.com/questions/12886286/addeventlistener-for-keydown-on-canvas) – bfavaretto 2013-03-26 21:40:32

回答

15

您無法將​​事件分配給畫布,因爲您無法將畫布與光標對焦。您需要將事件分配給窗口:

window.addEventListener("keydown", handle, true); 
5

您可以試着用窗口替換畫布

-2

我同意一樓,但您可以嘗試這樣做。如下:

//set attribute tabindex = 0 (other number), ensure the canvas in the focus sequence 
//like this, you can focus canvas 
//http://www.w3schools.com/tags/att_global_tabindex.asp 
<canvas id="snake" width="400" height="600" tabindex=0 > </canvas> 

//then register keydown event 
document.getElementById("snake").addEventListener("keydown", function(ev){ 
      console.log(ev); 
}, true); 
的[對的addEventListener布面KEYDOWN]