The basic idea is to draw the video on a canvas and use ittoDataURLExport Base64 format, assign SRC to image for image preview, click download Put Base64 into href attribute of A tag and simulate click to download

<video src="1.mp4" id="video" controls width="300"></video>
<img src="" alt="" id="image" width="300">
<button id="shot">screenshots</button>
<button id="download">download</button>
Copy the code

A video player, a preview area, a screenshot button, and a download button

const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const video = document.querySelector('#video');
const image = document.querySelector('#image');
const shot = document.querySelector('#shot');
const download = document.querySelector('#download');
let url = ' ';
Copy the code

Create a Canvas and get a reference to the DOM in the page

video.addEventListener('loadedmetadata'.function (e) {
  canvas.width = this.videoWidth;
  canvas.height = this.videoHeight;
});
Copy the code

Set the width and height of the canvas after the video is loaded

shot.addEventListener('click'.function () {
  ctx.drawImage(video, 0.0);
  url = canvas.toDataURL('image/jpg');
  image.src = url;
});
Copy the code

Click the Screenshot button and draw the video on the Canvas, then take the dataURL and assign it to the SRC of the image

download.addEventListener('click'.function () {
  const a = document.createElement('a');
  const event = new MouseEvent('click');
  a.download = 'screen_shot';
  a.href = url;
  a.dispatchEvent(event);
});
Copy the code

Finally, create an A tag, assign the url to href, create a click event and simulate the click event for download

Download successful