Skip to content

Instantly share code, notes, and snippets.

@jamesu
Created March 3, 2010 23:52
Show Gist options
  • Save jamesu/321207 to your computer and use it in GitHub Desktop.
Save jamesu/321207 to your computer and use it in GitHub Desktop.
How to make dynamic CSS3 animations!
// Creating CSS Animations dynamically
// - jamesu
//
// Assuming:
// - styleSheets[0] is the main stylesheet
// - frames[] is a list of translation,rotation,scale keyframe values
// Note:
// If you modify an existing animation, the old keyframes
// will continue being used until you re-assign the animation.
//
function buildAnim(name, frames) {
var frames = "";
var len=frames.length;
for (var i=0; i<len; i++) {
var kf = frames[i];
var dt = (i/(len-1)) * 100;
frames += dt + "% { -webkit-transform: translate(" + kf[0] + "px," + kf[1] + "px) rotate(" + kf[2] + "deg) scale(" + kf[3] + "," + kf[4] + "); } ";
}
var idx = document.styleSheets[0].cssRules.length;
document.styleSheets[0].insertRule("@-webkit-keyframes " + name + " { " + frames + "}", idx);
}
// e.g.
buildAnim('rotate', [
[0,0,0,1.0,1.0],
[0,0,90,1.0,1.0],
[0,0,180,1.0,1.0],
[0,0,270,1.0,1.0],
[0,0,360,1.0,1.0]
]);
// Get spinner and animate it!
var spinner = document.getElementById('spinner');
spinner.style.webkitAnimationIterationCount = 'infinite';
spinner.style.webkitAnimationTimingFunction = 'linear';
spinner.style.webkitAnimationDuration = '2.0s';
spinner.style.webkitAnimation = 'rotate';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment