Quiero descargar varios lienzos creados por html2canvas en una sola página con 1 clic. La descarga de 1 lienzo funcionó bien.
Intenté crear un bucle dentro de la función sendToCanvas , recorriendo cada ID (ya que sé el ID de cada elemento HTML que estoy enviando al lienzo y luego a descargar) pero no tiene el resultado deseado.
Esperaba descargar 4 archivos como jpeg, cada uno llamado file_1, file_2, file_3 y file_4
Supongo que simplemente hacer un bucle de cada ID en la función no es el camino a seguir. No escribí el código original. Estoy tratando de adaptarlo a mis necesidades.
var button = document.getElementById('download'); button.addEventListener('click', sendToCanvas); function download( canvas, filename ) { // create an "off-screen" anchor tag const a = document.createElement('a'); // the key here is to set the download attribute of the a tag a.download = filename; // convert canvas content to data-uri for link. When download // attribute is set the content pointed to by link will be // pushed as "download" in HTML5 capable browsers a.href = canvas.toDataURL("image/jpeg;base64, 0.5"); a.style.display = 'none'; document.body.appendChild( a ); a.click(); document.body.removeChild( a ); } function sendToCanvas(event){ var toCanvas = ["#redBlock", "#blueBlock", "#greenBlock", "#yellowBlock"] for (let i = 0; i < toCanvas.length; i++) { const element = document.querySelector(toCanvas[i]); html2canvas(element, { scale: 1, useCORS: true, }) .then( ( canvas ) => { download( canvas, 'file_' + (i + 1) ); }); } } #redBlock { width:100px; height:100px; background-color:red; } #blueBlock { width:100px; height:100px; background-color:blue; } #greenBlock { width:100px; height:100px; background-color:green; } #yellowBlock { width:100px; height:100px; background-color:yellow; } <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script> <button id="download">Download</button> <section id="redBlock"> </section> <section id="blueBlock"> </section> <section id="greenBlock"> </section> <section id="yellowBlock"> </section>