gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:57:55 25 4
gpt4 key购买 nike

我目前正在开发一个 React 组件,该组件需要将来自视频元素的帧传递到 Canvas 元素上。

当视频播放时, Canvas 上没有绘制任何东西。我相信这是因为我编写的绘制框架的方法不在范围内,如果我对接下来要尝试的方法有任何想法,我将不胜感激。

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 引用的上下文。只需使用 arrow function对于词汇上下文:

.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")
})

关于javascript - 函数传递给 video.addEventListener ("play") 事件未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53448142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com