0

I am making a tree map () and want to create a line break when the text is longer than say 10 characters.

Therefore this

enter image description here

would look like this

enter image description here

First I use a method for spitting the string at a specified length:

function wordwrap( str, width, brk, cut ) {    
            brk = brk || 'n';
            width = width || 75;
            cut = cut || false;
            if (!str) { return str; }
            var regex = '.{1,' +width+ '}(\s|$)' + (cut ? '|.{' +width+ '}|.+$' : '|\S+?(\s|$)');
            return str.match( RegExp(regex, 'g') ).join( brk )
        }

And here is the D3 for generating text at each node:

nodeEnter.append("svg:text")
                    .attr("x", function(d) { return d.children || d._children ? -10 : 10; })
                    .attr("dy", ".35em")
                    .attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
                    .text(function(d) {  if(d.name.length > 10) { return wordwrap(d.name, 10, '<br>') } } )
                    .style("fill-opacity", 1e-6)
                    .style("fill", "white")
                    .style("font-size", 22);

You can see that I have entered the wordwrap method into the D3 code. But all it does is show the
tag within the actual text of the tree graph.

How can I split the text based on length so that D3 newlines the string if it is above 10 characters.

Cybernetic
  • 12,628
  • 16
  • 93
  • 132
  • might be helpful: http://stackoverflow.com/questions/16701522/how-to-linebreak-an-svg-text-within-javascript. I don't think you can use a
    tag inside an svg text element.
    – Mike Atkins Jan 16 '16 at 19:21
  • 1
    See http://bl.ocks.org/mbostock/7555321 – Lars Kotthoff Jan 16 '16 at 19:59
  • Also check [How to linebreak an svg text within javascript](http://stackoverflow.com/questions/16701522/how-to-linebreak-an-svg-text-within-javascript) – Artem Jan 16 '16 at 22:41

1 Answers1

1

At this point you already noticed that "< br>" doesn't work inside a svg:text element so I see two ways of accomplishing what you need:

  1. Using svg textarea
  2. Including svg tspan whenever you want to add a line break.

For the first method look at: https://www.w3.org/TR/SVGTiny12/text.html#TextAreaElement

All you need to do is define a text area size and let svg handle the characters. You may want to resize your text to make it look the way it fits your need.

For the second method look at: https://www.w3.org/TR/SVG/text.html#TSpanElement

In this case you must include logic to append a tspan [append('svg:tspan')] inside your svg:text element whenever you want a line break.

You will have to change the logic of your nodeEnter.append but this is not difficult to accomplish either way.