this.drawText(canvas ,文字,左边距离,距离高度,行高,文字最大宽度)
drawText: function(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 += titleHeight;
lineWidth = 0;
lastSubStrIndex = i;
i -= 1
}
if (i == str.length - 1) { //绘制剩余部分
ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
}
}
},
小程序 canvas 文字换行
最新推荐文章于 2024-08-11 23:28:33 发布