Alex Rivera | Logout

How to listen to Keydown-Events in a KineticJS-managed HTML5-Canvas?

Asked 2012-09-05T12:51:51.280
11

I am trying to add an Event Listener to a Htm5-Canvas which is managed by Kineticjs (the Canvas was created via a Stage of KineticJS).

I tried out (using jQuery):

$(selector).keydown( function(e) {... } )

with the following Selectors:

  • window (it is working, but it is listening to the whole Window and thereby not good)
  • All Canvas-Elements $('canvas') <-- not working
  • The Container, where KineticJS and its Canvas are embedded <-- not working
  • The Container-Div of KineticJS (created by Kinetic) with $('.kineticjs-content').keydown( function() { ... } ) <-- not working

Only $(window) is working. After experimenting with plain Html5-Canvas i figured out, that the Canvas-Element has Built-in-Support for Keyboard-Events. So i think, KineticJS is doing something magic around here. Wrong Selector-Usage can be excluded.

I checked every Selector with this code: console.log( $(selector).length )

Can anyone help here? Thx in advance!

Edit
Report

2 Answers

0

As of right now On only supports mouse and touch events.

Each layer has its own canvas that you can grab and attach events to.

answered 2013-05-13T01:37:32.250
-2

You'll have to make sure that the canvas element has the focus before it can accept keyboard events. Unfotunately the .focus() method didn't work for me in Firefox, so I tried this and voilĂ 

$('canvas').attr('tabindex', 0);
$('canvas').keydown(function(e) {
    alert(e.keyCode);
    e.preventDefault();    // to stop the key events from bubbling up
});

Click the canvas and it will have the focus.

answered 2012-09-05T13:16:14.733

Your Answer