canvas video recorder
by Konstantin Cryman
HTML
<canvas id='testCanvas' width="320" height="240" ></canvas><br>
<button id="record"> record </button>
<input id="recordName" type="text" value="test_record">
<!--
<input id="recordExt" type="text" value="webm">
-->
JavaScript
// base record function
function CanvasVideoRecorder( canvas, _resultRecordName, __format ) {
const resultRecordName = _resultRecordName || 'transition_record';
const format = __format || 'webm'
const chunks = [];
const stream = canvas.captureStream();
const recorder = new MediaRecorder(stream);
recorder.ondataavailable = e => chunks.push(e.data);
recorder.onstop = e => {
// save recorded data
const toExport = new Blob(chunks, { type: 'video/' + format } );
console.log( 'toExport', toExport );
const vid = document.createElement('video');
vid.src = URL.createObjectURL( toExport );
vid.controls = true;
const a = document.createElement('a');
a.download = resultRecordName + '.' + format;
a.href = vid.src;
a.textContent = 'download the video';
a.click();
};
// return record api for one recording
return {
start: () => { recorder.start(); },
stop: () => { recorder.stop() }
};
}
//
//
//
//
//
//
//
//
// demo scripts
const can = document.getElementById( 'testCanvas' );
can.width = 320;
can.height = 240;
const ctx = can.getContext( '2d' );
ctx.fillStyle = '#ff0000';
let nextYPosition = 0;
let testPosition = 0;
let lastPosition = 0;
let lineGeight = can.height/80;
const animator = () => {
for( let i = 0; i < 15; i++ ){
ctx.fillStyle = 'rgb(' + [
Math.floor( Math.random() * 255 ),
Math.floor( Math.random() * 255 ),
Math.floor( Math.random() * 255 )
].join(',') + ')';
ctx.fillRect( testPosition, nextYPosition, testPosition - lastPosition, lineGeight );
lastPosition=testPosition;
testPosition+=Math.random()*5;
if( testPosition > can.width ){
testPosition = 0;
nextYPosition += lineGeight;
if( nextYPosition >= can.height ){
nextYPosition = 0;
}
}
}
...