I'm wondering if my keyboard is broken, or I have problem with the code. The code below detects if the user is pressing the "u", "d", "j", and "m" keys.
It seems impossible to recognize that all four keys are pressed at once. It can at most detect when 3 keys are pressed. I can't seem to find the problem. I would greatly appreciate your help.
var jkeypressed = false;
var ukeypressed = false;
var dkeypressed = false;
var mkeypressed = false;
function yeah() {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
canvas.height = 500;
canvas.width = 500;
document.addEventListener("keydown", function(ev) {
switch (ev.keyCode) {
case 77:
mkeypressed = true;
break;
case 74:
jkeypressed = true;
break;
case 85:
ukeypressed = true;
break;
case 68:
dkeypressed = true;
break;
}
}, false);
document.addEventListener("keyup", function(ev) {
switch (ev.keyCode) {
case 77:
mkeypressed = false;
break;
case 74:
jkeypressed = false;
break;
case 85:
ukeypressed = false;
break;
case 68:
dkeypressed = false;
break;
}
}, false);
context.fillStyle = "#33CCFF";
context.font = "20px Arial";
context.fillText(dkeypressed + ' ' + jkeypressed + ' ' + ukeypressed + ' ' + mkeypressed, 300, 50);
}
var x = setInterval(yeah, 1);
<canvas id="canvas"></canvas>
You can simplify your code to: Some things that I noticed/fixed:
I hope this helps :)