首页 > 解决方案 > 无法显示反应图片应用程序的画布元素

问题描述

我正在尝试创建一个简单的应用程序来使用 reactJS 拍照。

似乎我能找到的所有示例都是使用 refs 的老派,以及我们不再使用的所有有趣的东西,我试图避免这些。

但无论如何,目前它不起作用。根据我看到的教程,我需要将我的视频元素传递到画布中,我不明白。

无论如何,我当前的组件如下:

export default class Camera extends Component {
 constructor (props) {
    super(props)

    this.canvasRef = React.createRef()
    this.videoRef = React.createRef()
    this.state = {
      stream: {}
    }
  }

  async componentDidMount () {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ video: { width: 640, height: 480 } })

      if (stream) {
        this.setState({
          stream
        })
      }
    } catch (err) {
      console.error(err)
    }
  }

  render () {
    const video = document.getElementById('video')
    const context = (this.canvasRef && this.canvasRef.getContext('2d'))
    context && context.drawImage(document.getElementById('video'), 0, 0, 640, 480)
    return (
      <>
        <video id='video' width='640' heigh='480' src={this.state.stream} autoPlay={true}/>
        <button onClick={(evt) => console.warn('take photo')}>Take photo!</button>
        <div>
          <canvas id='canvas' width='640' height='480' ref={ref => (this.canvasRef = ref)} />
        </div>
      </>
    )
  }
}

就目前而言,我得到的只是一个空白屏幕。问题似乎与画布有关,但我不知道我做错了什么。我还应该提到,理想情况下我什至不想使用 refs。我只想使用道具和状态,但我想首先我必须让它像现在一样工作。

标签: javascriptreactjshtml5-canvas

解决方案


据我所知,命令式动画仍然是 refs 的一个非常有效的用例: https ://reactjs.org/docs/refs-and-the-dom.html 。

在您的构造函数中,声明您的画布:

this.canvasRef = React.createRef();

然后像这样使用它

const canvas = this.canvasRef.current;
const ctx = canvas.getContext("2d");

在您的渲染函数中,将 ref 分配给您的画布元素:

<canvas ref={this.canvasRef} /> 

我个人发现将 Canvas 用于反应生命周期非常棘手,但绝对可以做到。祝你好运!


推荐阅读