javascript - 在d3中,如何从SVG线中获取插值线数据?

标签 javascript graphics svg d3.js

我使用 D3 显示折线图,代码大致如下(给定比例函数 xy 和 float 组 data) :

 var line = d3.svg.line()
         .interpolate("basis")
         .x(function (d, i) { return x(i); })
         .y(function (d) { return y(d); });
 d3.select('.line').attr('d', line(data));

现在我想知道给定水平像素位置处线条的垂直高度data 数组的数据点少于像素,并且显示的线条是插值的,因此仅从给定像素处推导出线条的高度并不直接data 数组。

有什么提示吗?

最佳答案

这个解决方案比接受的答案要有效得多。它的执行时间是对数的(而接受的答案具有线性复杂度)。

var findYatXbyBisection = function(x, path, error){
  var length_end = path.getTotalLength()
    , length_start = 0
    , point = path.getPointAtLength((length_end + length_start) / 2) // get the middle point
    , bisection_iterations_max = 50
    , bisection_iterations = 0

  error = error || 0.01

  while (x < point.x - error || x > point.x + error) {
    // get the middle point
    point = path.getPointAtLength((length_end + length_start) / 2)

    if (x < point.x) {
      length_end = (length_start + length_end)/2
    } else {
      length_start = (length_start + length_end)/2
    }

    // Increase iteration
    if(bisection_iterations_max < ++ bisection_iterations)
      break;
  }
  return point.y
}

关于javascript - 在d3中,如何从SVG线中获取插值线数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33185364/

相关文章:

javascript - 如何避免在初始化期间提供虚拟 Vue 数据结构?

javascript - Android 警报 "Don' t 再次显示“Web View 中的复选框

Java 在 XOR 模式下绘制组件不绘制任何内容

python - 有没有办法让我们使用 pyopengl 显示 ply 文件?

javascript - 从nodejs在客户端发送JWT token 是否存在安全风险

android - 如果 Canvas 旋转,Canvas.getClipBounds() 会返回什么?

javascript - D3 JS Sankey图中的圆环图

svg - 将 D3.JS 示例 "bullet.html"保存到 SVG

javascript - 将 SVG 路径转换为 ​​canvas html5

javascript - CSS 选择器无法使用 jQuery