Accessing the device camera using HTML5 GetUserMedia
Download complete source file here.
Primarily here’s the code that does that:
navigator.mediaDevices.getUserMedia
which takes a “contstraints” object as an argument which at the minimum looks like this:
var constraints = { audio: false, video: true }
1 2 3 4 5 6 7 8 9 |
navigator.mediaDevices.getUserMedia(constraints).then(function (stream) { videoElem.srcObject = stream; videoElem.onloadedmetadata = function(e){ videoElem.play(); } streamRef = stream; }).catch(function (e) { console.log("Error", e); }); |
videoElem is a <video> element on the page.
1 2 3 4 5 6 7 8 9 10 11 |
try{ videoElem.pause(); var tracks = streamRef.getTracks(); for(var t in tracks){ tracks[t].stop(); } } catch(err){ console.log("Error stopping video: " + err); } |
For simplicity reasons, I haven’t written this code to fail gracefully or support older browsers which may support a slightly different syntax. This is something to consider when you may be using this for something serious.