下载原理:
首先引入html2Canvas.js 文件, 通过屏幕快照,截图 ,形成base64的图片,在将base64 转化为二进制文本流,最后用js 形成a标签,然后形成下载功能。
downpic () {
let fulu = document.getElementById("fulu")
let collapse = fulu.getElementsByClassName("at-collapse-item__wrap")
for (let i=0; i<collapse.length; i++){
collapse[i].style.display= 'block'
}
let otbeTarget = document.getElementsByClassName('downbutton')[0]
otbeTarget.style.display = 'none'
let picdown = document.querySelector('#picdown')
html2Canvas(picdown).then(canvas => {
let contentWidth = canvas.width
console.log(contentWidth)
let contentHeight = canvas.height
let pageHeight = contentWidth / 592.28 * 841.89
let leftHeight = contentHeight
let position = 20
// let imgWidth = 595.28
let imgWidth = 595.28
let imgHeight = 592.28 / contentWidth * contentHeight
let pageData = canvas.toDataURL('image/jpeg', 1.0)
this.downloadFile('附录.png', pageData)
otbeTarget.style.display = 'block'
for (let i=0; i<collapse.length; i++){
collapse[i].style.display= 'none'
}
})
},
// 下载
downloadFile (fileName, content) {
let aLink = document.createElement('a')
let blob = this.base64ToBlob(content) // new Blob([content]);
let evt = document.createEvent('HTMLEvents')
evt.initEvent('click', true, true)
aLink.download = fileName
aLink.href = URL.createObjectURL(blob)
aLink.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}))
},
base64ToBlob (code) {
let parts = code.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)
}
return new Blob([uInt8Array], {type: contentType})
},