/
Camera.js
98 lines (86 loc) · 2.14 KB
/
Camera.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
const React = require('inferno-compat')
const {storePicture} = require('../store')
class Camera extends React.Component {
constructor (props) {
super(props)
this.state = {
takingPicture: false
}
const functions = [
'setTakingPicture',
'clearTakingPicture',
'takePicture'
]
functions.forEach(fn => {
this[fn] = this[fn].bind(this)
})
}
setTakingPicture () {
this.setState({takingPicture: true})
}
clearTakingPicture () {
this.setState({takingPicture: false})
}
takePicture () {
let videoStream
this.setTakingPicture()
navigator
.mediaDevices
.getUserMedia({video: true, audio: false})
.then(stream => {
this.video.srcObject = stream
this.video.play()
videoStream = stream
})
.catch(error => console.error('oh no:', error))
this.video.addEventListener('canplay', () => {
setTimeout(() => {
const context = this.canvas.getContext('2d')
const style = getComputedStyle(this.video)
const width = parseInt(style.width)
const height = parseInt(style.height)
this.canvas.setAttribute('width', width)
this.canvas.setAttribute('height', height)
context.drawImage(
this.video,
0, 0,
width, height
)
storePicture(this.canvas.toDataURL('image/jpeg', true))
.then(picture => {
this.props.addPicture(picture)
this.clearTakingPicture()
videoStream.getTracks()[0].stop()
})
.catch(error => console.error('error adding picture', error))
}, 1000)
})
}
render () {
const {
takingPicture
} = this.state
return (
<div>
{takingPicture &&
<div>
<video
ref={node => {
this.video = node
}}
/>
<canvas
ref={node => {
this.canvas = node
}}
/>
</div>
}
<button onClick={this.takePicture}>
📷
</button>
</div>
)
}
}
module.exports = Camera