ZXING-JS
by marcelow
HTML
<script src="https://zxing-js.github.io/library/examples/zxing.qrcodereader.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/normalize.css">
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/milligram.min.css">
<scripts src=""></scripts>
<main class="wrapper" style="padding-top:2em">
<section class="container" id="demo-content">
<h1 class="title">Scan QR Code from Video Camera</h1>
<p>This example shows how to scan a QR code with ZXing javascript library from the device video camera. If more than one video input devices are available (for example front and back camera) the example shows how to read them and use a select to change
the input device.</p>
<div>
<a class="button" id="startButton">Start</a>
<a class="button" id="resetButton">Reset</a>
</div>
<div>
<video id="video" width="100%" height="100%" style="border: 1px solid gray"></video>
</div>
<div id="sourceSelectPanel" style="display:none">
<label for="sourceSelect">Change video source:</label>
<select id="sourceSelect" style="max-width:400px">
</select>
</div>
<label>Result:</label>
<blockquote>
<p id="result"></p>
</blockquote>
<p>See the <a href="https://github.com/zxing-js/library/tree/master/docs/examples/qr-camera/">source code</a> for this example.</p>
</section>
<footer class="footer">
<section class="container">
<p>ZXing TypeScript Demo. Licensed under the <a target="_blank" href="https://github.com/zxing-js/library#license" title="MIT">MIT</a>.</p>
</section>
</footer>
</main>
JavaScript
const codeReader = new ZXing.BrowserQRCodeReader()
console.log('ZXing code reader initialized')
codeReader.getVideoInputDevices()
.then((videoInputDevices) => {
const sourceSelect = document.getElementById('sourceSelect')
const firstDeviceId = videoInputDevices.length > 1 ? videoInputDevices[1].deviceId : videoInputDevices[0].deviceId
console.log(videoInputDevices);
if (videoInputDevices.length > 1) {
videoInputDevices.forEach((element) => {
const sourceOption = document.createElement('option')
sourceOption.text = element.label
sourceOption.value = element.deviceId
sourceSelect.appendChild(sourceOption)
})
const sourceSelectPanel = document.getElementById('sourceSelectPanel')
sourceSelectPanel.style.display = 'block'
}
document.getElementById('startButton').addEventListener('click', () => {
codeReader.decodeFromInputVideoDevice(firstDeviceId, 'video').then((result) => {
console.log(result)
document.getElementById('result').textContent = result.text
}).catch((err) => {
console.error(err)
document.getElementById('result').textContent = err
})
console.log(`Started continous decode from camera with id ${firstDeviceId}`)
})
document.getElementById('resetButton').addEventListener('click', () => {
codeReader.reset()
console.log('Reset.')
})
})
.catch((err) => {
console.error(err)
})