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

前端 未结 2 2054
情话喂你
情话喂你 2021-02-08 20:38

I am using raphael.js to draw a simple SVG line graph like this:

\"line

When the user hovers the gr

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-08 20:59

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

提交回复
热议问题