微信小程序-canvas生成图片并保存到本地


本文摘自PHP中文网,作者hzc,侵删。

前言


需求场景:我们知道,微信小程序可以分享给好友或者微信群,不能分享到朋友圈,那分享到朋友圈就需要特殊处理一下,这里我们把小程序和canvas结合起来使用,生成自定义图片并保存到本地。

代码


  • wxml文件

1

2

3

4

<view>

    <button type="default" size="defaultSize" bindtap="exportImg">生成图片</button>

</view>

<canvas canvas-id="myCanvas"></canvas>

  • js文件

通过canvasAPI绘制

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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()

通过wx.canvasToTempFilePath获取本地路径

1

2

3

4

5

6

7

8

9

10

wx.canvasToTempFilePath({

    x: 0,

    y: 0,

    width: 300,

    height: 500,

    canvasId: 'myCanvas',

    success: function (res) {

        console.log(res.tempFilePath);

    }

})

通过wx.saveImageToPhotosAlbum保存图片到本地

1

2

3

4

5

6

7

wx.saveImageToPhotosAlbum({

    filePath: tempFilePath,//canvasToTempFilePath返回的tempFilePath

    success: (res) => {

        console.log(res)

    },

    fail: (err) => {}

})

简单的效果图


Snipaste_2020-06-13_10-08-40.png

阅读剩余部分

相关阅读 >>

微信小程序api 模板消息

如何使用html5 canvas绘制文字的轮廓

微信小程序api nfc-nfcf标签

微信小程序云开发api 删除一条记录

html5 canvas常用属性方法(介绍)

微信小程序视图容器 cover-view

分享一个用canvas合成海报图片的移动端项目

微信小程序api nfc-nfcv标签

微信小程序云开发api 指定查询排序条件

微信小程序 数据类型

更多相关阅读请进入《canvas》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...