The mousemove event works and calls onMouseMove each time I move on the canvas. Although, the keydown and keyup events never work. I click on the canvas and hit some keys, but no event is triggered. Does anyone know why the events are not working? Thank you for any advice! I'm following the html5 course on udacity if anyone is curious where the code came from.
InputEngineClass = Class.extend({
keyState: new Array(),
setup: function() {
document.getElementById("gameCanvas").addEventListener('mousemove', gInputEngine.onMouseMove);
document.getElementById("gameCanvas").addEventListener('keydown', gInputEngine.onKeyDown);
document.getElementById("gameCanvas").addEventListener('keyup', gInputEngine.onKeyUp);
},
onMouseMove: function (event) {
console.log("Called onMouseMove");
var posx = event.clientX;
var posy = event.clientY;
},
onKeyDown: function (event) {
console.log("KEY DOWN!!!");
keyState[event.keyID] = true;
gInputEngine.update();
},
onKeyUp: function (event) {
console.log("KEY UP!!!");
keyState[event.keyID] = true;
},
update: function() {
KeyW = 87;
if(gInputEngine.keyState[KeyW]) console.log("FORWARD!!!");
}
});
gInputEngine = new InputEngineClass();
gameCanvas
? If it never gets the keyboard focus (or has children that get the focus), then it won't get keyboard events. An object has to first get the keyboard focus before keyboard events are sent to it. – jfriend00body = document.getElementById("body");
canvas = document.createElement("canvas");
canvas.setAttribute("id", "gameCanvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
body.appendChild(canvas);
– user1668814canvas.setAttribute("tabindex", 0);
– user1668814canvas.contentEditable=true;
Both work, but I'll have to do some reading to see which is better and why. Found these ideas on another keyboard focus post. – user1668814