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:
.ai-ellipsis {
display: block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
-moz-binding: url(<q>assets/xml/ellipsis.xml#ellipsis</q>);
}
This is my SVG:
<g class="bar" transform="translate(0,39)">
<text class="label" x="-3" y="6.5" dy=".35em" text-anchor="start">Construction</text>
<rect height="13" width="123"></rect>
</g>
It's generated as follows:
barEnter.append("text").attr("class", "label")
.attr("x", -3).attr("y", function() { return y.rangeBand() / 2})
.attr("dy", ".35em").attr("text-anchor", "start")
.text(function(d) {
return d.Name;
});
Currently the text is overflowing and overlapping the rect element.
Is there any way I can say "if text is more than a certain width, crop it and add ellipses"?
a wrapper function for overflowing text:
usage:
I am not aware of an equivalent CSS class for SVG, but you can use
foreignObject
to embed HTML in SVG. This gives you access to this functionality and is more flexible in general (e.g. you can do automatic line breaking easily).See here for a complete example.
Use this function to set the SVG node text. The value for the threshold (eg. 20) depends on you. This means that you will display up to 20 characters from your node text. All the texts grater than 20 characters will be trim and display "..." at the end of the trim text.
Usage eg. :
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.
View on JSFiddle.
I implemented a native function that doesn't depend on d3, this function implements 3 way fallbacks: