Recording a div
Unanswered
Dwarf Hotot posted this in #help-forum
Dwarf HototOP
I would like to record a div to an mp4 file. But I'm not entirely sure how to do it.
3 Replies
Dwarf HototOP
import React, { useRef, useState } from "react";
import html2canvas from 'html2canvas';
export default function Test() {
const divRef = useRef(null);
const videoRef = useRef(null);
const mediaRecorderRef = useRef(null);
const recordedChunksRef = useRef([]);
const startRecording = async () => {
const canvas = await html2canvas(divRef.current);
const stream = canvas.captureStream();
// Check stream continuity by attempting to play it
checkStreamContinuity(stream);
// Create a new MediaRecorder for each recording session
mediaRecorderRef.current = new MediaRecorder(stream);
mediaRecorderRef.current.ondataavailable = (event) => {
if (event.data.size > 0) {
recordedChunksRef.current.push(event.data);
}
};
mediaRecorderRef.current.onstop = () => {
const blob = new Blob(recordedChunksRef.current, { type: 'video/webm' });
const videoUrl = URL.createObjectURL(blob);
videoRef.current.src = videoUrl;
};
recordedChunksRef.current = [];
mediaRecorderRef.current.start();
};
const stopRecording = () => {
if (mediaRecorderRef.current) {
mediaRecorderRef.current.stop();
}
};
// Function to check stream continuity
const checkStreamContinuity = (stream) => {
const video = document.createElement('video');
video.srcObject = stream;
// Attach the video to the DOM or play it programmatically
// Adjust as needed based on your application's structure
// document.body.appendChild(video);
// Listen for the 'ended' event to check if the video plays to the end
video.addEventListener('ended', () => {
console.log('Stream is continuous');
});
// Play the video
video.play()
.then(() => {
console.log('Stream playing');
})
.catch((error) => {
console.error('Error playing stream:', error);
});
};
return (
<div className={"flex flex-col w-full"}>
<div ref={divRef} className={"w-96 h-96 bg-red-500"}>Your content here</div>
<button onClick={startRecording}>Start Recording</button>
<button onClick={stopRecording}>Stop Recording</button>
<video ref={videoRef} controls style={{ display: 'block', marginTop: '10px' }} />
</div>
)
}I do get something back on the video element
But it's only a single frame