san*_*zer 16 javascript svg d3.js
我试图获得text我用d3.js创建的一堆元素的宽度
这就是我创建它们的方式:
var nodesText = svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(function(d) {
return d.name;
})
.attr("x", function(d, i) {
return i * (w / dataset.length);
})
.attr("y", function(d) {
return 45;
});
Run Code Online (Sandbox Code Playgroud)
然后我使用宽度创建rectangles与text盒子相同的大小
var nodes = svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", function(d, i) {
return i * (w / dataset.length);
})
.attr("y", function(d) {
return 25;
})
.attr("width", function(d, i) {
//To Do: find width of each text element, after it has been generated
var textWidth = svg.selectAll("text")
.each(function () {
return d3.select(this.getComputedTextLength());
});
console.log(textWidth);
return textWidth;
})
.attr("height", function(d) {
return 30;
})
Run Code Online (Sandbox Code Playgroud)
我尝试从这里使用Bbox方法,但我真的不明白.我认为选择实际元素是我出错的地方.
Lar*_*off 11
我会将长度作为原始数据的一部分:
var nodesText = svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(function(d) {
return d.name;
})
.attr("x", function(d, i) {
return i * (w / dataset.length);
})
.attr("y", function(d) {
return 45;
})
.each(function(d) {
d.width = this.getBBox().width;
});
Run Code Online (Sandbox Code Playgroud)
然后是
var nodes = svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("width", function(d) { return d.width; });
Run Code Online (Sandbox Code Playgroud)