【发布时间】:2021-09-24 07:57:29
【问题描述】:
我目前正在开发一个 API,它将 videoTrack 作为输入并返回处理后的 videoTrack。我设法在画布上绘制处理后的视频,并希望使用canvas.captureStream() 从中捕获视频流。
事实证明,只有当我将画布加载到 DOM document.body.appendChild(myTempCanvas) 并保持显示时,我才能捕获非空白流,如果我隐藏画布 myTempCanvas.style.display="none",流将变为空白。
那么有什么方法可以捕获流并同时隐藏画布?
示例:如果取消注释 canvas.style.display = "none"; 行,则 output_video 也会变为空白。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Demo</title>
</head>
<body>
<div class="container">
<video autoplay class="input_video" ></video>
<canvas class="output_canvas"></canvas>
<video autoplay class="output_video" ></video>
</div>
<script>
const video = document.getElementsByClassName("input_video")[0];
const canvas = document.getElementsByClassName("output_canvas")[0];
const output_video = document.getElementsByClassName("output_video")[0];
let imageCapture = null;
let tmpStream = null;
navigator.mediaDevices.getUserMedia({
video: true
})
.then((stream) => {
imageCapture = new ImageCapture(stream.getVideoTracks()[0]);
window.requestAnimationFrame(frameloop);
tmpStream = canvas.captureStream(20);
// canvas.style.display = "none";
output_video.srcObject = tmpStream;
})
function frameloop() {
imageCapture.grabFrame()
.then(imageBitmap => {
drawCanvas(canvas, imageBitmap);
window.requestAnimationFrame(frameloop);
})
}
/* Utils */
function drawCanvas(canvas, img) {
canvas.width = getComputedStyle(canvas).width.split('px')[0];
canvas.height = getComputedStyle(canvas).height.split('px')[0];
let ratio = Math.min(canvas.width / img.width, canvas.height / img.height);
let x = (canvas.width - img.width * ratio) / 2;
let y = (canvas.height - img.height * ratio) / 2;
canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height,
x, y, img.width * ratio, img.height * ratio);
}
</script>
</body>
</html>
</script>
</body>
</html>
【问题讨论】:
-
您是否尝试使用
height:0;whidth:0;overflow: hidden;和position:fixed;将画布隐藏在 div 中?像这样的东西应该可以解决问题。 -
或使用负上/左
-
之前的重复目标都不是关于这个问题的,所以我确实重新提出了这个问题。但是,您所描述的不工作应该“正常工作”,因此请提供minimal reproducible example 和有关您的环境的信息。
-
@PeterO。每次我可以提供完整的答案时,我都会这样做。我提出了一些建议来帮助 OP 完成某些工作,但由于我无法准确解释那里发生的事情(我只有一些线索),我更愿意让其他人就 why 其中一部分,没有发布无用/不完整和/或错误的答案。
-
再一次,请提供minimal reproducible example。要回答标题中的问题,yes you can。您需要可见的画布意味着您正在做一些至少 odd 的事情。 DOM 中的不可见静音视频存在限制,但(据我所知)没有关于画布的限制。选项卡在后台时,许多计时方法都有限制,但将样式设置为无显示应该不会对其产生影响。所以,是的,我们需要一个最少的复制品才能为您提供最好的帮助。之前提供的 hack 是 hack,而不是解决方案。
标签: javascript canvas webrtc webgl mediastream