Use the html2canvas library to realize the function of web page screenshot

Record that the vue project uses the html2canvas library to realize the function of web page screenshots, reducing future references and detours. The purpose is to record, please advise me if there are any deficiencies.

1. Install the html2canvas library

npm install html2canvas --save

2. Introduce the html2canvas library into the Vue component that needs screenshots:

import html2canvas from 'html2canvas'

3. Realize screenshot function

Add a canvas element to the HTML structure part that needs to be screenshotted, and give it a class/ref/id, and you will be able to get the DOM node later:

<template>
  <div>
    <button @click="capture">截图</button>
    <canvas class="canvas">
    <!-- 需要截图的部分 -->
    ...
    </canvas>
  </div>
</template>

Define a method by yourself, use the html2canvas library to convert the element that needs to be screenshot into a Canvas, and draw the generated image on the canvas element:

    // 使用 html2canvas 库将需要截图的元素转换为 Canvas,
    // 并将生成的图片绘制到 canvas 元素上
    capture() {
    
    
      // 获取需要截图的元素,这里选择了canvas部分
      const targetElement = document.querySelector('.canvas');
      // 使用html2canvas生成截图,并将结果保存到变量screenshot中
      html2canvas(targetElement, {
    
    
        useCORS: true, // 使用跨域资源共享(CORS)
	    scrollX: 0, // 截图时x轴滚动条的位置
	    scrollY: -window.scrollY // 截图时y轴滚动条的位置
      }).then(canvas => {
    
    
      // 将截图转为png格式的base64编码,并保存到screenshot变量中
        this.screenshot = canvas.toDataURL('image/png');
        // 将截图转为blob对象,并保存到screenshotBlob变量中
        this.screenshotBlob = canvas.toBlob((blob)=>{
    
    
            this.screenshotBlob=blob;
            this.upload()//这里将截图转为blob对象,并保存到screenshotBlob变量中,并通过回调函数在控制台输出blob对象并上传至服务器
        });
      })
    },

**Note:** To upload the screenshot to the server, you need to convert the screenshot into a blob object, and add the following types of request headers

headers: {
    
     'Content-Type': 'multipart/form-data;'}

4. Effect picture:

html2canvas screenshot

Guess you like

Origin blog.csdn.net/lFFFFFFl/article/details/129185872