利用 html2canvas 和 jszip 第三方库
import html2canvas from 'html2canvas'
import jszip from 'jszip'
具体实现:
downloadAll() {
this.loading = true
let _this = this
const stations = document.getElementsByClassName('station_bar')
let promises = []
let zip = new jszip()
for (let i = 0; i < stations.length; i++) {
let element = stations[i]
let times = 16
const canvas = document.createElement('canvas')
let canvasBox = element
const width = parseInt(window.getComputedStyle(canvasBox).width)
const height = parseInt(window.getComputedStyle(canvasBox).height)
canvas.width = width * times
canvas.height = height * times
canvas.style.width = width + 'px'
canvas.style.height = height + 'px'
const context = canvas.getContext('2d')
context.scale(times, times)
const options = {
backgroundColor: null,
canvas: canvas,
useCORS: true,
}
let promise = html2canvas(canvasBox, options).then((canvas) => {
// toDataURL 图片格式转成 base64
let dataURL = canvas.toDataURL('image/jpeg', 0.3)
let fileName = `${this.stationData.StationName}_${
i + 1
}_${this.getCurrentDateTime()}.jpeg`
zip.file(fileName, dataURL.split(',')[1], { base64: true })
})
promises.push(promise)
}
Promise.all(promises).then(function () {
zip.generateAsync({ type: 'blob' }).then(function (content) {
_this.loading = false
// 创建下载链接
var link = document.createElement('a')
link.href = URL.createObjectURL(content)
link.download = `${_this.stationData.StationName}_${_this.getCurrentDateTime()}_image.zip`
link.click()
})
})
},
下载单张:
downloadPicture() {
this.$emit('update:loading', true)
let times = 16
const canvas = document.createElement('canvas')
let canvasBox = this.$refs.stationBarRef.$el
const width = parseInt(window.getComputedStyle(canvasBox).width)
const height = parseInt(window.getComputedStyle(canvasBox).height)
canvas.width = width * times
canvas.height = height * times
canvas.style.width = width + 'px'
canvas.style.height = height + 'px'
const context = canvas.getContext('2d')
context.scale(times, times)
const options = {
backgroundColor: null,
canvas: canvas,
useCORS: true,
}
html2canvas(canvasBox, options).then((canvas) => {
this.$emit('update:loading', false)
// toDataURL 图片格式转成 base64
let dataURL = canvas.toDataURL('image/jpeg', 0.3)
this.downloadImage(dataURL)
})
},
downloadImage(url) {
let a = document.createElement('a')
a.href = url
let name = `${this.data.StationName}_${this.index}_${this.getCurrentDateTime()}.jpeg`
a.download = name
a.click()
},
标签:canvas,const,批量,dom,height,width,let,times,下载
From: https://www.cnblogs.com/baixi1271/p/17422955.html