JSFiddle - React, Tailwind, and code Playground

by Julien Etienne

HTML

<svg width='500' height='300' viewBox='0 0 500 300' preserveAspectRatio='xMidYMin meet'>
    <text>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec porttitor tristique justo, at efficitur mauris aliquam et. Quisque.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec porttitor tristique justo, at efficitur mauris aliquam et. Quisque.    
    </text>
</svg>

CSS

@import url(http://fonts.googleapis.com/css?family=Open+Sans);
 svg {
    background: yellow;
}
text {
    font-family:'Open Sans', sans-serif;
    font-size: 16px;
    font-weight: normal;
}

JavaScript

var testWidth = 180;
var svg = document.getElementsByTagName('svg')[0];
var text = document.getElementsByTagName('text')[0];
var style = style || {};

style.paragraph = {
    x: 50,
    y: 50,
    extent: {
        width: testWidth
    },
    lineHeight: 18

};


function create(el) {
    this.NS = "http://www.w3.org/2000/svg";
    return document.createElementNS(this.NS, el);
}

function getBox(el, info) {
    return el.getBoundingClientRect()[info] || el.parentNode.getBBox()[info];

}

function initText(selector) {
    var group = create('g');
    var rect = create('rect');
    svg.insertBefore(group, selector);
    group.appendChild(rect);
    group.appendChild(selector);
    rect.style.fill = 'yellowgreen';
    setStyles(group, rect, selector);
}

function setStyles(g, r, txt) {
    var p = style.paragraph;
    g.setAttribute('transform', 'translate(50,50)');
    r.setAttribute('x', "0");
    r.setAttribute('y', "0");
    r.setAttribute('width', testWidth/*getBox(txt, 'width')*/);
    r.setAttribute('height', getBox(txt, 'height')/1.4);
    txt.setAttribute('x', 0);
    txt.setAttribute('y', getBox(txt, 'height')/1.4);
    //   console.log(Object.keys(p)[0], p)
    breakWords(r, txt, p);
}

initText(text);


// From extent.width caculate number of lines
function breakWords(rec, t, p){
//Get total length of words
    var pLength = getBox(t,'width');
//put words into array
    var words = t.textContent.split(' ');
// calc number of lines
    var lineCount = Math.ceil( pLength / p.extent.width +1);
//For words.length, add a word & check the width, store number of words added.
// if the total span width is greater than the block
// repllace span with number of words minus one. 
// add new line   
var tempText = create('text');
    svg.appendChild(tempText);

var lines =[];
    for(var i =0; i < lineCount; i++){
// Add tspan line
      lines[i] = create('tspan');
// Append line
     tempText.appendChild(lines[i]);
    }
    
   // var textWidth =...