前端打包下載圖片javascript
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <img src="assets/logo.png" class="yaojianbaogao" width="50" data-title="霍痕" data-alt="1.png"> <img src="assets/logo.png" class="yaojianbaogao" width="50" data-title="霍痕" data-alt="2.png"> <a href="javascript:;" onclick="downloadzip()">打包下載</a> <script src="https://cdn.bootcss.com/jszip/3.2.0/jszip.min.js"></script> <script src="https://cdn.bootcss.com/FileSaver.js/2014-11-29/FileSaver.min.js"></script> <script> function downloadzip() { var imgs = document.getElementsByClassName('yaojianbaogao'); var zip = new JSZip(); var file_name = 'images.zip'; Array.from(imgs).forEach((item,index,array) => { file_name = ''; var zipFolder = zip.folder('images'); var img = new Image(); img.setAttribute("crossOrigin",'Anonymous') img.src = item.getAttribute('src'); img.onload = function(){//圖片加載完,再draw 和 toDataURL var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.height; var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, img.width, img.height); var imgdata = canvas.toDataURL(); var img_arr = imgdata.split(','); zipFolder.file(item.getAttribute('data-alt'), img_arr[1], {base64: true}); if(Object.getOwnPropertyNames((zipFolder.files)).length -1 === array.length) { zip.generateAsync({type: "blob"}).then(function (content) { saveAs(content, file_name); }); } }; }); } </script> </body> </html>
toDataUrl()方法可能會跨域,若是用nginx能夠直接加一個headercss
add_header 'Access-Control-Allow-Origin' '*';
html