代码如下
canvasTextAutoLine: function (ctx, initX, initY, lineHeight, str, canvasWidth) {
var lineWidth = 0;
var lastSubStrIndex = 0;
var linenum = 0;
for (let i = 0; i < str.length; i++) {
lineWidth += ctx.measureText(str[i]).width;
if (lineWidth > canvasWidth - initX*2) { //减去initX,防止边界出现的问题
ctx.fillText(str.substring(lastSubStrIndex, i), initX, initY);
initY += lineHeight;
lineWidth = 0;
lastSubStrIndex = i;
if(linenum>1){
break;
}else{
++linenum;
}
}
if (i == str.length - 1) {
ctx.fillText(str.substring(lastSubStrIndex, i + 1), initX, initY);
}
}
},
试试 image 组件的 mode 属性。
https://developers.weixin.qq.com/miniprogram/dev/component/image.html