如何检测在 javascript 中单击了 svg 路径的哪一段
How to detect which segment of a svg path is clicked in javascript?
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
点击路径时,我得到鼠标位置的x
和y
,那么如何检测点击了哪条曲线段?
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>
相关文章:
- 使用onclick绘制SVG路径
- Canvas+svg路径动画,在路径中的特定点暂停一段时间,然后继续
- 如何设置SVG路径的样式以拍摄图像
- Html5-使用SVG路径绘制的组织层次结构在左手边被剪裁
- SVG路径命中测试
- 更快的SVG路径操作
- 以编程方式确定由 SVG 路径生成的形状
- 将 SVG 路径雕刻成矩形,在矩形中留下一个“孔”
- 使用正则表达式提取 svg 路径
- 如何在 JavaScript 中计算 SVG 路径的椭圆路径坐标
- SVG 路径未显示
- svg路径动画整个路径
- 使用Javascript获取SVG路径的绝对坐标
- 画布的SVG路径
- 如何在HTML中创建一个信息框,显示与悬停SVG路径相关的信息
- 尝试使用javascript更改多个svg路径
- 悬停在表行上填充svg路径
- 自定义Javascript Alert Popup onclick svg路径
- 使用RaphaelJS和GSAP制作SVG路径动画
- 单击事件在svg路径上不起作用