js_调用摄像头,拍照功能
注意点,http情况下,是不支持调用摄像头的,因为在http的情况下,navigator.mediaDevices为undefind。
以下三种情况是可以打开摄像头的:
-
1、localhost 域
-
2、开启了 HTTPS 的域
-
3、使用 file:/// 协议打开的本地文件(难怪我特么本地直接开也能用!)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>摄像头拍照</title> </head> <body> <video id="video" width="480" height="320" controls></video> <div> <button id="capture">拍照</button> <button id="open">开启</button> <button id="close">关闭</button> </div> <canvas id="canvas" width="480" height="320"></canvas> <script> //访问用户媒体设备的兼容方法 function getUserMedia(constraints, success, error) { if (navigator.mediaDevices.getUserMedia) { //最新的标准API navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error); } else if (navigator.webkitGetUserMedia) { //webkit核心浏览器 navigator.webkitGetUserMedia(constraints, success, error) } else if (navigator.mozGetUserMedia) { //firfox浏览器 navigator.mozGetUserMedia(constraints, success, error); } else if (navigator.getUserMedia) { //旧版API navigator.getUserMedia(constraints, success, error); } } let video = document.getElementById('video'); let canvas = document.getElementById('canvas'); let context = canvas.getContext('2d'); function success(stream) { //兼容webkit核心浏览器 let CompatibleURL = window.URL || window.webkitURL; //将视频流设置为video元素的源 console.log(stream); //video.src = CompatibleURL.createObjectURL(stream); video.srcObject = stream; video.play(); } function error(error) { console.log(`访问用户媒体设备失败${error.name}, ${error.message}`); } if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator .mozGetUserMedia) { //调用用户媒体设备, 访问摄像头 getUserMedia({ video: { width: 480, height: 320 } }, success, error); } else { alert('不支持访问用户媒体'); } // 点击拍照 document.getElementById('capture').addEventListener('click', function () { context.drawImage(video, 0, 0, 480, 320); console.log(canvas.toDataURL("image/png")) }) // 点击开启 document.getElementById('open').addEventListener('click', function () { // getUserMedia({ // video: { // width: 480, // height: 320 // } // }, success, error); }) // 点击关闭 document.getElementById('close').addEventListener('click', function () { video.srcObject.getTracks()[0].stop() }) // canvas转图片 // function convertCanvasToImage(canvas) { // var image = new Image(); // image.src = canvas.toDataURL("image/png"); // return image; // } </script> </body> </html>
“世界是个叙述者, 而我们却蒙上黑布, 嗤之以鼻。”