d3.js:水平居中<g>元素的父元素'元素

d3.js: Horizontally center a <g> element with an unknown size within it's parent <svg> element

本文关键字:元素 js d3 水平居中      更新时间:2023-09-26

我正在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")