Skip to content

Instantly share code, notes, and snippets.

@threedaymonk
Created March 15, 2015 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save threedaymonk/69bc4a5fd3e751097f22 to your computer and use it in GitHub Desktop.
Save threedaymonk/69bc4a5fd3e751097f22 to your computer and use it in GitHub Desktop.
Alternative animation implementation for beta.jisho.org, using an easing function to accelerate towards the middle of a stroke, and decelerate at the end
var Animation = Class(function Animation() {});
Animation.mixin(Canvas);
Animation.prototype.extend(Event.Listener);
Animation.prototype.extend({
reset: function() {
this.relativePosition = 0;
this.maxPosition = this.totalFrames - 1;
this.completed = false;
this.animating = false;
},
ease: function(v, vmax) {
return -vmax/ 2 * (Math.cos(Math.PI * v / vmax) - 1);
},
getCurrentFrame: function() {
var easedPosition = this.ease(this.relativePosition, this.maxPosition);
return Math.min(1 + Math.round(easedPosition), this.totalFrames);
},
advance: function() {
if (this.relativePosition >= this.maxPosition) {
if (!this.completed) {
this.animating = false;
this.completed = true;
this.broadcast('AnimationComplete', this);
}
} else {
this.relativePosition += this.speed;
}
},
drawCurrentFrameAndAdvance: function() {
this.drawFrame(this.getCurrentFrame());
this.advance();
},
drawCurrentFrameAndRequestNext: function() {
var self = this;
this.clear();
this.animating = true;
this.drawCurrentFrameAndAdvance();
if(this.animating) {
window.requestAnimationFrame(function() {
self.drawCurrentFrameAndRequestNext();
});
}
},
animate: function() {
if(this.animating) return;
this.reset();
this.drawCurrentFrameAndRequestNext();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment