Search code examples
javascriptqr-code

QR code to dataURL


I am trying to generate a QR code using davidshimjs/qrcodejs with the code below. But, when i try to generate DataURL, it gives following error :

TypeError: document.getElementById(...).toDataURL is not a function

Below is my code:

HTML :

<div id="qrcode"></div>

JS :

var qrcode = new QRCode("qrcode", {
    text: QRId,
    width: 200,
    height: 200,
    colorDark : "#000000",
    colorLight : "#ffffff",
    correctLevel : QRCode.CorrectLevel.H
});
var dataURL = document.getElementById('qrcode').toDataURL();

Solution

  • That's because toDataURL only works on the <canvas> element.

    canvas.toDataURL(type, encoderOptions);

    See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL

    UPDATE

    Here is how you would get the data URL...

    var QRId = "123456789"
    var qrcode = new QRCode("qrcode", {
        text: QRId,
        width: 200,
        height: 200,
        colorDark : "#000000",
        colorLight : "#ffffff",
        correctLevel : QRCode.CorrectLevel.H
    });
    
    // get the qr div, then find the canvas element inside it
    var canvas = document.getElementById('qrcode').querySelector('canvas');
    
    var dataURL = canvas.toDataURL();
    
    document.getElementById('result').innerHTML = dataURL;
    <script src="https://cdn.rawgit.com/davidshimjs/qrcodejs/master/qrcode.js"></script>
    
    <div id="qrcode"></div>
    
    <div id="result"></div>