What is the equivalent of .getComputedTextLength()
method in d3
. .getComputedTextLength()
works on Dom
element not d3
element's object.
Edit (Image added)
D3 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With