我已经getUserMedia
使用headtrackr库使用 HTML5 实现了头部跟踪功能。另外,我有一个画布,我正在画一个笑脸,当网络摄像头跟踪它时,它会随着头部的移动而移动。
到目前为止,一切都很好。一切正常。我面临的问题是停止网络摄像头。我遵循了这一点,但没有任何效果。
我知道无论如何我必须停止流。我有一个停止按钮,它不仅可以停止相机,还需要清除画布。这就是实际问题所在。我的停止功能实现没有释放网络摄像头,即它保持打开但头部跟踪停止并且画布也没有被清除。
下面是我的javascript代码
var cameraStream = null;
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia
|| navigator.mozGetUserMedia || navigator.msGetUserMedia;
var videoInput = document.getElementById('inputVideo');
if (!navigator.getUserMedia) {
fallback();
} else {
navigator.getUserMedia({
audio : true,
video : true
}, success, fallback);
}
document.addEventListener('facetrackingEvent', function(event) {
$('#parameters').html(
"Height: " + event.height + " Width: " + event.width + "\n X: "
+ event.x + " Y: " + event.y);
setTimeout(function() {
drawCircle(event.x, event.y);
}, 500);
});
function fallback(e) {
videoInput.src = 'fallbackvideo.webm';
console.log('Reeeejected!', e);
}
function success(stream) {
alert(stream);
cameraStream = stream;
var canvasInput = document.getElementById('inputCanvas');
videoInput.src = window.URL.createObjectURL(stream);
var htracker = new headtrackr.Tracker();
htracker.init(videoInput, canvasInput);
htracker.start();
}
function drawCircle(x, y) {
canvas = document.getElementById('faceCanvas');
context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = '#0000FF';
context.fillStyle = '#FFFF00';
context.lineWidth = 4;
context.beginPath();
context.arc(x, y, 50, 0, Math.PI * 2, true);
context.closePath();
context.stroke();
context.fill();
// The smile
context.strokeStyle = '#FF0000';
context.lineWidth = 2;
context.beginPath();
context.arc(x, y - 10, 40, 0.2 * Math.PI, 0.8 * Math.PI, false);
// context.closePath();
context.stroke();
// context.fill();
// The Left eye
context.strokeStyle = '#000000';
context.fillStyle = '#000000';
context.beginPath();
context.arc(x - 20, y - 15, 10, 0 * Math.PI, 2 * Math.PI, false);
context.closePath();
context.stroke();
context.fill();
// The Right Eye
context.strokeStyle = '#000000';
context.fillStyle = '#000000';
context.beginPath();
context.arc(x + 20, y - 15, 10, 0 * Math.PI, 2 * Math.PI, false);
context.closePath();
context.stroke();
context.fill();
}
/**
* stops head tracking
*/
function stopTracking(){
cameraStream.stop();
videoInput.src="";
canvas = document.getElementById('faceCanvas');
context = canvas.getContext('2d');
context.clearRect(0,0,canvas.width,canvas.height);
}
我的 HTML 代码在这里
<canvas id="inputCanvas" ></canvas>
<video id="inputVideo" autoplay=""></video>
<div id="parameters"></div>
<canvas id="faceCanvas"></canvas>
<button id="stop" onclick="stopTracking();">Stop Tracking</button>
<script src="resources/js/facedetection.js"></script>
<script src="resources/js/headtrackr.min.js"></script>
<script src="resources/js/jquery-1.9.1.min.js"></script>