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"?
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"?
Share Improve this question asked May 19, 2021 at 18:39 santasanta 12.5k51 gold badges161 silver badges266 bronze badges1 Answer
Reset to default 5You 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