反应网络摄像头 - 截取屏幕截图问题

时间:2016-09-03 23:53:26

标签: javascript reactjs npm

我试图使用react-webcam模块。我能够在网页上镜像网络摄像头视频。但是,当按下按钮时,我遇到了实现getScreenshot函数的问题。有人有建议吗?以下是我的代码。谢谢。

import React, { Component } from 'react';
import { emotionCapture } from '../actions';
import Webcam from 'react-webcam';

export default class FaceEmotion extends Component{

    constructor(props){
        super(props);
        this.state = { screenshot: null }
        this.screenshot = this.screenshot.bind(this);
    }
    // this is the area I'm having issues with. Thanks!
    screenshot() {
        console.log(Webcam);
        var screenshot = Webcam.getScreenshot();
        this.setState({screenshot: screenshot});
      }

    render(){

        return (
            <div>   
             <Webcam audio ={false}/>
             <button onClick={this.screenshot}>Capture</button>
             { this.state.screenshot ? <img src={this.state.screenshot} /> : null }
            </div>
            )
    }
}

2 个答案:

答案 0 :(得分:1)

尝试添加对网络摄像头组件的引用。这样您就可以获得屏幕上的网络摄像头。

import React, { Component } from 'react';
import { emotionCapture } from '../actions';
import Webcam from 'react-webcam';

export default class FaceEmotion extends Component{

    constructor(props){
        super(props);
        this.state = { screenshot: null }
        // this can be moved directly to the onClick event
        // this.screenshot = this.screenshot.bind(this);
    }
    // this is the area I'm having issues with. Thanks!
    screenshot() {
        // access the webcam trough this.refs
        var screenshot = this.refs.webcam.getScreenshot();
        this.setState({screenshot: screenshot});
      }

    render(){

        return (
            <div>   
             <Webcam audio ={false} ref='webcam'/> // add the reference
             <button onClick={this.screenshot.bind(this)}>Capture</button>
             { this.state.screenshot ? <img src={this.state.screenshot} /> : null }
            </div>
            )
    }
}

答案 1 :(得分:0)

在您的组件中添加以下代码

setRef = (webcam) => {
    this.webcam = webcam;
  };

然后将其用作渲染之类的参考

<Webcam
    audio={false}
    ref={this.setRef}
/>

然后捕获以执行以下操作

this.webcam.getScreenshot();

这将为您提供base64编码的图像字符串