Last active
August 27, 2021 08:28
-
-
Save Asgarrrr/70721accbbc60705b976359ec3c40109 to your computer and use it in GitHub Desktop.
Allows video export of a canvas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Allows video export of a canvas | |
* | |
* @param {Number} [fps = 60] — Frames per second. | |
* @param {Number} [recordTime = 6000] — Canvas recording time in ms | |
* @param {Object} [options] — Recording settings, please refer to https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder#properties | |
*/ | |
function canvasToVideo( fps = 60, recordTime = 6000, options ) { | |
navigator.getUserMedia = ( navigator.getUserMedia || navigator.webkitGetUserMedia ||navigator.mozGetUserMedia || navigator.msGetUserMedia ); | |
if ( !navigator.mediaDevices ) | |
throw new Error( "getUserMedia not supported." ); | |
const canvas = document.querySelector( "canvas" ) | |
, stream = canvas.captureStream( fps ) | |
, recordedChunks = []; | |
options = options || { | |
videoBitsPerSecond : 68000000, | |
videoMaximizeFrameRate : true, | |
mimeType : window.chrome ? "video/webm;codecs=vp9" : "video/webm;" | |
}; | |
mediaRecorder = new MediaRecorder( stream, options ); | |
mediaRecorder.ondataavailable = handler; | |
mediaRecorder.start(); | |
function handler( e ) { | |
if ( e.data.size > 0 ) { | |
recordedChunks.push( e.data ); | |
download(); | |
} | |
} | |
function download() { | |
const blob = new Blob( recordedChunks, { type: "video/webm" } ) | |
, url = URL.createObjectURL( blob ) | |
, a = document.createElement( "a" ); | |
document.body.appendChild( a ); | |
a.style = 'display: none'; | |
a.href = url; | |
a.download = `${prompt( "filename" )}.wepm` | |
a.click(); | |
window.URL.revokeObjectURL( url ); | |
} | |
setInterval( () => console.log( mediaRecorder ), 1500 ); | |
setTimeout( ( event ) => { console.log( "—— Recording end" ); mediaRecorder.stop() }, recordTime ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment