- 其实打开一个新窗口,将DOM元素的canvas写成图片
- 如果页面中有滚动条等特殊情况,需要在生成图片前将相关的样式/Class移除,生成图片结束后再恢复
import * as html2canvas from 'html2canvas';
// html2canvas only copies visible elements to the screenshot canvas. Therefore we set
// everything below our target element visible at first...
document.getElementById('xxx').style.overflow = 'visible';
if (document.getElementById('yyy')) {
document.getElementById('yyy').classList.remove('scroll-div');
}
// ... take the screenshot...
html2canvas(document.getElementById(_target)).then(canvas => {
// ... make it write out to our
const win = window.open();
const doc = win.document;
doc.write(`<img src=${canvas.toDataURL()} />`);
doc.close();
// change the overflow style back to default (= auto) so it doesn't mess up the template
document.getElementById(‘xxx’).style.overflow = 'auto';
if (document.getElementById('yyy')) {
document.getElementById('yyy').classList.add('scroll-div');
}
});