要实现的功能:
点击朋友圈按钮弹出分享图片:
点击保存分享图片保存到手机
实现代码:
1.分享按钮点击事件
/** * 分享 */ weixinShare:function(){ var that = this; console.log(111); share.canvasImg((res)=>{ console.log(222); that.setData({ imagePath: res.tempFilePath, bgShare:false, left:43 }); }); }
2.生成图片
/** * 绘制分享图片 */ canvasImg(callback){ //小程序二维码 let promise1 = new Promise(function (resolve, reject) { /* 获得要在画布上绘制的图片 */ wx.getImageInfo({ src: ‘/images/qrcode.png‘, success: function (res) { console.log(res) resolve(res); } }) }); //背景图像 let promise2 = new Promise(function (resolve, reject) { wx.getImageInfo({ src: ‘/images/bg1.png‘, success: function (res) { console.log(res) resolve(res); } }) }); //用户头像 let promise3 = new Promise(function (resolve, reject) { wx.getImageInfo({ src: ‘/images/logo.png‘, success: function (res) { console.log(res) resolve(res); } }) }); Promise.all( [promise1, promise2, promise3] ).then(res => { const ctx = wx.createCanvasContext(‘shareWeixin‘) ctx.setFillStyle(‘#FFFFFF‘); ctx.fillRect(0,0,500,600); ctx.drawImage(‘../../../‘ + res[0].path, 220, 321, 100, 100) ctx.drawImage(‘../../../‘ + res[1].path, 0, 0, 331, 252) ctx.drawImage(‘../../../‘ + res[2].path, 10, 275, 30, 30) // 绘制文字 位置自己计算 参数自己看文档 // ctx.setTextAlign(‘left‘) // 位置 ctx.setFillStyle(‘#000000‘) // 颜色 ctx.setFontSize(15); ctx.fillText(‘海贼王‘,54,300); ctx.setFontSize(22) // 字号 ctx.fillText(‘生活小记者‘, 10, 341)// 内容 不会自己换行 需手动换行 ctx.fillText(‘快来关注校园时讯‘, 10, 377) // 内容 ctx.setFillStyle(‘#ccc‘) ctx.setFontSize(15) ctx.fillText(‘长按识别扫码查看详情‘,10,410); /* 绘制 */ ctx.stroke() ctx.draw(true,setTimeout(function(){ wx.canvasToTempFilePath({ x: 0, y: 0, width: 600, height: 800, destWidth: 600, destHeight: 800, canvasId: ‘shareWeixin‘, success: function (res) { // wx.saveImageToPhotosAlbum({ // filePath: res.tempFilePath, // }) callback && callback(res) }, fail: function (res) { console.log(res) } }) },500)) }) }
3.保存到手机
// 保存到手机图片 saveToPhone:function(){ var that = this; // console.log(that.data.imagePath); // 保存到本地 wx.downloadFile({ url: that.data.imagePath, success: function (res) { tempFilePaths = res.tempFilePath wx.saveFile({ tempFilePath: tempFilePaths, success(res) { savedFilePath = res.savedFilePath // console.log(‘保存路径‘); // console.log(savedFilePath) // 保存到手机 wx.saveImageToPhotosAlbum({ filePath: savedFilePath, success(res) { console.log(res) wx.showToast({ title: ‘成功‘, icon: ‘success‘, duration: 2000 }) }, fail(res) { console.log(‘保存到手机失败‘); console.log(res) } }) } }) }, fail: function (res) { console.log(‘保存到本地失败‘); console.log(res) } }) }
5.前端代码
<!-- 分享图片 --><view class=‘bg-shade‘ hidden="{{bgShare}}"></view> <canvas style="width: 600rpx; height: 800rpx;left:{{left}}px;" canvas-id="shareWeixin" class=‘share-bg‘></canvas><view hidden=‘{{bgShare}}‘ class=‘preview‘> <image src=‘{{imagePath}}‘ class=‘shareImg‘></image> <button type=‘primary‘ size=‘default‘ bindtap=‘saveToPhone‘>保存分享图</button></view>
总结: