Home > OS >  how can I access the src of image generated by javascript library
how can I access the src of image generated by javascript library

Time:06-04

I am working on QR Code Generator app where user input text and click on generate they get qr code generated but I want to add download button and for that I need src , but the image is generated dynamical so how I can do this

let qrCodeBox = document.querySelector('.qr-code')


let dnload = document.querySelector('.download')

btn.onclick = () => {
    let user_input = document.querySelector("#input_text");
    
    if (qrCodeBox.childElementCount == 0) {
        generate(user_input);
        qrCodeBox.style.display = "block";
        console.log(qrCodeBox.childNodes[1]);
        // dnload.innerHTML = `<a href="${qrCodeBox.childNodes[1]}">Download</a>`
        
      } else {
        qrCodeBox.innerHTML = "";
        generate(user_input);
      }
}

const generate = (user_input) => {
    let qrCode = new QRCode(qrCodeBox, {
        text: `${user_input.value}`,
        width: 180, //default 128
        height: 180,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H
    })

}

CodePudding user response:

You may try converting it into a dataURL.

var dataURL = document.getElementById('qrcode').toDataURL();

And then save it like this. ( you may append this from js)

<a href="dataURL" target="_blank" download="image.png">

Note: Not all browsers will support this. But modern browsers will.

CodePudding user response:

To get the src of qr code you can use

const src = document.querySelector("#qrcode > img").src;

As the library you are using creates a image tag in a qrcode container, so you can get src through above code.

  • Related