为了账号安全,请及时绑定邮箱和手机立即绑定

使用设备相机在 reactjs 中捕获图像

使用设备相机在 reactjs 中捕获图像

阿波罗的战车 2023-05-11 16:55:14
我可以访问设备相机并在 ReactJs 中拍照吗?目标是创建一个组件,允许相机通过单击按钮拍照。根据我的研究,我应该使用 mediaDevices,但我正在寻找 ReactJs 中的示例代码。请提供示例代码,或者如果您有实施此经验的经验,请指导我。
查看完整描述

1 回答

?
万千封印

TA贡献1891条经验 获得超3个赞

我已经准备了一个可以用作组件的示例代码。此代码片段适用于也有两个摄像头的设备。如果您想拍摄视频而不是照片,您还可以在输出中启用音频功能。


import React from "react";


class App extends React.Component {

  constructor() {

    super();


    this.cameraNumber = 0;


    this.state = {

      imageDataURL: null,

    };

  }


  initializeMedia = async () => {

    this.setState({ imageDataURL: null });


    if (!("mediaDevices" in navigator)) {

      navigator.mediaDevices = {};

    }


    if (!("getUserMedia" in navigator.mediaDevices)) {

      navigator.mediaDevices.getUserMedia = function (constraints) {

        var getUserMedia =

          navigator.webkitGetUserMedia || navigator.mozGetUserMedia;


        if (!getUserMedia) {

          return Promise.reject(new Error("getUserMedia Not Implemented"));

        }


        return new Promise((resolve, reject) => {

          getUserMedia.call(navigator, constraints, resolve, reject);

        });

      };

    }


    //Get the details of video inputs of the device

    const videoInputs = await this.getListOfVideoInputs();


    //The device has a camera

    if (videoInputs.length) {

      navigator.mediaDevices

        .getUserMedia({

          video: {

            deviceId: {

              exact: videoInputs[this.cameraNumber].deviceId,

            },

          },

        })

        .then((stream) => {

          this.player.srcObject = stream;

        })

        .catch((error) => {

          console.error(error);

        });

    } else {

      alert("The device does not have a camera");

    }

  };


  capturePicture = () => {

    var canvas = document.createElement("canvas");

    canvas.width = this.player.videoWidth;

    canvas.height = this.player.videoHeight;

    var contex = canvas.getContext("2d");

    contex.drawImage(this.player, 0, 0, canvas.width, canvas.height);

    this.player.srcObject.getVideoTracks().forEach((track) => {

      track.stop();

    });


    console.log(canvas.toDataURL());

    this.setState({ imageDataURL: canvas.toDataURL() });

  };


  switchCamera = async () => {

    const listOfVideoInputs = await this.getListOfVideoInputs();


    // The device has more than one camera

    if (listOfVideoInputs.length > 1) {

      if (this.player.srcObject) {

        this.player.srcObject.getVideoTracks().forEach((track) => {

          track.stop();

        });

      }


      // switch to second camera

      if (this.cameraNumber === 0) {

        this.cameraNumber = 1;

      }

      // switch to first camera

      else if (this.cameraNumber === 1) {

        this.cameraNumber = 0;

      }


      // Restart based on camera input

      this.initializeMedia();

    } else if (listOfVideoInputs.length === 1) {

      alert("The device has only one camera");

    } else {

      alert("The device does not have a camera");

    }

  };


  getListOfVideoInputs = async () => {

    // Get the details of audio and video output of the device

    const enumerateDevices = await navigator.mediaDevices.enumerateDevices();


    //Filter video outputs (for devices with multiple cameras)

    return enumerateDevices.filter((device) => device.kind === "videoinput");

  };


  render() {

    const playerORImage = Boolean(this.state.imageDataURL) ? (

      <img src={this.state.imageDataURL} alt="cameraPic" />

    ) : (

      <video

        ref={(refrence) => {

          this.player = refrence;

        }}

        autoPlay

      ></video>

    );


    return (

      <div className="App">

        {playerORImage}

        <button onClick={this.initializeMedia}>Take Photo</button>

        <button onClick={this.capturePicture}>Capture</button>

        <button onClick={this.switchCamera}>Switch</button>

      </div>

    );

  }

}


export default App;


查看完整回答
反对 回复 2023-05-11
  • 1 回答
  • 0 关注
  • 120 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信