具體實現效果如下所示:
1、在cordova打包功能添加插件
cordova plugin add cordova-plugin-qrscanner
2、在typings.d.ts中定義插件
declare var QRScanner: any ;
下面就可以實現代碼啦~
一、html
前端顯示配合onsenui框架進行頁面開發:
<ons-page>
<ons-toolbar>
<div class="left">
<img src="./assets/img/icon/back.png" (click)="goPage('back')" />
</div>
<div class="center">掃一掃</div>
<div class="right">
<img src="./assets/img/pic/ycode.png" />
</div>
</ons-toolbar>
<!--掃一掃 S-->
<div class="background qrscanner"></div>
<div class="content qrscanner">
<div class="qrscanner-area">
</div>
<div class="through-line"></div>
</div>
<!--掃一掃 E-->
</ons-page>
二、css
.toolbar {
background: -webkit-linear-gradient(left, #0094fe, #01adff) !important;
color: black;
}
.center {
color: #fff;
}
.left img {
width: 13px;
height: 21px;
-o-object-fit: contain;
object-fit: contain;
vertical-align: middle;
margin-left: 15px;
}
.toolbar .back-button__icon {
fill: #ffffff !important;
}
.toolbar .right img {
width: 23px;
height: auto;
vertical-align: middle;
margin-right: 15px;
}
.toolbar .left .ons-icon {
font-size: 22px;
padding-left: 10px;
color: #ffffff;
}
/*掃碼*/
.qrscanner {
background: transparent;
}
.qrscanner-area {
width: 280px;
height: 280px;
position: absolute;
top: 20%;
left: 50%;
border: 1px solid #00AFFF;
margin-left: -140px;
}
.through-line {
left: 50%;
margin-left: -140px;
width: 280px;
height: 10px;
background: rgba(16, 141, 233, 0.1);
position: absolute;
animation: myfirst 5s linear infinite alternate;
}
@keyframes myfirst {
0% {
top: 20%;
}
25% {
top: calc(20% + 70px);
}
50% {
top: calc(20% + 70px*2);
}
75% {
top: calc(20% + 70px*3);
}
100% {
top: calc(20% + 70px*4);
}
}
三、ts
ngOnInit() {
this.starScan();
}
//掃一掃的主要方法
starScan() {
setTimeout(() => {
QRScanner.destroy();
QRScanner.prepare(function(err, status) {
if(err) {
//console.error(err._message);
Commons.showAlert(err._message);
} else {
QRScanner.show(function() {
QRScanner.scan(function(err, result) {
if(err) {
Commons.showAlert(err);
QRScanner.destroy(function(status) {});
} else {
Commons.showAlert('result: ' + result);
QRScanner.cancelScan();
}
});
});
}
});
}, 500)
}