简体   繁体   中英

How to capture thumbnails (frame) from video with HTML5 and Jquery?

I have a simple block in which I would like to capture a frame from video every 5 seconds and display them something like this below.

在此处输入图片说明

Here is a solution I have tried.

<video id="video" controls="controls">
    <source src="http://www.w3schools.com/html/mov_bbb.mp4">
    </source>
</video>

<div id="time-ruler"></div>
<canvas id="canvas" width="300" height="300"></canvas>

<div id="thumbnailContainer"></div>

Here is javascript

video.addEventListener('loadeddata', function() {
    var duration = video.duration;
    var i = 0;

    var interval = setInterval(function() {
        video.currentTime = i;
        generateThumbnail(i);
        i = i+5;
        if (i > duration) clearInterval(interval);
    }, 300);
});

function generateThumbnail(i) {
    //generate thumbnail URL data
    var context = canvas.getContext('2d');
    context.drawImage(video, 0, 0, 220, 150);
    var dataURL = canvas.toDataURL();

    //create img
    var img = document.createElement('img');
    img.setAttribute('src', dataURL);

    //append img in container div
    document.getElementById('thumbnailContainer').appendChild(img);
}

Here is jsfiddle: live demo

Unfortunately, this is not working as expected.

What do I need to do to get what I want?

Check the following: https://jsfiddle.net/psbqn9d0/1/

It won't create the view you shown in the picture, but will change the thumbnail every 5 second. I have also added few logging to help you understand the code.

Now, if you want to achieve what is shown in figure then this is possible:-

  1. if you have loaded the video completely. Then create all the thumbnails and add them to the container.
  2. you create the thumbnails on the server and send them to user (like done by most video sites (so we can see what is in the video without loading!))
  3. OR you can create all the thumbnails without loading the whole video. I am not sure if this is the best way, but this will definitely work.

You should create another video tag with the same source link, and hide it using css. Then you will create a javascript function which will seek it to every 5th second programmatically and keep saving the thumbnails and adding them in your container. This way, your thumbnails will be generated for the whole video without loading the whole video.

I hope it clarifies your doubts!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM