第一种不加限制
/**
* 绘制多行文本
* ctx canvas对象
* str 文本
* leftWidth 距离左侧的距离
* initHeight 距离顶部的距离
* titleHeight 文本的高度
* canvasWidth 文本的宽度
* @returns {*}
*/
drawText (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
let lineWidth = 0;
let lastSubStrIndex = 0; //每次开始截取的字符串的索引
for (let i = 0; i < str.length; i++) {
lineWidth += ctx.measureText(str[i]).width;
if (lineWidth > canvasWidth) {
ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
initHeight += 22; //22为 文字大小20 + 2
lineWidth = 0;
lastSubStrIndex = i;
titleHeight += 22;
}
if (i == str.length - 1) { //绘制剩余部分
ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
}
}
// 标题border-bottom 线距顶部距离
titleHeight = titleHeight + 10;
return titleHeight;
},
第二种加限制
//字体换行,可以限制换行条数
/**
ctx: 画布的上下文环境
content: 需要绘制的文本内容
drawX: 绘制文本的x坐标
drawY: 绘制文本的y坐标
lineHeight:文本之间的行高
lineMaxWidth:每行文本的最大宽度
lineNum:最多绘制的行数
*/
textPrewrap(ctx, content, drawX, drawY, lineHeight, lineMaxWidth, lineNum) {
var drawTxt = ''; // 当前绘制的内容
var drawLine = 1; // 第几行开始绘制
var drawIndex = 0; // 当前绘制内容的索引
// 判断内容是否可以一行绘制完毕
if (ctx.measureText(content).width <= lineMaxWidth) {
ctx.fillText(content.substring(drawIndex, i), drawX, drawY);
} else {
for (var i = 0; i < content.length; i++) {
drawTxt += content[i];
if (ctx.measureText(drawTxt).width >= lineMaxWidth) {
if (drawLine >= lineNum) {
ctx.fillText(content.substring(drawIndex, i) + '..', drawX, drawY);
break;
} else {
ctx.fillText(content.substring(drawIndex, i + 1), drawX, drawY);
drawIndex = i + 1;
drawLine += 1;
drawY += lineHeight;
drawTxt = '';
}
} else {
// 内容绘制完毕,但是剩下的内容宽度不到lineMaxWidth
if (i === content.length - 1) {
ctx.fillText(content.substring(drawIndex), drawX, drawY);
}
}
}
}
},