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// if you want to manually trigger the frames, that can be useful if you struggle to create a real-time animation:
var videoStream = canvas.captureStream(0);
// and then every time you want to capture a frame (in your render loop for example):
videoStream.getVideoTracks()[0].requestFrame();
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!