又是好一阵忙碌,终于迎来短暂的闲暇,忙里偷闲写了这篇文章。
最近项目中使用到了摄像头扫码、拍照,因为是web项目,不能直接使用java调用摄像头,更不能写个插件让客户去安装,唯一的方法只能使用js去调用摄像头,由此记录下自己的实现。
开始准备使用网上现成的js插件(webcam.js),但是项目中同时接入了高拍仪,高拍仪实际也是摄像头,当摄像头存在2个或以上时,调用就会不正常,不调用应该调用的摄像头。查询了插件的相关文档,没有在插件中找到指定摄像头的api,遂自己DIY了一个插件(webvideo.js)。水平有限、如发现问题请留言。下面是相关API和压缩后的js代码,完整代码可以在这里下载。
WebVideo.open(obj)
打开摄像头,obj为js对象,不传使用默认值,如下:
{
width: 600,//窗口宽度
height: 450,//窗口高度
scale: 1,//照片比例,默认与视频大小相同
imgType: “png”,//照片格式,默认为png
deviceLabel: “HIK”,//摄像头品牌,默认为海康
isScan: true,//扫码或拍照,默认为扫码
dom: null,//摄像头窗口父元素,默认为body
videoBox:{}//摄像头相关,自定义可传入video(视频),closeBtn(关闭按钮),clickBtn(拍照按钮),startBtn(录像开始按钮),stopBtn(录像结束按钮),根据需要选择传入。
}
默认效果如下:
WebVideo.getPic()
立即获取一张base64的照片。
WebVideo.takePic(callback)
点击拍照按钮拍照,callback参数为base64图片。
WebVideo.downloadPic(base64, imgName)
下载图片,可与WebVideo.getPic()或WebVideo.takePic(callback)联合使用。
WebVideo.scanQRCode(callback,timer)
扫描二维码,callback参数为base64图片,timer为扫码间隔(毫秒),扫码成功后callback中return true结束扫码。
WebVideo.recordVideo(callback)
录制视频,callback参数为blob格式数据,默认为单按钮操作,点击一次为开始录像,再次点击为录像结束。
WebVideo.downloadVideo(blob, fileName)
下载视频,可与WebVideo.recordVideo()联合使用。
WebVideo.blobTofile(blob, fileName)
blob转file。
WebVideo.getStream()
获取视频流。
WebVideo.close()
手动关闭窗口。
WebVideo.closeListner(callback)
窗口关闭监听,callback无参数。
(function(g){var b={width:600,height:450,scale:1,imgType:"png",deviceLabel:"HIK",isScan:!0,dom:null,videoBox:{}},k={open:function(c){b.dom=document.body;c?(Object.assign(b,c),c.videoBox||m()):m();var a={audio:!1,video:{deviceId:void 0,width:b.width*2,height:b.height*2}};navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices?navigator.mediaDevices.enumerateDevices().then(function(d){var e;d.forEach(function(f){"videoinput"==f.kind&&-1!=f.label.indexOf(b.deviceLabel)&&(e=f.deviceId,console.log("\u8c03\u7528\u6444\u50cf\u5934id\uff1a"+
f.deviceId));console.log(f.kind+","+f.label+","+f.deviceId)});a.video.deviceId=e;n(a)}).catch(function(d){console.log(d.name+": "+d.message)}):n(a)},getPic:function(){var c=document.createElement("canvas");c.width=b.videoBox.video.videoWidth*b.scale;c.height=b.videoBox.video.videoHeight*b.scale;c.getContext("2d").drawImage(b.videoBox.video,0,0,c.width,c.height);return c.toDataURL("image/"+b.imgType)},takePic:function(c){b.videoBox.clickBtn.addEventListener("click",function(){c(k.getPic())},!1)},downloadPic:function(c,
a){var d=document.createElement("a");d.href=c;d.download=a?a+"."+b.imgType:(new Date).getTime()+"."+b.imgType;b.dom.appendChild(d);d.click();d.remove()},scanQRCode:function(c,a){p(c,a)},recordVideo:function(c){var a,d=!1;if(b.videoBox.startBtn&&b.videoBox.stopBtn)b.videoBox.startBtn.addEventListener("click",function(){d||(a=q(c),d=!0);a.start();h("\u5f55\u5236\u5f00\u59cb")},!1),b.videoBox.stopBtn.addEventListener("click",function(){a.stop();h("\u5f55\u5236\u7ed3\u675f")},!1);else{var e=!0;b.videoBox.clickBtn.addEventListener("click",
function(){e?(d||(a=q(c),d=!0),a.start(),e=!1,h("\u5f55\u5236\u5f00\u59cb")):(a.stop(),e=!0,h("\u5f55\u5236\u7ed3\u675f"))},!1)}},getStream:function(){return b.stream},downloadVideo:function(c,a){var d=document.createElement("a");d.href=g.URL.createObjectURL(c);d.download=a?a+".mp4":(new Date).getTime()+".mp4";b.dom.appendChild(d);d.click();g.URL.revokeObjectURL(d.href);d.remove()},blobTofile:function(c,a){return new File([c],a?a+".mp4":(new Date).getTime()+".mp4")},close:function(){b.videoBox.closeBtn.click()},
closeListner:function(c){b.videoBox.closeBtn.addEventListener("click",function(){c&&c()},!1)}},p=function(c,a){setTimeout(function(){var d=k.getPic();c(d)||p(c,a)},a)},q=function(c){var a=new MediaRecorder(b.stream,{audioBitsPerSecond:128E3,videoBitsPerSecond:25E5,mimeType:"video/webm"});a.ondataavailable=function(d){console.log("# ondataavailable, size = "+parseInt(d.data.size/1024)+"KB");var e=[];e.push(d.data);c&&c(new Blob(e,{mineType:"video/mp4"}))};return a},n=function(c){void 0===navigator.mediaDevices&&
(navigator.mediaDevices={});void 0===navigator.mediaDevices.getUserMedia&&(navigator.mediaDevices.getUserMedia=function(a){var d=navigator.webkitGetUserMedia||navigator.mozGetUserMedia;return d?new Promise(function(e,f){d.call(navigator,a,e,f)}):Promise.reject(Error("getUserMedia is not implemented in this browser"))});navigator.mediaDevices.getUserMedia(c).then(function(a){b.stream=a;"srcObject"in b.videoBox.video?(b.videoBox.video.srcObject=a,l(function(){a.getTracks()[0].stop()})):(b.videoBox.video.src=
g.URL.createObjectURL(a),l(function(){g.URL.revokeObjectURL(b.videoBox.video.src);a.stop()}));b.videoBox.video.onloadedmetadata=function(){b.videoBox.video.play()}}).catch(function(a){h("\u8fde\u63a5\u8bbe\u5907\u5931\u8d25");l();console.log(a.name+": "+a.message)})},m=function(){if(0===Object.keys(b.videoBox).length){var c=document.createElement("div");c.style.cssText="position: absolute;width: "+(b.width-32)+"px;height: "+(b.height-56)+"px;top: 50%;left: 50%;margin-top: "+-b.height/2+"px;margin-left: "+
-b.width/2+"px;box-sizing: content-box;border:16px solid #5bc0de;border-top: 40px solid #5bc0de;z-index: 999;font-size: 20px;border-radius: 15px;";var a=document.createElement("a");a.text="\u5173\u95ed";a.style.cssText="position: absolute;top: -35px;right: 0;color: #fff;cursor: pointer;";var d=document.createElement("video");d.style.cssText="width: "+(b.width-32)+"px;height: "+(b.height-56)+"px;background-color: #999; object-fit: fill;";c.appendChild(a);c.appendChild(d);b.dom.appendChild(c);b.videoBox.div=
c;b.videoBox.closeBtn=a;b.videoBox.video=d;b.isScan||(a=document.createElement("img"),a.style.cssText="position: absolute;width:100px;height:100px;bottom: 30px;left:"+(b.width/2-50)+"px;",a.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAG4AAABqCAYAAABdymTtAAAUv0lEQVR4Xu1dC3RWVXb+QpI/7ycJeY0PAlQy5IWAiAhkEHnYKQFsqaOggIq2MguXHZbLTgu0TGspdY3OjIzSSi04zCwyUxEHKbUBNJbHSAwx4REgjBkIIRCSPy/+PEnXd/1venLzP+69/7l/HrjXyuKRc8/Z53xnn7PP3vvsE4ChSWEAIgEsB/A4gEkGu1EC4BcAdgBoAeAw+P2AFw8YcA68MxDoBOYHAP7Me3GfShQA+BcAxQC6farJ4o8HK3BxAP4GwIsARlg8Bu6qvwXgpwA2AbgxQDy4bXawAfd3ANYB4FLoiU4D2AfgfwHw7+cNDuwYABMATAPwXQCZXr7vAPDPAP7WYDuWFR8MwI0HUAgg1UMv/w3AmwC+BEBJsIIo2VkA/gLAcx4aqAEwF0C5FUzorXMggZsO4GMP0vUEAO45nXo7I7lcMIAlAH7lpt42AH8M4KDkdnVVNxDAzQPwXy64ozJAqVqri3P/F3rNyRuVJS3lA9jrT5b8CVwagIsAbJoO2gHMBkAVfShQDoBDAKhAicSVgXvnJX90wh/AESh29AFNhwgi94pKf3TUgjbudi71YzV1fw5gBoB2C9rsrdJq4P7UuU+JfaBykQ3glJUd82PdVK7KAARp2lzmPORbwoqVwB0DMFXD9SoA/25JTwa+UipT72nYOAFgihWsWQFcLIBrAKiVqcTlg0tllxWdGER1UnH5VLMtcO/7lnNMpLEqGziqz7/RcDcTQJE0jodGRVxpuOKIRJvqL2WxLxM4WhZo9VCpGUC0LEaHaD3UmGME3n8G4Psy+iILOKryuQJDewAslsHgMKiDB/g/F/pxFkCGr/2SAdx1AAkCIy877Xq+8jacvqex/MdCh2i0Fsf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AxdfTHH7SpXensgAjm2JGWb5718CcH89VC93w6OceMtG3WJM54BRh0QWcKzvpwCYz1kl5sAc9pnPvcwt7Wok7fUUmcCxD5SyX2g6Q+OpP56pHEzyyXTG2rOg1OfcZAPHwaN2SaVFvH9Q5ExoKiuWfjCBJPJCYzHPZLzlqxJjR5inSupZ1wrgVIZpLtLGz0vLQDsIkXsUwK81fFHqZL9BoDRhJXCsnwGczEArEmdghuYdn0GIg26WGMrIiy3aS/p8CUx9K0B3ZXoLWg0c+WCwCy/ya6WPnX3Yuazq5XcwlaOpj8viBA1TdMvwzGap+cwfwKn9olmHr2VpTVP0Jk+XdTvID8iOc05EbZQa92/+ji9eWk7+BE7tzGPOc562c+z4ZgA/tLzX5hpgbmX+uLKJcktgbL/faCCAUztHa/geF3uD+vvFTMQCgHviQBABmgvgIzeN0+nJScg++J0GEji1s9z79juPEe4GgE9OMuKM15dM3yv3MrocCz6stxLAX3koSyPxIxpf2m0JnNhpLpUv6XhUl0eNfU4nLh8ovGRw5L7lVCpoHPiuU5nwVAWlnvZX9cqTwebkFx8MEueqVzzEbwTwvB+OLO5GlZLNO4IbNE5P+SiYqHGwAid2hffC6Oan0sIlykqies9oLsY3Wp9YxYeeDAXgXHWPgUv0ZTHYhrnHqIYbITqBqQW+C4B+MfdJmo3U6sey/wfDBJPhtrZm1gAAAABJRU5ErkJggg==",
c.appendChild(a),b.videoBox.clickBtn=a)}},h=function(c){var a=document.createElement("span");a.style.cssText="position: absolute;top:"+(b.height/2-25)+"px;left:"+(b.width/2-70)+"px;background-color: rgba(91, 192, 222, 0.5);color:#fff;width:140px;height:50px;line-height:50px;text-align:center;border-radius:5px;";a.innerText=c;b.videoBox.div.appendChild(a);setTimeout(function(){a.remove()},2E3)},l=function(c){b.videoBox.closeBtn.addEventListener("click",function(){b.videoBox.div.remove();b={width:600,
height:450,scale:1,imgType:"png",deviceLabel:"HIK",isScan:!0,dom:g.document.body,videoBox:{}};c&&c()},!1)};g.WebVideo=k})(window);