How to record a canvas element

I write this short article because I haven’t find many resources in order to record a HTML5 canvas element in JavaScript properly on the web.

I assume that you have the following HTML code in your page:

<canvas></canvas>
<video></video>

Then, we have to create a MediaStream object from your canvas. For that we use the captureStream function:

var videoStream = canvas.captureStream(30); // the parameter is the desired framerate, see the MDN doc for more info

Then, we have to create a MediaRecorder object:

var mediaRecorder = new MediaRecorder(videoStream);

We have to store the available data returned by this MediaRecorder object:

var chunks = [];
mediaRecorder.ondataavailable = function(e) {
chunks.push(e.data);
};

And to convert it into a video when we finished the recording:

mediaRecorder.onstop = function(e) {
var blob = new Blob(chunks, { 'type' : 'video/mp4' }); // other types are available such as 'video/webm' for instance, see the doc for more info
chunks = [];
var videoURL = URL.createObjectURL(blob);
video.src = videoURL;
};

To start and stop the recording, just use the following functions:

mediaRecorder.start();
mediaRecorder.stop();

I wrote you a simple example which record a canvas element for five seconds:

I hope I helped you and I wish you a great day!