-
-
Save elrumordelaluz/45e0d3fe0c968eebd7588410eb3ff285 to your computer and use it in GitHub Desktop.
<Shake /> [2]
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 Shake from './Shake'; | |
class App extends Component { | |
render() { | |
return ( | |
<div className="App"> | |
<Shake> | |
<Shake /> | |
</Shake> | |
<Shake h={0} v={100} r={0} dur={1000} int={3}> | |
<Shake custom /> | |
</Shake> | |
</div> | |
); | |
} | |
} | |
export default App; |
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 from 'react' | |
const Shake = ({ | |
h = 5, | |
v = 5, | |
r = 3, | |
dur = 300, | |
q = 'infinite', | |
tf = 'ease-in-out', | |
int = 10, | |
max = 100, | |
orig = 'center center', | |
...props, | |
}) => { | |
const random = (max, min = 0) => { | |
return (Math.random() * (max - min) - max / 2); | |
}; | |
const doKeyframes = () => { | |
// el objecto que iremos llenando | |
let kf = {}; | |
const init = 'translate(0,0) rotate(0)'; | |
// loop con intervalos basados en `int` | |
for (let st = int; st <= max; st += int) { | |
// Numeros aleatorios en cada keyframe | |
const x = random(h); | |
const y = random(v); | |
const rot = random(r); | |
kf[`${st}%`] = { | |
transform: `translate(${x}px, ${y}px) rotate(${rot}deg)`, | |
} | |
} | |
// Init de las transformaciones en 0% y 100% | |
kf[`0%`] = kf[`100%`] = { | |
transform: init, | |
} | |
// Init también en caso el `max` < 100 | |
if (max < 100) { | |
kf[`${max}%`] = { | |
transform: init, | |
} | |
} | |
return kf; | |
}; | |
// Creamos los `@keyframes` | |
const keyframes = doKeyframes(); | |
const keyframesString = Object.keys(keyframes).reduce((acc, next) => { | |
return `${acc} ${next} { | |
transform: ${keyframes[next].transform}; | |
}`; | |
}, ''); | |
const name = `anim-${Date.now()}`; | |
const styles = `@keyframes ${name} { | |
${keyframesString} | |
}`; | |
let styleSheet = document.styleSheets[0]; | |
styleSheet.insertRule(styles, styleSheet.cssRules.length); | |
return ( | |
<div style={{ | |
display: 'inline-block', | |
animationName: name, | |
animationDuration: `${dur}ms`, | |
animationIterationCount: q, | |
transformOrigin: orig, | |
}}> | |
{ props.children } | |
</div> | |
); | |
}; | |
export default Shake; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment