ctx.setFillStyle("#000");
ctx.setTextAlign('left'); //是否居中顯示,參考點畫布中線
ctx.font = 'normal bold 16px PingFang SC';
var title ='阿斯頓發斯蒂芬克拉斯 剪短發拉 阿斯頓發送到發送 到發送時間段開了房間愛上';
this.dealWords({
ctx: ctx,//畫布上下文
fontSize: 14,//字體大小
word: title,//需要處理的文字
maxWidth: 295 * rpx,//一行文字最大寬度
x: 20 * rpx,//文字在x軸要顯示的位置
y: 320* rpx,//文字在y軸要顯示的位置
maxLine: 2//文字最多顯示的行數
})
ctx.draw();
},
// 多行文本
dealWords: function (options) {
options.ctx.setFontSize(options.fontSize);//設置字體大小
var allRow = Math.ceil(options.ctx.measureText(options.word).width / options.maxWidth);//實際總共能分多少行
var count = allRow >= options.maxLine ? options.maxLine : allRow;//實際能分多少行與設置的最大顯示行數比,誰小就用誰做循環次數
var endPos = 0;//當前字符串的截斷點
for (var j = 0; j < count; j++) {
var nowStr = options.word.slice(endPos);//當前剩余的字符串
var rowWid = 0;//每一行當前寬度
if (options.ctx.measureText(nowStr).width > options.maxWidth) {//如果當前的字符串寬度大于最大寬度,然后開始截取
for (var m = 0; m < nowStr.length; m++) {
rowWid += options.ctx.measureText(nowStr[m]).width;//當前字符串總寬度
if (rowWid > options.maxWidth) {
if (j === options.maxLine - 1) { //如果是最后一行
options.ctx.fillText(nowStr.slice(0, m - 1) + '...', options.x, options.y + (j + 1) * 14); //(j+1)*18這是每一行的高度
} else {
options.ctx.fillText(nowStr.slice(0, m), options.x, options.y + (j + 1) * 14);
}
endPos += m;//下次截斷點
break;
}
}
} else {//如果當前的字符串寬度小于最大寬度就直接輸出
options.ctx.fillText(nowStr.slice(0), options.x, options.y + (j + 1) * 18);
}
}
},