Create a QR Code Scanner or Reader in HTML CSS & JavaScript (original) (raw)

Last Updated : 26 Jul, 2024

In this article, we will see how we can implement a QR Code Scanner with the help of HTML CSS & JavaScript. A QR code scanner will provide the user with two options to scan the QR code either by uploading the image file of the URL to be scanned or by using the camera of your system to scan the QR code and decode it. This application will show you an alert message with the decoded text of the QR code.

Preview:

Approach

HTML5-qrcode library methods:

**Example: This example shows the implementation of the QR code scanner or Reader.

HTML `

QR Code Scanner / Reader

Scan QR Codes

CSS

/* style.css file*/ body { display: flex; justify-content: center; margin: 0; padding: 0; height: 100vh; box-sizing: border-box; text-align: center; background: rgb(128 0 0 / 66%); } .container { width: 100%; max-width: 500px; margin: 5px; }

.container h1 { color: #ffffff; }

.section { background-color: #ffffff; padding: 50px 30px; border: 1.5px solid #b2b2b2; border-radius: 0.25em; box-shadow: 0 20px 25px rgba(0, 0, 0, 0.25); }

#my-qr-reader { padding: 20px !important; border: 1.5px solid #b2b2b2 !important; border-radius: 8px; }

#my-qr-reader img[alt="Info icon"] { display: none; }

#my-qr-reader img[alt="Camera based scan"] { width: 100px !important; height: 100px !important; }

button { padding: 10px 20px; border: 1px solid #b2b2b2; outline: none; border-radius: 0.25em; color: white; font-size: 15px; cursor: pointer; margin-top: 15px; margin-bottom: 10px; background-color: #008000ad; transition: 0.3s background-color; }

button:hover { background-color: #008000; }

#html5-qrcode-anchor-scan-type-change { text-decoration: none !important; color: #1d9bf0; }

video { width: 100% !important; border: 1px solid #b2b2b2 !important; border-radius: 0.25em; }

JavaScript

// script.js file

function domReady(fn) { if ( document.readyState === "complete" || document.readyState === "interactive" ) { setTimeout(fn, 1000); } else { document.addEventListener("DOMContentLoaded", fn); } }

domReady(function () {

// If found you qr code
function onScanSuccess(decodeText, decodeResult) {
    alert("You Qr is : " + decodeText, decodeResult);
}

let htmlscanner = new Html5QrcodeScanner(
    "my-qr-reader",
    { fps: 10, qrbos: 250 }
);
htmlscanner.render(onScanSuccess);

});

`

**Output: