vue3.0 ts 使用html2canvas(截图)下载png

vue3.0 ts 使用html2canvas(截图)下载png

在这里插入图片描述
例如 要将这个页面截图下载出来

  1. 先画这个页面

这里页面代码就不贴出来了

  1. 用div将这个页面包裹起来
 <div id="capture">
 <!-- 页面组件 -->
   <WeeklyReport></WeeklyReport>
  </div>
  1. 安装html2canvas

npm install --save html2canvas

  1. 在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图片就搞定啦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值