Home>Article>Web Front-end> WeChat applet-canvas generates images and saves them locally

WeChat applet-canvas generates images and saves them locally

hzc
hzc forward
2020-06-13 10:14:32 3058browse

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 withcanvasto 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


WeChat applet-canvas generates images and saves them locally

Summary# The

drawImage

method of##canvasonly supports local images and does not support network images, so I used thegetImageInfomethod to transfer both the avatar and background images. one time.

The avatar obtained through

userInfois square, not the circle required. Theclip()method is used here and needs to be coordinated withsave()andrestore(), because if it is not restored after cropping, the next drawing will be in that small area.

This

demodoes not use the API for generating QR codes. Friends who are interested can try it out.Here is the link

Recommended tutorial: "

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!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete