一、安装 html2canvas
npm install html2canvas
二、使用
const imgViewRef= ref()
const downloadHandle = () => {
const element = imgViewRef.value.contentWindow.document.body
const elementWidth = element.offsetWidth + 52
const elementHeight = element.offsetHeight
const canvas = document.createElement('canvas')
canvas.width = elementWidth * 2
canvas.height = elementHeight * 2
canvas.style.width = elementWidth + 'px'
canvas.style.height = elementHeight + 'px'
const context = canvas.getContext('2d')
context!.scale(2, 2)
html2canvas(element, {
allowTaint: true,
useCORS: true,
logging: true,
canvas: canvas
}).then((canvas) => {
const imgUrl = canvas.toDataURL('image/jpeg')
const dataArr = imgUrl.split(',')
const bstr = atob(dataArr[1])
let n = bstr.length
const u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
const fileName = `导出的文件名称.jpg`
const img = new File([u8arr], fileName, { type: 'jpg' })
const aTag = document.createElement('a')
aTag.download = fileName
const href = URL.createObjectURL(img)
aTag.href = href
aTag.click()
URL.revokeObjectURL(href)
}).catch(err => {
console.log(err)
})
}