小程式的二維碼生成並且長按儲存到手機
wxml部分
wxss部分
.container {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
}
.container image {
width: 686rpx;
height: 686rpx;
background-color: #f9f9f9;
}
.canvas-box {
position: fixed;
top: 999999rpx;
left: 0;
}
js部分(qr地址下載地址:https://github.com/demi520/wxapp-qrcode/blob/master/utils/qrcode.js )
var QR = require("…/…/js/qrcode.js");
Page({
/**
- 頁面的初始資料
*/
data: {
timestart:0, //長按開始
timeend:0, //長按結束
canvasHidden: false, //canvas顯示
imagePath: ‘’, //圖片路徑
},
/**
- 生命週期函式–監聽頁面載入
*/
onLoad: function (options) {
//option為上個頁面傳遞過來的引數
var jiaoyanCode = ‘9123546’;
// if (options) {
// jiaoyanCode = options.jiaoyanCode;
// }
console.log(jiaoyanCode);
var size = this.setCanvasSize(); //動態設定畫布大小
this.createQrCode(jiaoyanCode, "mycanvas", size.w, size.h);
},
//適配不同螢幕大小的canvas
setCanvasSize: function () {
var size = {};
try {
var res = wx.getSystemInfoSync();
var scale = 750 / 686; //不同螢幕下canvas的適配比例;設計稿是750寬 686是因為樣式wxss檔案中設定的大小
var width = res.windowWidth / scale;
var height = width; //canvas畫布為正方形
size.w = width;
size.h = height;
} catch (e) {
// Do something when catch error
console.log(“獲取裝置資訊失敗” + e);
}
return size;
},
/**
- 繪製二維碼圖片
*/
createQrCode: function (url, canvasId, cavW, cavH) {
//呼叫外掛中的draw方法,繪製二維碼圖片
QR.api.draw(url, canvasId, cavW, cavH);
setTimeout(() => {
this.canvasToTempImage();
}, 1000);
},
/**
- 獲取臨時快取照片路徑,存入data中
*/
canvasToTempImage: function () {
var that = this;
//把當前畫布指定區域的內容匯出生成指定大小的圖片,並返回檔案路徑。
wx.canvasToTempFilePath({
canvasId: ‘mycanvas’,
success: function (res) {
console.log(res,“dadas”)
var tempFilePath = res.tempFilePath;
console.log(tempFilePath);
that.setData({
imagePath: tempFilePath,
// canvasHidden:true
});
},
fail: function (res) {
console.log(res);
}
});
},
/**
- 點選圖片進行預覽
*/
previewImg: function (e) {
var img = this.data.imagePath;
console.log(img);
wx.previewImage({
current: img, // 當前顯示圖片的http連結
urls: [img] // 需要預覽的圖片http連結列表
});
},
//點選開始時的時間
timestart: function (e) {
var _this = this;
_this.setData({ timestart: e.timeStamp });
},
//點選結束的時間
timeend: function (e) {
var _this = this;
_this.setData({ timeend: e.timeStamp });
},
bingLongClick() {//長按事件 儲存二維碼
var _this = this;
var times = _this.data.timeend - _this.data.timestart;
if (times > 300) {
wx.saveImageToPhotosAlbum({
filePath: _this.data.imagePath,//返回的臨時檔案路徑,下載後的檔案會儲存到一個臨時檔案
success: function (res) {
wx.showToast({
title: ‘儲存成功’,
})
},
fail(res){
wx.showToast({
title: ‘儲存失敗請截圖’,
})
}
})
}
}
})