一、需求
1. 将页面某元素节点的内容转化为图片
2. 将图片的blob文件流传给服务器(简而言之:拿到图片的File对象)
二、使用 html2canvas 案列
1. 安装 html2canvas
npm install html2canvas
or
yarn add html2canvas
2. 使用
import html2canvas from 'html2canvas'
html2canvas(document.body).then(function(canvas) {
document.body.appnedChild(canvas)
})
三、 实现需求
1. 解析图片,导出blob文件流
// 解析图片,导出blob文件流
async captureElementAsFile () {
// 元素节点
const content = this.$refs.printContainer
const canvas = await html2canvas(content, {
allowTaint: true, // 是否允许不同源的图片污染画布 (允许绘制)
useCORS: true, // 是否尝试使用 CORS 从服务器加载图片 (允许跨域)
// logging: true, // 启用日志记录以进行调试
width: content.clientWidth * 1.005, // 设置图片宽度
height: content.clientHeight * 1.005 // 设置图片高度
})
// 转blob文件流
const blob = await new Promise(resolve => {
canvas.toBlob(resolve, 'image/png')
})
// blob文件流转File对象
const file = new File([blob], 'element.png', { type: 'image/png' })
// 转base64格式图片
const base64 = canvas.toDataURL('image/png')
},
2. 下载图片
方案一:
async downloadImage () {
const content = this.$refs.equipmentInfo
const canvas = await html2canvas(content)
const url = canvas.toDataURL('image/png')
const filename = 'qrCode.png'
const link = document.createElement('a')
link.href = url
link.download = filename
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
方案二:
async downloadImage () {
const content = this.$refs.printContainer
const canvas = await html2canvas(content, {
allowTaint: true,
useCORS: true,
logging: true
})
const dataURL = canvas.toDataURL('image/png')
console.log(dataURL, 'dataURL')
const link = document.createElement('a')
link.download = 'drawing.png'
link.href = dataURL
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
四、使用html2canvas存在的问题
问题:
1、如果将节点转为图片时,节点内容存在第三放文件资源时,
可能会忽略编译第三方资源,亦或者会出现请求第三方文件跨域的问题。
2、下载第三方资源图片可能会出现跨域问题
解决方法:给html2canvas进行配置,使用 allowTaint,useCors 属性
同时需要配置你的第三方资源服务器,使服务器允许跨域
案列:鄙人的电放资源文件是图片,并且保存在阿里云的oss服务器上,(阿里云的oss服务器需要购买)
你需要去 阿里云的oss服务器 配置允许跨域
html2canvas中文文档: https://allenchinese.github.io/html2canvas-docs-zh-cn/https://allenchinese.github.io/html2canvas-docs-zh-cn/