I want to access my device camera using javascript . But this code only works in firefox and that too on desktop . I want to access my camera on other browsers as well as mobile devices.
function start()
{
var video = document.getElementById('video'),
vendorUrl = window.URL;
navigator.mediaDevices.getUserMedia({
video: true,
audio: true
})
.then(function(stream) {
video.src = vendorUrl.createObjectURL(stream);
video.play();
})
.catch(function(err) {
alert("no");
});
};
I want to access my device camera using javascript . But this code only works in firefox and that too on desktop . I want to access my camera on other browsers as well as mobile devices.
function start()
{
var video = document.getElementById('video'),
vendorUrl = window.URL;
navigator.mediaDevices.getUserMedia({
video: true,
audio: true
})
.then(function(stream) {
video.src = vendorUrl.createObjectURL(stream);
video.play();
})
.catch(function(err) {
alert("no");
});
};
Share
Improve this question
asked Mar 25, 2018 at 7:59
Yeshwant BhattYeshwant Bhatt
311 silver badge4 bronze badges
1
- Possible duplicate of how to make getUserMedia() work on all browsers – Sebastian Simon Commented Mar 25, 2018 at 8:06
2 Answers
Reset to default 3
(function() {
'use strict';
var video = document.querySelector('video')
, canvas;
function takeSnapshot() {
var img = document.querySelector('img') || document.createElement('img');
var context;
var width = video.offsetWidth
, height = video.offsetHeight;
canvas = canvas || document.createElement('canvas');
canvas.width = width;
canvas.height = height;
context = canvas.getContext('2d');
context.drawImage(video, 0, 0, width, height);
img.src = canvas.toDataURL('image/png');
document.body.appendChild(img);
}
if (navigator.mediaDevices) {
// access the web cam
navigator.mediaDevices.getUserMedia({video: true})
.then(function(stream) {
video.srcObject = stream
video.addEventListener('click', takeSnapshot);
})
.catch(function(error) {
document.body.textContent = 'Could not access the camera. Error: ' + error.name;
});
}
})();
video, img {
max-width:100%;
}
<video autoplay></video>
Copy it to your local and run
Hope this helps you
Mobile browsers need a valid click event to start playing video, so video.play() will not work on mobile until it receives this. Just add a play icon over the video (only on mobile) to induce the user to click, and bind video.play() to this click event.