在我的D3折线图中,我正在尝试创建鼠标悬停效果,如下例所示:http://bl.ocks.org/mbostock/3902569
在这个例子中,作者使用平分函数,据我所知,只支持线性尺度.问题是,在我的图表中,我有一个带有不同的离散rangePoint元组的序数x轴.因此,如果它像下面的情况(m =鼠标位置),我想得到最接近的x值的像素位置,在这个例子中将是x2.
m | x1----------x2----------x3
有没有办法做到这一点?
使用您的链接示例,这里mousemove
是序数量表函数的快速实现:
var tickPos = x.range(); function mousemove(d){ var m = d3.mouse(this), lowDiff = 1e99, xI = null; // if you have a large number of ticks // this search could be optimized for (var i = 0; i < tickPos.length; i++){ var diff = Math.abs(m[0] - tickPos[i]); if (diff < lowDiff){ lowDiff = diff; xI = i; } } focus .select('text') .text(ticks[xI]); focus .attr("transform","translate(" + tickPos[xI] + "," + y(data[xI].y) + ")"); }
完整代码: