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

社会主义新天地 提交于 2019-12-25 07:37:53

问题


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:


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(),


来源:https://stackoverflow.com/questions/24802534/how-can-i-wrap-long-text-labels-with-d3-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!