嵌套/同心组和mouseenter/mouseleve

nested/concentric group and mouseenter/mouseleave

本文关键字:mouseenter mouseleve 同心 嵌套      更新时间:2024-01-31

我在向同心圆组添加事件侦听器时遇到了一些问题。我想要的功能是:当鼠标在组上时,一个新的黑点(下面代码中的"Bullseye",大约3)应该出现在组的中心。当鼠标不在组上方时,不应出现黑点。

以下代码即将实现这一点:

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <div id="container"></div>
    <script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.4.min.js"></script>
    <script defer="defer">
var stage = new Kinetic.Stage({
    container: 'container',
    width: 578,
    height: 200
});
var layer = new Kinetic.Layer({});
var group = new Kinetic.Group({
    x: 0, // 
    y: 0 //
}); 

var circle = new Kinetic.Circle({
    x: stage.getWidth() / 2,
    y: stage.getHeight() / 2,
    radius: 70,
    fill: 'red',
    stroke: 'black',
    strokeWidth: 4
});
var circle2 = new Kinetic.Circle({
    x: stage.getWidth() / 2,
    y: stage.getHeight() / 2,
    radius: 50,
    fill: 'white',
    stroke: 'black',
    strokeWidth: 4
});

var circle3 = new Kinetic.Circle({
    x: stage.getWidth() / 2,
    y: stage.getHeight() / 2,
    radius: 20,
    fill: 'black',
    stroke: 'black',
    strokeWidth: 4,
    visible: false
});

group.add(circle); 
group.add(circle2); 
group.add(circle3); 
group.on("mouseenter", function(event){ 
    circle3.setVisible(true);
    stage.draw();
}); 

group.on("mouseleave", function(event){ 
    circle3.setVisible(false); 
    stage.draw(); 
}); 

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

    </script>
  </body>
</html>

然而,问题是"牛眼"在离开外圆(圆)进入内圆(圆2)时会闪烁。

(*)我尝试过各种解决方案,但似乎都不起作用。首先,我试图捕捉鼠标位置(layerX和layerY),并检测与画布上的组区域的碰撞。也就是说,如果x和y在它的边界内,我画牛眼。否则,我就把它去掉了。然而,这个解决方案的问题是,即使鼠标离开了组,牛眼有时也会在组中孤立。这是因为mouseout/mouseleve事件有时具有仍在圆圈内的layerX或layerY位置。

(*)使用mouseover和mouseout而不是mouseenter/mouseleve似乎不会影响任何事情。

(*)我不能单独将eventlistener添加到外圈,因为当鼠标在内圈上时,这会使靶心消失。

您可以通过关闭嵌套圆的事件侦听来防止闪烁,如下所示:

group.add(circle); 
group.add(circle2); 
group.add(circle3); 
// Don't listen for any events (e.g. mouseenter/leave) on the inner circles
circle2.setListening(false);
circle3.setListening(false);

它解决了你描述的问题,但我不确定你是否需要倾听这些圈子里的其他事件。。。如果是这样,您可能需要取消来自内部圈子的事件传播。