版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013305783/article/details/82717723
一、保存图片
微信小程序中使用得比较多的就是分享功能,基本上都会用到,尤其是对二维码图片,保存在本地或者将小程序分享给朋友,好在微信小程序提供的api中已经告诉了该怎么使用,下面就将所用到的分享出来。
首先是通过请求后端接口获取图片地址,当然也可以不用请求直接将地址写死。
wx.request({
url: getApp().data.serviceUrl +'/wechat/searchdata/proqrcode',//请求地址
data: {//发送给后台的数据
openid: that.data.openid
},
header: {//请求头
"Content-Type": "application/json;charset=UTF-8;"
},
method: "POST",//get为默认方法/POST
success: function (res) {
var imageurl = res.data.content
that.setData({
shareImgSrc: getApp().data.qrServiceUrl + imageurl
})
wx.getImageInfo({
src: that.data.shareImgSrc,//服务器返回的带参数的小程序码地址
success: function (res) {
//res.path是网络图片的本地地址
var qrCodePath = res.path;
//2. canvas绘制文字和图片
const ctx = wx.createCanvasContext('myCanvas');
// var imgPath = that.data.localImageUrl;
ctx.drawImage(qrCodePath, 0, 0, 200, 200);
ctx.setFillStyle('white')
ctx.fillRect(0, 520, 600, 280);
ctx.draw()
// that.setData({
// localImageUrl: qrCodePath
// })
},
fail: function (res) {
//失败回调
}
});
},
fail: function (err) { },//请求失败
})
经过上面一步已经图片展示出来了,接下来是将图片保存下来。这里通过按钮点击实现:
savedate: function (e) {
var that = this;
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: 200,
height: 200,
destWidth: 400,
destHeight: 400,
canvasId: 'myCanvas',
success: function (res) {
that.setData({
saveImgSrc: res.tempFilePath
})
},
fail: function (res) {
console.log(res)
}
})
//4. 将图片保存到相册
wx.saveImageToPhotosAlbum({
filePath: that.data.saveImgSrc,
success(res) {
wx.showModal({
title: '存图成功',
content: '图片成功保存到相册了,去发圈噻~',
showCancel: false,
confirmText: '好哒',
confirmColor: '#72B9C3',
success: function (res) {
if (res.confirm) {
console.log('用户点击确定');
}
// that.hideShareImg()
}
})
}
})
},
二、分享小程序
分享小程序需要在button中设置open-type,如下
<button class='sendfriend' bindtap = 'sendfriend' open-type="share">发送给微信好友</button>
通过onShareAppMessage方法实现发送给好友:
onShareAppMessage: function (ops) {
if (ops.from === 'button') {
// 来自页面内转发按钮
console.log(ops.target)
}
var that = this
return {
title: '分享给好友',
path: 'pages/index/index?scene='+that.data.openid,//点击分享消息是打开的页面
imageUrl: that.data.saveImgSrc,
success: function (res) {
// 转发成功
console.log("转发成功:" + JSON.stringify(res));
var shareTickets = res.shareTickets;
},
fail: function (res) {
// 转发失败
console.log("转发失败:" + JSON.stringify(res));
}
}
},