0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JSで複数のCanvasをPNGにしてZipでまとめてダウンロード

Last updated at Posted at 2024-02-06

ダミーの画像を量産したいなと思って、JavaScriptのみで画像を沢山作成してZipでダウンロードさせてみました。
Canvasから画像を生成してZipでまとめる部分が肝になると思いますのでその個所を一部抜粋。
jQuery使ってます。

$(function(){
  $("#download_btn").on("click", () => {
    // JSZipを読み込む
    const zip = new JSZip();

    // #chanvas_areaに入っているcanvasを取り出す
    const child_nodes = $("#canvas_area").children("canvas");

    // blobの生成が非同期になるのでPromiseで終了を捕捉する
    let add_to_zip = (zip_obj, canvas, filename) => {
      return new Promise((resolve, reject) => {
        canvas.toBlob(blob => {
          zip_obj.file(filename, blob);
          resolve();
        }, "image/png", 1);
      });
    }

    // 一旦add_to_zipを配列に入れておく
    add_to_zip_array = [];
    for (var i = 0; i < child_nodes.length; i++) {
      var name = $(child_nodes[i]).attr("name");
      add_to_zip_array.push(add_to_zip(zip, child_nodes[i], name + ".png"));
    }

    // 全てのblobができたらzipにまとめてダウンロードさせる
    Promise.all(add_to_zip_array).then(() => {
      zip.generateAsync({type:"blob"}).then(function(compressData) {
        var zip_blob = new Blob([compressData], { 'type': 'application/zip' });
        const a = document.createElement("a");
        a.href = URL.createObjectURL(zip_blob);
        a.download = "dummy.zip";
        a.click();
      });
    });
  });
});

ここで動作を確認できます
https://kensukesakakibara.github.io/DummyImageGenerator/

githubに上げてます
https://github.com/KensukeSakakibara/DummyImageGenerator

以上

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?