Skip to content

Instantly share code, notes, and snippets.

@elrumordelaluz
Last active October 6, 2016 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elrumordelaluz/45e0d3fe0c968eebd7588410eb3ff285 to your computer and use it in GitHub Desktop.
Save elrumordelaluz/45e0d3fe0c968eebd7588410eb3ff285 to your computer and use it in GitHub Desktop.
<Shake /> [2]
import React, { Component } from 'react';
import Shake from './Shake';
class App extends Component {
render() {
return (
<div className="App">
<Shake>
&lt;Shake /&gt;
</Shake>
<Shake h={0} v={100} r={0} dur={1000} int={3}>
&lt;Shake custom /&gt;
</Shake>
</div>
);
}
}
export default App;
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