Canvas .drawImage() 函数未绘制请求的视频缩略图

Canvas .drawImage() function doesn't draw the requested thumbnail of a video

我正在尝试创建一个功能,将视频中的特定时间范围显示为图像。该函数接受 2 个输入,即视频路径,以及 特定秒 ,其中应显示时间范围。

<!DOCTYPE html>
<html>
<body>

<div id="imageDiv" width="350" height="200"
style="border:1px solid #c3c3c3;">
</div>

<video id="myVideo" width="320" height="176" controls>
</video>

<script type="text/javascript">

// src will be the path to the video
// sec will be the second we want to display from the video

function dispImg(src, sec) {

    var video = document.getElementById("myVideo");
    video.src = src;
    video.type = "video/mp4";
    video.currentTime = sec;

    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    ctx.drawImage(video, 0, 0, 350, 200);
    document.getElementById("imageDiv").appendChild(canvas);
}

dispImg("sample.mp4", 10)
</script>
</body>
</html>

根据我当前的代码,我希望视频部分 (id="myVideo") 中显示的缩略图也绘制在 div 部分 (id="imageDiv") 中。不幸的是,情况并非如此,因为它在 div 部分是全白的。

对我的问题有什么建议吗?感谢您的任何反馈!

可能是视频加载不够远,或者在您拨打电话时视频尚未完成搜索 drawImage

如果这是原因,您可以等待事件触发,如下所示:

function dispImg(src, sec) {

    var video = document.getElementById("myVideo");
    video.src = src;
    video.type = "video/mp4";

    // For more events, see:
    // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#events
    video.addEventListener('seeked', (event) => {
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        ctx.drawImage(video, 0, 0, 350, 200);
        document.getElementById("imageDiv").appendChild(canvas);
    });
    // After creating the event handler, change the position of the video.
    video.currentTime = sec;
}

我觉得当你使用seeked事件时,你不需要等待canplaythrough.

等事件

你可能想看这个例子JSFiddle Timeline by kmturley

function createImage() {
    var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d');
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
    timeline.appendChild(canvas);
}