Skip to content

Instantly share code, notes, and snippets.

@betiol
Last active September 27, 2023 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save betiol/9c29fb403c2bbbdf0e331975ac0cf013 to your computer and use it in GitHub Desktop.
Save betiol/9c29fb403c2bbbdf0e331975ac0cf013 to your computer and use it in GitHub Desktop.
import React, { useState, useEffect, useRef } from "react";
import decodeQRCode from "jsqr";
const QRCodeScanner = () => {
const [result, setResult] = useState(null);
const videoRef = useRef(null);
const canvasRef = useRef(null);
const scanInterval = 1000;
useEffect(() => {
const videoConfig = {
video: { facingMode: "environment" }
};
navigator.mediaDevices
.getUserMedia(videoConfig)
.then((stream) => {
videoRef.current.srcObject = stream;
})
.catch((error) => {
console.error("Error:", error);
});
}, []);
useEffect(() => {
const scanTimer = setInterval(() => {
handleScan();
}, scanInterval);
return () => {
clearInterval(scanTimer);
};
}, []);
const handleScan = () => {
if (videoRef.current && videoRef.current.videoWidth > 0) {
canvasRef.current.width = videoRef.current?.videoWidth;
canvasRef.current.height = videoRef.current?.videoHeight;
const ctx = canvasRef.current.getContext("2d");
ctx.drawImage(videoRef.current, 0, 0);
const imageData = ctx.getImageData(
0,
0,
canvasRef.current.width,
canvasRef.current.height
);
const code = decodeQRCode(
imageData.data,
imageData.width,
imageData.height
);
if (code) {
setResult(code.data);
}
}
};
return (
<div>
<video ref={videoRef} onPlay={handleScan} autoPlay playsInline />
<canvas ref={canvasRef} style={{ display: "none" }} />
{result && (
<div>
<p>QR Code data:</p>
<p>{result}</p>
</div>
)}
</div>
);
};
export default QRCodeScanner;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment