在给定x坐标的情况下获取SVG路径上点的y坐标 [英] Get y coordinate of point along SVG path with given an x coordinate
本文介绍了在给定x坐标的情况下获取SVG路径上点的y坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用raphael.js绘制一个简单的SVG折线图,如下所示:
I am using raphael.js to draw a simple SVG line graph like this:
当用户悬停图形时,id喜欢在光标的 X 位置和该行的 Y 位置显示指向该行的弹出框就是这样的 X 位置:
When the user hovers the graph, id like to display a popover pointing to the line at the X position of the cursor, and at the Y position where the line is for that X position like so:
我需要走这条路,找到给定的 X 坐标的 Y 坐标.
I need to take the path and find the Y coordinate for a given X coordinate.
推荐答案
基于@Duopixel的D3解决方案,我使用DOM API在纯JavaScript中编写了以下函数供自己使用:
Based on @Duopixel's D3 solution, I wrote the following function for my own use, in pure javascript using DOM API:
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
}
}
这篇关于在给定x坐标的情况下获取SVG路径上点的y坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文