In this article, we will be using various qr code libraries to generate QR Code using Javascript or jQuery and then we will also see how to read or scan QR code using Javascript and HTML.
Generate QR Code using QRCode.js
QRCode.js is an external Javascript library which doesn't have any dependencies and can be directly used to generate QR Code in Javascript.
Here is how you can use it.
HTML
<!--script to include-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/davidshimjs/qrcodejs/gh-pages/qrcode.min.js"></script>
<input id="TextToConvert" type="text" /><br />
<div id="DivForQrCode"></div>
Javascript code
$("#TextToConvert").
on("blur", function () {
CreateQR();
}).
on("keydown", function (e) {
if (e.keyCode == 13) {
CreateQR();
}
});
function CreateQR(){
document.getElementById("DivForQrCode").innerHTML="";
var qrcode = new QRCode("DivForQrCode", {
text: document.getElementById("TextToConvert"),
width: 128,
height: 128,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
});
}
Here is the working fiddle
Generate QR Code using HTML and JavaScript
If you don't like jQuery you can use below Javascript which uses this library https://github.com/amanuel/JS-HTML5-QRCode-Generator
<textarea name="textField" rows="8" cols="50" onkeyup='updateQRCode(this.value)' onclick="this.focus();this.select();">QR Code Text</textarea>
<!-- This is where our QRCode will appear in. -->
<div id="qrcode"></div>
<script type="text/javascript">
function updateQRCode(text) {
var element = document.getElementById("qrcode");
var bodyElement = document.body;
if(element.lastChild)
element.replaceChild(showQRCode(text), element.lastChild);
else
element.appendChild(showQRCode(text));
}
updateQRCode('QR Code Text.');
</script>
Above link contains all the requires JS files, you can download it from there.
Read QR Code using Javascript
Above methods shows how to generate QR code, but in this section, we will see how to convert QR Code back to text using Javascript.
For that we will be using jsQR
If you have a Laptop with web-cam or if you are on mobile you can check this demo link
jsQR uses this simple code to decode QR code into text.
const code = jsQR(imageData, width, height, options?);
if (code) {
console.log("Found QR code", code);
}
Where,
- imageData - An Uint8ClampedArray of RGBA pixel values in the form [r0, g0, b0, a0, r1, g1, b1, a1, ...]. As such the length of this array should be * width * height. This data is in the same form as the ImageData interface, and it's also commonly returned by node modules for reading images.
- width - The width of the image you wish to decode.
- height - The height of the image you wish to decode.
- options (optional) - Additional options.