javascript - 无法显示反应图片应用程序的画布元素
问题描述
我正在尝试创建一个简单的应用程序来使用 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。我只想使用道具和状态,但我想首先我必须让它像现在一样工作。
解决方案
据我所知,命令式动画仍然是 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 用于反应生命周期非常棘手,但绝对可以做到。祝你好运!
推荐阅读
- c++ - 从 C++ 中的字符串中提取数字
- c++ - 循环中的输入数据类型检查未按预期工作(C++)
- c# - 在面向 4.6 的应用程序中链接时,3.5 程序集中的 DTD 验证失败
- python - Python 错误处理重试代码
- javascript - AngularJS。输入无效时需要禁用按钮
- haskell - 在 ghci 中声明函数时出现“函数中的非详尽模式”错误
- openlayers - Openlayers 文本框
- google-chrome - 如何让 chrome 允许视频自动播放?
- java - 某些设备返回纬度和经度 0.0
- powershell - 在 PowerShell 中重复所有行项目