/**
* canvas文本换行
* @param {*} ctx canvas对象
* @param {*} str 绘制的文本
* @param {*} leftWidth 距离左侧的距离
* @param {*} initHeight 距离顶部的距离
* @param {*} canvasWidth 文本的宽度
* @returns
*/
_drawText(ctx, str, leftWidth, initHeight, canvasWidth) {
var chr = str.split("");//这个方法是将一个字符串分割成字符串数组
var temp = "";
var row = [];
for (var a = 0; a < chr.length; a++) {
if (ctx.measureText(temp).width < canvasWidth) {
temp += chr[a];
}
else {
a--; //这里添加了a-- 是为了防止字符丢失,效果图中有对比
row.push(temp);
temp = "";
}
}
row.push(temp);
//如果数组长度大于2 则截取前两个
if (row.length > 2) {
var rowCut = row.slice(0, 2);
var rowPart = rowCut[1];
var test = "";
var empty = [];
for (var a = 0; a < rowPart.length; a++) {
if (ctx.measureText(test).width < canvasWidth) {
test += rowPart[a];
}
else {
break;
}
}
empty.push(test);
var group = empty[0] + "..."//这里只显示两行,超出的用...表示
rowCut.splice(1, 1, group);
row = rowCut;
}
for (var b = 0; b < row.length; b++) {
ctx.fillText(row[b], leftWidth, initHeight + b * 40, canvasWidth);
}
},