现在前端技术发展飞快,前端都能做app了,那么项目中,也会遇到调用安卓手机基层的一些功能,比如调用摄像头,完成扫描二维码功能
下面我就为大家讲解一下,我在项目中调用这功能的过程。
首先我们需要一个中间框架,hbuilder
http://www.html5plus.org/doc/zh_cn/accelerometer.html 这个是html5+的文档地址,我们找到Barcode模块,

有这么多,然后我们往下找
找到这段代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
<!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8" >
<title>Barcode Example</title>
<script type= "text/javascript" >
// 扩展API加载完毕后调用onPlusReady回调函数
document.addEventListener( "plusready" , onPlusReady, false );
// 扩展API加载完毕,现在可以正常调用扩展API
function onPlusReady() {
var e = document.getElementById( "scan" );
e.removeAttribute( "disabled" );
}
var scan = null ;
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 );
}
function startRecognize() {
scan = new plus.barcode.Barcode( 'bcid' );
scan.onmarked = onmarked;
}
function startScan() {
scan.start();
}
function cancelScan() {
scan.cancel();
}
function setFlash() {
scan.setFlash();
}
</script>
<style type= "text/css" >
*{
-webkit-user-select: none;
}
html,body{
margin: 0px;
padding: 0px;
height: 100%;
}
#bcid {
background: #0F0;
height:480px;
width:360px;
}
</style>
</head>
<body >
<input type= 'button' onclick= 'startRecognize()' value= '创建扫描控件' />
<input type= 'button' onclick= 'startScan()' value= '开始扫描' />
<input type= 'button' onclick= 'cancelScan()' value= '取消扫描' />
<input type= 'button' onclick= 'setFlash()' value= '开启闪光灯' />
<div id= "bcid" ></div>
<input type= 'text' id= 'text' />
</body>
</html>
|
这段代码,一定要放在我们vue的index.html页面里,别问我为什么,我也不知道,反正就是要全局
1
2
3
4
5
6
7
8
|
// 扩展API加载完毕后调用onPlusReady回调函数
document.addEventListener( "plusready" , onPlusReady, false );
// 扩展API加载完毕,现在可以正常调用扩展API
function onPlusReady() {
var e = document.getElementById( "scan" );
e.removeAttribute( "disabled" );
}
var scan = null ;
|
我写的是这样的,这代码是放在methods里面的
1
2
3
4
5
6
7
8
|
startRecognize() {
scan = new plus.barcode.Barcode( 'bcid' );
scan.onmarked = onmarked;
this .startScan
}
startScan () {
scan.start();
}
|
如果你们试了不行,那就在startRecognize函数内加一个setTimeout,延迟个200ms,我试了是可以使用的,扫描成功后会有个alert,这个可以改成扫描成功后的函数或者你们自己想要做的事情。