将侦听器添加到组

时间:2014-05-21 01:56:31

标签: javascript kineticjs

我怎么能这样做?组中的所有形状都不应该监听事件,但是组应该对事件进行操作,但是不起作用。我举了两组的例子,实际上它们非常多,所以我必须在图层中添加一个监听器,并听取所有内部组的bab呀声事件。

var stage = new Kinetic.Stage({
    container: 'container',
    width: 1000,
    height: 800
  });
  var layer = new Kinetic.Layer();


    var group1 =  new Kinetic.Group({listening: true});
    var group2 =  new Kinetic.Group();

    var circle = new Kinetic.Circle({
        x: stage.getWidth() / 2,
        y: stage.getHeight() / 2,
        radius: 70,
        listening: false,
        fillLinearGradientStartPoint: {x:70, y:-70},
        fillLinearGradientEndPoint: {x:70,y:70},
        fillLinearGradientColorStops: [0, 'black', 1, 'white'],
        stroke: 'black',
        strokeWidth: 4
    });
    var circle2 = new Kinetic.Circle({
        x: 100,
        y: 100,
        radius: 70,
        listening: false,
        fillLinearGradientStartPoint: {x:70, y:-70},
        fillLinearGradientEndPoint: {x:70,y:70},
        fillLinearGradientColorStops: [0, 'black', 1, 'white'],

        stroke: 'black',
        strokeWidth: 4
    });

    var circle3 = new Kinetic.Circle({
        x: 300,
        y: 300,
        radius: 70,
        listening: false,
        fillLinearGradientStartPoint: {x:70, y:-70},
        fillLinearGradientEndPoint: {x:70,y:70},
        fillLinearGradientColorStops: [0, '#678345', 1, '#824444'],
        stroke: 'black',
        strokeWidth: 4
    });
    var circle4 = new Kinetic.Circle({
        x: 200,
        y: 200,
        radius: 70,
        listening: false,
        fillLinearGradientStartPoint: {x:70, y:-70},
        fillLinearGradientEndPoint: {x:70,y:70},
        fillLinearGradientColorStops: [0, '#678345', 1, '#824444'],
        stroke: 'black',
        strokeWidth: 4
    });

   group1.add(circle);
   group1.add(circle2);

   group2.add(circle3);
   group2.add(circle4);




  // add the triangle shape to the layer
  layer.add(group1);
  layer.add(group2);

  layer.on("click",onClick);

  // add the layer to the stage
  stage.add(layer);

function onClick(e){
    console.log("click",e.target);

}

请帮忙!

1 个答案:

答案 0 :(得分:0)

只有组中的节点才会触发事件

  • 您的圈子会触发事件

  • 点击群组的非节点区域不会触发任何事件

解决方法是添加透明矩形作为背景,覆盖整个组宽度/高度。

var group=new Kinetic.Group({
    x:0,y:0,width:100,height:100
})

var groupListener=new Kinetic.Rect({
    x:group.x(),
    y:group.y(),
    width:group.width(),
    height:group.height(),

});

group.add(groupListener);

然后,您可以将侦听器分配给“不可见”groupListener矩形

groupListener.on("click",function(){
    console.log("clicked on non-node area of group");
});

演示:http://jsfiddle.net/m1erickson/ur6be/