I have just arranged for my first ever concert that is going to happen in mid-December in Hong Kong. As I was sorting out the logistics for ticket sales, I decided to build a simple system for myself. People can go on the stripe payment link
I didn't see many tutorials about it yet, so I have decided to make a note about my exploration. Hope you will enjoy!
This article will split into 2 parts:
In this section, our goal is to put the camera stream onto the page.
First, we need a <video>
element to show the camera stream.
<video id="stream" style="width: 100vw; height: 100vh;" />
Then, we can simply use getUserMedia
const stream = await navigator.mediaDevices.getUserMedia({
video: {
facingMode: { ideal: 'environment' }
},
audio: false
});
const videoEl = document.querySelector('#stream');
videoEl.srcObject = stream;
await videoEl.play();
Note that, the { ideal: 'environment' }
option is provided so the back camera on a phone is used. Find out more here
With these few lines of code, we capture the camera feed and displayed it on the screen. See codepen
The barcode detection apinew BarcodeDetector(...)
then barcodeDetector.detect(videoElement)
.
So we will add these two lines:
/* code from part one */
const barcodeDetector = new BarcodeDetector({formats: ['qr_code']});
const barcodes = await barcodeDetector.detect(videoEl)
Now the barcode detector will be activated at the exact moment the video starts streaming. We probably won't expect to find any QR code at the moment people turn on their camera. So we will need to continuously look at the video stream and call .detect(...)
until we got some barcodes.
In order to do that, we can .detect
every X ms until we got some barcodes. Simply use window.setInterval
for this.
/* code from part one */
const barcodeDetector = new BarcodeDetector({formats: ['qr_code']});
window.setInterval(async () => {
const barcodes = await barcodeDetector.detect(videoEl);
if (barcodes.length <= 0) return;
alert(barcodes.map(barcode => barcode.rawValue));
}, 1000)
Now the camera will look for barcode every second! See codepen
Final results (codepen
<video id="stream" style="width: 100vw; height: 100vh;"/>
(async () => {
const stream = await navigator.mediaDevices.getUserMedia({
video: {
facingMode: {
ideal: "environment"
}
},
audio: false
});
const videoEl = document.querySelector("#stream");
videoEl.srcObject = stream;
await videoEl.play();
const barcodeDetector = new BarcodeDetector({formats: ['qr_code']});
window.setInterval(async () => {
const barcodes = await barcodeDetector.detect(videoEl);
if (barcodes.length <= 0) return;
alert(barcodes.map(barcode => barcode.rawValue));
}, 1000)
})();
Happy coding!