10
votes

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();
1
What type of object is 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.jfriend00
It is a canvas created like this: body = document.getElementById("body"); canvas = document.createElement("canvas"); canvas.setAttribute("id", "gameCanvas"); canvas.width = window.innerWidth; canvas.height = window.innerHeight; body.appendChild(canvas);user1668814
Thank you @jfriend00 I googled keyboard focus and determined that I needed to add this to my canvas: canvas.setAttribute("tabindex", 0);user1668814
or canvas.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

1 Answers

24
votes

I'll turn my comment into an answer so you can wrap up this question.

For a DOM object to receive keyboard events, they must first be capable of getting the keyboard focus on a page. Only then will keyboard events be directed to that object. The simplest way to do that for a canvas object is to give it a tabIndex attribute.

canvas.setAttribute("tabindex", 0);

You can see someone else's summary of that problem here: http://www.dbp-consulting.com/tutorials/canvas/CanvasKeyEvents.html