What is the equivalent of .getComputedTextLength()
method in d3
. .getComputedTextLength()
works on Dom
element not d3
element's object.
Edit (Image added)
What is the equivalent of .getComputedTextLength()
method in d3
. .getComputedTextLength()
works on Dom
element not d3
element's object.
Edit (Image added)
4 Answers
Reset to default 14D3 selections are, in fact, objects (since D3 v4.0). However, there is no method for computing the length of the text in an object because the object itself has no presence in the DOM and, therefore, has no length. You can only compute the length (in pixels) of a DOM element.
That being said, you can use getComputedTextLength()
with a D3 selection, if you use that selection to point to the SVG element. For instance, using node()
:
d3.select("foo");//this is a D3 selection
d3.select("foo").node();//this is the DOM element
Here is a demo:
var svg = d3.select("svg");
var text = svg.append("text")
.attr("x", 10)
.attr("y", 30)
.text("Hello world!");
console.log("the text has " + d3.select("text").node().getComputedTextLength() + " px")
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>
Simply access the DOM elements inside selection operations with this
to benefit from bulk node processing customary with D3
, e.g.
d3.selectAll('tspan.myClass')
.each(function(d) {
console.log(this.getComputedTextLength());
});
or
d3.selectAll('tspan.myClass')
.attr('transform', function(d) {
var width = this.getComputedTextLength() + 2 * padding;
return 'translate(' + width / 2 + ' 0)');
});
this
is bound to the current DOM node.
selection.node()
only returns the first element in the selection.
As of D3
4.* there's also selection.nodes()
which recovers all DOM nodes in a selection, so you can do
d3.selectAll('tspan.myClass').nodes().forEach(function(el) {
console.log(el.getComputedTextLength());
});
though its use is less idiomatic than grabbing the element via this
inside selection.attr
, selection.style
, selection.filter
, selection.each
etc. as in the snippets above it.
If I understand it correctly, OP wants to have a function similar to getComputedTextLength
in D3.js, without using D3.js.
There's not such method in plain Javascript. However, if the element is an SVG element, you can use getBBox()
to retrieve the coordinates and dimension of the smallest rectangle that the element fits.
If the element doesn't belong to an SVG, use getClientRect()
or getBoundingClientRect()
.
Its node.getBoundingClientRect().width
.
In my case, this
is a d3 object. So you can use getComputedTextLength()
to get the width of the object.
If you are using plain javascript, you can use node.getBoundingClientRect().width
.