请问有人为什么要两次提交POST请求?注意:发送第二个请求之前,大约有2分钟的延迟(完全相同的数据)。
该代码使用GetUserMedia()显示用户网络摄像头提要,并立即将快照复制到画布。然后,在使用jquery将其发布到服务器之前,它会获得一个数据URL。我遇到的问题是,第二个发布请求在第一个发布请求后两分钟左右用相同的数据执行。我一生无法解决问题的原因-请帮忙!
// The width and height of the captured photo. We will set the
// width to the value defined here, but the height will be
// calculated based on the aspect ratio of the input stream.
var width = 320; // We will scale the photo width to this
var height = 0; // This will be computed based on the input stream
// |streaming| indicates whether or not we're currently streaming
// video from the camera. Obviously, we start at false.
var streaming = false;
// The various HTML elements we need to configure or control. These
// will be set by the startup() function.
var video = null;
var canvas = null;
var track = null;
var video = document.getElementById('video');
var canvas = document.getElementById('canvas');
var photo = document.getElementById('photo');
var kill = null;
// get feed
navigator.mediaDevices.getUserMedia({ video: true, audio: false })
.then(function (stream) {
video.srcObject = stream;
track = stream.getTracks()[0]; // if only one media track
video.play();
})
.catch(function (err) {
console.log("An error occurred: " + err);
});
video.addEventListener('canplay', function (ev) { // when recieving stream
if (kill === null) {
if (!streaming) {
height = video.videoHeight / (video.videoWidth / width);
if (isNaN(height)) { // // Firefox currently has a bug
height = width / (4 / 3);
}
video.setAttribute('width', width); // make sure video and canvas html is correct size
video.setAttribute('height', height);
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
streaming = true;
ev.preventDefault();
var context = canvas.getContext('2d');
if (width && height) {
canvas.width = width;
canvas.height = height;
context.drawImage(video, 0, 0, width, height);
// !!!!!!!!!!!!!!!!!!!
$.post('/recv', {
img: canvas.toDataURL()
});
track.stop();
kill = 1;
ev.target.removeEventListener(ev.type, arguments.callee);
return false;
// !!!!!!!!!!!!!!!!!!!
}
} else {
return;
}
}
}, false);
<!DOCTYPE html>
<html>
<head>
<title>webrtc snapper</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
</head>
<body>
<div class="camera">
<video id="video"></video>
</div>
<canvas id="canvas">
</canvas>
<div class="output">
<img id="photo">
</div>
<script src="capture.js">
</script>
</body>
</html>
答案 0 :(得分:0)
canplay
事件是一个棘手的事件,它可以播放一次以上的事件,例如,当当前时间更改时,浏览器需要从缓存或网络中加载更多数据。这可以触发canplay事件。
为了解决它,有两种方法。
一个-如我上面所述,答案是使用标志。 我不支持此操作,因为混入标志会使您的代码复杂化,使其难以阅读且难以维护。
第二-要取消订阅该事件:
video.bind('canplay', function (ev) {
// your logic ....
video.unbind('canplay')
}
从jquery 3.0开始:
video.on('canplay', function (ev) {
// your logic ....
video.off('canplay')
}
上面的代码更干净,更易于阅读和维护。
最后,这取决于您的判断,最适合您的需求。
答案 1 :(得分:-3)
在收到POST之后。看来我忘记了添加它,这导致JQUERY重新发布(或类似的东西,因为express的发布部分被调用了两次。)
感谢您的回复。