使用html2canvas实现图片或者dom元素的样式展示

html或者.vue.tsx模板

<div class="tan1" id="tan1">
				<div class="jiang" id="jiangImg1" style="margin: 1rem auto 0;width: 75%;height: 10rem;position: relative;background-color: transparent;">
					<img id="canvasimg1" src="https://xxxx/img/142a7391ae221">
					
				</div>
			</div>
这个是要将对应的dom转成图片的dom元素

样式最好写在行间

html2canvas的引入有两个,vue或者react或者nuxt都用,npm,pnpm,yarn下载都可以

npm install html2canvas pnpm install html2canvas yarn install html2canvas

然后script要记得引入
import html2canvas from 'html2canvas';

或者

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>

插入显示方法,用于展示后长按下载的

var element = document.getElementById('要制作的dom元'); 
var img1 = document.getElementById('要制作的dom中的img,防止跨域使用'); 
img1.crossOrigin = "anonymous"; // 这行很重要
html2canvas(element,
					{
						backgroundColor: null, // 设置画布背景为透明色
						scale: 2,
						width: element.offsetWidth, //设置跨高
						height: element.offsetHeight,
						useCORS: true,
						allowTaint: true, //允许跨域(图片跨域相关)
					}).then(function (canvas) {
						canvas.toBlob(blob => {
                            //插入方法
							const href = window.URL.createObjectURL(blob);
							var img = new Image();
							img.src = href;
							img.width = '100%';
							document.body.appendChild(img);
							$('#需要插入的dom元素展示').html(img)
						}, 'image/png'); 
					});

用于直接下载的

var element = document.getElementById('要制作的dom元'); 
var img1 = document.getElementById('要制作的dom中的img,防止跨域使用'); 
img1.crossOrigin = "anonymous"; // 这行很重要
html2canvas(element,
					{
						backgroundColor: null, // 设置画布背景为透明色
						scale: 2,
						width: element.offsetWidth, //设置跨高
						height: element.offsetHeight,
						useCORS: true,
						allowTaint: true, //允许跨域(图片跨域相关)
					}).then(function (canvas) {
						canvas.toBlob(blob => {
                            const href = window.URL.createObjectURL(blob);
                            const link = document.createElement('a');
                            link.href = href;
                            link.download = '海报'+'.png'; 
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
						}, 'image/png'); 
					});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值