I tried this and it worked, but the video starts lagging after 30 seconds. No matter what I do, the video records smoothly for 30 seconds and then starts lagging. Am I missing something?
I’m not using requestAnimationFrame because it only works if the tab is active. I’m seeing my PC’s memory and CPU usage while I’m recording. I don’t see any huge spikes
const screenVideo = document.createElement("video");
screenVideo.style.display = "none";
screenVideo.srcObject = screenStream;
screenVideo.muted = true;
const webcamVideo = document.createElement("video");
webcamVideo.style.display = "none";
webcamVideo.srcObject = videoStream;
webcamVideo.muted = true;
webcamVideo.onloadedmetadata = () => {
webcamVideo.play();
};
canvas = document.createElement("canvas");
screenVideo.onloadedmetadata = () => {
screenVideo.play();
canvas.width = screenVideo.videoWidth;
canvas.height = screenVideo.videoHeight;
};
canvasContext = canvas.getContext("2d");
const drawCombinedStream = () => {
if (!canvasContext || stopDrawingFrames) return;
canvasContext.clearRect(0, 0, canvas.width, canvas.height);
canvasContext.drawImage(screenVideo, 0, 0, canvas.width, canvas.height);
const overlaySize = 250;
const overlayX = 20;
const overlayY = canvas.height - overlaySize - 20;
const overlayRadius = overlaySize / 2;
const webcamAspectRatio =
webcamVideo.videoWidth / webcamVideo.videoHeight;
let drawWidth, drawHeight;
if (webcamAspectRatio > 1) {
drawHeight = overlaySize;
drawWidth = overlaySize * webcamAspectRatio;
} else {
drawWidth = overlaySize;
drawHeight = overlaySize / webcamAspectRatio;
}
const offsetX = overlayX - (drawWidth - overlaySize) / 2;
const offsetY = overlayY - (drawHeight - overlaySize) / 2;
canvasContext.save();
canvasContext.beginPath();
canvasContext.arc(
overlayX + overlayRadius,
overlayY + overlayRadius,
overlayRadius,
0,
Math.PI * 2,
);
canvasContext.clip();
canvasContext.drawImage(
webcamVideo,
offsetX,
offsetY,
drawWidth,
drawHeight,
);
canvasContext.restore();
setTimeout(drawCombinedStream, 1000 / 30);
};
drawCombinedStream();
combinedVideoStream = canvas.captureStream(30);