2017-09-15 1 views
0

Ich versuche, dünne Rechteckdiagramme zu erstellen, und ich brauche eine Methode, die den Text nehmen und richtig wickeln konnte.d3.js dynamische Textumhüllung

Das Ziel ist es, so etwas zu erstellen.

enter image description here

http://jsfiddle.net/0ht35rpb/167/

d3.js how to apply text wrapping declaratively Lars mit einer Lösung gekommen war - und ich habe versucht, es hier zu implementieren - aber ich konnte es nicht zur Arbeit kommen.

http://jsfiddle.net/0ht35rpb/168/

const axisLabel = chart 
    .append("g") 
    .append("text") 
    .attr('x', function(d) { 
    return path.centroid(d)[0]; 
    }) 
    .attr('y', function(d) { 
    return path.centroid(d)[1] + 4; 
    }) 
    .each(function(d) { 
     var arr = d.properties.eventname.split(" "); 
     if (arr != undefined) { 
     for (var i = 0; i < arr.length; i++) { 
      d3.select(this).append("tspan") 
      .text(function() { 
       return arr[i]; 
       }) 
       .attr("y", path.centroid(d)[1] + i * 8 + 8) 
       .attr("x", path.centroid(d)[0]) 
       .attr("text-anchor", "middle"); 
      } 
     } 
     }); 

gibt es diese Methode hier mit tspans und das funktioniert fast - aber der Text zentriert ist nicht wahr?

http://jsfiddle.net/0ht35rpb/169/

function wrap(text, width) { 
    text.each(function() { 
    var text = d3.select(this), 
     words = text.text().split(/\s+/).reverse(), 
     word, 
     line = [], 
     lineNumber = 0, 
     lineHeight = 1.1, // ems 
     y = text.attr("y"), 
     dy = parseFloat(text.attr("dy")), 
     tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em"); 
    while (word = words.pop()) { 
     line.push(word); 
     tspan.text(line.join(" ")); 
     if (tspan.node().getComputedTextLength() > width) { 
     line.pop(); 
     tspan.text(line.join(" ")); 
     line = [word]; 
     tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word); 
     } 
    } 
    }); 
} 

Antwort

0

Sie haben keine path in Ihrem Code und daher keinen Schwerpunkt. So

, sollte es sein:

.attr('x', function(d) { 
    return config.width/2; 
}) 
.attr('y', function(d) { 
    return config.height; 
}) 

Hier ist die aktualisierte Geige: http://jsfiddle.net/vumbvs9s/

Ihre zweite Geige angeht, nur Bostock die Funktion ändern Sie die aktuelle x Position zu bekommen:

var x = text.attr("x"); 

Hier ist die aktualisierte Geige: http://jsfiddle.net/a0s8h3wg/

+0

https://bl.ocks.org/mbstock/7555321 –