我知道
<input type="file" accept="image/*" capture>
允许用户拍照的方法(以及类似的其他示例 here 和 accept="video/*"
等),并且在使用此方法时,单击 <input>
通常会打开手机的相机应用,允许用户拍照,然后返回原始页面。
但是如何使用 Javascript 直接在 HTML 页面中预览相机<div>
和“拍照”按钮,即不必打开手机的相机应用程序?
(当然,用户必须授予对手机摄像头的访问权限)
最佳答案
感谢this tutorial ,我终于使用 getUserMedia
找到了解决方案.
注意:从 Chrome 的最新版本开始,出于安全原因,它仅在网站为 HTTPS 时才有效。您可以使用 "C:\Program Files\Google\Chrome\Application\chrome.exe"--unsafely-treat-insecure-origin-as-secure="http://123.123.123.123"
如果您想在非 HTTPS 网站上测试它。
var videoElement = document.querySelector('video');
var audioSelect = document.querySelector('select#audioSource');
var videoSelect = document.querySelector('select#videoSource');
audioSelect.onchange = getStream;
videoSelect.onchange = getStream;
getStream().then(getDevices).then(gotDevices);
function getDevices() { return navigator.mediaDevices.enumerateDevices(); }
function gotDevices(deviceInfos) {
window.deviceInfos = deviceInfos;
for (const deviceInfo of deviceInfos) {
const option = document.createElement('option');
option.value = deviceInfo.deviceId;
if (deviceInfo.kind === 'audioinput') { option.text = deviceInfo.label || `Microphone ${audioSelect.length + 1}`; audioSelect.appendChild(option); }
if (deviceInfo.kind === 'videoinput') { option.text = deviceInfo.label || `Camera ${videoSelect.length + 1}`; videoSelect.appendChild(option); }
}
}
function getStream() {
if (window.stream) { window.stream.getTracks().forEach(track => { track.stop(); }); }
const audioSource = audioSelect.value;
const videoSource = videoSelect.value;
const constraints = { audio: {deviceId: audioSource ? {exact: audioSource} : undefined}, video: {deviceId: videoSource ? {exact: videoSource} : undefined} };
return navigator.mediaDevices.getUserMedia(constraints).then(gotStream).catch(handleError);
}
function gotStream(stream) {
window.stream = stream;
audioSelect.selectedIndex = [...audioSelect.options].findIndex(option => option.text === stream.getAudioTracks()[0].label);
videoSelect.selectedIndex = [...videoSelect.options].findIndex(option => option.text === stream.getVideoTracks()[0].label);
videoElement.srcObject = stream;
}
function handleError(error) { console.error('Error: ', error); }
<div id="container">
<div class="select"><label for="audioSource">Audio source: </label><select id="audioSource"></select></div>
<div class="select"><label for="videoSource">Video source: </label><select id="videoSource"></select></div>
<video autoplay muted playsinline></video>
</div>
关于javascript - 如何直接在 HTML 页面中拍照(而不打开相机应用程序)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58477150/