onkeydown事件在画布上不起作用? [英] onkeydown event not working on canvas?

查看:113
本文介绍了onkeydown事件在画布上不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个画布和一个分配给它的 onkeydown 事件.当按下任何键时,控制台应该记录该键的keyCode.但是它不会输出任何东西,甚至不会输出 undefined .其他处理程序,例如 onclick 可以正常工作,但 onkeydown 则不能.我也尝试过使用 onkeypress onkeyup ,但是它们也不起作用.这是完整的代码:

I've got a canvas and an onkeydown event assigned to it. When any key is pressed, the console is supposed to log the keyCode of the key. But it's not outputting anything, not even undefined. Other handlers like onclick are working fine, but onkeydown is not. I've also tried using onkeypress and onkeyup, but these don't work either. Here's the full code:

canvas.onkeydown = function(e){
    if(e.keyCode === 37){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        ctx.drawImage(knife,knifeX - 10, knifeY);
        knifeX -= 10;
    }
    else if(e.keyCode === 39){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        ctx.drawImage(knife,knifeX + 10, knifeY);
        knifeX += 10;           
    }
    else if(e.keyCode === 38){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        ctx.drawImage(knife,knifeX, knifeY + 10);
        knifeY += 10;
    }
    else if(e.keyCode === 40){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        ctx.drawImage(knife,knifeX, knifeY - 10);
        knifeY -= 10;               
    }
    console.log(e.keyCode);     
}

推荐答案

相反,如果使用 canvas.onkeydown ,请使用 window.onkeydown ,否则,您需要专注于画布才能正常工作.

Instead if using canvas.onkeydown use window.onkeydown otherwise you will need to focus on to the canvas for it to work.

window.onkeydown = function(){};

仅当您专注于画布元素时,才可以附加到canvas元素.窗口对象就是整个浏览器.

Attaching to the canvas element will only work if your focused in on that element. The window object is the whole browser.

这篇关于onkeydown事件在画布上不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆