Reputation: 73
I did a long search and felt the need to ask here. The npm packages I used before did nothing. Has anyone done or experienced such an application before? All I want to do is record it as a video while drawing on the canvas element. Thanks in advance.
Upvotes: 4
Views: 2521
Reputation: 18473
Yes, you can use MediaStream, captureStream and MediaRecorder for that
Here's an example where some coloured squares are painted on a canvas, then a video is created with the recording:
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const stream = canvas.captureStream();
const recorder = new MediaRecorder(stream, { mimeType: 'video/webm' });
const video = document.querySelector('video');
ctx.fillStyle = 'red';
ctx.fillRect(100, 100, 50, 50);
setTimeout(() => {
ctx.fillStyle = 'blue';
ctx.fillRect(200, 50, 50, 50);
}, 1000);
recorder.start();
setTimeout(() => recorder.stop(), 2000);
recorder.addEventListener('dataavailable', (evt) => {
const url = URL.createObjectURL(evt.data);
video.src = url;
});
<canvas></canvas>
<video controls></video>
But basically once you get to the point where you have the recording URL, you can do anything with it, including creating a download link, automatically downloading the recording, etc.
Upvotes: 5