微信小程序分享图片二维码生成
<canvas canvas-id="shareImg" style="width:100%;height:{{height}}px"></canvas>
<button wx:if="{{is_show}}" class='share_quan' bindtap='share_quan'
style="background: #f56e6b;color:#fff;position: fixed;bottom: 0;width:100%;z-index:9999;height:45px;line-height: 45px;">分享朋友圈</button>
const app = getApp()
Page({
data: {
imgs: '',
code: '',
userInfo: {},
height: 100,
width: 100,
is_show: false,
siteInfo: '',
},
getUserDetail: function () {
let _this = this;
wx.showLoading({
title: '海报生成中',
})
_this.GetCode();
},
GetCode: function () {
let _this = this;
var user_id = app.getUserId();
if (!user_id) {
wx.hideLoading()
wx.showModal({
title: '温馨提示:',
content: '返回首页点击 领取按钮 获取用户信息授权',
showCancel: false,
confirmText: '关闭提示',
success(res) {
wx.navigateBack();
}
})
return false
}
wx.request({
url: app.globalData.hostName + '/qrcode',
data: {
user_id: user_id
},
method: 'POST',
header: {
'content-type': 'application/json'
},
success(res) {
if (res.data.status == 0) {
_this.setData({
code: res.data.msg
})
_this.CodeImage()
} else {}
}
})
},
CodeImage: function () {
var code = this.data.code
var height = wx.getSystemInfoSync().windowHeight
var width = wx.getSystemInfoSync().windowWidth
this.setData({
height: height - 45,
width: width
})
var that = this
wx.downloadFile({
url: app.globalData.location + 'mmkj.jpg',
success(res) {
if (res.statusCode === 200) {
that.setData({
imgs: res.tempFilePath
})
wx.downloadFile({
url: code,
success(res1) {
if (res1.statusCode === 200) {
that.setData({
code: res1.tempFilePath,
is_show: true
})
const ctx = wx.createCanvasContext('shareImg');
ctx.drawImage(that.data.imgs, 0, 0, width, height);
ctx.drawImage(that.data.code, width - (100 + width * 0.05), height - 150, 100, 120);
ctx.setTextAlign('center')
ctx.setFillStyle('black')
ctx.setFontSize(28)
ctx.setFillStyle('gray')
ctx.stroke()
ctx.draw()
}
wx.hideLoading()
}
})
}
}
})
},
onLoad: function (options) {
this.getUserDetail()
},
share_quan: function () {
var height = wx.getSystemInfoSync().windowHeight - 45
var width = wx.getSystemInfoSync().windowWidth
var that = this;
wx.showLoading({
title: '图片正在生成中...'
})
setTimeout(function () {
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: width,
height: height,
destWidth: width,
destHeight: height,
canvasId: 'shareImg',
fileType: 'jpg',
success: function (res) {
wx.hideLoading()
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success(res) {
wx.showModal({
content: '图片已保存到相册',
showCancel: false,
confirmText: '好的',
success: function (res) {
if (res.confirm) {
console.log('用户确定了');
that.setData({
hidden: true
})
}
}
})
},
})
},
fail: function () {
console.log("保存失败......")
}
})
},
2000)
},
})