计算与长度限制:Textlength字母间距与D3.js(Compute textlength wi

2019-09-29 03:13发布

当我计算textpath元素的文本长度时,我的样式“字母间距”有不同的价值不会改变。

有没有办法来处理,由于额外的间距长度多余?

目前,我计算到长度限制:Textlength隐藏在二层,partion图形一些标签:

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;}

Answer 1:

事实上, getComputedTextLength()是忽略了一封信空间。

你可以尝试getBBox()代替:

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;
 }
}); 

不幸的是,这不会帮助你,因为你面对的倾斜通路,而不是一个水平文本。 所以,你可以尝试调整getComputedTextLength与给定值,根据您的字距:

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;
 }
}); 


文章来源: Compute textlength with letter-spacing with D3.js