1、使用 html2canvas 插件, yarn add html2canvas --save
2、使用 html2canvas 的组件
<div class="btn" @click="screenShot">截屏保存</div>
import html2canvas from 'html2canvas'
methods:{
//这里的html标签是获取页面最大的dom元素;根据实际业务场景自行更改
const el = document.querySelector('html')
html2canvas(el, { allowTaint: true, useCORS: true }).then((canvas) => {
//document.body.appendChild(canvas) 页面布局会乱
//转换base64
const file = canvas.toDataURL('image/png')
//下载浏览器弹出下载信息的属性
const saveInfo = {
//导出文件格式自己定义,我这里用的是时间作为文件名
download: this.$moment().format('YYYY-MM-DD HH:mm:ss') + `.png`,
href: file,
}
// 上传后端服务器
this.sendUrl(file)
//前端下载
this.downloadFile(saveInfo)
})
}
// 前端浏览器下载截图
downloadFile(saveInfo) {
const element = document.createElement('a')
element.style.display = 'none'
for (const key in saveInfo) {
element.setAttribute(key, saveInfo[key])
}
document.body.appendChild(element)
element.click()
setTimeout(() => {
document.body.removeChild(element)
}, 300)
},
// 图片地址转换
dataURLtoFile(dataURI, type) {
let binary = atob(dataURI.split(',')[1])
let array = []
for (let i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i))
}
return new Blob([new Uint8Array(array)], { type: type })
},
// 图片上传服务器
async sendUrl(file) {
var formData = new FormData()
let blob = this.dataURLtoFile(file, 'image/jpeg')
let fileOfBlob = new File([blob], new Date() + '.jpg')
formData.append('file', fileOfBlob)
// 注意:下面方法是自己的请求接口。。。。
const { code, message } = await sysFileInfoUploadList(formData)
if (code === 200) {
this.$message.success('上传成功!')
} else {
this.$message.error(message)
}
},
菜鸟一枚,记录文档 方便查阅