简体   繁体   English

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

[英]Get y coordinate of point along SVG path with given an x coordinate

I am using raphael.js to draw a simple SVG line graph like this:我正在使用 raphael.js 绘制一个简单的 SVG 线图,如下所示:

线形图

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:当用户悬停图形时, id 喜欢显示一个弹出框,指向光标X位置的线,以及Y位置的线所在的X位置,如下所示:

沿线带有弹出框的游标

I need to take the path and find the Y coordinate for a given X coordinate.我需要走路径并找到给定X坐标的Y坐标。

Based on @Duopixel's D3 solution, I wrote the following function for my own use, in pure javascript using DOM API:基于@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
  }
}

If you know all the points of your path, it might be more performant to search the d attribute of your path for the specific x coordinate you are looking for, and retrieve the y coordinate using regexp:如果您知道路径的所有点,那么在路径的d属性中搜索您要查找的特定 x 坐标并使用正则表达式检索 y 坐标可能会更高效:

const regex = new RegExp(`${x} ((\d*.\d*))`)
const match = regex.exec(d)

If you want to find the y of and arbitrary x coordinate not in your paths d attribute, you could loop through all the coordinates of your path and find the x coordinate that is closest to the one you're looking for.如果您想找到不在路径 d 属性中的 y 坐标和任意 x 坐标,您可以遍历路径的所有坐标并找到最接近您要查找的坐标的 x 坐标。 Not sure if that would be faster than stepping through the path and calling getPointAtLength though.不确定这是否比单步执行路径并调用getPointAtLength更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM