我正在使用d3 v4。当有人滚过我的折线图时,我希望有一个框显示有关他们正在滚动的图表中的点的信息,所以我将其包括在内
svg.append("rect")
.attr("class", "overlay")
.attr("width", width)
.attr("height", height)
.on("mouseover", function() {
focus.style("display", null);
})
.on("mouseout", function() {
focus.style("display", "none");
})
.on("mousemove", mousemove);
function mousemove() {
var x0 = x.invert(d3.mouse(this)[0]),
i = bisectDate(data, x0, 1),
d0 = data[i - 1],
d1 = data[i],
d = x0 - d0.date > d1.date - x0 ? d1 : d0;
focus.attr("transform", "translate(" + x(d.index_date) + "," + y(d.value) + ")");
focus.select("text").text(d.value).append("tspan")
.attr("x", 10).attr("dy", "1.5em").text(formatDate(d.index_date));
var bbox = focus.select("text").node().getBBox();
rect.attr("width", bbox.width + 4).attr("height", bbox.height + 4);
}
问题是,当你越来越靠近折线图的右边时,信息开始切断 - https://jsfiddle.net/rgw12x8d/2/。我如何调整东西,以便即使你在最右边的一个点滚动,信息框仍然完全可见?
答案 0 :(得分:2)
您可以对d3.mouse(this)[0])
进行测试,看看它是否位于图表的右侧,例如大于width/2
如果是这样,那么将x放在x(d.index_date) - (bbox.width + 4)
上的翻译中,这会将框移到鼠标位置的左侧
例如:
function mousemove() {
var x0 = x.invert(d3.mouse(this)[0]),
i = bisectDate(data, x0, 1),
d0 = data[i - 1],
d1 = data[i],
d = x0 - d0.date > d1.date - x0 ? d1 : d0;
focus.select("text").text(d.value).append("tspan")
.attr("x", 10).attr("dy", "1.5em").text(d3.timeFormat("%Y-%b-%d")(d.index_date));
var bbox = focus.select("text").node().getBBox();
var rectWidth = bbox.width + 4
rect.attr("width", rectWidth).attr("height", bbox.height + 4)
var translateX = d3.mouse(this)[0] > (width/2)
? x(d.index_date) - rectWidth
: x(d.index_date);
focus.attr("transform", "translate(" + translateX + "," + y(d.value) + ")");
}
您也需要调整圈子的cx,我不在此处