我已经按照此处的答案在多系列折线图上创建了工具提示。如果我将鼠标悬停在最后一个日期上,如您在此图片中所见:
工具提示重叠。我想要的是当工具提示重叠时,将它们中的任何一个移动得更高或更低。我试图通过更改下面的代码来做到这一点。
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
}
Run Code Online (Sandbox Code Playgroud)
我的想法是重新计算end. 如果lines[0].getTotalLength()and的减法lines[1].getTotalLength()小于或大于一个值,则更新 end 的值(例如 end = end + 20)。但我在这里没有得到代码工作。
有人知道怎么做这个吗?或者有没有更简单的方法来避免工具提示重叠?
在此处查看更改:
https://jsfiddle.net/fk6gfwjr/1/
基本上,工具提示需要按 y 位置排序,然后我们确保该排序顺序中的相邻工具提示间隔最小距离(我选择了 15 像素)。然后将先前计算的 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)+")";
}
;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1466 次 |
| 最近记录: |