canvas绘图文字换行,第一行文字少计算一个字宽度
/** * 绘制多行文本 * [@param](/user/param) ctx canvas对象 * [@param](/user/param) str 文本 * [@param](/user/param) leftWidth 距离左侧的距离 * [@param](/user/param) initHeight 距离顶部的距离 * [@param](/user/param) titleHeight 文本行高 * [@param](/user/param) canvasWidth 文本区宽度 * [@returns](/user/returns) {*} */ 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; } if (i == str.length - 1) { //绘制剩余部分 ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight); } } }, onLoad: function (options) { const ctx = wx.createCanvasContext('scene'); const canvasWidth = 300; const canvasHeight = 400; const bgColor= '#577C8A'; //开始绘制背景区 ctx.setFillStyle(bgColor) ctx.fillRect(0, 0, canvasWidth, canvasHeight) //开始绘制文字区 ctx.setFontSize(18); ctx.setFillStyle('#fff'); let str = '哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈'; this.drawText(ctx, str, 50, 200, 22, 200);// 调用行文本换行函数 ctx.draw()}, |
用canvas做文本换行的时候 第一行的长度总是少了一个字的宽度呢?
