Access Device Camera from static HTML page using Javascript Camera API

<video id="video"></video>
if(navigator && navigator.mediaDevices){
//Your browser is supporting camera API.
}else{
console.log("camera API is not supported by your browser")
}
if(navigator && navigator.mediaDevices){
navigator.mediaDevices.getUserMedia(options)
.then(function(stream) {
//use the stream to you code
})
.catch(function(err) {
//Handle error here
});
}else{
console.log("camera API is not supported by your browser")
}
{ audio: true }
{ video: { facingMode: "user" } }
{ video: { facingMode: { exact: "environment" } } }
if(navigator && navigator.mediaDevices){
const options = { audio: false, video: { facingMode: "user", width: 200, height: 200 } }
navigator.mediaDevices.getUserMedia(options)
.then(function(stream) {
var video = document.querySelector('video');
video.srcObject = stream;
video.onloadedmetadata = function(e) {
video.play();
};
})
.catch(function(err) {
//Handle error here
});
}else{
console.log("camera API is not supported by your browser")
}
var video, canvas, ctx;
if(navigator && navigator.mediaDevices){
const options = { audio: false, video: { facingMode: "user", width: 300, height: 300 } }
navigator.mediaDevices.getUserMedia(options)
.then(function(stream) {
video = document.querySelector('video');
video.srcObject = stream;
video.onloadedmetadata = function(e) {
video.play();
};
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext('2d');
})
.catch(function(err) {
//Handle error here
});
}else{
console.log("camera API is not supported by your browser")
}

function clickPhoto() {
ctx.drawImage(video, 0,0, canvas.width, canvas.height);
}
<body>
<div style="text-align: center;">
<video id="video" style="text-align: center; border-radius: 20px;"></video>
</div>
<div style="text-align: center;">
<button type="button" class="btn btn-warning" onclick="clickPhoto();">Take Photo</button>
</div>
<div style="text-align: center;">
<canvas id="myCanvas" width="300" height="300" style="text-align: center; border-radius: 20px;"></canvas>
</div>
</body>

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Khan M. Tabish

Khan M. Tabish

I am a web developer - both front end developer / designer and backend programmer and passionate about new technologies.