之前业务说字段太多,浏览器缩放截图字太小,就想着试着做个截图功能,谷歌了一下,看到了html2canvas...使用的时候就遇到了一些坑,主要体现在截图不全,白屏的问题。问题因人而异。
const handleClick = (e) => {
e.target.setAttribute('class', 'test1');
// 找到目标元素的父元素
const parent = document.querySelector('test1').parentNode.parentNode.parentNode.cloneNode(true);
// 截图的时候希望字段一起展示,thhead就是字段展示层
const thhead = document.querySelector('.ant-table-thead').firstChild.cloneNode(true);
// 因为html2canvas是将dom转换为canvas,所以这里创建了个table
const table = document.createElement('table');
// 这里把要截的dom插入到table中 table.appendChild(thhead);
table.appendChild(parent);
// html2canvas只能截可见元素,所以添加到body中
document.body.appendChild(table);
table.setAttribute('class', 'test2');
// 下面两句是为了解决截图有时候截图不全甚至白屏的问题
document.body.scrollTop = document.documentElement.scrollTop = 0;
document.documentElement.style.position = 'fixed';
screenshot(document.querySelector('.test2'), {
allowTaint: true, // 允许加载跨域资源
}).then((canvas) => {
const dataURL = canvas.toDataURL('image/jpeg');
// 新开标签页,展示截图
const win = window.open();
// 这里我做了截图的缩放,适应浏览器窗口,不产生滚动条
win.document.write(`<div ><img style="width: auto;height: auto; max-width: 100%; max-height: 100%;" src=${dataURL}></img></div>`); });
// 完成后移除添加的table,避免对页面产生影响
document.body.removeChild(table);
// 搭配上面解决截图不全,白屏使用的
document.documentElement.style.position = ''; };
简单点截个部分
初稿就是这样,分享给需要的同学,同时作为备忘录供自己以后使用