In this article, we will learn how to generate QR Code using Javascript, and download the generated QR Code in .jpg format.
QR codes are two-dimensional barcodes that can be scanned by smartphones and other devices. QR codes can contain information such as URLs, text, or contact information.
Step 1 – Working on the UI
I will add an input field to accept the input string/data for generating the QR code. Two buttons to display the QR Code and to download the QR Code in .jpg format. And finally, a div that will display the QR Code.
Below is the sample Html code.
<html> <head></head> <body> <input type="text" id="qrData" /> <br /><br /> <input type="button" value="Generate QR Code" onclick="GenerateQrCode()" /> <input type="button" value="Download QR Code" onclick="DownloadQrCode()" /> <br /><br /> <div id="qrcode"></div> <!--Display QR Code in this div--> </body> </html>
Step 2 – Download the QRCode.js library
To download the QRCode.js library follow the below link and download the .zip file.
https://davidshimjs.github.io/qrcodejs/
Once downloaded, extract the folder and find the qrcode.min.js file
Copy the qrcode.min.js file and paste it into your project folder.
Include the qrcode.min.js into our HTML file.
Step 3 – Write JS Code to Generate QR Code
function GenerateQrCode() { var userData = document.getElementById("qrData").value; //Reading the textbox value var qrCode = new QRCode(document.getElementById("qrcode")); //Initializing the library qrCode.makeCode(userData); //Code to generate qr code }
Step 4 – Write JS Code to download QR Code
Include the below library in the our html file.
<script src=”http://html2canvas.hertzen.com/dist/html2canvas.js”></script>
Add the below function to download the generated QR Code.
function DownloadQrCode() { var container = document.getElementById("qrcode"); html2canvas(container, { allowTaint: true }).then(function (canvas) { var link = document.createElement("a"); document.body.appendChild(link); link.download = "html_image.jpg"; link.href = canvas.toDataURL(); link.target = '_blank'; link.click(); }); }
Step 5 – Demo
I hope, this blog post has helped you in learning and understand how to generate QR code using Javascript.
Thank You.
Dont’ forget to checkout: Top 5 Tips for Beginner React Developer