addEventListener keydown不工作

时间:2013-03-26 21:32:19

标签: javascript html5 html5-canvas

我在互联网上提供了一些基本的Pong代码并试图添加按键,代码在这里:http://cssdeck.com/labs/ping-pong-game-tutorial-with-html5-canvas-and-sounds

我补充说:

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);
}

但即使我尝试按下各种键,也不会调用该函数。为什么是这样?我很确定Canvas是焦点。

3 个答案:

答案 0 :(得分:17)

您无法将keydown事件分配给画布,因为您无法使用光标聚焦画布。您需要将事件分配给窗口:

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

答案 1 :(得分:6)

您可以尝试将 canvas 替换为窗口

答案 2 :(得分:-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);