var text = vis.selectAll("text")
.data(words, function(d) { return d.text.toLowerCase(); });
text.enter().append("text")
.attr("text-anchor", "middle")
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")"})
.style("font-size", function(d) { return d.size + "px"; })
var bbox = text.node().getBBox();
Run Code Online (Sandbox Code Playgroud)
如何使用getBBox()获取每个文本的文本区域?
nra*_*itz 19
这里最好的方法取决于你想要做什么.大多数d3回调函数都会提供当前的DOM元素this,因此这应该有效:
text.each(function() {
console.log(this.getBBox());
});
Run Code Online (Sandbox Code Playgroud)
除此之外,问题是您需要使用该数字的上下文.例如,要获得文本宽度的总和,您可以执行以下操作:
var textWidth = 0;
text.each(function() {
textWidth += this.getBBox().width;
});
Run Code Online (Sandbox Code Playgroud)
小智 9
您还可以使用node()在元素上同步执行此操作:
console.log(text.node().getBBox());
Run Code Online (Sandbox Code Playgroud)