对文字进行截取显示,可用于Antv G6中的树图显示。
/**
* 对关系图表的超长文本进行处理
* @param str 待处理的文本
* @param maxWidth 文字的最大长度
* @param fontSize 文字的大小
*/
export const fittingString = (str, maxWidth, fontSize) => {
let currentWidth = 0
let res = str
const pattern = new RegExp('[\u4E00-\u9FA5]+') // distinguish the Chinese charactors and letters
str.split('').forEach((letter, i) => {
if (currentWidth > maxWidth) return
if (pattern.test(letter)) {
// Chinese charactors
currentWidth += fontSize
}
if (currentWidth > maxWidth) {
res = `${str.substr(0, i)}\n${str.substr(i)}`
}
})
return res
}