思路:weapp-qrcode生成二维码,二维码转图片放到准备好的canvas中,再在canvas中添加想要的内容,最后把canvas转成图片并下载
<template>
<view class="home">
<view class="qr">
<view class="qr-title">种苗追溯</view>
<view class="qr-content">
<view class="qr-content-qrcode">
<canvas style="width: 150px; height: 150px; margin: 0 auto;position: absolute;top: -500px;" canvas-id="myQrcode"></canvas>
<canvas style="width: 180px; height: 270px; margin: 0 auto;" canvas-id="myBg" v-show="!needLongTapSaveImg"></canvas>
<image :src="tempFilePath" style="width: 180px; height: 270px; margin: 0 auto;" v-show="needLongTapSaveImg"></image>
</view>
</view>
<view class="qr-btn">
<div class="qr-btn-cancel" @click="back">取消</div>
<div class="qr-btn-download" @click="save">下载</div>
</view>
</view>
</view>
</template>
<script>
import drawQrcode from 'weapp-qrcode';
export default {
data() {
return {
info: {},
codeURL: '',
fileInfo:{}
};
},
onLoad(options) {
this.info = JSON.parse(decodeURIComponent(options.info));
console.log('info',this.info);
this.codeURL = this.info.url;
this.init();
},
methods: {
back() {
uni.navigateBack();
},
init() {
uni.showLoading({
title: '生成中',
mask: true
});
drawQrcode({
width: 150,
height: 150,
canvasId: 'myQrcode',
text: this.codeURL,
callback: e => {
setTimeout(()=>{
//这里不异步会导致真机下载的二维码不可用
this.showCode()
},1000)
}
});
},
showCode(){
//二维码转图片
uni.canvasToTempFilePath({
width: 150,
height: 150,
canvasId: 'myQrcode',
success: qrcodeTempRes => {
// 获取到单二维码的tempFilePath
// 将二维码的tempFilePath画到背景canvas上
uni.getSystemInfo({
success: systemRes => {
// 获取屏幕宽高 做居中用
//this.windowWidth = systemRes.windowWidth;
//this.windowHeight = systemRes.windowHeight;
let ctx = uni.createCanvasContext('myBg');
ctx.fillStyle = 'rgb(255,255,255)';
ctx.fillRect(0,0,180,270);
// 二维码
ctx.drawImage(qrcodeTempRes.tempFilePath, 15, 20, 150, 150); // 列表名 // 以下为二维码下方要求显示的文本内容
ctx.setTextAlign('left');
ctx.setFontSize(14);
ctx.setFillStyle('rgb(2,172,65)');
ctx.fillText(this.info.seedBatch, 10, 205);
ctx.setFillStyle('rgb(137,154,137)');
ctx.setFontSize(14);
ctx.fillText(`扫一扫查看种苗追溯`, 28, 230);
ctx.draw(true, () => {
uni.hideLoading()
setTimeout(() => {
// 获取到合并后的地址
uni.canvasToTempFilePath({
canvasId: 'myBg',
fileType: 'jpg',
success: res2 => {
this.tempFilePath = res2.tempFilePath;
//#ifdef H5
this.needLongTapSaveImg = true;
//#endif
console.log('res2',res2);
this.fileInfo = res2
}
});
});
});
}
});
}
})
},
save() {
uni.showLoading({
title: '保存中',
mask: true
});
uni.saveImageToPhotosAlbum({
filePath: this.fileInfo.tempFilePath,
success: function () {
wx.showToast({
title: '保存成功'
})
}
})
}
}
};
</script>