How to linebreak an svg text within javascript? How to linebreak an svg text within javascript? javascript javascript

How to linebreak an svg text within javascript?


This is not something that SVG 1.1 supports. SVG 1.2 does have the textArea element, with automatic word wrapping, but it's not implemented in all browsers. SVG 2 does not plan on implementing textArea, but it does have auto-wrapped text.

However, given that you already know where your linebreaks should occur, you can break your text into multiple <tspan>s, each with x="0" and dy="1.4em" to simulate actual lines of text. For example:

<g transform="translate(123 456)"><!-- replace with your target upper left corner coordinates -->  <text x="0" y="0">    <tspan x="0" dy="1.2em">very long text</tspan>    <tspan x="0" dy="1.2em">I would like to linebreak</tspan>  </text></g>

Of course, since you want to do that from JavaScript, you'll have to manually create and insert each element into the DOM.


I suppese you alredy managed to solve it, but if someone is looking for similar solution then this worked for me:

 g.append('svg:text')  .attr('x', 0)  .attr('y', 30)  .attr('class', 'id')  .append('svg:tspan')  .attr('x', 0)  .attr('dy', 5)  .text(function(d) { return d.name; })  .append('svg:tspan')  .attr('x', 0)  .attr('dy', 20)  .text(function(d) { return d.sname; })  .append('svg:tspan')  .attr('x', 0)  .attr('dy', 20)  .text(function(d) { return d.idcode; })

There are 3 lines separated with linebreak.


With the tspan solution, let's say you don't know in advance where to put your line breaks: you can use this nice function, that I found here:http://bl.ocks.org/mbostock/7555321

That automatically does line breaks for long text svg for a given width in pixel.

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);      }    }  });}