相处SVG路径点的y坐标给定的x坐标(Get y coordinate of point along

2019-08-17 22:03发布

我使用raphael.js画一个简单的SVG线图所示:

当用户将鼠标悬停的图表中,Id喜欢显示酥料饼的指向在光标的X位置的线,和在Y位置,其中线是等,使得X位置:

我需要采取的路径,找到Y坐标为给定的X坐标。

Answer 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
  }
}


文章来源: Get y coordinate of point along SVG path with given an x coordinate