You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Canvas录制1080P/30fps屏幕与摄像头画面,30秒后卡顿的问题求助

使用Canvas录制1080P/30fps屏幕与摄像头画面,30秒后卡顿的问题求助

我写了一段用Canvas合成屏幕流和摄像头流然后录制的代码,前30秒录制都很流畅,但30秒之后视频就开始卡顿了,不管怎么测试都是这个规律,有没有大佬能帮我看看是不是哪里漏了什么细节?

另外说下我的排查情况:我没有用requestAnimationFrame来绘制帧,因为这个API在标签页非激活状态下会失效,不符合我的需求;录制过程中我一直在观察电脑的内存和CPU占用,没看到明显的突增情况,这就更让我摸不着头脑了。

核心代码如下:

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);

备注:内容来源于stack exchange,提问作者tedGuy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.15 10:24:51