Small program canvas text wrap to generate pictures

1. Picture transparency and rotation

let ctx = wx.createCanvasContext('shareImg')
ctx.drawImage('../../../' + res[0].path, 0, 0, w, h)
ctx.save()
ctx.globalAlpha = 0.2
ctx.rotate(-15*Math.PI/180)

Second, the font is bold

let text = '这是加粗的文本'
ctx.fillText(text, 194, 378 + 0.5)
ctx.fillText(text, 194 + 0.5, 378)
ctx.fillText(text, 194 , 378)

3. Text wrapping

this.canvasTextAutoLine('这是换行的文本',ctx,85,467,60,560)
/*
canvas文字换行
str:要绘制的字符串
ctx:canvas对象
initX:绘制字符串起始x坐标
initY:绘制字符串起始y坐标
lineHeight:字行高,自己定义个值即可
canvasWidth:画布的宽度
*/
canvasTextAutoLine(str,ctx, initX, initY, lineHeight,canvasWidth) {
    const arrText = str.split('')//字符串分割为数组
    let currentText = ''// 当前字符串及宽度
    let currentWidth
    for (let letter of arrText) {
        currentText += letter
        currentWidth = ctx.measureText(currentText).width
        if (currentWidth > canvasWidth) {
            ctx.fillText(currentText, initX, initY)
            currentText = ''
            initY += lineHeight
        }
    }
    if (currentText) {
        ctx.fillText(currentText, initX, initY)
    }
},

Four, generate pictures

note:

  • Draw the local picture directly into the relative path: ctx.drawImage ('../../ images / xxx.png', x, y, w, h).
  • If the picture comes from the network, you must first configure the legal domain name of downloadFile on the domain name of the applet server, which must be the https protocol, otherwise it cannot be drawn on the real machine.
  • If the network image address is data requested asynchronously, you need to use wx.downloadFile () to download the image locally, and then draw the temporary local path using drawImage ():
wx.downloadFile({
    url: src,
    success: function (res) {
        if(res.tempFilePath) {
            ctx.drawImage(res.tempFilePath, x, y, w, h)
        }
    }
})
                        
  • If there are multiple network pictures, you also need to wait for all the pictures to load before drawing. Here you can use promise to achieve:
wx.showLoading({ title: '努力生成中...' })
//小程序本地路役图片
let promise1 = new Promise(function (resolve, reject) {
    wx.getImageInfo({
        src: '../../../images/bg1.png',
        success: function (res) {
            resolve(res)
        },
        fail: function (error) {
            reject(error)
        },
    })
});
//网络异步请求
let promise2 = new Promise(function (resolve, reject) {
    api.orderDetail().then(res => {
        if(res.code == 0) {
            resolve()
        }
    }).catch((error) => {
        reject(error)
    })
});
Promise.all([promise1,promise2]).then(result => {
    let ctx = wx.createCanvasContext('shareImg')
    ctx.drawImage('../../' + result[0].path, 0, 0, w, h)
    ctx.save()
    wx.downloadFile({
        url: result[1].pic,
        success: function (res) {
            console.log(res)
            if(res.tempFilePath) {
                ctx.drawImage(res.tempFilePath, 178, 790, 216, 216)

                ctx.stroke()
                //draw的第一个参数为false表示仅有一个画布
                //第二个参数一定要加定时器,不然会出现生成的图片黑白
                ctx.draw(false, setTimeout(() => {
                    wx.canvasToTempFilePath({
                        x: 0,
                        y: 0,
                        width: w,
                        height: h,
                        destWidth: w,
                        destHeight: h,
                        canvasId: 'shareImg',
                        success: function (res) {
                            _this.setData({ "finishCreateCanvas": true })
                        },
                        fail: function (res) {
                            _this.createCanvasFail()
                         },
                        complete: function (res) {
                            wx.hideLoading()
                        }
                    })
                }, 500))}
            }
        },fail: function (error) {
            //如果有图片数据请求失败,在这里做进一步的处理
            _this.createCanvasFail()
        },
    })
}).catch((error) => {
    //如果有图片数据请求失败,在这里做进一步的处理
    _this.createCanvasFail()
})

Fifth, generate pictures
Before generating pictures, you must ensure that the canvas has been drawn. For this, you can use the wx.canvasToTempFilePath () method to save it as a temporary picture path in the form of a timer. The code has been shown above.

//生产环境时 记得这里要加入获取相册授权的代码
wx.saveImageToPhotosAlbum({
    filePath: _this.data.prurl,
    success(res) {
        wx.showModal({
            content: '图片已保存到相册,赶紧晒一下吧~',
            showCancel: false,
            confirmText: '好哒',
            confirmColor: '#72B9C3',
            success: function (res) {
                if (res.confirm) {
                    console.log('用户点击确定');
                }
            }
        })
    }
})

Guess you like

Origin www.cnblogs.com/10manongit/p/12700419.html