我想从使用网络摄像头录制的视频中捕获帧,并将帧作为 base64 格式编码图像或每 10 秒作为 jpg 图像发送到服务器。
我编写了使用网络摄像头的代码,并且我知道可以单击或捕获图像,但我如何每隔 x 秒向服务器发送一个帧?
P.S- 网络摄像头将 24*7 在线并且应该每 x 秒发送一次帧
这是我的代码:
<!DOCTYPE html>
<html>
<head>
<title> Webcam Trial </title>
<style>
body {
margin: 0;
font-family: Arial, Helvetica, sans-serif;
}
.topnav {
overflow: hidden;
background-color: #333;
}
.topnav a {
float: left;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
#container {
margin: 0px auto;
width: 599px;
height: 600px;
border: 10px #333 solid;
}
#videoElement {
width: 599px;
height: 600px;
background-color: #cc22cc;
}
</style>
</head>
<body>
<div class="topnav">
<a class="active" href="#home">Video Demo</a>
</div>
<div>
<h2>Video demo</h2>
</div>
<div id="container">
<video autoplay="true" id="videoElement">
</video>
</div>
<script>
var video = document.querySelector("#videoElement");
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({video: true})
.then(function(stream) {
video.srcObject = stream;
})
.catch(function(err0r) {
console.log("Something went wrong!");
});
}
</script>
</body>
</html>
请帮我解决这个问题。
编辑的 JS 部分(使用了 Philip 的回答,仍然无法使其工作):
<script>
var video = document.querySelector("#videoElement");
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({video: true})
.then(function(stream) {
video.srcObject = stream;
})
.catch(function(error) {
console.log("Something went wrong!");
});
}
const cnv = document.createElement('canvas'),
ctx = cnv.getContext('2d');
ctx.drawImage(video,50,50);
let data = cnv.toDataUrl();
x=10000;
function every (x) {
let last = new Date().getTime();
(function loop () {
const now = new Date().getTime(),
delta = now - last;
if (delta >= x) {
//capture video
last = now;
}
window.requestAnimationFrame(loop);
})();
}
最佳答案
要捕获单个帧,您需要一个 <canvas>
元素并使用其 Context2d.drawImage()
1 方法如下:
const cnv = document.createElement('canvas'),
ctx = cnv.getContext('2d');
ctx.drawImage(video, 0,0);
//2
let data = cnv.toDataURL('image/png');
每 x
做到这一点seconds 你需要一种间隔3,可能是这样的:
function every (x) {
let last = new Date().getTime();
(function loop () {
const now = new Date().getTime(),
delta = now - last;
if (delta >= x) {
//capture video
last = now;
}
window.requestAnimationFrame(loop);
})();
}
关于javascript - 如何每 10 秒捕获一次帧并将其发送到服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55098689/