问题
When I compute the text length of a textpath element the value doesn't change when I style the 'letter-spacing' differently.
Is there a way to deal with the extra length due the extra spacing ?
Currently I compute the textlength to hide some labels on a bilevel-partion graph:
textsElements
.attr("dy", function(d) {
var offset = (radius / strokeWidth)/2;
var rotation = getRotationDeg(d)
return rotation > 0 && rotation < 180 ? -offset : offset;
})
.append("textPath")
.attr("startOffset", "50%")
.attr("class","labels-text")
.style("text-anchor", "middle")
.attr("xlink:href", function (d) { return '#' + createTextPathId(d); })
.text(function (d) { return d.name; });
// Hide labels that are to long
textsElements.each(function(d){
var el = d3.select(this);
d.labelToLong= false;
if(( d.hiddenArcLength - this.getComputedTextLength()) < 5) {
el.style("opacity",0);
d.labelToLong = true;
}
});
textpath.labels-text {letter-spacing: 1px;}
回答1:
Indeed, getComputedTextLength()
is ignoring the letter space.
You could try getBBox()
instead:
textsElements.each(function(d){
var el = d3.select(this);
d.labelToLong= false;
if(( d.hiddenArcLength - this.getBBox().width) < 5) {
el.style("opacity",0);
d.labelToLong = true;
}
});
Unfortunately, this will not help you because you are dealing with inclined paths, not a horizontal text. So, you can try to tweak getComputedTextLength
with a given value, according to your kerning:
textsElements.each(function(d){
var el = d3.select(this);
var tweak = 1.2;//you can make this value >1 or <1, according to the kerning
d.labelToLong= false;
if(( d.hiddenArcLength - this.getComputedTextLength()*tweak) < 5) {
el.style("opacity",0);
d.labelToLong = true;
}
});
来源:https://stackoverflow.com/questions/37300187/compute-textlength-with-letter-spacing-with-d3-js