H5使用Quagga实现浏览器扫码二维码

2020-07-03  本文已影响0人  远方_8378

1.使用Quagga必须在https环境下才能测试,这里我使用github进行测试
2.设置默认后摄像头扫码  设置deviceId, Quagga.CameraAccess.enumerateVideoDevices().then(function(devices)获取deviceId

<htmllang="en">

<head>

<metacharset="UTF-8">

<metaname="viewport"content="width=device-width, initial-scale=1.0">

<title>Document</title>

</head>

<style>

*{

padding:0;

margin:0;

  }

#cameras{

width:350px;

height:350px;

border:1pxsolid red;

overflow: hidden;

margin:50pxauto;

  }

</style>

<body>

<divid="root">

<h2>实现扫码</h2>

<selectid="selected"  v-model="deviceId" @change="handleSelect">

<optionv-for="item in devices":key="item.deviceId":value="item.deviceId">{{item.deviceId}}</option>

</select>

<divid="cameras"></div>

</div>

<scriptsrc="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<scriptsrc="./quagga.js"></script>

<script>

newVue({

el:document.getElementById('root'),

data:{

deviceId:'',

devices:[]

},

mounted(){

this.onlyOne=true

this.initCameraSelection()

},

methods:{

init(){

const self=this;

Quagga.init(this.states(),function(err){

if(err){

console.log(err);

}

Quagga.start();

});

},

states(){

return{

inputStream:{

type:"LiveStream",

target:document.getElementById('cameras'),

constraints:{

width:{min:350},

height:{min:350},

facingMode:"environment",

deviceId:this.deviceId,

aspectRatio:{min:1,max:2}

}

},

locator:{

patchSize:"medium",

debug:{

showCanvas:false,

showPatches:false,

showFoundPatches:false,

showSkeleton:false,

showLabels:false,

showPatchLabels:false,

showRemainingPatchLabels:false,

boxFromPatches:{

showTransformed:false,

showTransformedBox:false,

showBB:false

}

},

halfSample:true

},

numOfWorkers:1,

multiple:false,

frequency:10,

decoder:{

readers:[{

format:"code_93_reader",

config:{}

}]

},

locate:true

}

},

handleSelect(){

this.init()

},

initCameraSelection(){

const self=this

returnQuagga.CameraAccess.enumerateVideoDevices()

.then(function(devices){

self.deviceId=devices[1].deviceId

self.devices=devices

self.init()

Quagga.onDetected(function(data){

varcode=data.codeResult.code;

Quagga.stop()

});

});

}

}

})

</script>

</body>

</html>

效果: 

上一篇下一篇

猜你喜欢

热点阅读