0

so I need to show what key is being pressed in my web app , I want to put it in html 5 canvas.

when I'm pressing Q , it will show the Q button.

Here my code(i'm using 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();
    }
}

can anyone tell me what function do I need to show the key ? If there's already solution, please give me the link, I've tried to search before but can't find anything.

Thanks

3 Answers3

0

You have a problem... The key code changes in different operation systems.

Here you get a table with some key codes: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

0

You can show each key pressed with something like this I guess:

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

You're almost there.

I have made a slight tweak to your javascript below:

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();
    }
}
Rounin
  • 27,134
  • 9
  • 83
  • 108