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!

itinance
  • 11,711
  • 7
  • 58
  • 98

6 Answers6

4

I suggest using one of the Keyboard Plugins out there:

They work well together with KineticJS.

andyrandy
  • 72,880
  • 8
  • 113
  • 130
1

If you can include javascript into it, here is the code:

if(keyIsPressed && keycode == somenumber){
doSomething();
} 
verymessi
  • 117
  • 1
  • 12
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.

Yamiko
  • 5,303
  • 5
  • 30
  • 52
0

From the limited experience I have with this (2 days), I saw that each layer you add becomes a canvas, so if you have a reference to the topmost layer in a variable (i.e. topmostLayer), you can do

var canvas = $(topmostLayer.getContext().canvas);

With this in place, what @devnull69 suggested just works:

canvas.attr('tabindex', 0);
canvas.keydown(function (ev) { ... });

I have it in place in my application and works fine.

Community
  • 1
  • 1
Wasp
  • 3,395
  • 19
  • 37
0

see link, you need:

var canvas=layer.getCanvas()._canvas;
$(canvas).attr('tabindex', 0); // increase tabindex if needed
canvas.focus();
$(canvas).keydown(function (e) {
    console.log(e.keyCode); // your handler here
});
kofifus
  • 17,260
  • 17
  • 99
  • 173
-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.

devnull69
  • 16,402
  • 8
  • 50
  • 61
  • In a plain Html5-Application your answer is right. But in a kineticjs-managed Canvas it will not work also. – itinance Sep 10 '12 at 07:15