gpt4 book ai didi

javascript - 使用给定的 x 坐标获取沿 SVG 路径的点的 y 坐标

转载 作者:数据小太阳 更新时间:2023-10-29 04:42:43 26 4
gpt4 key购买 nike

我正在使用 raphael.js 绘制一个简单的 SVG 折线图,如下所示:

line graph

当用户悬停图形时,id 喜欢在光标的 X 位置显示一个指向该线的弹出框,并在该线所在的 Y 位置像这样的 X 位置:

cursors with popovers along the line

我需要找到路径并找到给定 X 坐标的 Y 坐标。

最佳答案

基于@Duopixel 的 D3 解决方案,我使用 DOM API 在纯 javascript 中编写了以下函数供我自己使用:

function findY(path, x) {
var pathLength = path.getTotalLength()
var start = 0
var end = pathLength
var target = (start + end) / 2

// Ensure that x is within the range of the path
x = Math.max(x, path.getPointAtLength(0).x)
x = Math.min(x, path.getPointAtLength(pathLength).x)

// Walk along the path using binary search
// to locate the point with the supplied x value
while (target >= start && target <= pathLength) {
var pos = path.getPointAtLength(target)

// use a threshold instead of strict equality
// to handle javascript floating point precision
if (Math.abs(pos.x - x) < 0.001) {
return pos.y
} else if (pos.x > x) {
end = target
} else {
start = target
}
target = (start + end) / 2
}
}

关于javascript - 使用给定的 x 坐标获取沿 SVG 路径的点的 y 坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15578146/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com