Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent method of ".getComputedTextLength()" in d3.js

What is the equivalent of .getComputedTextLength() method in d3. .getComputedTextLength() works on Dom element not d3 element's object.
Edit (Image added)
enter image description here

like image 784
ozil Avatar asked Mar 10 '17 12:03

ozil


1 Answers

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>
like image 170
Gerardo Furtado Avatar answered Nov 14 '22 22:11

Gerardo Furtado