Compute textlength with letter-spacing with D3.js

你。 提交于 2020-01-05 04:06:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!