html2canvas合成图片 前端跨域问题 uniapp

9 篇文章 1 订阅

问题描述 前端图片跨域
在这里插入图片描述

---->修改源码: img.src = src + ‘?t=’ + new Date().getTime();
在这里插入图片描述

前端—> 封装一个html2canvas组件

<template>
	<view class="html2canvas" :prop="domId" :change:prop="html2canvas.create">
		<slot></slot>
	</view>
</template>

<script>
	export default {
		name: 'html2canvas',
		props: {
			domId: {
				type: String,
				required: true
			}
		},
		methods: {
			async renderFinish(base64) {
				try{
					this.$emit('renderFinish', base64);
				}catch(e){
					this.$emit('renderFinish', "err");
					//TODO handle the exception
				}
			},
			showLoading() {
				uni.showToast({
					title: "正在生成图片",
					icon: "none",
					mask: true,
					duration: 100000
				})
			},
			hideLoading() {
				uni.hideToast();
			}
		}
	}
</script>



<script module="html2canvas" lang="renderjs">
import html2canvas from 'html2canvas';
export default {
	methods: {
		async create(domId) {
			if(!domId) return;
			try {
				const _this = this;
				const timeout = setTimeout(async ()=> {
					const shareContent = document.querySelector(domId);
					let width = shareContent.offsetWidth; 
					let height = shareContent.offsetHeight; 
					let _canvas = document.createElement("canvas"); 
					let scale = 2; //定义任意放大倍数 支持小数
					_canvas.width = width * scale; //定义canvas 宽度 * 缩放
					_canvas.height = height * scale; //定义canvas高度 *缩放
					let context =  _canvas.getContext("2d"); //获取context,设置scale 
					context.translate(0, 0);
					const canvas = await html2canvas(shareContent,{
						logging: true,
						async: false,
						useCORS: true, // 【重要】开启跨域配置
						allowTaint: false,//允许跨域图片
						taintTest: false,//是否在渲染前测试图片
						backgroundColor:"#746F6C",
						canvas: _canvas, 
						width:width, //dom 原始宽度
						height:height ,//dom 原始高度
						scale:scale, // 添加的scale 参数
						proxy:'https://file.zhenqingkongjian.com/'
					});
					console.log(canvas)
					const base64 = canvas.toDataURL('image/jpeg');
					console.log(base64)
					this.$ownerInstance.callMethod('renderFinish', base64);
					clearTimeout(timeout);
				}, 500);
			} catch(error){
				this.$ownerInstance.callMethod('renderFinish',"err");
			}
		},
		
	}
}
</script>


<style lang="scss">

</style>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值