将html里面的dom转化为图片
<template>
<div class="m-item" ref="imageTofile">
...
</div>
</template>
<script>
import html2canvas from 'html2canvas';
...
toImage() {
const canvas = document.createElement('canvas');
let canvasBox = this.$refs.imageTofile as HTMLElement;
if (canvasBox) {
const width = parseInt(window.getComputedStyle(canvasBox).width);
const height = parseInt(window.getComputedStyle(canvasBox).height);
canvas.width = width * 2.1;
canvas.height = height * 2.1;
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
const context = canvas.getContext('2d');
if (context) {
context.scale(2, 2);
const options = {
backgroundColor: null,
canvas: canvas,
useCORS: true,
};
return html2canvas(canvasBox, options).then((canvas) => {
let dataURL = canvas.toDataURL('image/png');
return this.downloadImage(dataURL);
});
}
}
}
downloadImage(url: string) {
return {
url,
name:`${this.item.roomNumber}-${this.item.userName}-${this.item.date}`
}
}
type imageType = {
url: string;
name: string;
}
async handleDownloadImage () {
const list = this.$refs.rooms as MRoomItem[]
const result: Promise<imageType>[] = []
list.forEach((item) => {
const value = item.toImage()
if (value) {
result.push(value)
}
})
const allResult = await Promise.all(result)
console.log(allResult)
const zip = new JSZip()
const fileFolder = zip.folder('文件夹')
const fileList = []
allResult.forEach((item) => {
fileFolder?.file(`${item.name}.png`, item.url.substring(22), {
base64: true
})
})
zip.generateAsync({type: 'blob'}).then((res=>{
FileSaver.saveAs(res,'打包.zip')
}))
}
</script>