微信小程序 canvas 文字自动换行

Page({

    drawCanvas: function(ctx) {// 地址
        ctx.setFontSize(14)
        ctx.setFillStyle('#9E7240')
        ctx.textAlign="center";
        const txHash = this.data.info.txHash ? this.data.info.txHash : '暂无信息'
        this.drawText(ctx,txHash,187, 517 , 232,232) // 自动换行
       
        ctx.draw()
        ctx.save()
    },// 文本自动换行
    drawText: function(ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
        var lineWidth = 0;
        var 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 += 16; //16为字体的高度
                lineWidth = 0;
                lastSubStrIndex = i;
                titleHeight += 30;
            }
            if (i == str.length - 1) { //绘制剩余部分
                ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
            }
        }
        // 标题border-bottom 线距顶部距离
        titleHeight = titleHeight + 10;
        return titleHeight
    },

    
})

猜你喜欢

转载自www.cnblogs.com/cynthia-wuqian/p/10286493.html