2016-01-31 61 views
3

当存在是的DOM中的SVG元素,它可能使用getBBox函数来获得它的边框,如下例所示:抢占getBBox计算

http://bl.ocks.org/mbostock/1160929

是否有可能得到边界框没有实际添加元素到DOM?

换句话说,我可以计算出一些文字的边框会是什么如果它连接到某个节点没有实际安装呢?

目标是为图形迭代添加标签,同时避免重叠文本。

回答

2

在显示文本之前无法计算文本的高度。原因是他们可能会影响文本高度的许多事情(CSS类,字体存在或不在计算机中......)。

实现它的最简单方法是创建隐藏的文本,获取其高度,然后计算位置。

1

如何

  1. 添加文本
  2. 获取边界
  3. 删除文本。

事情是这样的:

//add the text 
var text = svg.append("text") 
    .attr("id", "text-to-remove") 
    .attr("x", 480) 
    .attr("y", 250) 
    .attr("dy", ".35em") 
    .attr("text-anchor", "middle") 
    .style("font", "300 128px Helvetica Neue") 
    .text("Hello, getBBox!"); 
//get bbox 
var bbox = text.node().getBBox(); 

//remove the text 

d3.select("#text-to-remove").remove(); 

//use bbox 
var rect = svg.append("rect") 
    .attr("x", bbox.x) 
    .attr("y", bbox.y) 
    .attr("width", bbox.width) 
    .attr("height", bbox.height) 
    .style("fill", "#ccc") 
    .style("fill-opacity", ".3") 
    .style("stroke", "#666") 
    .style("stroke-width", "1.5px"); 

工作代码here

希望这有助于!