【问题标题】:Get y coordinate of point along SVG path with given an x coordinate使用给定的 x 坐标获取沿 SVG 路径的点的 y 坐标
【发布时间】:2013-03-22 19:12:41
【问题描述】:

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

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

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

【问题讨论】:

标签: javascript svg raphael


【解决方案1】:

基于@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
  }
}

【讨论】:

    【解决方案2】:

    如果您知道路径的所有点,则在路径的 d 属性中搜索您要查找的特定 x 坐标并使用正则表达式检索 y 坐标可能会更高效:

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

    如果您想找到不在您的路径 d 属性中的 y 和任意 x 坐标,您可以遍历路径的所有坐标并找到最接近您要查找的 x 坐标。不确定这是否会比单步执行路径并调用 getPointAtLength 更快。

    【讨论】:

      猜你喜欢
      • 2014-05-03
      • 1970-01-01
      • 2020-04-22
      • 2018-05-12
      • 2011-02-14
      • 1970-01-01
      • 1970-01-01
      • 2015-05-23
      • 1970-01-01
      相关资源
      最近更新 更多