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 =...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.