<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>录制</title> <script src="js/jquery.min.js"></script> </head> <body> <video src="" id="video"></video> <button id="rec">开始录制</button> <button id="camera">拍照</button> <!--canvs绘制--> <canvas width="640" height="480" id="outrec"></canvas> <!--base64绘制--> <img id="imgvideo" width="640" height="480" src="" /> <script type="text/javascript"> var video = document.getElementById("video"); //视频dom元素 //001.开启摄像头 $('#rec').click(function() { //视频获取 var Devicestate = navigator.mediaDevices.getUserMedia({ audio: true, video: true }) Devicestate.then(function(mediaStream) { video.src = window.URL.createObjectURL(mediaStream); console.log(mediaStream) video.onloadedmetadata = function(e) { video.play(); }; }); //用户拒绝使用,或者没有摄像头 Devicestate.catch(function(err) { console.log(err.name); }); }); //002.点击拍照按钮 $('#camera').click(function() { //视频转换到canvs var outrec = document.getElementById("outrec"); var outreccon = outrec.getContext("2d"); outreccon.drawImage(video, 0, 0, 640, 480); var img = outrec.toDataURL("image/jpeg", 0.5) $('#imgvideo').attr('src', img); }); </script> </body> </html>
需要注意参考w3c查看兼容性,另外谷歌浏览器只允许https网页调用