JS 利用 Canvas 截取视频第一帧

151 阅读1分钟
import React, { useRef, useState } from 'react';

export default function CoursePlay() {
    const [base64, setBase64] = useState('');
    const videoRef = useRef();
    const canvasRef = useRef();

    const handleFirstFrame = () => {
        console.log('handleFirstFrame');
        const ctx = canvasRef.current.getContext('2d');
        canvasRef.current.width = videoRef.current.videoWidth;
        canvasRef.current.height = videoRef.current.videoHeight;

        ctx.drawImage(videoRef.current, 0, 0, canvasRef.current.width, canvasRef.current.height);
        const base64 = canvasRef.current.toDataURL();
        setBase64(base64);
        console.log('🚀 ~ handleFirstFrame ~ base64:', base64);
    }

    return (
        <>
            <video
                ref={videoRef}
                muted
                autoPlay
                controls
                preload="auto"
                crossOrigin="anonymous"
                src="https://testvideoqn.feierlaiedu.com/kcschool/20221028085902_E6A281E88081E5B888E4B893E5B1.mp4"
                poster="https://qnunion.feierlaiedu.com/kcschool/20221228021453_1gifE69687E4BBB620-20E589AFE.gif"
                style={{ width: '100%', height: '59.2vw', objectFit: 'cover' }}
                onLoadedData={handleFirstFrame}
            />

            canvas:
            <canvas ref={canvasRef} style={{ width: '100%', height: '59.2vw' }} />

            image:
            <img src={base64} style={{ width: '100%' }} />
        </>
    );
}

注意:

  1. 在某些浏览器(例如 Chrome 70.0)中,如果没有设置 muted 属性,autoplay 将不会生效。
  2. 需要设置 crossorigin 属性,否则跨域的视频资源导出 base64 可能会失败。