Home > Web Front-end > JS Tutorial > body text

WeChat applet-canvas generates images and saves them locally

hzc
Release: 2020-06-13 17:37:55
forward
3165 people have browsed it

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>
Copy after login
  • 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()
Copy after login

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);
    }
})
Copy after login

Save the image to local through wx.saveImageToPhotosAlbum

wx.saveImageToPhotosAlbum({
    filePath: tempFilePath,//canvasToTempFilePath返回的tempFilePath
    success: (res) => {
        console.log(res)
    },
    fail: (err) => {}
})
Copy after login

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!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template