SVG1&2 multiline text

by toubia95

HTML

<script src="https://cdn.jsdelivr.net/npm/@svgdotjs/[email protected]/dist/svg.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/path-data-polyfill@latest/dist/path-data-polyfill.min.js"></script>
<!-- SVG 1.1 & SVG 1.2 Tiny-->
<svg id="svg1" width="200" height="200" xmlns="http://www.w3.org/2000/svg">
  <text x="10" y="20">
    <tspan x="10" dy="1.2em">1.Ceci est un exemple</tspan>
    <tspan x="10" dy="1.2em">de texte dans un bloc</tspan>
    <tspan x="10" dy="1.2em">qui gère les retours à la ligne.</tspan>
  </text>
</svg>

<!-- SVG 2 with polyfill -->
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
    <textArea x="10" y="20" width="380" height="180">
      2.Ceci est un exemple de texte dans un bloc qui gère automatiquement les retours à la ligne.
    </textArea>
  </svg>

<!-- svg.js -->
<div id="drawing1"></div>

<!-- svg.js sans découpage -->
<div id="drawing2"></div>

JavaScript

// svg2 avec découpage
const draw1 = SVG().addTo('#drawing1').size(200, 200);
const text1 = draw1.text('3.Ceci est un exemple de texte dans un bloc qui gère automatiquement les retours à la ligne.').move(10, 20).font({ size: 16 });
text1.text(function(add) {
  add.tspan('3.Ceci est un exemple').newLine();
  add.tspan('de texte dans un bloc').newLine();
  add.tspan('qui gère automatiquement').newLine();
  add.tspan('les retours à la ligne.').newLine();
});
    
// svg2 - découpage auto ?
const draw2 = SVG().addTo('#drawing2').size(200, 200);
const textElement = draw2.text('').move(10, 20).font({ size: 16 });

const textContent = 'Ceci est un exemple de texte dans un bloc qui gère automatiquement les retours à la ligne.';
const maxWidth = 180;

function wrapText(textElement, textContent, maxWidth) {
  const words = textContent.split(' ');
  let line = '';
  words.forEach(word => {
    const testLine = line + word + ' ';
    textElement.text(testLine);
    if (textElement.node.getComputedTextLength() > maxWidth && line.length > 0) {
      textElement.text(line.trim());
      line = word + ' ';
      textElement.add(tspan => tspan.text(line.trim()).dy('1.2em').x(10));
    } else {
      line = testLine;
    }
  });
  textElement.add(tspan => tspan.text(line.trim()).dy('1.2em').x(10));
}

wrapText(textElement, textContent, maxWidth);