Skip to content

Instantly share code, notes, and snippets.

@azechi
Last active April 4, 2019 03:41
Show Gist options
  • Save azechi/4e6dacd5d5a48ba6655005c1d4038bb6 to your computer and use it in GitHub Desktop.
Save azechi/4e6dacd5d5a48ba6655005c1d4038bb6 to your computer and use it in GitHub Desktop.
Read QR Code from video with web browser using cozmo/jsQR
<!DOCTYPE html>
<html>
<head>
<style>
#canvas {
width: 100%;
vertical-align: bottom;
}
body {
max-width: 640px;
margin: 0 auto;
}
</style>
<script src="https://cdn.jsdelivr.net/gh/cozmo/jsQR/dist/jsQR.js"></script>
</head>
<body>
<div id="container">
<canvas id="canvas" hidden></canvas>
</div>
<hr />
<button id="on_off">on_off</button>
<div id="output"></div>
<script src="main.js"></script>
</body>
</html>
const canvasElement = document.getElementById("canvas");
const canvas = canvasElement.getContext("2d");
const output = document.getElementById("output");
const video = document.createElement("video");
document.getElementById("on_off").addEventListener("click", main);
async function main() {
if (video.srcObject) {
video.srcObject.getTracks().forEach( t => t.stop());
video.srcObject = null;
} else {
const stream = await navigator.mediaDevices.getUserMedia({audio:false, video:{ facingMode: "environment"}});
video.srcObject = stream;
video.setAttribute("playsinline", true);
video.play();
requestAnimationFrame(tick);
}
}
function tick() {
if (video.readyState == video.HAVE_ENOUGH_DATA){
canvasElement.hidden = false;
canvasElement.width = video.videoWidth;
canvasElement.height = video.videoHeight;
canvas.drawImage(video, 0, 0, canvasElement.width, canvasElement.height);
var img = canvas.getImageData(0, 0, canvasElement.width, canvasElement.height);
const code = jsQR(img.data, img.width, img.height, {inversionAttemps: "dontInvert"});
if (code) {
output.innerText = code.data;
main().catch(e => alert(e));
return;
}
}
requestAnimationFrame(tick);
}
@azechi
Copy link
Author

azechi commented Apr 4, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment