vue使用html2canvas实现一键截图并赋值到剪贴板,只截取当前显示器上可视的内容

使用html2canvasclipboard API实现整页截图并填充至剪切板。

访问剪切板的api只支持在https或者本地localhost上使用,如果是http,则无法使用
首先需要从npm安装html2canvas

npm install html2canvas

然后在代码中导入这个包:

import html2canvas from 'html2canvas'

之后绑定一个按钮来实现该功能,比如点击一个按钮,然后就开始截图当前页面并赋值到剪贴板。

    to_clipboard() {
    
    
      if (window.ClipboardItem) {
    
    
        html2canvas(document.getElementsByClassName('app-wrapper')[0], {
    
    
          x: window.scrollX,
          y: window.scrollY,
          height: window.innerHeight,
          width: window.innerWidth
        }).then(canvas => {
    
    
          // 将canvas转换为blob类型
          canvas.toBlob(blob => {
    
    
            // 创建一个图像剪贴板项
            const item = new window.ClipboardItem({
    
     'image/png': blob })
            // 使用Clipboard API将图片写入剪贴板
            navigator.clipboard.write([item]).then(() => {
    
    
              this.$message.success('Screenshot copied to clipboard')
            }).catch(error => {
    
    
              this.$message.error('Failed to copy screenshot to clipboard: ', error)
            })
          })
        })
      } else {
    
    
        this.$message.error('This browser does not support ClipboardItem.')
      }
    },

上述代码解释:document.getElementsByClassName('app-wrapper')[0]是获取当前需要截图的元素,如果想截取整个页面所有元素,可以使用如下代码:

// 获取要截图的元素(这里以body为例)
const element = document.body;
html2canvas(element).then(canvas => {
    
    

而对于下方的

x: window.scrollX,
y: window.scrollY,
height: window.innerHeight,
width: window.innerWidth

x表示的是从哪个高度开始截屏,y表示从哪个宽度开始截屏,height表示截取多高,width表示截取多宽。
如果不写的话,默认就是截取整个元素。
如图,我如果不写的话,截取的内容就特别长,因为该页面有滚动条,会把所有的内容都截下来。
在这里插入图片描述
写了之后,限制了宽高,就只展示当前显示器上所能看到的这一页内容,而不截取滚动条其它看不见的部分。

猜你喜欢

转载自blog.csdn.net/changyana/article/details/131635674