Skip to content

Instantly share code, notes, and snippets.

@teledirigido
Last active August 29, 2015 14:24
Show Gist options
  • Save teledirigido/667beed4cefe13007e25 to your computer and use it in GitHub Desktop.
Save teledirigido/667beed4cefe13007e25 to your computer and use it in GitHub Desktop.
Animate SVG with javascript
/*
USAGE:
var svg = new animate_svg({
id: '#svg-logo',
frames: 100
});
svg.init();
FAQ:
Not everything is animated?
Make sure everything is a path (http://graphicdesign.stackexchange.com/questions/15475/convert-primitive-to-path-using-svg-format-in-illustrator)
*/
var animate_svg = function(options){
this.options = options;
this.init = function(){
var _self = this;
// Check
$(_self.options.id).length === 0 && console.log('div' + _self.options.id + ' doesn\'t exists!');
var current_frame = 0,
total_frames = _self.options.frames,
path = new Array(),
length = new Array(),
handle,
myobj = $(_self.options.id)[0].cloneNode(true);
path_length = $(_self.options.id+' path').length;
var init = function() {
$(_self.options.id+' path').each(function(i,a){
$(this).attr('id', 'i'+i );
});
$(_self.options.id).css({'opacity':1});
for ( var i = 0 ; i < path_length ; i++ ){
path[i] = document.getElementById('i'+i);
l = path[i].getTotalLength();
length[i] = l;
path[i].style.strokeDasharray = l + ' ' + l;
path[i].style.strokeDashoffset = l;
}
handle = 0;
}
var draw = function() {
var progress = current_frame/total_frames;
if (progress > 1) {
window.cancelAnimationFrame(handle);
} else {
current_frame++;
for(var j = 0 ; j < path_length ; j++ ){
path[j].style.strokeDashoffset = Math.floor(length[j] * (1 - progress));
}
handle = window.requestAnimationFrame(draw);
}
};
init();
draw();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment