HTML5视频和画布

时间:2015-11-03 09:15:57

标签: html5-canvas html5-video

我有一个视频,我需要在不同时间从中捕获3张图像。时间不是随机的,我必须在指定时间拍摄图像(13:10:02,13:10:03,13:10:04)。当我访问页面时,图像应该显示在页面上,而不是当我单击按钮或类似的东西时。 到目前为止,我尝试了一个我在互联网上找到的例子,但在这个例子中,图像在点击一个按钮后显示,我不知道如何给出指定的时间。

<video controls>
    <source src="http://www.jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v" type="video/mp4"></source>
    <source src="http://www.jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v" type="video/mp4"></source>
</video>
<canvas id="canvas" width="640" height="480"></canvas>
<button id="snap" onclick="snap()">Snap Photo</button>

<script>
    var video=document.querySelector('video');
    var canvas=document.querySelector('canvas');
    var context=canvas.getContext('2d');
    var w,h,ratio;
    //add loadedmetadata which will helps to identify video attributes......
    video.addEventListener('loadedmetadata',function()
    {
        ratio=video.videoWidth/video.videoHeight;
        w=video.videoWidth-100;
        h=parseInt(w/ratio,10);
        canvas.width=w;
        canvas.height=h;
    },false);
    ///define a function

    function snap()
    {
        context.fillRect(0,0,w,h);
        context.drawImage(video,0,0,w,h);
    }
</script>

1 个答案:

答案 0 :(得分:1)

您可以通过在视频对象上设置currentTime来设置要绘制到画布的帧的时间。
然后你需要等待视频完成搜索,将视频绘制到画布上移动到下一帧 当然,在开始绘制帧之前,您需要等待视频加载。

var images = [ // defined canvases and times for frames
    {
        canvas: '#canvas1',
        time: 10.0 // in seconds
    },
    {
        canvas: '#canvas2',
        time: 19.0
    },
    {
        canvas: '#canvas3',
        time: 26.0
    },
];

function drawFrame(video, time, canvas, callback)
{
    var context = canvas.getContext("2d");
    video.addEventListener("seeked", function(e) {
        e.target.removeEventListener(e.type, arguments.callee); // remove the handler or else it will draw another frame on the same canvas, when the next seek happens
        context.fillRect(0, 0, canvas.width, canvas.height);
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        callback();
    });
    video.currentTime = time;
}
function draw(video, images, i)
{
    if (i >= images.length)
        return;
    drawFrame(video, images[i].time, images[i].canvas, function() {
        draw(video, images, i+1);
    });
}
var video = document.createElement('video');
video.addEventListener('loadedmetadata', function() // when the metadata is loaded set the canvases size and start drawing frames
{
    var ratio = video.videoWidth / video.videoHeight;
    var w = video.videoWidth - 100; // set the width of the images to 100 px less than the video
    var h = w / ratio; // fix the height accordingly
    for (var i=0; i<images.length; i++)
    {
        images[i].canvas = document.querySelector(images[i].canvas);

        images[i].canvas.width = w;
        images[i].canvas.height = h;
    }

    draw(video, images, 0);
});
video.src = "http://www.jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v";

JSFiddle