In vue3, use html2canvas to screenshot the area containing videos, pictures, and text.

Requirement: Take a screenshot of the specified area on the page, which contains pictures, text, and videos.

The first step is to install

npm install html2canvas

The second step is to introduce on the page:

import html2canvas from 'html2canvas';

The third step, page usage:
1) HTML part:

<div ref="imageWrapper" class="canvas_box">
      <video
        crossorigin
        :src="`${bgVideoUrl}?_=${Date.now()}`"
        autoplay
        muted
        loop
      ></video>
      <img
        crossorigin="anonymous"
        :src="`${bgSrc}?_=${Date.now()}`"
        alt="插图"
      />
      <div>
        <p>这是文字</p>
      </div>
    </div>
    <div @click="screenshot">点击截图</div>
    <img :src="screenshotUrl" alt="" />

2) js part:

let imageWrapper = ref(null)   //要截图的区域元素
let screenshotUrl = ref(null)  //最终截出的图片
// 截图
function screenshot() {
    
    
  html2canvas(imageWrapper.value, {
    
    
    useCORS: true,// 使用跨域
  }).then((canvas) => {
    
    
    const imageDataURL = canvas.toDataURL('image/png');
    screenshotUrl.value = imageDataURL
    console.log(screenshotUrl.value)
  })
}

Notice

At first, the picture I cut out only had text, and the illustrations and videos were blank. I did not cut out the illustrations and videos on the page. In the end, I found out that it was cross-domain Caused by a>, the easiest way is of course to add a request header that supports cross-domain to the server.
But my pictures and videos are all taken from the Alibaba server and are oss links. Even after adding cross-domain support, it still doesn’t work.
I finally tried it, adding crossorigin to all videos and pictures, and adding random parameters after the accessed address to prevent the browser from caching the pictures, and then html2canvasAdd useCORS: true to the function and use span, so that the cut-out picture will be fine~
Insert image description here

Guess you like

Origin blog.csdn.net/qdm13209211861/article/details/134125253