uniapp 生成使用HTML2canvas生成二维码海报保存到手机相册

  1.  需求点击生成二维码海报(点击后跳转到qr海报页面)
  2. renderjs 调用 HTML2canvas
  3. 生成base64后转为临时路径,保存到手机相册
<template>
	<view class="poster">
		<!-- @click="html2canvas.create" -->
		<view ref="qrPoster" id="qrPoster" class="poster-image"
			:style="{'backgroundImage': 'url('+posterImageSrc+')	'}">
			<!-- <image :src="posterImageSrc" mode="widthFix" v-show="false" @load="html2canvas.create"></image> -->
			<image ref="qrImage" id="qrImage" :src="qrImageSrc" @load="html2canvas.create" mode="widthFix">
			</image>
			<!-- <image ref="qrImage" id="qrImage" :src="qrImageSrc" mode="widthFix"></image> -->
			<!-- <image v-if="imageUrl" :src="qrImageSrc" mode="widthFix"></image> -->
		</view>
		<!-- <canvas canvas-id="myCanvas" width="300" height="600"></canvas> -->
	</view>
</template>

<script>
	import html2canvas from 'html2canvas';
	import {
		navigation
	} from '@dcloudio/uni-app-plus';

	import {
		Log
	} from "@icon-park/vue";
	export default {
		data() {
			return {
				tempImagePath: "",
				imageUrl: '', // 图片的 URL
				posterImageSrc: "",
				qrImageSrc: "",
			}
		},
		onLoad({
			src
		}) {
			this.posterImageSrc = JSON.parse(src)
			this.getQr()
		},
		mounted() {
			// html2canvas(document.querySelector('.poster-image'), setup).then((canvas) => {
			// 	console.log(canvas, 'canvas');
			// 	document.body.appendChild(canvas); // 自动在下方显示绘制的canvas图片
			// });

			// this.creatImg()

			// this.exportPicture()

			// console.log(this.$refs.qrImage.$el);

			// this.$refs.qrImage.$el.onload = function() {
			// 	console.log('onload');
			// 	this.capturePage()
			// }
		},
		methods: {
			getQr() {
				this.$u.api.getQr().then(res => {
					console.log(res);
					this.qrImageSrc = res.data.ewmUrl
				})
			},
			toQrPoster() {
				uni.navigateTo({
					url: "/pages/sys/task/qrPoster?base64=" + JSON.stringify(this.base64)
				})
			},
			capturePage() {
				const targetElement = this.$refs.qrPoster.$el; // 需要生成图片的元素,此处表示当前页面的根元素
				console.log('capturePage');
				html2canvas(targetElement).then(canvas => {
					console.log('将 Canvas 转换为图片');
					// 将 Canvas 转换为图片
					// const dataUrl = canvas.toDataURL('image/png');
					const dataUrl = canvas.toDataURL();

					// 更新图片的 URL
					this.imageUrl = dataUrl;

					console.log(dataUrl, 'dataUrl');

					navigation.createDownload({
						mediaUri: dataUrl,
						title: 'imageName',
						description: 'Save image to gallery',
						mimeType: 'image/png',
						success: () => {
							uni.showToast({
								title: '图片保存成功',
								duration: 2000,
							});
						},
						fail: (err) => {
							uni.showToast({
								title: '图片保存失败',
								duration: 2000,
								icon: 'none',
							});
							console.error(err);
						},
					});
				});
			},
			onImageLoad() {
				this.creatImg()
			},
			// 生成图片
			creatImg() {
				html2canvas(document.getElementById('qrPoster'), {
					width: dom.offsetWidth, //设置canvas尺寸与所截图尺寸相同,防止白边
					height: dom.offsetHeight, //防止白边
					logging: true,
					useCORS: true,
					allowTaint: true,
					scale: window.devicePixelRatio,
					dpi: 300,
					scrollY: 0
				}).then((canvas) => {
					const link = canvas.toDataURL("image/jpg");
					console.log(link, 'link');
					this.exportPicture(link);
				});
			},
			// 导出图片
			exportPicture(link, name = "网络营系统二维码海报" + new Date().getTime()) {
				const file = document.createElement("a");
				file.style.display = "none";
				file.href = link;
				file.download = decodeURI(name);
				document.body.appendChild(file);
				file.click();
				document.body.removeChild(file);
			},
			renderFinish(opt) {
				uni.hideLoading()
				this.base64 = opt.path
				this.save()
			},
			showLoding() {
				this.isShowPoster = true
				uni.showLoading({
					title: '图片生成中'
				})
			},
			hideLoading() {
				uni.hideLoading()
			},
			// 保存图片
			save() {
				console.log('save');

				// uni.canvasToTempFilePath({
				// 	canvasId: "myCanvas",
				// 	success: (res) => {
				// 		this.tempFilePath = res.tempFilePath;
				// 		console.log('success', res);
				// 		uni.saveImageToPhotosAlbum({
				// 			filePath: res.tempFilePaths,
				// 			success: function() {
				// 				console.log('saveImageToPhotosAlbum success');
				// 			},
				// 			fail: (error) => {
				// 				console.log('转换为临时路径失败:', error);
				// 			}
				// 		});
				// 	},
				// 	fail: (error) => {
				// 		console.log('转换为临时路径失败:', error);
				// 	}
				// });

				// return

				let that = this;
				const bitmap = new plus.nativeObj.Bitmap("test")
				bitmap.loadBase64Data(this.base64, function() {
					const url = "_doc/" + new Date().getTime() + ".png"; // url为时间戳命名方式
					bitmap.save(url, {
						overwrite: true, // 是否覆盖
						// quality: 'quality' // 图片清晰度
					}, (i) => {
						uni.saveImageToPhotosAlbum({
							filePath: url,
							success: function() {
								// that.base64 = url
								// that.toQrPoster()
								uni.showToast({
									title: '图片保存成功',
									icon: 'none'
								})
								bitmap.clear()
							}
						});
					}, (e) => {
						console.log(e);
						uni.showToast({
							title: '图片保存失败',
							icon: 'none'
						})
						bitmap.clear()
					});
				}, (e) => {
					uni.showToast({
						title: '图片保存失败',
						icon: 'none'
					})
					bitmap.clear()
				})
			},
		}
	}
</script>
<script module="html2canvas" lang="renderjs">
	import html2canvas from 'html2canvas'
	export default {
		mounted() {
			// this.create()
		},
		methods: {
			create() {
				this.$ownerInstance.callMethod('showLoding', true) // this.$ownerInstance.callMethod用于两个script之间交流
				const timer = setTimeout(async () => {
					try {
						const dom = document.getElementById('qrPoster')
						const canvas = await html2canvas(dom, {
							width: dom.offsetWidth, //设置canvas尺寸与所截图尺寸相同,防止白边
							height: dom.offsetHeight, //防止白边
							logging: true,
							useCORS: true,
							allowTaint: true,
							scale: window.devicePixelRatio,
							dpi: 300,
							scrollY: 0
						})
						// const base64 = canvas.toDataURL('image/png');
						// canvas.setAttribute("canvas-id", 'myCanvas');
						// document.body.appendChild(canvas);
						// console.log('canvas:', canvas, base64)

						// const file = document.createElement("a");
						// file.style.display = "none";
						// file.href = base64;
						// file.download = decodeURI(name);
						// document.body.appendChild(file);
						// file.click();
						// document.body.removeChild(file);

						this.$ownerInstance.callMethod('renderFinish', {
							path: canvas.toDataURL('image/png', 1.0)
						})
						clearTimeout(timer)
					} catch (e) {
						this.$ownerInstance.callMethod('hideLoading', true)
						console.log(e)
					}
				}, 1000)
			}
		}
	}
</script>

<style>
	.poster-image {
		padding: 20rpx;
		box-sizing: border-box;
		text-align: center;
		width: 100vw;
		height: 100vh;
		background-size: cover;
		/* background-position: 100%; */
	}

	.poster-image image {
		position: absolute;
		bottom: 80rpx;
		right: 80rpx;
		width: 200rpx;
		height: 200rpx;
	}
</style>

<style lang="scss">
	.poster-image {
		text-align: center;
	}

	// .poster-image image {
	// 	width: 100%;
	// 	height: 85vh;
	// }

	.generatePoster {
		display: flex;
		justify-content: space-around;
		width: 100%;
		position: absolute;
		bottom: 20rpx;
	}
</style>

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在uniapp生成二维码并保存到本地,可以按照以下步骤进行操作: 1. 首先,使用weapp.qrcode生成二维码。这个库可以用于生成二维码的数据。 2. 然后,使用uni.canvasToTempFilePath方法将生成的二维码转换为临时图片文件。 3. 使用canvas绘制二维码。 4. 接下来,使用uni.canvasToTempFilePath方法再次生成图片文件。 5. 最后,使用uni.saveImageToPhotosAlbum方法将图片保存到本地相册。 具体代码示例如下: ```javascript // 1. 使用weapp.qrcode生成二维码 const qrcode = require('weapp.qrcode'); const qrData = 'your qrcode data'; const qrcodeImg = qrcode.createQrCodeImg(qrData); // 2. 使用uni.canvasToTempFilePath生成临时图片文件 uni.canvasToTempFilePath({ canvasId: 'canvas', // canvas的id success: function (res) { const tempFilePath = res.tempFilePath; // 3. 使用canvas绘制二维码 const ctx = uni.createCanvasContext('canvas'); ctx.drawImage(qrcodeImg, 0, 0, 200, 200); // 绘制二维码图片 ctx.draw(false, function () { // 4. 使用uni.canvasToTempFilePath生成图片文件 uni.canvasToTempFilePath({ canvasId: 'canvas', success: function (res2) { const qrCodeFilePath = res2.tempFilePath; // 5. 使用uni.saveImageToPhotosAlbum保存到本地 uni.saveImageToPhotosAlbum({ filePath: qrCodeFilePath, success: function () { console.log('保存成功'); }, fail: function (err) { console.log('保存失败', err); } }); }, fail: function (err2) { console.log('生成二维码图片文件失败', err2); } }); }); }, fail: function (err3) { console.log('生成临时图片文件失败', err3); } }); ``` 通过以上步骤,你就可以在uniapp生成二维码并保存到本地相册了。<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span>

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值