-
Notifications
You must be signed in to change notification settings - Fork 0
/
scaner.js
66 lines (57 loc) · 1.98 KB
/
scaner.js
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
const scannerVideo = document.getElementById('scanner-video');
const scannerCanvas = document.getElementById('scanner-canvas');
const scannerButton = document.getElementById('scanner-button');
const stopScanButton = document.getElementById('stop-scan-button');
const codeReader = new ZXing.BrowserMultiFormatReader();
let currentFacingMode = 'environment';
function startScanner() {
navigator.mediaDevices.getUserMedia({
video: {
facingMode: currentFacingMode
}
})
.then(function (stream) {
scannerVideo.srcObject = stream;
scannerVideo.setAttribute('playsinline', true);
scannerVideo.play();
tick();
scan();
})
.catch(function (err) {
console.error('Não foi possível acessar a câmera', err);
});
}
function tick() {
scannerCanvas.width = scannerVideo.videoWidth;
scannerCanvas.height = scannerVideo.videoHeight;
scannerCanvas.getContext('2d').drawImage(scannerVideo, 0, 0, scannerCanvas.width, scannerCanvas.height);
requestAnimationFrame(tick);
}
function scan() {
codeReader.decodeFromCanvas(scannerCanvas, function (result, err) {
if (result) {
alert(result.text);
}
if (err && !(err instanceof ZXing.NotFoundException)) {
console.error(err);
}
requestAnimationFrame(scan);
})
}
scannerButton.addEventListener('click', function () {
startScanner();
});
stopScanButton.addEventListener('click', function () {
scannerVideo.srcObject.getTracks().forEach(track => track.stop());
scannerCanvas.style.display = 'none';
scannerButton.disabled = false;
stopScanButton.disabled = true;
});
function switchCamera() {
currentFacingMode = (currentFacingMode === 'environment') ? 'user' : 'environment';
scannerVideo.srcObject.getTracks().forEach(track => track.stop());
startScanner();
}
document.getElementById('switch-camera-button').addEventListener('click', function () {
switchCamera();
});