本文摘自PHP中文网,作者hzc,侵删。
前言
需求场景:我们知道,微信小程序可以分享给好友或者微信群,不能分享到朋友圈,那分享到朋友圈就需要特殊处理一下,这里我们把小程序和canvas
结合起来使用,生成自定义图片并保存到本地。
代码
1 2 3 4 | <view>
<button type= "default" size= "defaultSize" bindtap= "exportImg" >生成图片</button>
</view>
<canvas canvas-id= "myCanvas" ></canvas>
|
通过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);
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,
success: (res) => {
console.log(res)
},
fail: (err) => {}
})
|
简单的效果图

阅读剩余部分
相关阅读 >>
微信小程序 小程序直播-接入说明
微信小程序 运行时性能
微信小程序api 文件-获取本地文件信息
canvas 学习 3---画坐标系
如何使用html5 canvas绘制线条
微信小程序地图 map
微信小程序api 网络
sdk数据库 database
微信小程序api color(绘图颜色)
sdk数据库 command聚合操作符字符串操作符
更多相关阅读请进入《canvas》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » 微信小程序-canvas生成图片并保存到本地