First, use local canvas interception

After uploading a video to a web page, it would be better if we could set up a cover image for the video, but if we use the default implementation of the video tag, some browsers will show the first frame of the video, and some browsers won’t show it at all.

By creating a Canvas tag and using its context.drawImage() method to draw the video on the canvas, then using canvas.todataURL method to convert the image on the canvas to base64 format, The BASE64 URL is used as the poster attribute of the video tag. ToDataURL has a cross-domain problem that requires special processing, consistent with the cross-domain processing of images.

Note:

  • Canvas cannot operate cross-domain pictures, so cross-domain problems need to be dealt with in advance.
  • Safari has some temporary problems and can only capture the first frame.
/** * Get the cover image of the video *@param Url Video address *@param The second number of seconds * /
async function getVideoBase64(url: string, second: number = 0) {
  const video = document.createElement('video');
  video.setAttribute('crossOrigin'.'anonymous'); // Handle cross-domain
  video.setAttribute('src', url);
  // Mute operation to prevent playback failure
  video.setAttribute('muted'.'muted');
  video.addEventListener('loadeddata'.async() = > {const canvas = document.createElement('canvas');
    const { width, height } = video; // Canvas has the same size as the image
    canvas.width = width;
    canvas.height = height;

    if (second) {
      video.currentTime = second;
      // Play to the current time frame, to capture the current screen
      await video.play();
      await video.pause();
    }

    canvas.getContext('2d')? .drawImage(video,0.0, width, height);
    return canvas.toDataURL('image/jpeg');
  });
}
Copy the code

Second, use Ali Cloud OSS to capture videos

Used to describe

Using Ali OSS, we can achieve the specified frame screenshots based on OSS built-in functions, and then use an IMG tag to display the cover, the effect is better;

Matters needing attention

1. When using video truncated frame, charge according to the number of pictures captured by video truncated frame. For more information on billing details, see Data Processing Fees. 2. Currently, only H264 video files can be captured. 3. The OSS does not provide the operation of saving video frames by default. Images of video frames must be manually downloaded to the local PC.

The main parameters

X-oss-process =video/snapshot,t_1,f_jpg,w_0,h_0,m_fast Internal parameter names and values are separated by downconversion lines, for example,t_1 indicates that the time is the first millisecond

Capture instance

https://s2.codooncdn.com/course-platform/1c5a1bc3-0439-4d66-bde8-d80b68a2af12/2020-12-21T14.16.12/1592951xWLD5xfNd0t2fE4 g6sBmp4?x-oss-process=video/snapshot,t_1,f_jpg,w_0,h_0,m_fastCopy the code

Reference: Ali Cloud Help center – video frame