gpt4 book ai didi

javascript - 在 HTML Canvas 上播放视频

转载 作者:行者123 更新时间:2023-12-05 02:38:01 26 4
gpt4 key购买 nike

我正在尝试将视频播放到 HTML Canvas。除了当我试图隐藏视频源并只显示 Canvas 时,我没有任何问题。在这种情况下,我只会得到一个“白屏”。如果视频元素没有隐藏,一切都会按预期工作。我不想显示视频元素和 Canvas 元素,我只想显示具有视频源“流式传输”的 Canvas 元素。有什么建议么?附上代码示例...

let sourcevideo = document.getElementById("sourcevideo");
let outputcanvas = document.getElementById("outputcanvas");
let canvasctx = outputcanvas.getContext("2d");

function initCanvas() {
outputcanvas.width = sourcevideo.videoWidth;
outputcanvas.height = sourcevideo.videoHeight;
console.log(outputcanvas.width, outputcanvas.height);
drawVideo();
}

function drawVideo() {
canvasctx.drawImage(
sourcevideo,
0,
0,
outputcanvas.width,
outputcanvas.height
);
requestAnimationFrame(drawVideo);
}

sourcevideo.addEventListener("loadeddata", initCanvas);
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>

<body>
<div id="videocontainer">
<video id="sourcevideo" controls src="https://upload.wikimedia.org/wikipedia/commons/transcoded/c/c4/Physicsworks.ogv/Physicsworks.ogv.240p.vp9.webm"></video>
</div>
<canvas id="outputcanvas"></canvas>
</body>

</html>

最佳答案

首先,使用此 $('#sourcevideo').css('visibility', 'hidden'); 隐藏视频容器的可见性,然后您将看到静止图像,以防止使用 autoplay="autoplay",通过这样做,您的视频元素将隐藏,您的 Canvas 也将正确运行视频。

let sourcevideo = document.getElementById("sourcevideo");
let outputcanvas = document.getElementById("outputcanvas");
let canvasctx = outputcanvas.getContext("2d");

function initCanvas() {
outputcanvas.width = sourcevideo.videoWidth;
outputcanvas.height = sourcevideo.videoHeight;
console.log(outputcanvas.width, outputcanvas.height);
drawVideo();
}

function drawVideo() {
canvasctx.drawImage(
sourcevideo,
0,
0,
outputcanvas.width,
outputcanvas.height
);
requestAnimationFrame(drawVideo);
}
sourcevideo.addEventListener("loadeddata", initCanvas);
sourcevideo.style.visibility = 'hidden';
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>

<body>
<div>
<canvas id="outputcanvas"></canvas>
</div>
<div id="videocontainer">
<video id="sourcevideo" autoplay="autoplay" controls src="https://upload.wikimedia.org/wikipedia/commons/transcoded/c/c4/Physicsworks.ogv/Physicsworks.ogv.240p.vp9.webm"></video>
</div>

</body>

</html>

关于javascript - 在 HTML Canvas 上播放视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69819307/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com