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');
});