Skip to content

Instantly share code, notes, and snippets.

@DanElliottPalmer
Created March 27, 2013 09:39
Show Gist options
  • Save DanElliottPalmer/5253015 to your computer and use it in GitHub Desktop.
Save DanElliottPalmer/5253015 to your computer and use it in GitHub Desktop.
Raphael - Animate a path being drawn. Example of usage at the bottom.
function AnimatePathString() {
this._ = {
"animating": false,
"tmrID": null
};
if (arguments.length >= 3) {
this.start.apply(this, arguments);
}
}
AnimatePathString.prototype = {};
AnimatePathString.prototype.isAnimating = function() {
return this._.animating;
};
AnimatePathString.prototype.start = function(rPath, strPathString, intDuration, fnOnComplete) {
if (this.isAnimating()) {
this.stop();
}
if (!fnOnComplete) {
fnOnComplete = function() {};
}
var rToPath = rPath.paper.path(strPathString).attr({
"fill": "none",
"stroke": "none",
"stroke-opacity": 0
}),
intTotalLength = rToPath.getTotalLength(),
intStartTime = Date.now(),
intInterval = Math.floor(intDuration / intTotalLength),
self = this;
rPath.attr({
"path": rToPath.getSubpath(0, 1)
});
this._.animating = true;
this._.tmrID = setInterval(function() {
var delta = Date.now() - intStartTime,
currentLength = delta / intDuration * intTotalLength;
rPath.animate({
"path": rToPath.getSubpath(0, currentLength)
}, intInterval);
if (delta >= intDuration) {
self.stop();
fnOnComplete();
}
}, intInterval);
return this;
};
AnimatePathString.prototype.stop = function() {
if (this.isAnimating()) {
clearInterval(this._.tmrID);
this._.animating = false;
}
return this;
};
//Example
var canvas = Raphael(0, 0, 1000, 1000);
var pathstr = "M57,183.75c0,0,58.75-56,114.75,0M171.75,183.75c0,0,18.875-19.875,38.75,0";
var path = canvas.path("M0,0L1,1z").attr({
"stroke-dasharray": "-",
"stroke-width": 2,
"transform": "s2,2"
}),
anim = new AnimatePathString(path, pathstr, 1500, function() {
console.log("Complete");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment