传递给 video.addEventListener( "play") 事件的函数未定义



我目前正在开发一个React组件,该组件要求将视频元素中的帧传递到画布元素上。

当视频工作时,画布上没有画任何东西。我认为这是因为我写的画框架的方法不在范围内,如果我不确定下一步该怎么做,我会很感激对其他方法的任何想法。

import React, { Component, Fragment } from 'react'
class Stream extends Component {
constructor(props) {
super(props);
this.video = React.createRef();
this.canvas = React.createRef();
this.screen = React.createRef();
this.drawFrame = this.drawFrame.bind(this);
}
drawFrame(video) {
const screen = this.screen.current
screen.height = 500
screen.width = 500
let context = screen.getContext('2d')
context.drawImage(video, 0, 0, screen.width, screen.height)
context.drawImage(video, 0, 0, screen.width, screen.height)
requestAnimationFrame(this.drawFrame)
console.log("Screen", screen)
}
componentDidMount() {
// This code runs a video stream.
const video = this.video.current
navigator.mediaDevices.getUserMedia({ video: true, audio: false })
.then(function(stream) {
video.srcObject = stream
video.play()
// Says drawFrame is undefined if line below in uncommented.
//video.addEventListener("play", this.drawFrame(video), false);
console.log("Video is playing from component")
})
.catch(function(err) {
console.log("An error occurred! " + err)
})
}
componentDidUpdate() {}
render() {
return(
<Fragment>
<video
ref={this.video}
width="500"
height="500"
>Video stream is not available.</video>
<canvas
ref={this.screen}
width="500"
height="500"
>Canvas is not available in this browser.</canvas>
<canvas
ref={this.canvas}
width="500"
height="500"
>Canvas is not available in this browser.</canvas>
</Fragment>
)
}
}
export default Stream

您丢失了this引用的上下文。只需对词法上下文使用箭头函数:

.then((stream) => ...

如果你不能使用箭头函数,那么用老方法,关闭this并将其存储在另一个变量中,然后使用它:

componentDidMount() {
const _this = this;
// This code runs a video stream.
const video = this.video.current
navigator.mediaDevices.getUserMedia({ video: true, audio: false })
.then(function(stream) {
video.srcObject = stream
video.play()
video.addEventListener("play", _this.drawFrame(video), false);
console.log("Video is playing from component")
})

最新更新