最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - QR code to dataURL - Stack Overflow

programmeradmin8浏览0评论

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();

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();
Share Improve this question asked Aug 11, 2016 at 15:32 Ravi Shankar BhartiRavi Shankar Bharti 9,2686 gold badges30 silver badges52 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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

canvas.toDataURL(type, encoderOptions);

See: https://developer.mozilla/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./davidshimjs/qrcodejs/master/qrcode.js"></script>

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

<div id="result"></div>

Simple solution

Include the library in <head> tag

<script type="text/javascript" src="https://cdn.rawgit./davidshimjs/qrcodejs/gh-pages/qrcode.min.js"></script>

A simple function which converts a text to its equivalent QR image data URL.

function textToQrImageDataUrl(txt) {
    var qrDiv = document.createElement("div");

    // This will put a <canvas> inside the given <div> element, and draw
    // the QR image on it
    new QRCode(qrDiv, txt);

    return qrDiv.querySelector('canvas').toDataURL();
}

Test it in HTML

<img id="qrImg" src="#">

<script type="text/javascript">
// This will use the same javascript function that I have defined above
var imgDataUrl = textToQrImageDataUrl("abcd");
document.getElementById('qrImg').setAttribute("src", imgDataUrl);
</script>
发布评论

评论列表(0)

  1. 暂无评论