【转载】用原生JS和html5进行视频截图并保存到本地
支持并尊重原创!原文地址:http://www.cnblogs.com/xieshuxin/p/6731637.html
1 <!doctype html> 2 3 <html> 4 <head> 5 <meta charset="utf-8"> 6 <title>Video视频截图</title> 7 <style> 8 body, h1, h2, p { margin:0; padding:0; } 9 html { font-family:"微软雅黑"; } 10 h1 { font-size:24px; font-weight:normal; padding:20px 0; text-align:center; color:#858585; background:-webkit-linear-gradient(rgba(0, 186, 255, .8), rgba(0, 130, 255, .8)); border-bottom:1px solid #009cff; color:#FFF; margin-bottom:50px; } 11 video { display:block; margin:0 auto 30px auto; } 12 canvas { display:none; } 13 button { display:block; width:480px; height:50px; font-size:24px; margin:0 auto; border:1px solid #0085ff; color:#FFF; background:-webkit-linear-gradient(rgba(80, 170, 255, .8), rgba(0, 132, 255, .8)); cursor:pointer; border-radius:5px; margin-bottom:30px; } 14 button:hover { background:-webkit-linear-gradient(rgba(0, 132, 255, .8), rgba(80, 170, 255, .8)); border-color:#1988ff; } 15 h2, p { width:480px; margin:0 auto; color:#858585; } 16 h2 { margin-bottom:1em; font-size:18px; } 17 p { font-size:14px; line-height:24px; } 18 </style> 19 <script> 20 window.onload = function () { 21 var button = document.querySelectorAll('.screen')[0]; 22 var video = document.querySelectorAll('video')[0]; 23 var canvas = document.querySelectorAll('canvas')[0]; 24 var ctx = canvas.getContext('2d'); 25 var width = 480; 26 var height = 270; 27 28 canvas.width = width; 29 canvas.height = height; 30 video.src = 'movie.mp4?t=' + new Date().getTime(); 31 video.width = width; 32 video.height = height; 33 video.autoplay = true; 34 video.loop = true; 35 button.onclick = function () { 36 ctx.drawImage(video, 0, 0, width, height); // 将video中的数据绘制到canvas里 37 saveImage(canvas, 'screen_' + new Date().getTime() + '.png'); // 存储图片到本地 38 }; 39 }; 40 function saveImage (canvas, filename) { 41 var image = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream'); 42 saveFile(image, filename || 'file_' + new Date().getTime() + '.png'); 43 } 44 function saveFile(data, filename) { 45 save_link.href = data; 46 save_link.download = filename; 47 48 var event = document.createEvent('MouseEvents'); 49 event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); 50 save_link.dispatchEvent(event); 51 } 52 </script> 53 </head> 54 <body> 55 <h1>Video视频截图</h1> 56 <video>仅支持H264格式MP4</video> 57 <canvas></canvas> 58 <button class="screen">截图</button> 59 <h2>当前,video 元素支持三种视频格式:</h2> 60 <p>Ogg = 带有 Theora 视频编码和 Vorbis 音频编码的 Ogg 文件</p> 61 <p>MPEG4 = 带有 H.264 视频编码和 AAC 音频编码的 MPEG 4 文件</p> 62 <p>WebM = 带有 VP8 视频编码和 Vorbis 音频编码的 WebM 文件</p> 63 </body> 64 </html>