- 其實打開一個新窗口,將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');
}
});