vue实现复制文字复制图片实例详解

发布时间:2023-03-25 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了vue实现复制文字复制图片实例详解脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

正文

复制文字和图片是我们经常会使用到的需求,我们这篇文章主要介绍使用navigator.clipboard.wrITe()来实现复制文字和图片。不过这个属性是需要考虑浏览器的兼容性的,可以参考MDN

document.execCommand('copy')

在很久之前我们是使用document.execCommand('copy')来实现复制文本的,但是现在mdn上已经将这个命令废弃了。

当一个 HTML 文档切换到设计模式时,document暴露 execCommand 方法,该方法允许运行命令来操纵可编辑内容区域的元素。如果传入copy命令,那么就能实现复制的功能。

比如像下面这样

  // 复制文字
  copyText(link, cb) {
    let input = document.createElement('textarea');
    input.style.cssText = 'position: absolute; top: 0; left: 0; opacity: 0; z-index: -10;';
    input.value = link;
    document.body.apPEndChild(input);
    input.select();
    document.execCommand('copy');
    document.body.removeChild(input);
    if (typeof cb === 'function') {
      cb();
    }
  }

Clipboard

Clipboard 接口实现了 Clipboard API,如果用户授予了相应的权限,其就能提供系统剪贴板的读写访问能力。在 Web 应用程序中,Clipboard API 可用于实现剪切、复制和粘贴功能。

方法

Clipboard提供了以下方法,方便我们读取剪切板的内容。

  • read():从剪贴板读取数据(比如图片),返回一个 Promise对象。在检索到数据后,PRomise 将兑现一个 ClipboardItem对象的数组来提供剪切板数据。
  • readText():从操作系统读取文本;返回一个 Promise,在从剪切板中检索到文本后,promise 将兑现一个包含剪切板文本数据的 DOMString
  • write(): 写入任意数据至操作系统剪贴板。这是一个异步操作,在操作完成后,返回的 promise 的将被兑现。
  • writeText(): 写入文本至操作系统剪贴板。返回一个 Promise,在文本被完全写入剪切板后,返回的 promise 将被兑现。

复制文本

复制文本的方法很简单,就是使用navigator.clipboard.writeText()方法。

具体代码实现如下:

copyTextToClipboard(text) {
  return new Promise((resolve, reject) => {
    navigator.clipboard.writeText(text).then(
      () => {
        resolve(true)
      },
      () => {
        reject(new Error('复制失败'))
      }
    )
  })
}

复制图片

复制图片主要用到navigator.clipboard.write()方法。 因为我们在页面中通常是要根据一个img元素复制图片,主要实现思路如下:

  • 先将img元素转成base64
  • 再将base64转成blob对象
  • 根据blob对象new一个ClipboardItem对象
  • 最后再根据navigator.clipboard.writeText()将内容写入剪贴板中

具体代码实现如下:

  // 图片元素转base64
  getBase64Image(img) {
    let canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;
    let ctx = canvas.getContext('2d');
    ctx?.drawImage(img, 0, 0, img.width, img.height);
    let dataURL = canvas.toDataURL('image/png');
    return dataURL;
  },
  // base64图片转为blob
  getBlobImage(dataurl) {
    let arr = dataurl.split(',');
    let mime = arr[0].match(/:(.*?);/)[1];
    let bstr = atob(arr[1]);
    let n = bstr.length;
    let u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  },
  // 复制图片
  copyImage(dom, cb) {
    let dataurl = this.getBase64Image(dom);
    let blob = this.getBlobImage(dataurl);
    navigator.clipboard.write([
      new window.ClipboardItem({
        [blob.type]: blob
      })
    ]).then(function() {
      if (typeof cb === 'function') {
        cb();
      }
    }, function() {
      console.LOG('图片复制失败!');
    });
  }

以上就是vue实现复制文字复制图片实例详解的详细内容,更多关于vue复制文字图片的资料请关注脚本宝典其它相关文章!

脚本宝典总结

以上是脚本宝典为你收集整理的vue实现复制文字复制图片实例详解全部内容,希望文章能够帮你解决vue实现复制文字复制图片实例详解所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。