使用手机相机拍照
Using mobile camera to take a picture
我需要向我的网络应用程序添加一项功能,以允许用户使用他们的移动设备拍照。幸运的是 HTML5 和现代浏览器都支持这个 API,但是我很难找到任何可用的示例。
这是我找到的一个示例,它似乎有效(在 DuckDuckGo 浏览器上除外):
<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>
如何让它选择后置摄像头,即 capture="environment" 而不是 "user"?
您需要提供以下约束对象;目前你没有通过正确的要求 rear camera
.
const constraints = {
audio: true,
video:
{
facingMode: { exact: "environment" }
}
}
我需要向我的网络应用程序添加一项功能,以允许用户使用他们的移动设备拍照。幸运的是 HTML5 和现代浏览器都支持这个 API,但是我很难找到任何可用的示例。
这是我找到的一个示例,它似乎有效(在 DuckDuckGo 浏览器上除外):
<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>
如何让它选择后置摄像头,即 capture="environment" 而不是 "user"?
您需要提供以下约束对象;目前你没有通过正确的要求 rear camera
.
const constraints = {
audio: true,
video:
{
facingMode: { exact: "environment" }
}
}