Open In App

How to make a QR Code generator using qrcode.js ?

Last Updated : 19 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Modern web applications require generating QR codes for certain features where we need to enable a convenient way of data sharing like QR codes for the end users. Some popular QR codes use cases are UPI payment addresses, invoice details, contact cards, web links, etc. QR(Quick Response) code is a machine-readable matrix type of barcode that contains an array of black and white square grid, typically utilized to keep the URLs or other data for reading by the imaging systems, i.e. camera on a smartphone. QR code has faster readability and more storage capacity as compared to UPC barcodes. Now, the task is to create the QR Code generator with the help of qrcode.js, along with understanding the various ways to implement it through the illustrations.

QRCode.js is a popular open-source front-end easy-to-use javascript library that facilitates to create the QRCode. This library supports Cross-browser QR Code generation with HTML 5 canvas and table tag. QRCode.js doesn’t have any additional dependencies.

 Syntax: This library exposes a class named QRCode to us and the constructor expects two parameters as follows: 

new QRCode(Target,Options);

Parameter Values:

  • Target [string or HTML element] : This parameter specifies the string, which is the id or the element which we want to target for displaying the QR code. For instance,
new QRCode(document.getElementById("id-of-element"), "content of QR Code");
or
new QRCode("id-of-element", "content of QR code");
  • Options [string or JSON]: This parameter contains 2 options: 
    • string: For basic usage we can directly provide the content of QR code
    • JSON: When we need some customization
      • text [string]: content of QR code
      • width,height [int]: width and height of QR code
      • colorDark[string]: color of qr code
      • colorLight[string]: color of qr code background
      • correctlevel:  error correction level
new QRCode(document.getElementById("qrcode"), "content as string");
or
var qrcode = new QRCode("test", {
 text: "http://www.geeksforgeeks.org",
 width: 256,
 height: 256,
 colorDark : "#000000",
 colorLight : "#ffffff",
 correctLevel : QRCode.CorrectLevel.H
});

Approach: A QR code can be generated at the back end on the server and as well at the front end on the client side. This article will cover the client-side QR code generation.

Requirements or Dependencies: We can use/import the following libraries into the project in a 3 ways: 

  • Download the script file locally [Link]
  • Via CDN [Link]
  • Node package manager [Link]

Procedure to be followed for Generating QR Code:

  • Import the above-mentioned libraries to our project.
  • Decide the target location on the web page where we would like to display the QR code.
  • Create an element/container for QR Code at the target location and provide it an identifier like id.
  • Decide upon the appearance of the QR code and its content.
  • Create a QRCodejs object with a target and options.

Note: Below examples demonstrates the CDN link for importing the library.

Static QR code Generation: This is suitable when the content for the QR code is already available at the time of rendering the page and is not going the change by actions performed by the user. We place a <div> element that will contain a QR code. This <div> has an id for identification and can be placed at a suitable location in the body element as per the requirements. Then, we need to include a <script> tag where we initialize the QR code class object with the <div> element’s id and options as the QR code’s content.

Example 1: Here in this example, the content of the QR code is the link to GeeksforGeeks website.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8" />
    <meta name="viewport"
         content="width=device-width,
                        initial-scale=1.0" />
    <title>QR Code Generator</title>
    
    <style>
        h1, h3 {
          color: green;
        }
        body, header {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
    </style>
    <script src=
    </script>
</head>
 
<body>
    <header>
        <h1>GeeksforGeeks</h1>
        <h3>QR code generator using qrcode.js</h3>
        <h3>To visit geeksforgeeks.org scan below code</h3>
    </header>
    <main>
        <div id="qrcode"></div>
    </main>
     
    <script>
        var qrcode = new QRCode("qrcode",
        "https://www.geeksforgeeks.org");
    </script>
</body>
 
</html>


Output

Static QR code generation example

Dynamic QR code Generation: This is suitable when the content of the QR code is not available at the time of rending the page and depends on actions performed by the user which should lead to the generation of a QR code on the fly. Here, similar to the previous example, we need to place the target <div> element with an id which will contain a QR code once it is generated. For the dynamic generation demonstration, the below example uses a form with an input element for receiving the QR code’s content from the user.

In the script, we mainly have 2 things, i.e. generateQrCode function & Form submission event listener. In generateQrCode function, this will accepts QR code content as a parameter and generates the QR code with the QR code’s target div element and options with content. Whereas, In Form submission event listener, once the form is submitted, first thing we do is prevent the submission event as we don’t want to send the request to any server. Then we check if the QRcode object is already available or not.

  • If not available then we generate the QRcode object using the generator function defined by us, which in turn also renders the QR code in the target <div> element.
  • If already available then use the existing object and use a method provided by the QRcode class that is makeCode which requires one parameter that is QR-code content and when invoked re-generates the QR code with updated content but with existing other options if provided previously.

Example 2: This example illustrate generating the Dynamic QR code using the QRCode.js.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8" />
    <meta name="viewport"
          content="width=device-width,
                         initial-scale=1.0" />
    <title>QR Code Generator</title>
    <style>
        h1, h3 {
          color: green;
        }
        body, header {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
    </style>
 
    <script src=
    </script>
</head>
 
<body>
    <header>
        <h1>GeeksforGeeks</h1>
        <h3>QR code generator using qrcode.js</h3>
        <h3>Enter QR code content and generate QR</h3>
    </header>
    <main>
        <form action="/"
              id="qr-generation-form">
            <input type="text"
                   name="qr-code-content"
                   id="qr-content"
                   value=""
                   placeholder="Enter QR content"
                   autocomplete="off" />
            <input type="submit"
                   value="Generate QR Code" />
        </form><br />
        <div id="qr-code"></div>
    </main>
</body>
<script>
    let qrContentInput = document.getElementById("qr-content");
    let qrGenerationForm =
    document.getElementById("qr-generation-form");
    let qrCode;
     
    function generateQrCode(qrContent) {
      return new QRCode("qr-code", {
        text: qrContent,
        width: 256,
        height: 256,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H,
      });
    }
     
    // Event listener for form submit event
    qrGenerationForm.addEventListener("submit", function (event) {
      // Prevent form submission
      event.preventDefault();
      let qrContent = qrContentInput.value;
      if (qrCode == null) {
           
        // Generate code initially
        qrCode = generateQrCode(qrContent);
      } else {
           
        // If code already generated then make
        // again using same object
        qrCode.makeCode(qrContent);
      }
    });
</script>
 
</html>


Output

A dynamic QR code generator

Reference: Library Repository: https://github.com/davidshimjs/qrcodejs



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads