MUI 結合 HTML5+ 實現的二維碼掃描功能
一、說明
二維碼的掃描在手機APP的開發中是很常見的一個需求,畢竟用的也多嘛。html5+ 提供了 Barcode模塊管理條碼掃描,支持常見的條碼(一維碼及二維碼)的掃描識別功能。可調用設備的攝像頭對條碼圖片掃描進行數據輸入,解碼後返回碼數據及碼類型。通過plus.barcode可獲取條碼碼管理對象。(html5產業聯盟)
二、實現效果
三、主要實現代碼邏輯(完整項目案例)
與之前寫的有一些差別,這個是組件更新之後的寫法,並修復了評論中出現的部分問題。上一篇博客地址:基於MUI框架的使用HTML5+實現的二維碼掃描功能
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<link href="css/mui.min.css" rel="stylesheet" />
<script src="js/mui.min.js"></script>
<style type="text/css">
#bcid {
width: 100%;
height: 100%;
position: absolute;
background: #000000;
}
html,
body,
div {
height: 100%;
width: 100%;
}
.fbt {
color: #0E76E1;
width: 50%;
background-color: #ffffff;
float: left;
line-height: 44px;
text-align: center;
}
</style>
</head>
<body>
<header class="mui-bar mui-bar-nav" style="background-color: #ffffff;">
<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
<h1 class="mui-title" style="color: #0E76E1;">物品二維碼掃描</h1>
<span class="mui-icon mui-icon-spinner-cycle mui-spin mui-pull-right" id="turnTheLight"></span>
</header>
<div id="bcid">
<!--盛放掃描控件的div-->
</div>
<div class="mui-bar mui-bar-footer" style="padding: 0px;">
<div class="fbt" onclick="scanPicture();">從相冊選擇二維碼</div>
<div class="fbt mui-action-back">取 消</div>
</div>
<script type="text/javascript">
scan = null; //掃描對象
mui.plusReady(function() {
mui.init();
startRecognize();
});
function startRecognize() {
try {
var filter;
//自定義的掃描控件樣式
var styles = {
top: '100px',
left: '0px',
width: '100%',
height: '500px',
position: 'static',
}
//掃描控件構造
scan = plus.barcode.create('bcid', filter, styles);
scan.onmarked = onmarked;
scan.onerror = onerror;
plus.webview.currentWebview().append(scan);
scan.start();
//打開關閉閃光燈處理
var flag = false;
document.getElementById("turnTheLight").addEventListener('tap', function() {
if (flag == false) {
scan.setFlash(true);
flag = true;
} else {
scan.setFlash(false);
flag = false;
}
});
} catch (e) {
alert("出現錯誤啦:\n" + e);
}
};
function onerror(e) {
alert(e);
};
function onmarked(type, result) {
var text = '';
switch (type) {
case plus.barcode.QR:
text = 'QR: ';
break;
case plus.barcode.EAN13:
text = 'EAN13: ';
break;
case plus.barcode.EAN8:
text = 'EAN8: ';
break;
}
//掃描成功之後的處理
alert(text + " : " + result);
scan.start();
};
// 從相冊中選擇二維碼圖片
function scanPicture() {
plus.gallery.pick(function(path) {
plus.barcode.scan(path, onmarked, function(error) {
plus.nativeUI.alert("無法識別此圖片");
});
}, function(err) {
plus.nativeUI.alert("Failed: " + err.message);
});
}
</script>
</body>
</html>
三、總結
1,這個模塊還是存在一些問題的,不能像原生的那樣順滑,並且,還沒有全屏,通過調樣式實現的話,效果也不是那麼好。
2,關於樣式上面的調節,在上一篇博客有介紹,這裏不再贅述。
3,這篇博客是接着上一篇的,主要修復了評論下面提出的問題。
4,完整項目案例鏈接。