admin管理员组文章数量:1327301
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
2 Answers
Reset to default 6That'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>
本文标签: javascriptQR code to dataURLStack Overflow
版权声明:本文标题:javascript - QR code to dataURL - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742204803a2432614.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论