Search code examples
javascripthtmlvideohtml5-video

Capturing Video Frame and then Exporting as Bitmap in HTML5


I have a web application where I play back video.

I am considering using the HTML5 <video> element and have determined it will allow me to meet all of my requirements except one: allowing the user to take a snapshot of the current video frame and save it as a raster image format (i.e. JPG).

For this requirement I have not found a solution, and any guidance on this matter would be greatly appreciated.

To help answer the question here are more details. I will download the video files from a server via HTTP and then play them back in the browser. This will not be a video stream, but instead a download with playback starting after the file has been received. The video will be in the MP4 format.

The solution only needs to run in IE 9. (Although naturally I would like the solution to be as cross-browser/platform as possible.)


Solution

  • Capture the image to a canvas element:

    var video  = document.getElementById(videoId);
    var canvas = document.createElement('canvas');
    canvas.width  = video.videoWidth;
    canvas.height = video.videoHeight;
    var ctx = canvas.getContext('2d');
    ctx.drawImage(video, 0, 0);
    

    Then use the toDataURL() method to get the image:

    canvas.toDataURL('image/jpeg');
    

    Be aware that for all this to work the video has to be from the same origin as the page.