1、首先安装html2canvas和canvas2Image,利用npm install (下载完后会发现当你引入canvas2Image的时候会报错,我发现的问题是node_modules中没有export的)
2、然后进入主要的代码环节
其中tab代表你想要截图的div元素
domImg就是将这张图片添加到那个元素上(自己可以随意定义)
imgName顾名思义就是你下在图片的命名
html2canvas(tab, {
useCORS: true, // 【重要】开启跨域配置
allowTaint: true, // 允许跨域图片
taintTest: false // 是否在渲染前测试图片
}).then(canvas => {
let context = canvas.getContext('2d')
context.mozImageSmoothingEnabled = false
context.webkitImageSmoothingEnabled = false
context.msImageSmoothingEnabled = false
context.imageSmoothingEnabled = false
let newImg = Canvas2Image.convertToImage(
canvas,
canvas.width,
canvas.height
)
document.getElementById('download').appendChild(newImg)
newImg.id = 'newImg'
// let domImg = document.getElementById('newImg')
domImg.style.width = '100%'
// this.dis = false
let src = canvas.toDataURL()
let aLink = document.createElement('a')
let parts = src.split(';base64,')
let contentType = parts[0].split(':')[1]
let raw = window.atob(parts[1])
let rawLength = raw.length
let uInt8Array = new Uint8Array(rawLength)
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i)
}
let blob = new Blob([uInt8Array], { type: contentType })
let evt = document.createEvent('HTMLEvents')
evt.initEvent('click', true, true)// initEvent 不加后两个参数在FF下会报错 事件类型,是否冒泡,是否阻止浏览器的默认行为
aLink.download = imgName
aLink.href = URL.createObjectURL(blob)
// aLink.dispatchEvent(evt);
// aLink.click()
aLink.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }))// 兼容火狐
3、这样就可以啦