如何检测在javascript中单击svg路径的哪个段?

时间:2016-01-17 19:59:08

标签: javascript svg

SVG路径元素,例如:

<path id="path1" 
d="M 160 180 C 60 140 230 20 200 170 C 290 120 270 300 200 240 C 160 390 50 240 233 196" 
stroke="#009900" stroke-width="4" fill="none"/>

它有4个svg片段(人眼中有3个曲线段):

    M 160 180 
    C 60 140 230 20 200 170 
    C 290 120 270 300 200 240 
    C 160 390 50 240 233 196

点击路径后,我得到鼠标位置的xy,然后如何检测点击了哪个曲线段?

    function isInWhichSegment(pathElement,x,y){
        //var segs = pathElement.pathSegList; //all segments
        //
        //return the index of which segment is clicked
        //
    }

1 个答案:

答案 0 :(得分:1)

您可以使用 SVGPathElements 的几种方法。不是很直接,但你可以得到路径的总长度,然后用 getPointAtLength 检查坐标的每个长度,并将其与点击的坐标进行比较。一旦你确定点击是在哪个长度,你得到那个长度为 getPathSegAtLength 的段。比如那样:

&#13;
&#13;
 var pathElement = document.getElementById('path1')
 var len = pathElement.getTotalLength();

 pathElement.onclick = function(e) {
   console.log('The index of the clicked segment is', isInWhichSegment(pathElement, e.offsetX, e.offsetY))
 }

 function isInWhichSegment(pathElement, x, y) {
   var seg;
   // You get get the coordinates at the length of the path, so you
   // check at all length point to see if it matches
   // the coordinates of the click
   for (var i = 0; i < len; i++) {
     var pt = pathElement.getPointAtLength(i);
     // you need to take into account the stroke width, hence the +- 2
     if ((pt.x < (x + 2) && pt.x > (x - 2)) && (pt.y > (y - 2) && pt.y < (y + 2))) {
       seg = pathElement.getPathSegAtLength(i);
       break;
     }
   }
   return seg;
 }
&#13;
<svg>
  <path id="path1" d="M10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80" stroke="#009900" stroke-width="4" fill="none" />
</svg>
&#13;
&#13;
&#13;