[英]HTML5 & javascript - taking pictures from a device supporting multiple cameras
I am developing a Vuejs based PWA.我正在开发一个基于 Vuejs 的 PWA。 I have implemented a component to take pictures using the device built-in camera.我已经实现了一个使用设备内置相机拍照的组件。 It is using它正在使用
navigator.mediaDevices.getUserMedia
API with a video
element to display the stream from the camera. navigator.mediaDevices.getUserMedia
API 带有一个video
元素,用于显示来自相机的流。canva
and its getContext("2d").drawImage
methods to get the picture from the stream and show it to the user一个canva
及其getContext("2d").drawImage
方法从流中获取图片并将其显示给用户navigator.mediaDevices.enumerateDevices
API to get a list of available cameras and the constraint parameter of getUserMedia
to switch between these. navigator.mediaDevices.enumerateDevices
API 获取可用摄像机列表和getUserMedia
的约束参数以在这些之间切换。This is all working great :)这一切都很好:)
But now I have stumbled on a new issue: some recent smartphones have multiple rear cameras that the built-in camera software would combine to take only one shoot (one camera would be good at low exposure, another one at high exposure and yet another one in some other conditions, etc.).但是现在我偶然发现了一个新问题:最近的一些智能手机有多个后置摄像头,内置相机软件会将这些摄像头组合起来只拍摄一张照片(一个相机适合低曝光,另一个适合高曝光,还有一个在其他一些条件下,等等)。 In this case my app will show all the cameras and will let the user use them independently.在这种情况下,我的应用程序将显示所有相机并让用户独立使用它们。 The intended behavior would be to combine them just like the built-in software.预期的行为是像内置软件一样将它们组合起来。 How is that possible?这怎么可能?
After trying on multiple devices having 1 (front), 2 (back and front) and multiples camera sensors (1 front, several back), my solution consists in using the label property of the MediaDeviceInfo
object returned by mediaDevices.enumerateDevices()
:在尝试具有 1 个(正面)、2 个(背面和正面)和多个摄像头传感器(1 个正面,多个背面)的多个设备后,我的解决方案包括使用mediaDevices.enumerateDevices()
返回的MediaDeviceInfo
对象的 label 属性:
Then my code getting the id of the front camera and of the combined backed camera is the following (it assumes there is always one and only one front camera):然后我的代码获取前置摄像头和组合后置摄像头的 id 如下(它假设总是只有一个前置摄像头):
return navigator.mediaDevices.enumerateDevices()
.then(mediaDevices => {
let cameras = mediaDevices.filter(mediaDevice => mediaDevice.kind === 'videoinput');
console.log("#potential camera=" + cameras.length);
if(cameras.length<=2)
return cameras.map(x => x.deviceId);
else {
let front = cameras.find(x => x.label.match(/\bfront\b/));
let back = cameras.filter(x => x.label.match(/\bback\b/) && x.label.match(/\b0\b/))
if(!front || back.length!=1) {
console.log("no clear front and back, taking first and last one - cameras=", cameras);
return [cameras[0].deviceId, cameras[cameras.length-1].deviceId];
}
else {
console.log("clear front and back");
return [front.deviceId, back[0].deviceId];
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.