如何显示正在按下的键

时间:2015-12-28 11:16:43

标签: javascript html5-canvas

所以我需要在我的网络应用中显示正在按下的键,我想把它放在html 5画布中。

当我按下Q时,它会显示Q按钮。

这是我的代码(我使用的是javascript):

window.addEventListener("keypress",onKeyPress);

function onKeyPress(e)
{
    console.log(e.keyCode);
    var str = String.fromCharCode(e.keyCode);
    console.log(str+":"+e.keyCode);
    var tune = new Audio();


    if (e.keyCode == 113)
    {
        tune = new Audio("Assets/Tune/C.mp3");
        tune.play();
    }
}

任何人都可以告诉我,显示密钥需要什么功能? 如果已有解决方案,请给我链接,我之前尝试过搜索但找不到任何内容。

由于

3 个答案:

答案 0 :(得分:0)

你有问题...... 关键代码在不同的操作系统中发生变化。

这里有一个包含一些关键代码的表格: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

答案 1 :(得分:0)

你可以用这样的东西显示每个按键,我猜:

var str = String.fromCharCode(e.keyCode);
var c = document.getElementById("Canvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText(str,10,50);

答案 2 :(得分:0)

你几乎就在那里。

我已对您的javascript稍作调整:

window.addEventListener("keypress",onKeyPress);

function onKeyPress(e) {
    var keyPressed = e.which || e.keyCode;
    console.log(keyPressed);
    var str = String.fromCharCode(keyPressed);
    console.log(str+":"+keyPressed);
    var tune = new Audio();


    if (e.keyCode == 113)
    {
        tune = new Audio("Assets/Tune/C.mp3");
        tune.play();
    }
}