是否可以通过网站控制手机上的摄像头灯?

Tin*_*rus 16 javascript mobile google-chrome

是否可以通过网站控制手机上的摄像头灯?通过Chrome或Firefox说.我知道可以使用Android或iOS应用程序,许多手电筒应用程序都在那里.我知道可以通过getUserMedia系列功能控制摄像机.如果没有,有谁知道什么时候可用?

Dan*_*ick 21

这是一个网站的小"火炬应用程序":

编辑1:我也做了一个jsfiddle

//Test browser support
const SUPPORTS_MEDIA_DEVICES = 'mediaDevices' in navigator;

if (SUPPORTS_MEDIA_DEVICES) {
  //Get the environment camera (usually the second one)
  navigator.mediaDevices.enumerateDevices().then(devices => {
  
    const cameras = devices.filter((device) => device.kind === 'videoinput');

    if (cameras.length === 0) {
      throw 'No camera found on this device.';
    }
    const camera = cameras[cameras.length - 1];

    // Create stream and get video track
    navigator.mediaDevices.getUserMedia({
      video: {
        deviceId: camera.deviceId,
        facingMode: ['user', 'environment'],
        height: {ideal: 1080},
        width: {ideal: 1920}
      }
    }).then(stream => {
      const track = stream.getVideoTracks()[0];

      //Create image capture object and get camera capabilities
      const imageCapture = new ImageCapture(track)
      const photoCapabilities = imageCapture.getPhotoCapabilities().then(() => {

        //todo: check if camera has a torch

        //let there be light!
        const btn = document.querySelector('.switch');
        btn.addEventListener('click', function(){
          track.applyConstraints({
            advanced: [{torch: true}]
          });
        });
      });
    });
  });
  
  //The light will be on as long the track exists
  
  
}
Run Code Online (Sandbox Code Playgroud)
<button class="switch">On / Off</button>
Run Code Online (Sandbox Code Playgroud)

该代码受到此存储库,此Web系列和此博客帖子的启发

编辑2: 这仅适用于Chrome(也许是Opera).它在iOS上的Chrome中无效,因为Chrome无法访问相机.我现在无法在Android上测试它.我用输出创建了一个新的jsfiddle.如果你有一部Android手机并且它不适合你,它可能会告诉你原因:https: //jsfiddle.net/jpa1vwed/

随意调试,评论和编辑.

  • 这适用于iOS吗?我有一个工作的应用程序在iOS上的Safari 11中使用getUserMedia访问摄像头但是剪切不适合我.有没有人测试过这个? (3认同)
  • 有人可以更新这个以向火炬添加切换功能吗?一旦手电筒打开,就无法将其关闭 (2认同)
  • @DanielBudick Chrome 可以并且确实访问 iPhone 上的两个摄像头,您需要使用正确的 html5 输入标签`&lt;input type="file"accept="image/*" capture="environment"&gt;`“environment”用于后向和“用户”代表正面。 (2认同)

ltl*_*Boy 5

您可以使用MediaStream图像捕捉API通过创建ImageCapture中VideoStreamTrack和设置选项“fillLightMode”“闪”“火炬”。例:

<video autoplay="true"></video>
<img />
<button onclick="takePhoto()">Take Photo</button>
<script type="text/javascript">
    var imageCapture = null;
    var deviceConfig = {
        video: {
            width: 480,
            height: 640,
            facingMode: "environment", /* may not work, see https://bugs.chromium.org/p/chromium/issues/detail?id=290161 */
            deviceId: null
        }
    };

    var imageCaptureConfig = {
        fillLightMode: "torch", /* or "flash" */
        focusMode: "continuous"
    };

    // get the available video input devices and choose the one that represents the backside camera
    navigator.mediaDevices.enumerateDevices()
            /* replacement for not working "facingMode: 'environment'": use filter to get the backside camera with the flash light */
            .then(mediaDeviceInfos => mediaDeviceInfos.filter(mediaDeviceInfo => ((mediaDeviceInfo.kind === 'videoinput')/* && mediaDeviceInfo.label.includes("back")*/)))
            .then(mediaDeviceInfos => {
                console.log("mediaDeviceInfos[0].label: " + mediaDeviceInfos[0].label);

                // get the device ID of the backside camera and use it for media stream initialization
                deviceConfig.video.deviceId = mediaDeviceInfos[0].deviceId;
                navigator.mediaDevices.getUserMedia(deviceConfig)
                        .then(_gotMedia)
                        .catch(err => console.error('getUserMedia() failed: ', err));
            });

    function takePhoto () {
        imageCapture.takePhoto()
                .then(blob => {
                    console.log('Photo taken: ' + blob.type + ', ' + blob.size + 'B');

                    // get URL for blob data and use as source for the image element
                    const image = document.querySelector('img');
                    image.src = URL.createObjectURL(blob);
                })
                .catch(err => console.error('takePhoto() failed: ', err));
    }

    function _gotMedia (mediastream) {
        // use the media stream as source for the video element
        const video = document.querySelector('video');
        video.srcObject = mediastream;

        // create an ImageCapture from the first video track
        const track = mediastream.getVideoTracks()[0];
        imageCapture = new ImageCapture(track);

        // set the image capture options (e.g. flash light, autofocus, ...)
        imageCapture.setOptions(imageCaptureConfig)
                .catch(err => console.error('setOptions(' + JSON.stringify(imageCaptureConfig) + ') failed: ', err));
    }
</script>
Run Code Online (Sandbox Code Playgroud)

注意:

  • 撰写本文时,API仍在开发中,将来可能会更改。
  • 要在Chrome中启用ImageCapture,必须将标志“ chrome:// flags /#enable-experimental-web-platform-features”设置为“ true”
  • 为使ImageCapture中的 Firefox中的标志“dom.imagecapture.enabled”“about:config中”已被设置为“真”但是在撰写本文时,不支持“ setOptions”

也可以看看: