Javascript: Copy a video frame and turn it into an image


/ Published in: JavaScript
Save to your folder(s)

Very cool example of copying a frame from an MP4 and displaying it on the canvas or image. In order for images to be saved, the video must come from the same domain


Copy this code and paste it in your HTML
  1. <html>
  2. <head>
  3. <title>JS and HTML5 Rule</title>
  4. <script type='text/javascript'>
  5.  
  6. window.onload = function (){
  7.  
  8. var video = document.getElementById('my_video');
  9. var thecanvas = document.getElementById('thecanvas');
  10. var img = document.getElementById('thumbnail_img');
  11.  
  12.  
  13. video.addEventListener('pause', function(){
  14.  
  15. draw( video, thecanvas, img);
  16.  
  17. }, false);
  18.  
  19. };
  20.  
  21.  
  22. function draw( video, thecanvas, img ){
  23.  
  24. // get the canvas context for drawing
  25. var context = thecanvas.getContext('2d');
  26.  
  27. // draw the video contents into the canvas x, y, width, height
  28. context.drawImage( video, 0, 0, thecanvas.width, thecanvas.height);
  29.  
  30. // get the image data from the canvas object
  31. var dataURL = thecanvas.toDataURL();
  32.  
  33. // set the source of the img tag
  34. img.setAttribute('src', dataURL);
  35.  
  36. }
  37. </script>
  38. </head>
  39. <body>
  40. The Video
  41. <br />
  42. <video id="my_video" controls>
  43. <source src="http://jamesbaca.net/slides/source_code/html5_andJSThumbs/VeryMaryKate.mp4" type="video/mp4" />
  44. </video>
  45. <br />
  46. The Canvas
  47. <br />
  48. <canvas id="thecanvas">
  49. </canvas>
  50. <br />
  51. The Image
  52. <br />
  53. <img id="thumbnail_img" alt="Right click to save" />
  54. <br />
  55. </body>
  56. </html>

URL: http://jamesbaca.net/slides/source_code/html5_andJSThumbs/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.