Search code examples
jqueryhtmlkineticjs

Kinetic.js: Click event for each rect


How do you create a click event for every Kinetic.Rect in a group?

Let's say i have this:

var bar1 = new Kinetic.Rect({
      x: 0,
      y: 100,
      width: 400,
      height: 10,
      fill: 'grey',
      stroke: 'black',
      strokeWidth: 2
});

var bar2 = new Kinetic.Rect({
      x: 0,
      y: 100,
      width: 400,
      height: 10,
      fill: 'grey',
      stroke: 'black',
      strokeWidth: 2
});

Is there a way to have the same click event for both bars? Using jQuery possibly?


Solution

  • you can create a var layer = new Kinetic.Layer(); and add your bars to it then bind the layer with .on

    layer.add(bar1);
    layer.add(bar2);
    //...
    layer.on('click',function(e) {
              //...
              //bar1/bar2 is e.targetNode 
    

    see http://konvajs.github.io/docs/events/Multi_Event.html

    otherwise

    function handleClick(e) {
           //..
           //bar1/bar2 is e.target
             }
    
    bar1.on("click",handleClick);
    bar2.on("click",handleClick);
    //...