mozmorris/react-webcamを使ってブラウザからreactでカメラを利用する。
まずは環境を作る。
$ yarn create react-app webcam-sample --typescript $ cd webcam-sample/ $ yarn add react-webcam @types/react-webcam
スクリーンショットを撮るサンプルがGitHubにあるので、それを参考にしてTypeScriptで書いてみる。
スクリーンショットを撮ったらとりあえず、imgタグに突っ込んでおく。
仕事で使うならこれをサーバ側に保存したり、canvasに流して加工できるようにする必要があるだろう。
App.tsxを編集する。
import React from "react"; import Webcam from "react-webcam"; interface State { img_src: string; } export default class App extends React.Component<any, State> { constructor(props: any) { super(props); this.state = { img_src: "" }; } capture = () => { const imageSrc = (this.refs.webcam as Webcam).getScreenshot(); if (imageSrc) { this.setState({ img_src: imageSrc }); } }; render() { const videoConstraints = { width: 1280, height: 720, facingMode: "user" }; return ( <div> <div> <Webcam audio={false} height={350} ref={"webcam"} screenshotFormat="image/jpeg" width={350} videoConstraints={videoConstraints} onUserMediaError={() => window.alert('cant access your camera')} /> </div> <div> <button onClick={this.capture}>Capture photo</button> </div> <div> <img src={this.state.img_src} /> </div> </div> ); } }
これで起動すれば、ブラウザが立ち上がってカメラへのアクセスを許可するか聞いてくる。
$ yarn start