Published
Edited
Mar 15, 2019
1 fork
Importers
18 stars
Insert cell
Insert cell
{
const svg = DOM.svg(width,100);
svg.appendChild(
createSVGtext({text:words, x:20,y:20})
)
return svg;
}
Insert cell
Insert cell
Insert cell
function createSVGtext(config = {}) {

let {text, x = 0, y = 0,
fontSize = 14, fill = '#333',
textAnchor = "left",
maxCharsPerLine = 65,
lineHeight = 1.3} = config;

if (typeof config == "string") text = config;

let svgText = document.createElementNS('http://www.w3.org/2000/svg', 'text');
svgText.setAttributeNS(null, 'x', x);
svgText.setAttributeNS(null, 'y', y);
svgText.setAttributeNS(null, 'font-size', fontSize);
svgText.setAttributeNS(null, 'fill', fill);
svgText.setAttributeNS(null, 'text-anchor', textAnchor);

let words = text.trim().split(/\s+/).reverse(),
word,
dy = 0,
lineNumber = 0,
line = [];

while(word = words.pop()) {

line.push(word);
let testLineLength = line.join(" ").length;

if (testLineLength > maxCharsPerLine){
line.pop();
let svgTSpan = document.createElementNS('http://www.w3.org/2000/svg', 'tspan');
svgTSpan.setAttributeNS(null, 'x', x);
svgTSpan.setAttributeNS(null, 'dy', dy + "em");

let tSpanTextNode = document.createTextNode(line.join(" "));
svgTSpan.appendChild(tSpanTextNode);
svgText.appendChild(svgTSpan);

line = [word];
dy = lineHeight;
}
}
let svgTSpan = document.createElementNS('http://www.w3.org/2000/svg', 'tspan')
svgTSpan.setAttributeNS(null, 'x', x);
svgTSpan.setAttributeNS(null, 'dy', dy + "em");

let tSpanTextNode = document.createTextNode(line.join(" "));
svgTSpan.appendChild(tSpanTextNode);
svgText.appendChild(svgTSpan);

return svgText;
}
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more