QR code generator in javascript

 Here is a javascript code for generating QR code from website url. Please try it


<!DOCTYPE html>

<html>

<head>

  <title>QR code generator</title>

</head>

<body>

  <div>

    <input type="text" id="urlInput" placeholder="Enter website URL">

    <button id="generateButton">Generate QR code</button>

  </div>

  <script>

    function generateQRCode(url) {

    // create a new canvas element

    var canvas = document.createElement('canvas');

    // set the canvas size

    canvas.width = 128;

    canvas.height = 128;

    // get the canvas context

    var ctx = canvas.getContext('2d');

    // fill the canvas with white

    ctx.fillStyle = 'white';

    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // set the QR code color to black

    ctx.fillStyle = 'black';

    var qrCodeData = url;

    var qrCodeErrorCorrectionLevel = "H";

    var qrCode = new QRcode(qrCodeData, qrCodeErrorCorrectionLevel);

    var cells = qrCode.modules;

    for (var r = 0; r < cells.length ; r++) {

        for (var c = 0; c < cells.length ; c++) {

            if(cells[r][c]) {

                var x = c * 4;

                var y = r * 4;

                ctx.fillRect(x, y, 4, 4);

            }

        }    

    }

    return canvas;

  }

    document.getElementById("generateButton").addEventListener("click", function() {

    var url = document.getElementById("urlInput").value;

    var canvas = generateQRCode(url);

    var link = document.createElement("a");

    link.href = canvas.toDataURL();

    link.download = "qrcode.png";

    link.click();

    });

  </script>

</body>

</html>


Comments

Popular posts from this blog