如何在javascript中检测svg路径的哪一段被点击?

cui*_*ing 5 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"/>
Run Code Online (Sandbox Code Playgroud)

它有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
Run Code Online (Sandbox Code Playgroud)

当点击路径时,我得到了鼠标位置xy鼠标位置,那么如何检测点击了哪条曲线段呢?

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

Jul*_*ire 1

您可以使用几种SVGPathElements方法。并不是很简单,但您可以获取路径的总长度,然后使用getPointAtLength检查每个长度点的坐标,并将其与单击的坐标进行比较。一旦您计算出点击的长度,您就可以使用getPathSegAtLength获取该长度的段。例如:

 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;
 }
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)