最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using mobile camera to take a picture - Stack Overflow

programmeradmin10浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 5

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

发布评论

评论列表(0)

  1. 暂无评论