Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to record video on canvas in React

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.

like image 294
Tolga Günaydın Avatar asked Nov 01 '25 20:11

Tolga Günaydın


1 Answers

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.

like image 65
Nino Filiu Avatar answered Nov 03 '25 09:11

Nino Filiu