preface

Requirement scenario: As we know, wechat applets can be shared with friends or wechat groups, but not with moments of friends, so sharing in moments of friends requires special treatment. Here, we combine the applets with canvas to generate customized pictures and save them locally.

code

  • WXML file
<view> <button type="default" size="defaultSize" bindtap="exportImg"> generate images </button> </view> <canvas canvas-id="myCanvas"></canvas>Copy the code
  • Js file

Draw through the canvasAPI

const ctx = wx.createCanvasContext('myCanvas'); 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); Ctx.restore (); ctx.restore(); Ctx.settextalign ('center') ctx.setFillstyle ('# FFF ') ctx.setfontSize (16) ctx.filltext (userinfo.nickname, 100, 180)// User nickname ctx.stroke() ctx.draw()Copy the code

Obtain the local path by wx.canvastotempFilepath

wx.canvasToTempFilePath({ x: 0, y: 0, width: 300, height: 500, canvasId: 'myCanvas', success: function (res) { console.log(res.tempFilePath); }})Copy the code

Through the wx. SaveImageToPhotosAlbum save image to the local

Wx. SaveImageToPhotosAlbum ({filePath: tempFilePath, / / canvasToTempFilePath returned tempFilePath success: (res) => { console.log(res) }, fail: (err) => {} })Copy the code

Simple renderings

conclusion

  1. canvasthedrawImageThe method only supports local images, not network images, so I use both profile and background imagesgetImageInfoThis method has been rotated.
  2. The avatar obtained by userInfo is square, not round as required, as used hereclip()Method, need to cooperatesave()andrestore()“, because after clipping, if not restored, the next drawing will be in that small area.
  3. This demo does not use the GENERATION of TWO-DIMENSIONAL code API, interested friends can do it. Here is the link

Reference documentation

Micro channel applets generated photo sharing

Canvas implements round frame images

Official documents of wechat applets