Preface
Demand scenario: We know that WeChat applet can be shared with friends or WeChat groups, but cannot be shared with Moments, so sharing with Moments requires special Let’s deal with it. Here we combine the applet with canvas
to generate a custom picture and save it locally.
Code
wxml file
<view> <button type="default" size="defaultSize" bindtap="exportImg">生成图片</button> </view> <canvas canvas-id="myCanvas"></canvas>
js File
Drawing through canvasAPI
const ctx = wx.createCanvasContext('myCanvas'); //绘制背景图 ctx.drawImage(res.path, 0, 0, screenWidth, 500); //绘制背景图上层的头像 ctx.save(); ctx.arc(100, 100, 30, 0, 2 * Math.PI); ctx.clip(); ctx.drawImage(avatarUrl, 50, 50, 110, 110);//根据微信getUserInfo接口获取到用户头像 ctx.restore(); //绘制文字 ctx.setTextAlign('center') ctx.setFillStyle('#fff') ctx.setFontSize(16) ctx.fillText(userInfo.nickName, 100, 180)//用户昵称 ctx.stroke() ctx.draw()
Get the local path through wx.canvasToTempFilePath
wx.canvasToTempFilePath({ x: 0, y: 0, width: 300, height: 500, canvasId: 'myCanvas', success: function (res) { console.log(res.tempFilePath); } })
Save the image to local through wx.saveImageToPhotosAlbum
wx.saveImageToPhotosAlbum({ filePath: tempFilePath,//canvasToTempFilePath返回的tempFilePath success: (res) => { console.log(res) }, fail: (err) => {} })
Simple rendering
Summary# The
drawImage method of ##canvas
only supports local images and does not support network images, so I used the
getImageInfo method to transfer both the avatar and background images. one time.
userInfo is square, not the circle required. The
clip() method is used here and needs to be coordinated with
save() and
restore(), because if it is not restored after cropping, the next drawing will be in that small area.
demo does not use the API for generating QR codes. Friends who are interested can try it out.
Here is the link
JS Tutorial"
The above is the detailed content of WeChat applet-canvas generates images and saves them locally. For more information, please follow other related articles on the PHP Chinese website!