H5调用摄像头
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7 <title>摄像头拍照</title> 8 </head> 9 <body> 10 <video id="video" width="480" height="320" controls> 11 </video> 12 <div> 13 <button id="capture">拍照</button> 14 </div> 15 <canvas id="canvas" width="480" height="320"></canvas> 16 <script> 17 //访问用户媒体设备的兼容方法 18 function getUserMedia(constraints, success, error) { 19 if (navigator.mediaDevices.getUserMedia) { 20 //最新的标准API 21 navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error); 22 } else if (navigator.webkitGetUserMedia) { 23 //webkit核心浏览器 24 navigator.webkitGetUserMedia(constraints,success, error) 25 } else if (navigator.mozGetUserMedia) { 26 //firfox浏览器 27 navigator.mozGetUserMedia(constraints, success, error); 28 } else if (navigator.getUserMedia) { 29 //旧版API 30 navigator.getUserMedia(constraints, success, error); 31 } 32 } 33 34 let video = document.getElementById('video'); 35 let canvas = document.getElementById('canvas'); 36 let context = canvas.getContext('2d'); 37 38 function success(stream) { 39 //兼容webkit核心浏览器 40 let CompatibleURL = window.URL || window.webkitURL; 41 //将视频流设置为video元素的源 42 console.log(stream); 43 44 //video.src = CompatibleURL.createObjectURL(stream); 45 video.srcObject = stream; 46 video.play(); 47 } 48 49 function error(error) { 50 console.log(`访问用户媒体设备失败${error.name}, ${error.message}`); 51 } 52 53 if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) { 54 //调用用户媒体设备, 访问摄像头 55 getUserMedia({video : {width: 480, height: 320}}, success, error); 56 } else { 57 alert('不支持访问用户媒体'); 58 } 59 60 document.getElementById('capture').addEventListener('click', function () { 61 context.drawImage(video, 0, 0, 480, 320); 62 }) 63 </script> 64 </body> 65 </html>
参考站:https://blog.csdn.net/c_kite/article/details/78536451