Tim Johnson
Tim Johnson

Reputation: 287

Keyboard Input Not Working with WebAssembly and Emscripten

I have a basic bit of code that renders to a webgl canvas element. When i call the event registration methods I either get no callback at all (when i specify the canvas name or #canvas as below or an error in chrome when i specify #document or #window related to not being able to register with a null object)

emscripten_set_keydown_callback("#canvas", nullptr, true, Platform::keyCallback);
emscripten_set_keyup_callback("#canvas", nullptr, true, Platform::keyCallback);

My Canvas element in html is

<canvas id="canvas" oncontextmenu="event.preventDefault()" width="640px" height="480px"></canvas>

and my test method for input is..

EM_BOOL Platform::keyCallback(int eventType, const EmscriptenKeyboardEvent *keyEvent, void *userData)
{
    printf("TEST\n");
}

Note: printf does work as I have other output to the console.

Thanks in advance for your help

Upvotes: 1

Views: 2502

Answers (2)

Luther
Luther

Reputation: 1838

Just to add another answer as I found that 'tabindex=-1' wasn't enough and needed to bring the canvas object in to focus.

I achieved this by adding code similar to this:

addOnPostRun(function()
{
     var canvas = document.getElementById('my_canvas');
     if (canvas)
         canvas.focus();
});

to the postfix code specified in '--post-js ./your_postfix_file.js' when building using emcc.

Upvotes: 0

Tim Johnson
Tim Johnson

Reputation: 287

Turns out the issue was in the HTML file. I needed to add "tabindex=-1" into the canvas. For example:

<canvas id="canvas" oncontextmenu="event.preventDefault()" width="640px" height="480px" tabindex=-1></canvas>

As a result of this change the code now seems to work perfectly.

Upvotes: 1

Related Questions