我花了一些基本傍代码在互联网上公布,并尝试添加按键,该代码是在这里: 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是关注的焦点。
你可以不分配keydown
事件到画布上,因为你不能专注与光标在画布上。 您需要为事件指定窗口:
window.addEventListener("keydown", handle, true);
我同意一楼的,但你可以尝试这样做。 如下:
//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);