Archive for October, 2019

Automatically add line breaks in SVG text

Add line breaks in SVG text with jQuery, based on a separator. In the example below the separator is plain text <br>.

<div class="svg-container">
  <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <text>
      <tspan x="0" y="0" style="font-family: Helvetica; font-size: 8px;">Lorem ipsum <br> dolor sit amet</tspan>
    </text>
  </svg>
</div>
$('.svg-container').each(function() {
  // line breaks
  $(this).find('text').each(function() {
    if (/<br>/i.test($(this).text())) {
      var tspan = $(this).find('tspan:first-child');
      var tspanX = tspan.attr('x');
      var tspanY = tspan.attr('y');
      var tspanStyle = tspan.attr('style');
      
      tspan.hide();
      
      var lines = $(this).text().split('<br>');
      var lineHeight = parseFloat(tspan.css('fontSize'));
      for (var i = 0; i < lines.length; ++i) {
        $(this).append('<tspan x="'+ tspanX +'" y="'+ (parseFloat(tspanY) + (lineHeight * i)) +'" style="'+ tspanStyle +'">'+ $.trim(lines[i]) +'</tspan>');
      }
    }
  });

  // refresh svg
  $(this).html($(this).html());
});