santa
santa

Reputation: 12512

Using mobile camera to take a picture

I need to add a functionality to my web app to allow users take pictures with their mobile device. Luckily HTML5 and modern browsers support this API, however I'm having pretty hard time finding any working examples.

Here's an example I found, which seems to work (except on DuckDuckGo browser):

<video id="player" autoplay></video>
<button id="capture">Capture</button>
<canvas id="canvas" width=320 height=240></canvas>
<script>
    const player = document.getElementById('player');
    const canvas = document.getElementById('canvas');
    const context = canvas.getContext('2d');
    const captureButton = document.getElementById('capture');

    const constraints = {
        video: true,
    };

    captureButton.addEventListener('click', () => {
        // Draw the video frame to the canvas.
        context.drawImage(player, 0, 0, canvas.width, canvas.height);
    });

    // Attach the video stream to the video element and autoplay.
    navigator.mediaDevices.getUserMedia(constraints)
        .then((stream) => {
            player.srcObject = stream;
        });
</script> 

How do I make it choose the back camera, i.e. capture="environment" instead of "user"?

Upvotes: 3

Views: 7281

Answers (1)

Rahul Kumar
Rahul Kumar

Reputation: 3157

You need to provide the following constraints object; currently you are not passing the correct one to require rear camera.

const constraints = {
  audio: true,
  video:
  {
    facingMode: { exact: "environment" }
  }
}

Check docs here

Upvotes: 5

Related Questions