2013-03-26 44 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]