# 按 V 錄 5 秒影片（WebM）

正式網址：https://newmediaart.course.monolab.world/snippets/record-webm

用瀏覽器內建的 MediaRecorder 把畫布錄成影片，不用裝函式庫；檔案比 GIF 小很多，錄影時畫面照常跑、滑鼠互動也會錄進去。

- **分類**：存檔與輸出
- **行數**：54 行（p5.js 1.x／2.x）
- **在哪一堂用到**：[第 1 堂](https://newmediaart.course.monolab.world/lesson/01)

把 SECONDS、recorder 兩行放在最上面，keyPressed 裡的 if、startRecording、pad、timestamp 貼到下面。要上 IG 可以再用剪輯軟體把 WebM 轉成 MP4。

```js
// 按 V 把畫布錄成 5 秒影片（瀏覽器內建 MediaRecorder，不用裝函式庫）
// Chrome、Firefox 存成 .webm；Safari 存成 .mp4
const SECONDS = 5;
let recorder = null;

function setup() {
  createCanvas(600, 600);
}

function draw() {
  background(15);
  noStroke();
  for (let i = 0; i < 12; i++) {
    const a = frameCount * 0.02 + (i * TWO_PI) / 12;
    fill(255, 150 + i * 8, 80);
    circle(width / 2 + cos(a) * 180, height / 2 + sin(a) * 180, 40);
  }
}

function keyPressed() {
  if ((key === 'v' || key === 'V') && !recorder) {
    startRecording();
  }
}

function startRecording() {
  const stream = drawingContext.canvas.captureStream(60); // 每秒 60 格
  const chunks = [];
  recorder = new MediaRecorder(stream);
  recorder.ondataavailable = (e) => chunks.push(e.data);
  recorder.onstop = () => {
    const type = recorder.mimeType || 'video/webm';
    const a = document.createElement('a');
    a.href = URL.createObjectURL(new Blob(chunks, { type: type }));
    const ext = type.includes('mp4') ? '.mp4' : '.webm';
    a.download = 'sketch-' + timestamp() + ext;
    a.click(); // 跟 saveCanvas 一樣，交給瀏覽器下載
    recorder = null;
  };
  recorder.start();
  setTimeout(() => recorder.stop(), SECONDS * 1000);
  print('開始錄影 ' + SECONDS + ' 秒');
}

// 補零：7 → "07"。檔名長度一致，資料夾裡才會照時間排好
function pad(n) {
  return String(n).padStart(2, '0');
}

// 現在的日期時間：2026-09-29-1905-12（年-月-日-時分-秒）
function timestamp() {
  return year() + '-' + pad(month()) + '-' + pad(day()) + '-' +
    pad(hour()) + pad(minute()) + '-' + pad(second());
}
```

## 同類常用指令・存檔與輸出

- [按 S 存 JPG（檔名帶日期時間）](https://newmediaart.course.monolab.world/snippets/save-jpg-datetime)
- [按 S 存 PNG（透明背景）](https://newmediaart.course.monolab.world/snippets/save-png-transparent)
- [存高解析度圖（pixelDensity）](https://newmediaart.course.monolab.world/snippets/save-hires)
- [按 G 存 3 秒 GIF（saveGif）](https://newmediaart.course.monolab.world/snippets/save-gif)

[回到全部常用指令](https://newmediaart.course.monolab.world/snippets)

[到 Hahow 報名](https://hahow.in/cr/creative-code)。價格與優惠以 Hahow 頁面為準。
