How to auto text wrap text in snap svg?


Using the following plugin and code you could wrap text where there is \n :

Snap.plugin(function (Snap, Element, Paper, glob) { Paper.prototype.multitext = function (x, y, txt) { txt = txt.split("\n"); var t = this.text(x, y, txt); t.selectAll("tspan:nth-child(n+2)").attr({ dy: "1.2em", x: x }); return t; }; });

// And you can use it like this:

var ttt = paper.multitext(100, 100, "Sample\nmultiline\ntext").attr({ font: "18px Arial", textAnchor: "middle" });

And it produces: <a href="http://jsbin.com/panaxujuta/1/edit?html,output" rel="nofollow">http://jsbin.com/panaxujuta/1/edit?html,output</a>

Smaple multiline text

How can I automate this process using a rect Width as the limit for the lines of a long phrase or paragraph ? I don't want to use the foreignobject in svg for the purpose that I need the text later on . A native svg solution please. Any ideas would be greatly appreciated.

<strong>Edit</strong>: Instead of splitting on \n how can we split on certain width of a line of a text?

<strong>Edit2</strong>: I have this code that uses the above plugin, why this wouldn't work?:

var phrase = "Etiam porttitor risus in ex blandit sodales. Ut cursus mi augue, sit amet interdum diam interdum sit amet. Nunc nec lectus ex."; var textBoxWidth = 400; var words = phrase.split(" "); var newPhrase = words[0]; var t1 = paper.multitext(10,50,newPhrase) .attr({ fill: "none", stroke:"orange", "text-anchor":"start", "font-size":"18px", "font-family":"Arial"}); for(i=1;i<words.length;i++){ t1.attr({"text":newPhrase + " " + words[i]}); if(t1.getBBox().width<=textBoxWidth){ newPhrase += " " + words[i]; } else { newPhrase += " \n" + words[i] ; } }


Thanks for posting this. I had some of the wrapping to length code, but was having trouble because I wasn't using the array version of text().

The issue is you have to know the font size before you can limit the string. I was able to make this based off your code and wrapping logic based off <a href="https://stackoverflow.com/a/9899369/9970" rel="nofollow">https://stackoverflow.com/a/9899369/9970</a>. Its not perfect and could be faster if you cached the letter widths per font/size.

Snap.plugin(function (Snap, Element, Paper, glob) { Paper.prototype.multitext = function (x, y, txt, max_width, attributes) { var svg = Snap(); var abc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; var temp = svg.text(0, 0, abc); temp.attr(attributes); var letter_width = temp.getBBox().width / abc.length; svg.remove(); var words = txt.split(" "); var width_so_far = 0, current_line=0, lines=['']; for (var i = 0; i < words.length; i++) { var l = words[i].length; if (width_so_far + (l * letter_width) > max_width) { lines.push(''); current_line++; width_so_far = 0; } width_so_far += l * letter_width; lines[current_line] += words[i] + " "; } var t = this.text(x,y,lines).attr(attributes); t.selectAll("tspan:nth-child(n+2)").attr({ dy: "1.2em", x: x }); return t; }; });

Used like so

var bobo = paper.multitext(50, 50, "bobo bobo bobo bobo bobo bobo bobo bobo bobo", 150, { "font-size": "30px" });


  • Dictionary lookup with key as a matched group in python re.sub module
  • Image won't appear in JLabel
  • loop generate plots for variables in a data frame
  • Vim syntax highlighting for multiline fortran openmp directives
  • Run an exe in client machine from a website
  • Running bash in subprocess breaks stdout of tty if interrupted while waiting on `read -s`?
  • Does Python have an equivalent of Perl's qq?
  • How to test chat web app
  • CSS animation do not work for svg in
  • Replacing Colors in Gnuplot Heat Maps (pm3d map)
  • How to set the scrollbar to move at last line in multiline textbox?
  • Playing an array as sound and recording its output in parallel
  • Random characters in CSS class names
  • Google Scripts for Sheets - onEdit and “source”
  • big integers when reading file with readr in r
  • alogrithm for traveling throw a sequence [closed]
  • Update data in d3.js group
  • Inserting a (g) node in the middle of a tree (SVG) using jQuery
  • iOS 9 errors and correct conversion to swift 2
  • Fat binaries in iOS
  • Put value at centre of bins for histogram
  • Python delete lines of text line #1 till regex
  • How can I sort a a table with VBA with given text condition?
  • Modifying destination and filename of gulp-svg-sprite
  • Deserializing XML into class C#
  • How to show dropdown in excel using jrxml (jasper api)?
  • Function pointer “assignment from incompatible pointer type” only when using vararg ellipsis
  • bootstrap to use multiple ng-app
  • How to get icons for entities from eclipse?
  • json Serialization in asp
  • NSLayoutConstraint that would pin a view to the bottom edge of a superview
  • How get height of the a view with gone visibility and height defined as wrap_content in xml?
  • Understanding cpu registers
  • How do I configure my settings file to work with unit tests?
  • Turn off referential integrity in Derby? is it possible?
  • python draw pie shapes with colour filled
  • JaxB to read class hierarchy
  • Programmatically clearing map cache
  • How to Embed XSL into XML
  • How do I use LINQ to get all the Items that have a particular SubItem?