[PWA] Access the Camera in a PWA built with React
It‘s possible to access some,but not all,of the native device features from a PWA. One that we?canaccess,is the camera and camera roll. We‘ll use two different methods to allow users to upload images to our application. First,we‘ll add a file? Next,we‘ll access the camera feed directly by rendering a? ? class Profile extends Component { state = { image: null,supportsCamera: ‘mediaDevices‘ in navigator } changeImage = (e) => { this.setState({ image: URL.createObjectURL(e.target.files[0]) }) } startChangeImage = () => { this.setState({ enableCamera: !this.state.enableCamera }) } takeImage = () => { this._canvas.width = this._video.videoWidth this._canvas.height = this._video.videoHeight this._canvas.getContext(‘2d‘).drawImage( this._video,this._video.videoWidth,this._video.videoHeight ) this._video.srcObject.getVideoTracks().forEach(track => { track.stop() }) this.setState({ image: this._canvas.toDataURL(),enableCamera: false }) } render() { return ( <div> <nav className="navbar navbar-light bg-light"> <span className="navbar-brand mb-0 h1"> <Link to="/"> <img src={Back} alt="logo" style={{ height: 30 }} /> </Link> Profile </span> </nav> <div style={{ textAlign: ‘center‘ }}> <img src={this.state.image || GreyProfile} alt="profile" style={{ height: 200,marginTop: 50 }} /> <p style={{ color: ‘#888‘,fontSize: 20 }}>username</p> { this.state.enableCamera && <div> <video ref={c => { this._video = c if(this._video) { navigator.mediaDevices.getUserMedia({ video: true }) .then(stream => this._video.srcObject = stream) } }} controls={false} autoPlay style={{ width: ‘100%‘,maxWidth: 300 }} ></video> <br /> <button onClick={this.takeImage} >Take Image</button> <canvas ref={c => this._canvas = c} style={{ display: ‘none‘ }} /> </div> } <br /> { this.state.supportsCamera && <button onClick={this.startChangeImage} > Toggle Camera </button> } </div> </div> ) } } ? Video,Code (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |