-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathreact-accelerometer.js
More file actions
89 lines (74 loc) · 2.25 KB
/
react-accelerometer.js
File metadata and controls
89 lines (74 loc) · 2.25 KB
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
import PropTypes from 'prop-types';
const React = require('react')
/**
* @usage
* <ReactAccelerometer useGravity multiplier={3}>
* {(position, rotation) => (
* <div style={{ transform: `translate3d(${position.x}px, ${position.y}px, 0)`}}>
* Hello there
* </div>
* )}
* </ReactAccelerometer>
*/
class ReactAccelerometer extends React.Component {
constructor (props) {
super(props)
this.state = {
x: null,
y: null,
z: null,
rotation: null,
landscape: false
}
this.handleAcceleration = this.handleAcceleration.bind(this)
this.handleOrientation = this.handleOrientation.bind(this)
}
componentDidMount () {
this.handleOrientation()
window.addEventListener('devicemotion', this.handleAcceleration)
window.addEventListener('orientationchange', this.handleOrientation)
}
componentWillUnmount () {
window.removeEventListener('devicemotion', this.handleAcceleration)
window.removeEventListener('orientationchange', this.handleOrientation)
}
handleOrientation (event) {
const { orientation } = window
this.setState({ landscape: orientation === 90 || orientation === -90 })
}
handleAcceleration (event) {
const { landscape } = this.state
const { useGravity, multiplier } = this.props
const acceleration = useGravity ? event.accelerationIncludingGravity : event.acceleration
const rotation = event.rotationRate || null
const { x, y, z } = acceleration
this.setState({
rotation,
x: (landscape ? y : x) * multiplier,
y: (landscape ? x : y) * multiplier,
z: z * multiplier
})
}
render () {
const { children } = this.props
const { x, y, z, rotation } = this.state
/**
* We have to detect if one of the values was ever set by the 'devicemotion' event,
* as some browsers implement the API, but the device itself doesn't support.
*/
if (x || y || z) {
return children({ x, y, z }, rotation)
}
return children()
}
}
ReactAccelerometer.propTypes = {
children: PropTypes.func.isRequired,
multiplier: PropTypes.number,
useGravity: PropTypes.bool
}
ReactAccelerometer.defaultProps = {
multiplier: 1,
useGravity: true
}
module.exports = ReactAccelerometer