javascript - D3 - How to get width of previous elements in Text selection -
in code below, seek insert 3 strings on screen 1 next other
to so, need calculate screen width of labels have been displayed, highlighted in attr("x",...)
line.
how refer previous elements during selection in d3?
references: how refer previous element, how calculate width of text before displaying it
var labels = ['a label', 'another label', 'a third label'] var textitems = svg.append('g') .selectall('.my_labels_text') .data(labels) .enter() .append("text") .attr("class", "my_labels_text") .attr("text-anchor", "left") .attr("x", function (d, i) { return <cumulated width of labels displayed>}) .attr("y", 10) // arbitrary y value .text(function(d) { return d })
if need keep running width count; use variable in outer scope:
<!doctype html> <html> <head> <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script> </head> <body> <script> var labels = ['a label', 'another label', 'a third label']; var svg = d3.select('body') .append('svg') .attr('width', 1000) .attr('height', 500); var runningwidth = 10; var textitems = svg.append('g') .selectall('.my_labels_text') .data(labels) .enter() .append("text") .attr("class", "my_labels_text") .attr("text-anchor", "left") .text(function(d) { return d }) .attr("y", 10) // arbitrary y value .attr("x", function (d, i) { var thiswidth = this.getcomputedtextlength(), rv = runningwidth; runningwidth += thiswidth; return rv; }); </script> </body> </html>
Comments
Post a Comment