---
# System prepended metadata

title: Canvas to webm

---

# Canvas to webm

將 canvas 畫面禎輸出成 webm 

#### 限制：ios 無法

## 變數

```
const canvas = document.querySelector("canvas");
const recordBtn = document.getElementById('btn');
let recording = false;
let mediaRecorder;
let recordedChunks;
```

## 錄影

```
recordBtn.addEventListener("click", () => {
    recording = !recording;
    if(recording){
            recordBtn.textContent = "Stop";
            const stream = canvas.captureStream(25);
            mediaRecorder = new MediaRecorder(stream, {
                mimeType: 'video/webm;codecs=vp8',
                ignoreMutedMedia: true
            });
            recordedChunks = [];
            mediaRecorder.ondataavailable = e => {
                if(e.data.size > 0){
                    recordedChunks.push(e.data);
                }
            };
            mediaRecorder.start();
        } else {
            recordBtn.textContent = "Record"
            mediaRecorder.stop();
            setTimeout(() => {
                const blob = new Blob(recordedChunks, {
                    type: "video/webm"
                });
                const url = URL.createObjectURL(blob);
                const a = document.createElement("a");
                a.href = url;
                a.download = "recording.webm";
                a.click();
            },0);
        }
});
```
