Access camera from a browser
Asked Answered
C

11

55

Is it possible to access the camera (built-in on Apples) from a browser?

Optimal solution would be client-side javascript. Looking to avoid using Java or Flash.

Chitwood answered 19/8, 2012 at 6:47 Comment(4)
disables own cameraAscham
See: #6976579Defect
@Aesthete: quite like the HTML5 geolocation object, it would request the permission first.Defect
From what I remembered, Flash can access the webcam/camera. I have doubt about JS.Chronograph
C
19

As of 2017, WebKit announces support for WebRTC on Safari

Now you can access them with video and standard javascript WebRTC

E.g.

var video = document.createElement('video');
video.setAttribute('playsinline', '');
video.setAttribute('autoplay', '');
video.setAttribute('muted', '');
video.style.width = '200px';
video.style.height = '200px';

/* Setting up the constraint */
var facingMode = "user"; // Can be 'user' or 'environment' to access back or front camera (NEAT!)
var constraints = {
  audio: false,
  video: {
   facingMode: facingMode
  }
};

/* Stream it to video element */
navigator.mediaDevices.getUserMedia(constraints).then(function success(stream) {
  video.srcObject = stream;
});

Have a play with it.

Corn answered 4/8, 2017 at 1:26 Comment(1)
Hi, but ios webview is still not supported, is it? Do you have any workaround to access camera in ios webview? Other issue reference: #54320424 ThanksCocotte
D
17

The HTML5 spec does allow accessing the webcamera, but last I checked, it is far from finalized, and has very, very little browser support.

This is a link to get you started: http://www.html5rocks.com/en/tutorials/getusermedia/intro/

You'll probably have to use flash if you want it to work cross-browser.

W3 draft

Defect answered 19/8, 2012 at 6:51 Comment(0)
I
6

There is a really cool solution from Danny Markov for that. It uses navigator.getUserMedia method and should work in modern browsers. I have tested it successfully with Firefox and Chrome. IE didn't work:

Here is a demo:

https://tutorialzine.github.io/pwa-photobooth/

Link to Danny Markovs description page:

http://tutorialzine.com/2016/09/everything-you-should-know-about-progressive-web-apps/

Link to GitHub:

https://github.com/tutorialzine/pwa-photobooth/

Imagination answered 8/12, 2016 at 16:23 Comment(1)
THis doesn't work on iOS 10 devices (havent tested anything else). It says this browser doesnt support getUserMedia or something along those lines.Feudist
A
5

Yes it is possible to access the camera from the browser, following is the code that worked for me

<html><head>
</head><body>
    <video src="" ></video>
    <br />
<button id='flipCamera'>Flip</button>
</body>
<script>
  var front = false;
var video = document.querySelector('video');
  document.getElementById('flipCamera').onclick = function() { front = !front; };
  var constraints = { video: { facingMode: (front? "user" : "environment"), width: 640, height: 480  } };
  navigator.mediaDevices.getUserMedia(constraints)
  .then(function(mediaStream) {
    video.srcObject = mediaStream;
    video.onloadedmetadata = function(e) {
    video.play();
};
})
.catch(function(err) { console.log(err.name + ": " + err.message); })
</script></html>
Axletree answered 25/5, 2021 at 18:22 Comment(0)
C
3

Possible with HTML5.

http://www.html5rocks.com/en/tutorials/getusermedia/intro/

Chitwood answered 19/8, 2012 at 6:53 Comment(0)
B
2

You can use HTML5 for this:

<video autoplay></video>
<script>
  var onFailSoHard = function(e) {
    console.log('Reeeejected!', e);
  };

  // Not showing vendor prefixes.
  navigator.getUserMedia({video: true, audio: true}, function(localMediaStream) {
    var video = document.querySelector('video');
    video.src = window.URL.createObjectURL(localMediaStream);

    // Note: onloadedmetadata doesn't fire in Chrome when using it with getUserMedia.
    // See crbug.com/110938.
    video.onloadedmetadata = function(e) {
      // Ready to go. Do some stuff.
    };
  }, onFailSoHard);
</script>

Source

Bowleg answered 19/8, 2012 at 6:57 Comment(0)
M
2
    <style type="text/css">
        #container {
            margin: 0px auto;
            width: 500px;
            height: 375px;
            border: 10px #333 solid;
        }

        #videoElement {
          width: 500px;
          height: 375px;
          background-color: #777;
        }
    </style>    
<div id="container">
            <video autoplay="true" id="videoElement"></video>
        </div>
        <script type="text/javascript">
          var video = document.querySelector("#videoElement");
          navigator.getUserMedia = navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia||navigator.oGetUserMedia;
    
          if(navigator.getUserMedia) {
            navigator.getUserMedia({video:true}, handleVideo, videoError);
          }
    
          function handleVideo(stream) {
            video.srcObject=stream;
            video.play();
          }
    
          function videoError(e) {
    
          }
        </script>
Mclemore answered 9/12, 2020 at 19:30 Comment(2)
Please provide some more explanation!Bovill
navigator.getUserMedia() is deprecated. Use the newer version navigator.mediaDevices.getUserMedia() instead.Emerson
B
1

If you are just after a camera to take a still photo then just use on a mobile device. See https://stackoverflow.com/a/76922004

Bottali answered 7/2 at 16:26 Comment(0)
T
0

Video Tutorial: Accessing the Camera with HTML5 & appMobi API will be helpful for you.

Also, you may try the getUserMedia method (supported by Opera 12)

enter image description here

Trisyllable answered 19/8, 2012 at 6:59 Comment(1)
The link doesn't seem to go to a tutorial anymoreThermidor
B
0

**SIMPLE JAVASCRIPT VANILLA **

var video = document.querySelector("#videoElement");

if (navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia({ video: true })
        .then(function (stream) {
            video.srcObject = stream;
        })
        .catch(function (err0r) {
            console.log("Something went wrong!");
        });
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta content="stuff, to, help, search, engines, not" name="keywords">
<meta content="What this page is about." name="description">
<meta content="Display Webcam Stream" name="title">
<title>Display Webcam Stream</title>
<style>
  #container{
   align-self: center;
   margin-left: 350px;
   align-items: center;
   justify-content: center;
position: relative;
    width: 1000px;
    height: 1000px;
       background-color: black;
       padding: 3px;
  }
  #videoElement{
    transform: rotate(90deg);
   align-self: center;
   height: 50a0px;
   left: 20;
   width: 700px;
   position:absolute;
   padding: 1px;
   top: 120px;
  }
</style>
</head>
  
<body>
<div id="container">
    <video autoplay="true" id="videoElement">
    </video>
</div>
<script src="index.js">

</script>
</body>
</html>
Barrault answered 31/12, 2020 at 14:54 Comment(1)
It was just a black background on Safari and Chrome. It asked permission to use the camera but nothing appeared.Billingsley
I
0

As navigator.getUserMedia is deprecated and part of legacy API, use navigator.mediaDevices.getUserMedia instead. It proved to be compatible with Firefox and Chrome:

function loadCamera ()
{
   let v = document.getElementById ("myvideo");
   navigator.mediaDevices.getUserMedia({video:{width:v.width, height:v.height}})
      .then((mediaStream) => {  v.srcObject = mediaStream; })
      .catch(e => { console.error(`${e.name}: ${e.message}`); });

   v.play();
}

loadCamera ();

Also an option is to load it in memory, if the video image is intended to be manipulated or processed before showing, for instance background replacement, or as WebGL2 texture:

function makeVideo (height, width)
{
   let video  = document.createElement ("video");
   video.height      = height;
   video.width       = width;
   video.autoplay    = true;
   video.playsInline = true;
   video.muted       = true;
   video.loop        = true;
   return video;
}
async function loadCamera (height, width)
{
   let v  = makeVideo (height, width);

   navigator.mediaDevices.getUserMedia({video:{width:width, height:height}})
      .then((mediaStream) => {  v.srcObject = mediaStream; })
      .catch(e => { console.error(`${e.name}: ${e.message}`); });

   v.play();
   return v;

}

In then handler add any handling

loadCamera (180, 320).then(video => { document.body.appendChild(video); });
Incisor answered 26/11, 2023 at 15:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.