Javascript 计算D3中一组的高度和宽度

Javascript 计算D3中一组的高度和宽度,javascript,d3.js,Javascript,D3.js,我需要一个组的宽度和高度,换句话说,我需要取组中所有元素的最大宽度和高度,例如,此代码应打印400/280,但应打印null/null。这是否需要手动计算 var svg = d3.select("body") .append("svg") .attr("width", 500) .attr("height", 500);

我需要一个组的宽度和高度,换句话说,我需要取组中所有元素的最大宽度和高度,例如,此代码应打印400/280,但应打印null/null。这是否需要手动计算

        var svg = d3.select("body")
                        .append("svg")
                        .attr("width", 500)
                        .attr("height", 500);
        var g = svg.append('g');

        g.append('rect').attr('type',1)                                         
                        .attr("width", 400)
                        .attr("height", 200);

        g.append('rect').attr('type',3)
                        .attr("width", 300)
                        .attr("height", 280);

        console.log(g.attr('width'));
        console.log(g.attr('height'));

我想您可能在打印时遗漏了“rect”

g.append('rect').attr('type',3)

console.log(g.attr('width'));

getElementById()
函数可能会出现很多问题。首先,确保标签位于主体下方,而不是主体内部,因为这样会混淆所有内容。即使您决定使用标记的SRC属性链接它,也应该将它放在底部。另外,只要声明对象,而不是您正在寻找的属性,因为您在底部抓取属性

希望这有帮助


-Veggie

要获得宽度和高度,只需使用以下命令:

g.node().getBBox();
工作代码段:

var svg=d3.选择(“主体”)
.append(“svg”)
.attr(“宽度”,500)
.attr(“高度”,500);
var g=svg.append('g');
g、 追加('rect').attr('type',1)
.attr(“宽度”,400)
.attr(“高度”,200)
.attr(“填充”、“红色”);
g、 append('rect').attr('type',3)
.attr(“宽度”,300)
.attr(“高度”,280);
log(g.node().getBBox())


高度应为280,宽度应为400,而不是5和5。我在这里给出了输出示例,很抱歉,我将更新它