![見出し画像](https://assets.st-note.com/production/uploads/images/143387308/rectangle_large_type_2_61d044688157705ed771941c9860e982.png?width=800)
p5.jsの作品を動画にしたいメモ
まだまだ研究中! 🌱
p5.jsでつくった作品を動画化する方法について、
ありがとうございます!CCaptureで静止画を取り込んだあと、FFmpegで動画にしています。720x720以下、2000kbps以下にすることで動画の圧縮を防いでいます!
— kusakari (@kusakarism) May 19, 2024
と教えていただいたので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)にいい感じに投稿できるよう研究中です🤔
CCaptureで動画をつくるテスト! pic.twitter.com/e4UFFmpzFd
— レオナ@技術書典オンライン (@reona396) June 7, 2024
Processingとp5.jsとクリエイティブコーディングが大好きです。 めちゃくちゃ元気!