1. First get the video element and create the canvas
1
2
3
|
const video = document.getElementById( 'video' ); const canvas = document.createElement( "canvas" ); const canvasCtx = canvas.getContext( "2d" ) |
2. Pixel size and optimization of screenshots
devicePixelRatio can return the ratio of the physical pixel resolution of the current display device to the CSS pixel resolution, which can better restore the real video scene. Please refer to the official website for details.
1
2
|
const ratio = window.devicePixelRatio || 1; canvasCtx.scale(ratio, ratio); |
3. Process the canvas canvas
// The canvas size is the same as the image size, and the screenshot has no extra canvas.width = video.offsetWidth * ratio; canvas.height = video.offsetHeight * ratio;
4. Generate canvas and convert it into the format you need. I will convert it directly to base64 here.
canvasCtx.drawImage(video, 0, 0 , canvas.width, canvas.height) const imgBase64 = canvas.toDataURL("image/png");