我正在localhost XAMPP服务器上执行此代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<video onclick="changeFilter(this);"width=200 height=200 id="video" controls autoplay></video>
<p>
<button onclick="startWebcam();">Start WebCam</button>
<button onclick="stopWebcam();">Stop WebCam</button>
</p>
<script>
navigator.getUserMedia = ( navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
var webcamStream;
function startWebcam() {
if (navigator.getUserMedia) {
console.log("toto");
navigator.getUserMedia (
// constraints
{
video: true,
audio: false
},
// successCallback
function(localMediaStream) {
var video = document.querySelector('video');
video.src = window.URL.createObjectURL(localMediaStream);
webcamStream = localMediaStream;
},
// errorCallback
function(err) {
console.log("The following error occured: " + err);
}
);
} else {
console.log("getUserMedia not supported");
}
}
function stopWebcam() {
localMediaStream.stop();
}
</script>
</body>
</html>
此代码启动我的网络摄像头,但是当我按下Stop WebCam
按钮时,控制台会出现以下错误:
Uncaught TypeError: Cannot read property 'stop' of undefined function stopWebcam() { webcamStream.stop(); }
我是一名JavaScript新手,我在这里看不到问题。
答案 0 :(得分:1)
localMediaStream
。有关What is the scope of variables in JavaScript?
...试
function stopWebcam() {
webcamStream.stop();
}