我在 d3.js 中创建一个决策树,但我无法将它的 g 元素置于父 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 is not a function
我似乎无法通过谷歌找到将 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")
关于javascript - d3.js:在其父 <svg> 元素中水平居中具有未知大小的 <g> 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31735752/