Home>Article>Web Front-end> WeChat applet-canvas generates images and saves them locally
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 withcanvas
to generate a custom picture and save it locally.
Code
wxml file
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
drawImagemethod of##canvas
only supports local images and does not support network images, so I used the
getImageInfomethod to transfer both the avatar and background images. one time.
userInfois 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.
demodoes 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!