@alicloud/cloud-charts
Version:

93 lines (73 loc) • 2.31 kB
JavaScript
/**
* 计算省略后的文本
* @param text 原文本
* @param maxWidth 最大宽度
* @param font 字体样式
* @param ellipsisText 省略文本
* @param ellipsisType 省略方式,头/中间/尾
*/
export default function ellipsisLabel(text, maxWidth, font, ellipsisText, ellipsisType) {
if (ellipsisText === void 0) {
ellipsisText = '...';
}
if (ellipsisType === void 0) {
ellipsisType = 'tail';
}
var str = typeof text !== 'string' ? text.toString() : text;
var PLACEHOLDER_WIDTH = calcTextWidth(ellipsisText, font);
if (PLACEHOLDER_WIDTH >= maxWidth) {
return ellipsisText;
}
if (calcTextWidth(str, font) <= maxWidth) {
return text;
}
var leftWidth = maxWidth - PLACEHOLDER_WIDTH;
var length = str.length;
if (ellipsisType === 'tail') {
var leftStr = '';
for (var index = 1; index <= length; index++) {
var currentStr = str.slice(0, index);
if (calcTextWidth(currentStr, font) >= leftWidth) {
break;
}
leftStr = currentStr;
}
return "" + leftStr + ellipsisText;
} else if (ellipsisType === 'head') {
var _leftStr = '';
for (var _index = length - 1; _index >= 0; _index--) {
var _currentStr = str.slice(_index, length);
if (calcTextWidth(_currentStr, font) >= leftWidth) {
break;
}
_leftStr = _currentStr;
}
return "" + ellipsisText + _leftStr;
} else {
var left = '';
var right = '';
for (var _index2 = 1; _index2 < Math.floor(length / 2); _index2++) {
var currentLeft = str.slice(0, _index2);
var currentRight = str.slice(length - _index2, length);
if (calcTextWidth("" + currentLeft + currentRight, font) >= leftWidth) {
break;
}
left = currentLeft;
right = currentRight;
}
return "" + left + ellipsisText + right;
}
}
var ctx = null;
export function calcTextWidth(text, font) {
var fontSize = font.fontSize,
fontFamily = font.fontFamily,
fontWeight = font.fontWeight,
fontStyle = font.fontStyle,
fontVariant = font.fontVariant;
if (!ctx) {
ctx = document.createElement('canvas').getContext('2d');
}
ctx.font = [fontStyle, fontVariant, fontWeight, fontSize + "px", fontFamily].join(' ');
return ctx.measureText(text).width;
}