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.
Asked
Active
Viewed 1,547 times
1 Answers
5
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.

Nino Filiu
- 16,660
- 11
- 54
- 84
-
Thank you very much for your reply. However, I did not state what I wanted to do for react in the question. Sorry. My main problem is actually on the react side. – Tolga Günaydın May 21 '21 at 08:30
-
Yes but it's a pure JS solution so it works in React, where is the issue? – Nino Filiu May 21 '21 at 08:55
-
Actually, the problem is that I just haven't started react and I don't know exactly how to transfer it to react. When I transfer it like this, I get a property null error in the video src part. I also get an error like Cannot read property 'getContext' of null. So unfortunately it makes a lot of mistakes. – Tolga Günaydın May 21 '21 at 09:01
-
Well just use [refs](https://reactjs.org/docs/refs-and-the-dom.html) instead of `querySelector` and you're good. "How to transfer it to React" is hard to answer further if you don't explain your use case and include [an MRE](https://stackoverflow.com/help/minimal-reproducible-example). – Nino Filiu May 21 '21 at 09:04
-
ahh. Tank you i will look at refs parts. – Tolga Günaydın May 21 '21 at 09:06
-
Hello there. I managed to record video, but I want to also record audio. Do you have any knowledge about this topic? – Tolga Günaydın May 28 '21 at 07:34