uniapp app端 生成图片并保存到手机相册

一.npm 安装 html2canvas和image-tools插件

npm install --save html2canvas
npm i image-tools --save

二.使用

注:uniapp app端 由于没有document,不能进行相关的DOM操作,可用官方推出了renderjs来解决问题。renderjs | uni-app官网

<template>
	<view>
		<view id="canvasImg">
			<table>
				<tr v-for="(item , index) in dataList" :key="index">
					<td>{{item.name}}</td>
					<td>{{item.age}}</td>
					<td>{{item.sex}}</td>
				</tr>
			</table>
		</view>
		<view>
			<button style="width: 200upx;" @click="canvas.downImg">保存</button>
		</view>
	</view>
</template>
<script module="canvas" lang="renderjs">
	import html2canvas from 'html2canvas';
	export default {
		data() {
			return {}
		},
		methods: {
			downImg(e, ownerVm) {
				window.scrollTo(0, 0) //注意这里必须设置为顶部不然会出现图片不全
				html2canvas(document.querySelector('#canvasImg'), {
					allowTaint: true, //是否允许跨域图像渲染画布
					useCORS: true, //是否尝试使用 CORS 从服务器加载图像 解决图片跨域问题
				}).then(function(canvas) {
					ownerVm.callMethod('receive', canvas.toDataURL('image/jpeg', 1.0))
				}).catch(err => {
					ownerVm.callMethod('showToast', `生成图片失败,请重试,${err}`)
				})
			},
		}
	}
</script>
<script>
	import {
		base64ToPath
	} from 'image-tools'
	export default {
		data() {
			return {
				dataList: [{
						name: '张三',
						sex: '男',
						age: 19
					},
					{
						name: '张四',
						sex: '男',
						age: 19
					},
					{
						name: '张五',
						sex: '男',
						age: 19
					}
				],
				imgUrl: '',
			}
		},
		methods: {
			//提示
			showToast(content) {
				uni.showToast({
					title: content,
					icon: 'none',
					duration: 2000,
				});
			},
		
			// 将base64位的图片路径转换为临时路径
			receive(val) {
				//去除base64位中的空格
				this.imgUrl= val.replace(/[\r\n]/g, ''); 
				//将base64位的图片路径转换为临时路径
				setTimeout(() => {
					const url= this.imgUrl;
					base64ToPath(url).then(path => {
							this.saveImage(path)
						})
						.catch(error => {
							console.error('图片的临时路径转换出错了:', error);
						});
				}, 500);
			},
			// 保存图片到手机相册
			saveImage(path) {
				uni.saveImageToPhotosAlbum({
					path, // 需要临时文件路径,否则base64无法保存
					success: () => {
						this.showToast('保存图片到本地相册成功')
					},
					fail: () => {
						this.showToast('保存图片到本地相册失败')
					}
				});
			},

		},
	}
</script>

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值