前言
微信小程序提供了解析二维码的接口,可以直接调用解析二维码,但是小程序前端没有直接可以生成二维码的接口,需要借助服务端微信接口才能生成,这里借助weapp-qrcode实现功能。
最终效果
扫一扫在手机查看效果
代码
生成二维码
const QR = require('../../utils/weapp-qrcode.js')
Page({
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var that = this;
//url 为
var url = 'http://blog.zhangyuh.com'
var imgData = QR.drawImg(url, {
typeNumber: 4,
errorCorrectLevel: 'M',
size: 500
})
that.setData({
imgData:imgData
})
},
/**
* 保存图片至相册
*/
download () {
let that = this;
wx.showToast({
icon: 'loading',
title: '正在保存图片',
duration: 1000
})
//获取相册权限
wx.getSetting({
success (res) {
if (!res.authSetting['scope.writePhotosAlbum']) {
wx.authorize({
scope: 'scope.writePhotosAlbum',
success () {
that.savePhoto();
},
fail () {
wx.openSetting({
success () {
wx.authorize({
scope: 'scope.writePhotosAlbum',
success() {
that.savePhoto();
}
})
}
})
}
})
} else {
that.savePhoto();
}
}
})
},
/**
* 保存图片
*/
savePhoto() {
//把数据前面无法写入的信息去掉
var imageData = this.data.imgData.slice(22);
var save = wx.getFileSystemManager();
var number = Math.random();
save.writeFile({
filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.png',
data: imageData,
encoding: 'base64',
success: res => {
wx.saveImageToPhotosAlbum({
filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.png',
success: function (res) {
wx.showToast({
title: '保存成功',
})
},
fail: function (err) {
console.log(err)
}
})
console.log(res)
}, fail: err => {
console.log(err)
}
})
},
})
解析二维码
scan:function(){
var that = this;
wx.scanCode({
success (res) {
console.log(res);
var result = res.result;
wx.showModal({
title: '解析结果',
content: result,
confirmText:'复制',
cancelText:'重新生成',
success (res) {
if (res.confirm) {
wx.setClipboardData({ data: result, });
} else if (res.cancel) {
that.setData({
url:result
})
}
}
})
}
})
},