想要在浏览器窗口处于活动状态时每次按下键时读取键事件并打印键?

时间:2014-02-16 03:26:54

标签: javascript html

我想编写一个简单的JavaScript函数,它会显示每按一次键我按下的每个键的名称。我将尝试创建一个类似旧蜈蚣游戏的游戏,但我需要能够在每次按键时扫描按键。

问题:如何更改此代码以使其在按键事件请求中扫描并写出密钥的名称?

HTML code:

<body onload="docReady()" onkeydown="checkForNewKey()" onkeyup="" bgcolor='black'>

<canvas id="myCanvas" width="450" height="600" style="border:1px solid #00FFFF;">
    Your browser does not support the HTML5 canvas tag.
</canvas>

代码:

function checkForNewKey(){
    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");  <-- Exactly why does this need to be here and what does it do?

    ctx.font="30px Arial";
    var temp = evt.keyCode;
     ctx.fillText(temp,20,50);
 }

1 个答案:

答案 0 :(得分:1)

您应该使用按键事件。不确定写入画布的最终目标是什么,但请查看以获取更多信息: http://diveintohtml5.info/canvas.html

对于写信,这有效:

JSFiddle http://jsfiddle.net/kS7S3/

document.onkeypress = function (e) {
   var evt = evt || window.event;
   var charCode = typeof evt.which == "number" ? evt.which : evt.keyCode;
   console.log(charCode, String.fromCharCode(charCode));

   var c=document.getElementById("myCanvas");
   var ctx=c.getContext("2d");  
   ctx.font="30px Arial";
   ctx.clearRect(0,0,100,100);
   ctx.fillText(String.fromCharCode(charCode),20,50);

   return true; // proceed as usual
};

HTML

<canvas id="myCanvas" style="width:100px;;height:100px;background-color:red;"></canvas>