How to fire event in Javascript (with KineticJs) upon spacebar or arrowkey keystroke

StackOverflow https://stackoverflow.com/questions/23095644

  •  04-07-2023
  •  | 
  •  

سؤال

how does one fire an event in javascript upon space bar click or arrow key strike? I am using kineticjs as my framework, although that may be irrelevant as this may be able to be done in regular javascript. Thanks!

هل كانت مفيدة؟

المحلول

KineticJS doesn't handle keyboard events and I don't think it will be one day as Kinetic is used as a HTML5 Canvas JavaScript framework.

But KineticJS is compatible with JQuery which can provide you what you need.

Here is an example :

 $(document).keydown(function(event){

        console.log("key index : " + event.which);

        if (event.which == 38) {          //UP                                                              
            console.log("Up");
            event.preventDefault();
        } else if (event.which == 37) {   //LEFT                                                            
            console.log("Left");
            event.preventDefault();
        } else if (event.which == 39) {   //RIGHT                                                            
            console.log("Right");
            event.preventDefault();
        } else if (event.which == 40) {   //DOWN                                                            
            console.log("Right");
            event.preventDefault();
        }
 }

Hope it will help you.

Xavier

نصائح أخرى

KineticJS unfortunately doesn't handle keyboard events. You can do it with vanilla javascript but it can be a bit tedious. There are a few great libraries out there that can take care of it for you, I've been using KeyboardJS to great effect.

Quick example:

KeyboardJS.on("ctrl + c", function() {
  if (selectedNode) {
    tempNode = selectedNode.clone();
  }
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top