赞
踩
已经三个月没有写博客了吧,因为工作有点忙,写完之后就想在床上躺着,所以就一直没有写过了,今天七夕,没人给我玩。只能写博客了
最近工作上需要在前端页面进行拍照以及解析条形码和二维码,所以研究了下JS的API,但是只支持谷歌内核的浏览器
可以在这里看下: https://developer.mozilla.org/zh-CN/docs/Web/API
接下来上代码,这个是封装好的相机组件
/** * 创建相机对象 * @Author Fanxing * @param app 绑定div * @param width 宽度 (与app宽度相同 * @param height 高度 (与app高度相同 * @param type 没有类型,忽略。。不是相机前置或后置。。 * ps: 扫码结果在 res.text里,方法是qrcode 获取拍照图片调用 getImg */ function camera(app, width, height, type) { let appObject = document.getElementById(app); let video = document.createElement("video"); let span = document.createElement("span"); let facingMode = 'environment'; const codeReader = new ZXingBrowser.BrowserMultiFormatReader(); video.style.width = width video.id = 'video' video.style.height = height video.autoplay = "autoplay"; video.style.margin = 0; appObject.insertBefore(video, appObject.childNodes[0]); /** * 修改优先使用那颗摄像头,前置或后置 * */ this.setFacingMode = function(type) { // 前置摄像头:user 后置摄像头:environment facingMode = type; } this.establish = function establish() { let constraints = { video: { facingMode: facingMode, height: height, width: width }, audio: false }; let promise = navigator.mediaDevices.getUserMedia(constraints); promise.then(function(MediaStream) { video.srcObject = MediaStream; video.play(); }).catch(function(PermissionDeniedError) { console.log(PermissionDeniedError); }) } this.photograph = function photograph() { canvas = document.createElement("canvas"); canvas.height = height; canvas.width = width; let ctx = canvas.getContext('2d'); ctx.drawImage(video, 0, 0, width, height); return canvas; } // 解析码,获取解码的内容 this.qrcode = function qrcode() { var promise = codeReader.decodeOnceFromVideoElement(video); // codeReader.decodeOnceFromVideoElement(video).then(function(res){ // console.log("res:" + res) // return res; // }) console.log(promise) return promise; } this.getImg = function getImg() { return this.photograph().toDataURL('image/jpeg') } this.close = function close() { this.MediaStreamTrack && this.MediaStreamTrack.stop(); } // 开始疯狂扫码 this.starcode = function starcode() { alert("在外部实现!!!") } //停止疯狂扫码 this.stopcode = function stopcode() { alert("在外部实现!!!") } }
扫码功能需要:zxing-browser.min.js
DEMO:
<!doctype html> <html lang="en"> <head> <title>GET VIDEO</title> <meta charset="utf-8"> </head> <body> <span id="sa"></span> <div style="width:500px;height:800px;border: 1px solid red;" id="app"> </div> <button id="snap" onclick="qr()">拍照吧</button> <button id="snap" onclick="vi.close()">拍照</button> <script type="text/javascript" src="js/zxing-browser.min.js"></script> <script type="application/javascript" src="js/xcamera.js"></script> <script> let vi = new camera("app", 500, 1000); vi.establish() function qr() { vi.qrcode().then(function(res) { if (res.text != undefined) { alert("识别成功" + res.text); } }) } </script> </body> </html>
代码和zxing的下载地址:https://gitee.com/fxboy/html-camera
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。