vue截图到剪切板(使用html2canvas)

使用html2canvas将我们要转成图片的DOM元素转成canvas对象.

将canvas对象写入剪切板时两个思路:

1.document.execCommand('Copy');

// 安装后导入
import html2canvas from 'html2canvas';
// 传入要截图的DOM节点
html2canvas(this.$refs.paramInfoRef).then((canvas) => {
        // 得到的是一个canvas对象,将其转成一个uri给img对象
        const img = new Image();
        img.src = canvas.toDataURL();
        document.body.appendChild(img);
        img.onload = () => {
          // 获取选中对象
          const selection = window.getSelection();
          // 如果已有选种则清除选中
          if (selection.rangeCount > 0) selection.removeAllRanges();
          // 创建选中区域
          const range = document.createRange();
          // 添加图片到选种区域
          range.selectNode(img);
          // 添加到选种区域到选中对象
          selection.addRange(range);
          // 调用系统剪切板复制命令
          document.execCommand('Copy');
          // 清空选中区域
          selection.removeAllRanges();
        };
      });

结果: 网上很多帖子写了但是我测试后发现无效,放弃

2.navigator.clipboard.write()

import html2canvas from 'html2canvas';
html2canvas(this.$refs.paramInfoRef).then((canvas) => {
        // 将canvas转为blob对象
        canvas.toBlob((blob) => {
          // 将blob对象放入剪切板item中
          // eslint-disable-next-line no-undef
          const data = [new ClipboardItem({ [blob.type]: blob })];
          // 写入剪切板,成功会执行resolve,失败则走reject
          navigator.clipboard.write(data).then(() => {
            this.$message({
              message: '已保存到粘贴板',
              type: 'success',
              duration: 2000,
            });
          }, () => {
            this.$message({
              message: '保存截图失败',
              type: 'warning',
              duration: 2000,
            });
          });
        }, 'image/png');
      });

总结:亲测可用

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值