見出し画像

p5.jsの作品を動画にしたいメモ

まだまだ研究中! 🌱


p5.jsでつくった作品を動画化する方法について、

と教えていただいたのでCCaptureを触ってみました!

CCapture.jsはcanvasの内容を画像としてキャプチャできるライブラリです。
調べてみると、p5.js内にある saveFrames() も "saveFrames() will only save the first 15 frames of an animation" とあり、それよりも長いアニメーションを生成する際にはCCaptureの利用がおすすめされているようです。

コードは下記を参考にさせていただきました。

// trueでキャプチャ
const captureEnabled = true;
const fps = 60;
// 録画時間のミリ秒
const duration = 1000 * 3;
let startMillis;

let capturer = new CCapture({
  format: "png",
  framerate: fps,
  name: "myCanvas",
  verbose: true,
});

function setup() {
  createCanvas(300, 300);
  frameRate(fps);
}

function draw() {
  if (captureEnabled && frameCount === 1) {
    startCapturing();
  }

  let elapsed = millis() - startMillis;
  let t = map(elapsed, 0, duration, 0, 1);
  if (captureEnabled && t > 1) {
    finishCapture();
  }

  drawScene();

  if (captureEnabled) {
    handleCapture();
  }
}

// 通常のdrawの中身を書く
function drawScene() {
  background(200);
  push();
  translate(width / 2, width / 2);
  rotate(frameCount * 0.05);
  ellipse(0, 0, 200, 30);
  pop();
}

function startCapturing() {
  capturer.start();
  startMillis = millis();
}

function finishCapture() {
  noLoop();
  capturer.stop();
  capturer.save();
}

function handleCapture() {
  capturer.capture(document.getElementById("defaultCanvas0"));
}

↑を実行したら圧縮ファイルが作成されるので、解凍してffmpegで動画化!

$ ffmpeg -r 60 -f image2 -s 300x300 -i "./myCanvas/%07d.png" -vcodec libx264 -crf 17 -pix_fmt yuv420p output.mp4

WEBGLモードでも特に追加の記述なく録画できるようでした。


X(Twitter)にいい感じに投稿できるよう研究中です🤔


Processingとp5.jsとクリエイティブコーディングが大好きです。 めちゃくちゃ元気!