引入llqrcode.js可以用但是llqrcode不知道是不是开源的
<video id="video" style=" width: 100%; height: 200px;"></video> <canvas id="canvas" style=" width: 100%; height: 200px;" width="100%" height="200"></canvas> var content = ""; navigator.getUserMedia({ video: true }, function (stream) { var URL = window.URL || window.webkitURL; // 获取到window.URL对象 video.src = URL.createObjectURL(stream); // 将获取到的视频流对象转换为地址 video.play(); //当目前的播放位置已更改时 video.ontimeupdate = function () { var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var width = Number($(video).css("width").replace("px", "")); var height = Number($(video).css("height").replace("px", "")); canvas.width = width; canvas.height = height; ctx.drawImage(video, 0, 0, width, height); var imgFile = convertBase64UrlToBlob(canvas.toDataURL()); qrcode.decode(getObjectURL(imgFile)); qrcode.callback = function (imgMsg, a, b) { if (imgMsg.indexOf("error") != -1) return; console.log("imgMsg111111", imgMsg); if (!content) { content = imgMsg; } video.pause(); } } }, function (error) { console.log(error.name || error); });
//获取预览图片路径 var getObjectURL = function(file) { var url = null; if (window.createObjectURL != undefined) { // basic url = window.createObjectURL(file); } else if (window.URL != undefined) { // mozilla(firefox) url = window.URL.createObjectURL(file); } else if (window.webkitURL != undefined) { // webkit or chrome url = window.webkitURL.createObjectURL(file); } return url; } /** * 将以base64的图片url数据转换为Blob * @param urlData * 用url方式表示的base64图片数据 */ function convertBase64UrlToBlob(urlData) { var bytes = window.(urlData.split(',')[1]); //去掉url的头,并转换为byte //处理异常,将ascii码小于0的转换为大于0 var ab = new ArrayBuffer(bytes.length); var ia = new Uint8Array(ab); for (var i = 0; i < bytes.length; i++) { ia[i] = bytes.charCodeAt(i); } return new Blob([ab], { type: 'image/png' }); }
摄像头调不出来,navigator.getUserMedia这个方法过期了,可以尝试navigator.mediaDevices.getUserMedia,但是必须在https协议下用