d3防止文本扩展到SVG之外

时间:2016-06-18 03:03:11

标签: javascript css d3.js svg text

我有通过D3生成的折线图,文本显示在悬停时指针的右侧。问题是出现在最右边的文本是由SVG的边缘切断的。我知道一个简单的overflow:visible会允许它出现在外面,但我希望它留在SVG中。这可能吗?

enter image description here

1 个答案:

答案 0 :(得分:7)

您可以使用此技术:

enter image description here

  • 如果光标位于A区域:将文本或工具提示对齐到右侧
  • 如果光标位于B区:将文本或工具提示对齐到左侧

使用(svg_width / 2)获取中间

text.style ("text-anchor", function () {
     var position = d3.mouse();  // position[0] <= x    position[1]  <= y
     if (position[0] < (svg_width/2) ) {
            // you are on A zone
            return "start";
     } else {
            // you are on B zone
            return "end";
     }
})