4

In KineticJS, how do you detect a Click event where the click occurs outside an object/shape?

I am trying to get a Rect to change its scale to 2 when a user clicks on it, and return back to a scale of 1 when the user clicks anywhere outside it.

JSfiddle: http://jsfiddle.net/ABTAD/8/

Managed to detect a click on stage, but clicking on the Rect also fires the click handler!!! And somehow the .setScale(1) does not do anything, while console.log printes something out. How can I prevent the click handler from firing when the click is made on the Rect instead of the empty stage?

JS Code to detect click on stage

window.stage.getContainer().addEventListener('click', function(e) {
    $.each(window.layer.get('.box'), function(index, box) {
       box.setScale(1);
       console.log('clicked on stage');
    });
});
Nyxynyx
  • 61,411
  • 155
  • 482
  • 830
  • You know Im still learning Kinetic, but heres a JS pointer. You dont need to put window before things to make them global. If you put var before a variable decleration then it will be only available in the scope/function it was created in. Not putting the var before the variable decleration will make it global (the same as putting window. before it). Did you see this post?.. http://stackoverflow.com/questions/13866660/create-a-rectangle-with-mousedown-event-in-kineticjs he put a rect as the first layer that you can then check against. Also, is it a good idea to use normal events? – PAEz Dec 16 '12 at 16:26
  • Thanks!! I actually namespaced them with like `var App = {}; App.stage = ...` Havent seen that post, sounds like a gd idea – Nyxynyx Dec 16 '12 at 16:33
  • 4
    http://jsfiddle.net/ABTAD/11/ – PAEz Dec 16 '12 at 17:01
  • Awesome, you've nailed it. – Nyxynyx Dec 17 '12 at 01:21

1 Answers1

5

you can access the stage content wrapper with stage.getContent(). From there, you can add an event handler like this:

stage.getContent().addEventListener('click', ...); // regular javascript

or

$(stage.getContent()).on('click', ...); // jquery

Eric Rowell
  • 5,191
  • 23
  • 22