我正在d3.js中创建一个决策树,我在父svg元素中居中它的g元素时遇到了麻烦。元素的宽度是未知的
如何将g元素水平居中?
如果你需要代码样本,让我知道,我会张贴。谢谢!
编辑:var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(0,40)")
.attr("id", "decision-tree");
var box = d3.select("#decision-tree").getBBox();
这会导致控制台中出现错误:
Uncaught TypeError: d3.select(…)。getBBox不是一个函数
我似乎找不到任何使用getBBox与d3.js通过谷歌的例子。如果你知道的话,你能举出一些例子吗?
您可以在svg元素之前添加center
元素,使整个svg水平位于中间。但在svg
之后和g
之前插入center
元素是行不通的。您必须使用此解决方案或使用变量来翻译g
元素。请看下面的代码示例:
var svg = d3.select("body")
.append("center")
.append("svg")
.attr("width", width)
.attr("height", height)
svg.append("g")
.append("text")
.text("Blah Blah Blah")
注意下面的代码不会将text
放置在g
的中心:
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
svg.append("center")
.append("g")
.append("text")
.text("Blah Blah Blah")