/**
*
* @param ctx 2d上下文对象
* @param text 绘制文本
* @param x 坐标轴x位置
* @param y 坐标轴y位置
* @param options 包含 maxWidth 最大宽度,lineHeight 文字行高,row 限制行数,textIndent 首行缩进,fontSize 文字大小
*/
function textEllipsis(ctx, text, x, y, options) {
if (typeof text !== 'string' || typeof x !== 'number' || typeof y !== 'number') {
return;
}
let defaultOpt = {
maxWidth: 100,
lineHeight: 14,
row: 1000,
textIndent: 0,
fontSize: 14
};
let params = Object.assign({}, defaultOpt, options);
// 分割文本
let textArr = text.split('');
// 文本最终占据高度
let textHeight = 0;
// 每行显示的文字
let textOfLine = '';
// 控制行数
let limitRow = params.row;
let rowCount = 0;
// 循环分割的文字数组
for (let i = 0; i < textArr.length; i++) {
// 获取单个文字或字符
let singleWord = textArr[i];
// 连接文字
let connectText = textOfLine + singleWord;
// 计算接下来要写的是否是最后一行
let isLimitRow = limitRow ? rowCount === (limitRow - 1) : false;
// 最后一行则显示省略符,否则显示连接文字
let measureText = isLimitRow ? (connectText + '...') : connectText;
// 设置字体并计算宽度,判断是否存在首行缩进
ctx.font = `${params.fontSize}px "MicroSoft YaHei"`;
let width = ctx.measureText(measureText).width;
// 首行需要缩进满足条件
let conditionIndent = (params.textIndent && rowCount === 0);
let measureWidth = conditionIndent ? (width + params.textIndent) : width;
// 大于限制宽度且已绘行数不是最后一行,则写文字
if (measureWidth > params.maxWidth && i > 0 && rowCount !== limitRow) {
// 如果是最后一行,显示计算文本
let canvasText = isLimitRow ? measureText : textOfLine;
let xPos = conditionIndent ? (x + params.textIndent) : x;
// 写文字
ctx.fillStyle = '#000';
ctx.fillText(canvasText, xPos, y);
// 下一行文字
textOfLine = singleWord;
// 记录下一行位置
y += params.lineHeight;
// 计算文本高度
textHeight += params.lineHeight;
rowCount++;
if (isLimitRow) {
break;
}
} else {
// 不大于最大宽度
textOfLine = connectText;
}
}
if (rowCount !== limitRow) {
let xPos = (params.textIndent && rowCount === 0) ? (x + params.textIndent) : x;
ctx.fillStyle = '#000';
ctx.fillText(textOfLine, xPos, y);
}
// 计算文字总高度
let textHeightVal = rowCount < limitRow ? (textHeight + params.lineHeight) : textHeight;
return textHeightVal;
}
结果