当前位置: 首页 > Web前端 > HTML5

可以用浏览器打开手机摄像头

时间:2023-04-05 01:26:00 HTML5

可以切换前后摄像头,可以截取当前视频流图片兼容各大浏览器,主要使用的api://获取视频流导航器.mediaDevices.getUserMedia(constrains).then(success).catch(error);//获取设备摄像头信息navigator.mediaDevices.enumerateDevices().then(gotDevices).then(getStream).catch(handleError);之前在本机测试Chrome时出现问题,问题是没有Usehttpsasthetestlink。如果使用http,则项目无法打开摄像头。这可能与chrome的明文加密有关。如果使用http,代码会报NotSupportedErrorOnlysecureoriginsareallowed(see:https://goo.gl/Y0ZkNV)但是一开始并没有报这个错误。一开始我直接跑代码获取视频流。项目的代码好像停止运行了,相应位置的console.log也没有输出,也没有报这个错误。代码放在点击事件中,错误就出来了。.切换摄像头代码://多选框变化事件videoSelect.onchange=getStream;//获取设备音频输出设备和摄像头设备,这里我只使用摄像头设备函数gotDevices(deviceInfos){console.log('deviceInfos')console.log('deviceInfos:',deviceInfos);for(leti=0;i!==deviceInfos.length;i++){letdeviceInfo=deviceInfos[i];varoption=document.createElement('option');//console.log(deviceInfo)if(deviceInfo.kind==='videoinput'){//audiooutput,videoinputoption.value=deviceInfo.deviceId;option.text=deviceInfo.label||'相机'+(videoSelect.length+1);videoSelect.appendChild(选项);}}}兼容浏览器//访问用户媒体设备的兼容方法functiongetUserMedia(constrains,success,error){if(navigator.mediaDevices.getUserMedia){//最新标准APInavigator.mediaDevices.getUserMedia(constrains).then(success)).catch(错误);}elseif(navigator.webkitGetUserMedia){//webkit内核浏览器navigator.webkitGetUserMedia(constrains).then(成功).catch(错误);}elseif(navigator.mozGetUserMedia){//火狐浏览器navagator.mozGetUserMedia(constrains).then(success).catch(error);}elseif(navigator.getUserMedia){//旧版本APInavigator.getUserMedia(constrains).then(success).catch(error);}}获取视频流成功回调:getUserMedia||navigator.getUserMedia||navigator.webkitGetUserMedia||Cameraconstconstraints={audio:true,video:{width:{ideal:1280},height:{ideal:720},frameRate:{ideal:10,max:15},deviceId:{exact:videoSelect.value}}};console.log('获取视频流');getUserMedia(约束,成功,错误);}else{alert("您的浏览器不支持访问用户媒体设备");}}捕捉视频流为图片://注册相机按钮的点击事件document.getElementById("capture").addEventListener("click",function(){//画屏console.log('clickevent');context.drawImage(video,0,0,480,320);});来源地址

最新推荐
猜你喜欢