javascript - How can I rotate my text labels so they can't go upside-down (SVG)? -


i'm making sunburst diagram creation tool using d3.js, , i'm trying replicate way labels on this page flip never upside-down. problem use rotate transform attribute, that's used position label. code currently:

svg.selectall("text")     .data(partition.nodes)     .enter()     .append("text")     .attr("transform", function(d) { return "rotate(" + ((d.x + d.dx / 2 - math.pi / 2) / math.pi * 180) + ")"; })      .attr("x", function(d) { return math.sqrt(d.y); })     .attr("dx", "6") // margin     .attr("dy", ".35em") // vertical-align     .text(function(d) { return d.name;}); 

i found tspan rotate attribute, turned out red herring rotates individual letters. i'm basing diagram on this page.

thanks in advance!

one option nest text inside group. group positioned you're positioning text, except instead of using "x" attribute, you'd use transform attribute translate in addition existing rotate directive. note order of transformations matters here; need first rotate translate.

then you'd apply local transformation text within group. i.e. rotated 180 degrees if needs flipped. way text doesn't need moved position –– group takes care of –– need have small local adjustments when it's flipped (also, ir have aligned right in case).

the code below should more or less it, though it's impossible me test , tweak without working jsfiddle.

svg.selectall("g.label")   .data(partition.nodes)   .enter()   .append("g")   .attr("class", "label")   .attr("transform", function(d) {     // first, rotate group (not text) , translate     // same amount used applied via "x" attr     return       "rotate(" + ((d.x + d.dx / 2 - math.pi / 2) / math.pi * 180) + ") " +       "translate(" + math.sqrt(d.y) + ")";   })   .each(function(d, i) {     d3.select(this) // select containing group (which created above)       .append('text') // append text inside group       .attr("dx", "6") // margin       .attr("dy", ".35em") // vertical-align       .attr("transform", function(d) {         // locally transform text within containing group:         // label should flipped if group's rotation greater math.pi (aka 180 degs)         var shouldbeflipped = d.x + d.dx / 2 - math.pi / 2 > math.pi;         return "rotate(" + (shouldbeflippled ? 180 : 0) + ")"       })       .text(function(d) { return d.name;});   }); 

Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -