vue3.0 ts 使用html2canvas(截图)下载png
例如 要将这个页面截图下载出来
- 先画这个页面
这里页面代码就不贴出来了
- 用div将这个页面包裹起来
<div id="capture">
<!-- 页面组件 -->
<WeeklyReport></WeeklyReport>
</div>
- 安装html2canvas
npm install --save html2canvas
- 在script中引入 html2canvas 写js代码
<script lang="ts" setup>
import { reactive, ref, createVNode, onMounted } from 'vue'
import html2canvas from 'html2canvas'
const base64img = ref<any>()
const weeklyReport = () => {
console.log('生成周报')
html2canvas(document.querySelector('#capture')as HTMLElement).then((canvas) => {
// 转换成base64格式,这个格式可以挂载到img里,也可以下载下来,也可以打压缩包下载下来
const base64 = canvas
.toDataURL()
.replace(/^data:image\/(png|jpg);base64,/, '')
base64img.value = `data:image/png;base64,${base64}`
// console.log(base64img.value)
if (window.navigator.msSaveOrOpenBlob) {
let bstr = atob(base64img.value.split(",")[1]);
let n = bstr.length;
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
let blob = new Blob([u8arr]);
window.navigator.msSaveOrOpenBlob(blob, "周报" + "." + "pdf");
} else {
// 这里就按照chrome等新版浏览器来处理
let a = document.createElement("a");
a.href = base64img.value;
a.setAttribute("download", "周报");
a.click();
}
})
}
</script>
这样这个png图片就搞定啦!