Created
December 4, 2017 21:26
-
-
Save yadomi/706a4e4520d9d1ccf9c0625bf4dfe454 to your computer and use it in GitHub Desktop.
React Tweened State Component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
import TweenComponent from './TweenComponent'; | |
export default class Animated extends TweenComponent { | |
state = { | |
x: 0, | |
y: 0, | |
scale: 1, | |
}; | |
_handleClick1 = () => { | |
this.tweenState({ x: 100 }, 1000); | |
}; | |
_handleClick2 = () => { | |
this.tweenState({ scale: 2, y: 150 }, 350); | |
}; | |
_handleClick3 = () => { | |
this.tweenState({ x: 0, y: 0, scale: 1 }, 100); | |
}; | |
get style() { | |
return { | |
textAlign: 'center', | |
transform: `translate3d(${this.state.x}px, ${this.state.y}px, 0) scale(${ | |
this.state.scale | |
})`, | |
}; | |
} | |
render() { | |
return ( | |
<div> | |
<div style={{ textAlign: 'center', marginTop: '20%' }}> | |
<button onClick={this._handleClick1}>Animate</button> | |
<button onClick={this._handleClick2}>Animate mawr</button> | |
<button onClick={this._handleClick3}>Reset all the things</button> | |
</div> | |
<h1 style={this.style}>Hello</h1> | |
</div> | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
import { compose, pick, keys, __ } from 'ramda'; | |
import TWEEN from '@tweenjs/tween.js'; | |
export default class TweenComponent extends Component { | |
tweenState = ( | |
to, | |
duration = 100, | |
easingFunction = TWEEN.Easing.Quadratic.InOut, | |
) => { | |
this.values = compose(pick(__, this.state), keys)(to); | |
this.tween = new TWEEN.Tween(this.values) | |
.easing(easingFunction) | |
.to(to, duration) | |
.start(); | |
this.animate(duration); | |
}; | |
animate(duration) { | |
const start = Date.now(); | |
const loop = () => { | |
const elapsed = Date.now() - start; | |
if (elapsed <= duration) { | |
requestAnimationFrame(loop); | |
} | |
TWEEN.update(); | |
this.update(); | |
}; | |
loop(); | |
} | |
update() { | |
this.setState(this.values); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment