【p5.js】スケッチを画像としてダウンロードする

canvas要素をtoDataURL()メソッドで画像データに変換し、aタグのリンク先のURLに指定することで画像ファイルとしてダウンロードできるようにする。
そして、bodyタグの最後の行に以下の1行を追加する。

<script src="script.js"></script>

index.html

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>【p5.js】スケッチを画像としてダウンロードする</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>
    <script src="sketch.js"></script>
  </head>
  <body>
    <button id="download" type="button">Download</button>
    <script src="script.js"></script>
  </body>
</html>

sketch.js

function setup() {
  let canvas = createCanvas(windowWidth, windowHeight);
  canvas.position(0, 0);
  canvas.style('z-index', '-1');
}

function draw() {
  fill(0);
  rect(0, 0, width, height/2);
  fill(255);
  rect(0, height/2, width, height/2);
  arc(width/2, height/2, 300, 300, PI, TWO_PI);
  fill(0);
  arc(width/2, height/2, 300, 300, 0, PI);
  arc(width/2, height/2, 290, 290, PI, TWO_PI);
  fill(255);
  arc(width/2, height/2, 290, 290, 0, PI);
}

script.js

document.getElementById("download").onclick = function() {
  let canvas = document.getElementById("defaultCanvas0");
  let link = document.createElement("a");
  link.href = canvas.toDataURL();
  link.download = "sample.png";
  link.click();
}

今回の場合、「Download」ボタンをクリックすると、スケッチが sample.png という画像ファイルとしてダウンロードされる。

サンプルページ

タイトルとURLをコピーしました