1、安装html2canvas: npm install --save html2canvas
2、引入html2canvas: import html2canvas from 'html2canvas'
3、封装方法:
export const domCreateBase64 = (domCopy) => {
return new Promise(async (resolve, reject) => {
const body = document.body
body.appendChild(domCopy)
setTimeout(() => {
html2canvas(domCopy, {
// 提升截图效率,将不需要的元素忽略
scale: 1, ignoreElements: el => {
if (el == domCopy) return false;
if (el.tagName == 'BODY') return false;
if (el.tagName == 'HEAD') return false;
if (domCopy.compareDocumentPosition(el) == 20) return false;
if (el.tagName == 'STYLE') return false;
if (el.id == 'app') return false;
if (el.tagName == 'LINK') {
if (/\.js$/.test(el.href)) return true;
else return false;
}
if (el.tagName == 'SCRIPT') return true;
if (el.classList.contains('scene')) return true
return true
}
}).then(canvas => {
body.removeChild(domCopy)
//导出生成的base64编码
resolve(canvas.toDataURL('image/png'))
})
}, 300)
})
}
4、引入domCreateBase64 方法