Estoy tratando de cargar un código QR en el lienzo HTML5 encima de una imagen de fondo, pero no funciona por alguna razón. Si cambio el código QR a un <img> normal, funciona bien, pero esto no es bueno para mis propósitos.
He probado un millón de variaciones, pero aquí es donde estoy ahora:
setTimeout(function() { var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); var qr = document.getElementById('qrcode'); var imageObj = new Image(); var wot = new QRCode(document.getElementById("holder"), "www.example.com"); imageObj.onload = function(){ context.drawImage(imageObj, 0, 0); qr.style.backgroundImage = "url(" + wot._el.firstChild.nextElementSibling.currentSrc + ")"; context.font = "30pt Arial"; context.fillStyle = "red"; context.fillText("QR Code should be here", 30, 100); context.fillText("But it's not", 140, 400); }; imageObj.src = "https://via.placeholder.com/500x500?text=Background+Image"; }, ); <script src="https://cdn.rawgit.com/davidshimjs/qrcodejs/gh-pages/qrcode.min.js"></script> <div id="holder" style="display: none;"></div> <div style="width:255px; height:255px" id="qrcode"></div> <canvas id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML5 canvas tag. </canvas>Cualquier ayuda sería apreciada.
De acuerdo, según la actualización de su pregunta, se puede lograr de la siguiente manera. Primero crea una nueva etiqueta <img>
var img = document.createElement('img'); img.src = wot._el.firstChild.nextElementSibling.currentSrc; Luego inyecte en el <canvas>
context.drawImage(img, 30, 100);