使用uni-app和weapp-qrcode.js 生成二维码并保存到本地相册

<template>
	<view class="model-view" :style="showModal">
		<view class="model-out-box">
			<view class="model-content">
				<canvas  canvas-id="myQrcode" style="margin: 20px;"></canvas>
			</view>
			<tui-button shape="circle" width="100px" margin="10rpx auto" @click="downloadEwm()">保存</tui-button>
		</view>
	</view>		
	

</template>

<script>
	import qrCode from '../../libs/weapp-qrcode.js'
	export default {
		data(){
			return{
				code: '',
				text: '',
				showModal: false,
				qrCodeURL: ''
			}
		},
		onLoad(options) {
			this.code = options.code
			this.text = options.codeName
			this.initQrCode()
			uni.showLoading({ title: '刷新中' })
		},
		methods:{
			initQrCode() {
				let stringText = 'code:'+this.code+';name:'+this.text
				let that = this
				//使用his.$nextTick是等待数据
				this.$nextTick(function(){
					setTimeout(() => {
						//myQrcode为canvas的   canvas-id="myQrcode"   值
						new qrCode('myQrcode', {
							//传入的生成参数
							text: stringText,
							//canvas 画布宽
							width: 160,
							//canvas 画布高
							height: 160,
							//分别为两种交替色
							colorDark: "#333333",
							colorLight: "#FFFFFF",
							//二维码可辨识度
							correctLevel: qrCode.CorrectLevel.H
						})
					},500);
				});
				setTimeout(function () {
					uni.hideLoading()
				}, 500)
			},
			//保存生成的二维码
			downloadEwm() {
				uni.canvasToTempFilePath({
					x:0,
					y:0,
					width:160,
					height:160,
					destWidth:160,
					destHeight:160,
					canvasId:'myQrcode',
					success: function(res){
						let data = res.tempFilePath
						console.log("dsfjk",res)
						uni.saveImageToPhotosAlbum({
							filePath: data,
							success: function(){
								uni.showToast({
									title: '保存成功',
									duration: 2000
								})
							},
							fail: function() {
								uni.showToast({
									title: "保存失败,请稍后重试",
									icon: "none"
								});
							}
						})
					}
				})
			}
		}
	}
	

</script>

<style>
	.model-view{
		position: fixed;
		top: 0;
		z-index: 1;
		width: 100%;
		height: 100%;
		display:flex;
		justify-content: center;
		background-color:rgba(0,0,0,0.4);
	}
	.model-out-box{
		width: 200px;
		height: 270px;
		margin-top: 45%;
		display:flex;
		flex-direction: column;
		justify-content: space-between;
		align-items: center;
	}
	.model-content{
		width: 200px;
		height: 200px;
		border-radius: 10rpx;
		background: #fff;
		display:flex;
		align-items: center;
		justify-content: center;
	}
	.wrong-img{
		width: 30px;
		height: 30px;
	}
	

</style>
posted on 2023-03-01 10:10  yunkuang  阅读(772)  评论(0)    收藏  举报