如何在动力学中将事件传递给下面的节点

时间:2014-05-30 13:57:39

标签: javascript html5-canvas kineticjs

question that is very similar but answer doesn't work in my situation

我有一个圆圈,我想将click事件传递给它下面的任何对象。

我试过了:

将cancelbubble设置为false。 将cirle图层设置为listen = false对我不起作用,因为圆圈不再可拖动。

我做了一个小提琴here

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

    var colorPentagon = new Kinetic.RegularPolygon({
      x: 80,
      y: stage.getHeight() / 2,
      sides: 5,
      radius: 70,
      fill: 'red',
      stroke: 'black',
      strokeWidth: 4,
      draggable: true
    });
    colorPentagon.on('click', function(evt){ alert("pentagon");});

    var linearGradPentagon = new Kinetic.RegularPolygon({
      x: 360,
      y: stage.height()/2,
      sides: 5,
      radius: 70,
      fillLinearGradientStartPoint: {x:-50, y:-50},
      fillLinearGradientEndPoint: {x:50,y:50},
      fillLinearGradientColorStops: [0, 'red', 1, 'yellow'],
      stroke: 'black',
      strokeWidth: 4,
      draggable: true
    });
    linearGradPentagon.on('click', function(evt){ alert("pentagon");});

    var radialGradPentagon = new Kinetic.RegularPolygon({
      x: 500,
      y: stage.height()/2,
      sides: 5,
      radius: 70,
      fillRadialGradientEndRadius: 70,
      fillRadialGradientColorStops: [0, 'red', 0.5, 'yellow', 1, 'blue'],
      stroke: 'black',
      strokeWidth: 4,
      draggable: true
    });
    radialGradPentagon.on('click', function(evt){ alert("pentagon");});

    background.add(colorPentagon);
    //background.add(patternPentagon);
    background.add(linearGradPentagon);
    background.add(radialGradPentagon);
    stage.add(background);


  var hideCircle = new Kinetic.Circle({
    x: stage.width()/2,
    y: stage.height()/2,
    radius: 650,
    stroke: 'black',
    strokeWidth: 1000,
      draggable:true
  });

 hideCircle.on('click', function(evt){ alert("click");});


  // add the shape to the layer
  layer.add(hideCircle);

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

目前为了让它工作,我必须采取点击坐标并进行自己的检测。它有效,但我希望有更优雅的东西。

1 个答案:

答案 0 :(得分:1)

以下是将点击事件传递给底层节点的方法:

  • 您可以听取舞台上的点击次数

  • 确定点击是否位于底层的任何节点

  • 如果单击位于节点内,则触发该节点上的click事件。

以下是示例代码和演示:http://jsfiddle.net/m1erickson/sFX8y/

stage.on('contentClick',function(e){

    // get the mouse position
    var pos=stage.getPointerPosition();

    // fetch the node on the bottom layer that is under the mouse, if any.
    var hitThisNode=background.getIntersection(pos);

    // if a node was hit, fire the click event on that node
    if(hitThisNode){
        hitThisNode.fire("click",e,true);
    }
});