我使用 D3 显示折线图,代码大致如下(给定比例函数 x
、y
和 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/