Search code examples
javascripthtml2canvas

Using html2canvas action is working just once and i need the code works multiple times


im creating a web app using some html2canvas, the idea is: an user uploads a photo then choose a png image from a library to place over the image and the the user can download the image with the sticker aplied. Everything is working fine the first time, but when i try to use the download button a second time nothing happens. The console shows the following error:

Uncaught TypeError: Cannot set property 'id' of null at HTMLButtonElement.capture (index.html:82)

The line number 82 is: body.id = 'CapturaPantalla';

How could i reset the code everytime so the user could download the image multiple times?

This is the code:

<script>
   const capture = () => {
     const body = document.querySelector('#ImagenLista');
     body.id = 'CapturaPantalla';
     html2canvas(document.querySelector("#CapturaPantalla")).then(canvas => {
       document.body.appendChild(canvas);
     }).then(() => {
       var canvas = document.querySelector('canvas');
       canvas.style.display = 'none';
       var image = canvas.toDataURL("image/jpg").replace("image/jpg", "image/octet-stream");
       var a = document.createElement("a");
       a.setAttribute('download', 'YoSoyYVoyA.jpg');
       a.setAttribute('href', image);
       a.click();
     });
   };
   
   const btn = document.getElementById('DescargaImagen');
   
   function FuncionDescarga() {
   btn.addEventListener('click', capture);
   
   }
   
</script>

Thanks everyone in advance.


Solution

  • First, you are getting an element:

    const body = document.querySelector('#ImagenLista');
    

    Then, you change the ID of the element:

    body.id = 'CapturaPantalla';
    

    So when you go to select the element again, it has a different ID, therefore returning null.

    The solution should be obvious, but if for some reason you have to keep line 82, you can do this:

    if (body) {
      body.id = 'CapturaPantalla';
    }
    

    And a more compressed version:

    body && (body.id = 'CapturaPantalla');