JavaScrip gets the first frame of the video as the cover image

In JavaScript, you can use the HTML5 <video> element to load the video, and then use Canvas to capture the first frame of the video as the cover image. Here is a simple example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Video Thumbnail</title>
</head>
<body>

<video id="myVideo" width="320" height="240" controls>
    <source src="your-video.mp4" type="video/mp4">
    Your browser does not support the video tag.
</video>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 获取 video 元素
        var video = document.getElementById('myVideo');

        // 监听 video 的 loadeddata 事件
        video.addEventListener('loadeddata', function() {
            // 创建一个 Canvas 元素
            var canvas = document.createElement('canvas');
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;

            // 获取 2D 上下文
            var context = canvas.getContext('2d');

            // 在 Canvas 上绘制视频的第一帧
            context.drawImage(video, 0, 0, canvas.width, canvas.height);

            // 将 Canvas 转换为 data URL
            var dataURL = canvas.toDataURL('image/jpeg');

            // 创建一个图片元素用于显示封面图
            var img = document.createElement('img');
            img.src = dataURL;

            // 将图片元素添加到页面
            document.body.appendChild(img);
        });
    });
</script>

</body>
</html>

Please note that this example uses the loadeddata event, which is triggered after the first frame of the video has been loaded. A Canvas element is created here, the first frame of the video is drawn on the Canvas through the drawImage method, and then the Canvas is converted into a data URL. Finally, create an image element to display the cover image and add it to the page.

Replace "your-video.mp4" in the code with your actual video file path. This code works on modern browsers that support HTML5.

Guess you like

Origin blog.csdn.net/m0_52537869/article/details/134472309