微信小程序/uniapp使用canvas绘制文本结构生成图片

结构

宽高为自定义内容

<canvas canvas-id="html2Img" :style="'height:'+ height +'px;width:'+ width +'px'"></canvas>

~~~

 data(){
        return{
            secondValue:10,
            gonext:false,
            canvasHidden:true,
            width:375,
            height:90,
            x:0,
            y:0,
            textStr:'测试文本内容协议内容,相关协议测试文本内容;相关测试文本内容。测试文本内容11协议内容,相关协议测试文本内容;相关测试文本内容。'
        }
    },

js

主流程

 let that = this;
const ctx = uni.createCanvasContext('html2Img');
// 设置背景
this.height = this.getHeight(this.textStr);
ctx.setFillStyle('#ffffff');
ctx.fillRect(0, 0, this.width, this.height);
// 填充文字
ctx.setFillStyle('#000000');
ctx.setFontSize(18);
ctx.setTextAlign('center')
ctx.fillText('标题内容', 187, 30);

ctx.setFontSize(16);
this.drawLongText(ctx,this.textStr);
ctx.draw(false, () => {
uni.canvasToTempFilePath({
    x: 0,
    y: 0,
    canvasId: 'html2Img',
    quality: 1,
    success: (res) => {
        let base64 = 'data:image/jpeg;base64,' + uni.getFileSystemManager().readFileSync(res.tempFilePath, 'base64');
        console.log(base64);
    },
    fail:(err)=>{
        console.log(err)
    }
}, this)
});

单独封装的换行绘制问题

		drawLongText(ctx,str){
            let x = 25;
            let y = 50;
            var lastSubStrIndex = 0; //每次开始截取的字符串的索引
            for (let i = 0; i < str.length; i++) {
                
                if (x > 350) {
                    y += 20; //30为字体的高度
                    x = 25;
                    ctx.fillText(str.substring(lastSubStrIndex, i), x, y); //绘制截取部分
                }else{
                    ctx.fillText(str.substring(lastSubStrIndex, i), x, y); 
                }
                x += ctx.measureText(str[i]).width;
                if(i == str.length -1){
                    console.log(lastSubStrIndex + ':' + i)
                   ctx.fillText(str.substring(lastSubStrIndex+1, i+1), x, y);  
                }
                lastSubStrIndex = i;
                
            }

        
        },

动态设置height高度方法

		getHeight(str){
            let x = 25;
            let y = 60;
            for (let i = 0; i < str.length; i++) {
                if (x < 350) {
                    x += 16;
                }else{
                    x = 25;
                    y += 20;
                }
            }
            y += 30;
            return y;
        }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值