How can I wrap long text labels with D3.js?

2019-09-07 10:56发布

I have created a node-tree using D3 and would like to understand how to wrap texts that are too long.

  nodeUpdate.select("text")
      .text(function(d) {
        if(d.name == "root"){
            return "";
        } else {
            return d.name;
        }
       })
      .style("font-family", "Verdana")
      .style("fill-opacity", 1);

If d.name is too long I'd like it to fill several lines instead of one. I have found this http://bl.ocks.org/mbostock/7555321 but I do not seem to understand how this works, and I certainly don't understand how the "wrap" function gets it's input? On this example the wrap function has no parameters when called.

1条回答
叛逆
2楼-- · 2019-09-07 11:42

The code from http://bl.ocks.org/mbostock/7555321 has two key parts.

The call to wrap() done

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis)
.selectAll(".tick text")
  .call(wrap, x.rangeBand());

which is expecting a text element and a width like done in

node.append("text")
  // Make sure to have a text element
  .text(function(d) {
    return d.name;
  })
  .call(wrap, 50);

The confusing part here is that call statements apply to the current selection like .tick text or all nodes.

The second part is the required text.text() otherwise it does not work.

function wrap(text, width) {
  text.each(function() {
  var text = d3.select(this),
      words = text.text().split(/\s+/).reverse(),
查看更多
登录 后发表回答