我已经在多系列折线图上创建了工具提示,如下所示在这里回答 https://stackoverflow.com/questions/34886070/d3-js-multiseries-line-chart-with-mouseover-tooltip/34887578#34887578。如果我将鼠标悬停在最后一个日期上,如下图所示:
工具提示重叠。我想要的是当工具提示重叠时,将它们中的任何一个移动得更高或更低。我试图通过更改下面的代码来做到这一点。
var beginning = 0,
end = lines[i].getTotalLength(),
target = null;
//console.log(lines[i])
//console.log(end)
while (true){
target = Math.floor((beginning + end) / 2);
pos = lines[i].getPointAtLength(target);
if ((target === end || target === beginning) && pos.x !== mouse[0]) {
break;
}
console.log(pos)
if (pos.x > mouse[0]) end = target;
else if (pos.x < mouse[0]) beginning = target;
else break; //position found
}
我的想法是重新计算end
。如果减去lines[0].getTotalLength()
and lines[1].getTotalLength()
小于或大于某个值,然后更新 end 的值(例如 end = end + 20)。但我没有在这里得到代码工作。
有人知道怎么做这个吗?或者是否有更简单的方法来避免工具提示重叠?
请参阅此处的更改:
https://jsfiddle.net/fk6gfwjr/1/ https://jsfiddle.net/fk6gfwjr/1/
基本上,工具提示需要按 y 位置排序,然后我们确保按该排序顺序的相邻工具提示间隔最小距离(我选择 15px)。然后将先前计算的 y 位置的偏移量添加到工具提示文本中。我还给文本上了颜色,让他们更容易区分哪个是哪个。
var ypos = [];
d3.selectAll(".mouse-per-line")
.attr("transform", function(d, i) {
// same code as before
// ...
// add position to an array
ypos.push ({ind: i, y: pos.y, off: 0});
return "translate(" + mouse[0] + "," + pos.y +")";
})
// sort this array by y positions, and make sure each is at least 15 pixels separated
// from the last, calculate an offset from their current y value,
// then resort by index
.call(function(sel) {
ypos.sort (function(a,b) { return a.y - b.y; });
ypos.forEach (function(p,i) {
if (i > 0) {
var last = ypos[i-1].y;
ypos[i].off = Math.max (0, (last + 15) - ypos[i].y);
ypos[i].y += ypos[i].off;
}
})
ypos.sort (function(a,b) { return a.ind - b.ind; });
})
// Use the offset to move the tip text from it's g element
// don't want to move the circle too
.select("text")
.attr("transform", function(d,i) {
return "translate (10,"+(3+ypos[i].off)+")";
}
;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)