Vue uses html2canvas to achieve one-click screenshots and assigns them to the clipboard, only intercepting the visible content on the current display

Use html2canvasand clipboard APIto take a full page screenshot and fill it to the clipboard.

The API for accessing the clipboard is only supported on https or localhost, if it is http, it cannot be used
First you need to install html2canvas from npm

npm install html2canvas

Then import this package in your code:

import html2canvas from 'html2canvas'

Then bind a button to achieve this function, such as clicking a button, and then start to screenshot the current page and assign it to the clipboard.

    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.')
      }
    },

Explanation of the above code: document.getElementsByClassName('app-wrapper')[0]it is to obtain the elements that need to be screenshotted currently. If you want to capture all elements of the entire page, you can use the following code:

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

while for the following

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

x indicates the height from which the screenshot is taken, y indicates the width from which the screenshot is taken, height indicates the height of the screenshot, and width indicates the width of the screenshot.
If not written, the default is to intercept the entire element.
As shown in the picture, if I don’t write it, the intercepted content will be very long, because the page has a scroll bar, and all the content will be intercepted.
insert image description here
After writing, the width and height are limited, and only the content of this page that can be seen on the current display is displayed, without intercepting other invisible parts of the scroll bar.

Guess you like

Origin blog.csdn.net/changyana/article/details/131635674