-
Notifications
You must be signed in to change notification settings - Fork 3
/
CanvasRecorder.js
96 lines (84 loc) · 2.96 KB
/
CanvasRecorder.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// CanvasRecorder.js - smusamashah
// To record canvas effitiently using MediaRecorder
// https://webrtc.github.io/samples/src/content/capture/canvas-record/
function CanvasRecorder(canvas, video_bits_per_sec) {
this.start = startRecording;
this.stop = stopRecording;
this.save = download;
var recordedBlobs = [];
var supportedType = null;
var mediaRecorder = null;
var stream = canvas.captureStream();
if (typeof stream == undefined || !stream) {
return;
}
const video = document.createElement('video');
video.style.display = 'none';
function startRecording() {
let types = [
"video/webm",
'video/webm,codecs=vp9',
'video/vp8',
"video/webm\;codecs=vp8",
"video/webm\;codecs=daala",
"video/webm\;codecs=h264",
"video/mpeg"
];
for (let i in types) {
if (MediaRecorder.isTypeSupported(types[i])) {
supportedType = types[i];
break;
}
}
if (supportedType == null) {
console.log("No supported type found for MediaRecorder");
}
let options = {
mimeType: supportedType,
videoBitsPerSecond: video_bits_per_sec || 2500000 // 2.5Mbps
};
recordedBlobs = [];
try {
mediaRecorder = new MediaRecorder(stream, options);
} catch (e) {
alert('MediaRecorder is not supported by this browser.');
console.error('Exception while creating MediaRecorder:', e);
return;
}
console.log('Created MediaRecorder', mediaRecorder, 'with options', options);
mediaRecorder.onstop = handleStop;
mediaRecorder.ondataavailable = handleDataAvailable;
mediaRecorder.start(100); // collect 100ms of data blobs
console.log('MediaRecorder started', mediaRecorder);
}
function handleDataAvailable(event) {
if (event.data && event.data.size > 0) {
recordedBlobs.push(event.data);
}
}
function handleStop(event) {
console.log('Recorder stopped: ', event);
const superBuffer = new Blob(recordedBlobs, { type: supportedType });
video.src = window.URL.createObjectURL(superBuffer);
}
function stopRecording() {
mediaRecorder.stop();
console.log('Recorded Blobs: ', recordedBlobs);
video.controls = true;
}
function download(file_name) {
const name = file_name || 'recording.webm';
const blob = new Blob(recordedBlobs, { type: supportedType });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = name;
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 100);
}
}