安装html2canvas依赖
npm install --save html2canvas
导入
import html2canvas from 'html2canvas'
使用
let container = document.getElementById('views-container') html2canvas(container, { container.clientWidth, height: container.clientHeight, backgroundColor: '#0f3050', ignoreElements: (element) => { // 忽略不被绘制的dom元素 return element.className === 'tool product-view-tool' }}).then(canvas => { let src = canvas.toDataURL('image/jpg', 1) let image = new Image() image.src = src let url = image.src.replace(/^data:image/[^;]/, 'data:application/octet-stream') let a = document.createElement('a') a.download = '产品图.jpg' // 设置下载的文件名,默认是'下载' a.href = url document.body.appendChild(a) a.click() a.remove() // 下载之后把创建的元素删除 })