vue3 一键截取div内容(图片)至粘贴板

效果图如图所示:

完整代码如下:

npm install html2canvas --save
<template>
  <div class="page-main main">
    <div class="data_overview">
      <div class="text_top" ref="targetDiv">
        分析概述
        <hr>
        这是一段文本内容
        <hr />
        <img src="./图片.jpg" style="width: 300px;" alt="" srcset="">
        <hr />

        <el-timeline style="max-width: 600px">
          <el-timeline-item v-for="(activity, index) in activities" :key="index"             
            :timestamp="activity.timestamp">
            {{ activity.content }}
          </el-timeline-item>
        </el-timeline>
      </div>
      <div class="item_bottom">
        <el-button type="primary" @click="captureContent">一键截取图片</el-button>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup name="Terrace">
import { ref, reactive, getCurrentInstance, onMounted } from "vue";
const { proxy } = getCurrentInstance() as any;
import html2canvas from 'html2canvas';
const targetDiv = ref()
const activities = [
  {
    content: 'Event start',
    timestamp: '2018-04-15',
  },
  {
    content: 'Approved',
    timestamp: '2018-04-13',
  },
  {
    content: 'Success',
    timestamp: '2018-04-11',
  },
]


const captureContent = () => {
  const _targetDiv = targetDiv.value;
  console.log(_targetDiv);
  html2canvas(_targetDiv, { backgroundColor: '#fff' })
    .then(canvas => {

      const base64 = canvas.toDataURL('image/png')
      const myBlob = dataURLtoBlob(base64)

      // 1、直接下载图片实现
      // const myUrl = URL.createObjectURL(myBlob)
      // downloadFile(myUrl, '截取')

      // 2、复制到粘贴板实现
      const clipboardItem = new ClipboardItem({ 'image/png': myBlob });
      // 将数据添加到剪贴板
      navigator.clipboard.write([clipboardItem]).then(() => {
        console.log('Image copied to clipboard');
      }).catch(err => {
        console.error('Unable to copy image to clipboard', err);
      });
    });
}

const dataURLtoBlob = (dataurl: string) => {
  const arr: any[] = dataurl.split(',')
  const mime = arr[0].match(/:(.*?);/)[1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], { type: mime })
}

const downloadFile = (url: string, name: string) => {
  const a = document.createElement('a')
  a.setAttribute('href', url)
  a.setAttribute('download', name)
  a.setAttribute('target', '_blank')
  const clickEvent = document.createEvent('MouseEvents')
  clickEvent.initEvent('click', true, true)
  a.dispatchEvent(clickEvent)
}
</script>

<style lang="less" scoped>
.text_top {
  min-height: 200px;
  border: 1px solid red;
}

.main {
  font-size: 16px;
}
</style>
避坑提示:解决http下navigator.clipboard、ClipboardItem 为undefined问题

        开发环(http)
下使用navigator.clipboard进行复制操作,该功能会存在显示为undefned;查相关资料后,发现clipboard只有在安全域名下才可以访问(https、localhost),在http域名下只能得到undefined;

 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值