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

WeChat applet-canvas generates images and saves them locally

hzc
hzcforward
2020-06-13 10:14:323155browse

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(&#39;myCanvas&#39;);
//绘制背景图
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(&#39;center&#39;)
ctx.setFillStyle(&#39;#fff&#39;)
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: &#39;myCanvas&#39;,
    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 ##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.

The avatar obtained through

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.

This

demo does 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