最近遇到截图功能出现保存到本地的时候,浏览器显示网络错误下载失败。无法进行截图。
这个问题是canvas保存图片到本地时各个浏览器像素的限制不同,所以将图片数据转换成 Blob 数据流下载下来就行了。
let canvas = document.createElement('canvas')
let canvasBox = document.getElementById('container')//获取截图的范围
let width = parseInt(window.getComputedStyle(canvasBox).width)
let height = parseInt(window.getComputedStyle(canvasBox).height)
canvas.width = width*2
canvas.height = height*2
canvas.style.width = width + 'px'
canvas.style.height = height + 'px'
const context = canvas.getContext('2d')
context.scale(2,2)
html2canvas(canvasBox,{allowTaint:true}).then(canvas=>{
let name = this.getNowTime() //图片名称 时间生成
canvas.toBlob(
function(blob){
const ele = document.createElement("a")
ele.download = name + '.png'
ele.style.display = "none"
ele.href = URL.createObjectURL(blob)//字符内容转为blob地址
ele.click()
},"image/png",1
)
})
最后发现由于下载的dom包含地图元素,下载速度很慢。
html2canvas与部分css样式存在冲突,如transform。对于一些css动态样式可考虑js实现。