如何检测在 javascript 中单击了 svg 路径的哪一段

How to detect which segment of a svg path is clicked in javascript?

本文关键字:svg 路径 一段 何检测 检测 javascript 单击      更新时间:2023-09-26

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
        //
    }
可以使用

一些适用于 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;
 }
<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>