[我正在尝试构建一个应用程序,使相机每隔一分钟自动拍摄一次图像,我试图在按钮标签上添加间隔,这意味着当应用程序运行时,每隔一分钟就会自动捕获图像
import React, { Component } from 'react';
export class CameraFeed extends Component {
processDevices(devices) {
devices.forEach(device => {
console.log(device.label);
this.setDevice(device);
});
}
async setDevice(device) {
const { deviceId } = device;
const stream = await navigator.mediaDevices.getUserMedia({ audio: false, video: { deviceId } });
this.videoPlayer.srcObject = stream;
this.videoPlayer.play();
}
async componentDidMount() {
const cameras = await navigator.mediaDevices.enumerateDevices();
this.processDevices(cameras);
}
takePhoto = () => {
const { sendFile } = this.props;
const context = this.canvas.getContext('2d');
context.drawImage(this.videoPlayer, 0, 0, 680, 360);
this.canvas.toBlob(sendFile);
};
render() {
return (
<div className="c-camera-feed">
<div className="c-camera-feed__viewer">
<video ref={ref => (this.videoPlayer = ref)} width="680" heigh="360" />
</div>
<button onClick={this.takePhoto}>Take photo!</button>
<div className="c-camera-feed__stage">
<canvas width="680" height="360" ref={ref => (this.canvas = ref)} />
</div>
</div>
);
}
}
首先,您需要跟踪间隔ID
this.intervalId = null;
然后,您将创建事件处理程序,该事件处理程序将在单击按钮时触发,并为takePhoto
订阅一个间隔
takePhotoEachDelay = (delay = 60 * 1000) => {
setInterval(this.takePhoto, delay);
}
卸载时,您需要取消订购该间隔,以避免任何不良行为。
componentWillUnmount() {
if (this.intervalId) { clearInterval(this.intervalId); }
}
最后,
<button onClick={this.takePhotoEachDelay }>Take photo!</button>