2016-05-18 67 views
1

當我計算文本路徑元素的文本長度時,當我對「字母間距」進行不同的設置時,該值不會改變。用D3.js計算字母間距的文本長度

有沒有辦法處理額外的長度,由於額外的間距?

目前我計算到長度限制: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;} 
+0

我挺不理解你的問題:getComputedTextLength應考慮的空間。根據API:*「getComputedTextLength() 來自渲染此元素中所有字符的所有預先值的總和,包括字形上的提前值(水平或垂直),屬性」字距調整「 ,'letter-spacing'和'word-spacing'以及由'tspan'元素上的屬性'dx'和'dy'進行的調整對於非呈現環境,用戶代理應對字形度量做出合理的假設。「* –

+0

你是對的:我剛剛重現了你的問題,並且getComputedTextLength返回相同的值,而不管字母空間。 –

回答

0

事實上,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; 
} 
});