说明
CanvasRecorder.js是 ES5 写法,本文改为 ES6 写法,可以在 VUE 中使用
CanvasRecorder.js 介绍
详见:
https://www.malaoshi.top/show_1IX8QuEGJXio.html
代码
// https://github.com/SMUsamaShah/CanvasRecorder
class CanvasRecorder {
constructor(canvas, video_bits_per_sec){
this.canvas = canvas
this.video_bits_per_sec = video_bits_per_sec
this.recordedBlobs = [];
this.supportedType = null;
this.mediaRecorder = null;
// 指定60帧
this. stream = canvas.captureStream(60);
if (typeof this.stream == undefined || !this.stream) {
return;
}
this. video = document.createElement('video');
this.video.style.display = 'none';
}
start() {
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])) {
this.supportedType = types[i];
break;
}
}
if (this.supportedType == null) {
console.log("No supported type found for MediaRecorder");
}
let options = {
mimeType: this.supportedType,
videoBitsPerSecond: this.video_bits_per_sec || 2500000 // 2.5Mbps
};
this.recordedBlobs = [];
try {
this.mediaRecorder = new MediaRecorder(this.stream, options);
} catch (e) {
alert('MediaRecorder is not supported by this browser.');
console.error('Exception while creating MediaRecorder:', e);
return;
}
// console.log('Created MediaRecorder', this.mediaRecorder, 'with options', options);
this.mediaRecorder.onstop = (event) => {
// console.log('Recorder stopped: ', event);
const superBuffer = new Blob(this.recordedBlobs, { type: this.supportedType });
this.video.src = window.URL.createObjectURL(superBuffer);
};
this.mediaRecorder.ondataavailable = (event)=>{
if (event.data && event.data.size > 0) {
this.recordedBlobs.push(event.data);
}
}
this.mediaRecorder.start(100); // collect 100ms of data blobs
// console.log('MediaRecorder started', this.mediaRecorder);
}
stop() {
this.mediaRecorder.stop();
// console.log('Recorded Blobs: ', this.recordedBlobs);
this.video.controls = true;
}
download(file_name) {
const name = file_name || 'recording.webm';
const blob = new Blob(this.recordedBlobs, { type: this.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);
}
}
export {CanvasRecorder}
vue中使用
import {CanvasRecorder} from '../js/CanvasRecorder.js'
exportCanvas(){
const recorder = new CanvasRecorder(this.canvasDom)
this.play()
recorder.start();
setTimeout(function(){
recorder.stop();
recorder.download('下载.webm');
},3000)
}