I\'m using D3.js. I\'d like to find an SVG equivalent to this CSS class, which adds ellipses if text flows out of its containing div:
Just an update on the wrap function proposed by user2846569. getComputedTextLength() tends to be really slow, so...
EDIT
I diligently applied the advice by user2846569 and made a version with "binary" search, with some calibration and parametrized precision.
'use strict';
var width = 2560;
d3.select('svg').attr('width', width);
// From http://stackoverflow.com/questions/10726909/random-alpha-numeric-string-in-javascript
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i)
result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
function wrap() {
var self = d3.select(this),
textWidth = self.node().getComputedTextLength(), // Width of text in pixel.
initialText = self.text(), // Initial text.
textLength = initialText.length, // Length of text in characters.
text = initialText,
precision = 10, //textWidth / width, // Adjustable precision.
maxIterations = 100; // width; // Set iterations limit.
while (maxIterations > 0 && text.length > 0 && Math.abs(width - textWidth) > precision) {
text = /*text.slice(0,-1); =*/(textWidth >= width) ? text.slice(0, -textLength * 0.15) : initialText.slice(0, textLength * 1.15);
self.text(text + '...');
textWidth = self.node().getComputedTextLength();
textLength = text.length;
maxIterations--;
}
console.log(width - textWidth);
}
var g = d3.select('g');
g.append('text').append('tspan').text(function(d) {
return randomString(width, 'a');
}).each(wrap);
View on JSFiddle.