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

文章描述了如何在Vue项目中使用HTML2canvas和RenderJS技术,生成二维码海报,并将其转化为base64编码,最终保存到手机相册的过程,包括从API获取二维码图片和处理图片保存的逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  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>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值