Skip to content

Instantly share code, notes, and snippets.

@william-silversmith
Last active October 26, 2021 11:49
Show Gist options
  • Save william-silversmith/a575c01b0731940b06a2 to your computer and use it in GitHub Desktop.
Save william-silversmith/a575c01b0731940b06a2 to your computer and use it in GitHub Desktop.
Animating an Object
/* Example animation function
*
* Interpolate between a start and end position.
*
* obj.x represents a position parameter (e.g. 12.2)
* end_pos is the value obj.x will have at the end of the animation
* msec is the number of milliseconds we want to run the animation for
* easing is a timing function that accepts a number between 0 to 1
* and returns the proportion of the interpolation between start and end to move the object to.
*
* Returns: void (performs animation as a side effect)
*/
function animation (obj, end_pos, msec, easing) {
easing = easing || function (t) { return t }; // default to linear easing
var start_pos = obj.x;
// performance.now is guaranteed to increase and gives sub-millisecond resolution
// Date.now is susceptible to system clock changes and gives some number of milliseconds resolution
var start = window.performance.now(),
delta = end_pos - start_pos;
function frame () {
var now = window.performance.now();
var t = (now - start) / msec; // normalize to 0..1
if (t >= 1) { // if animation complete or running over
obj.x = end_pos; // ensure the animation terminates in the specified state
return;
}
var proportion = easing(t);
obj.x = start_pos + proportion * delta;
requestAnimationFrame(frame); // next frame!
}
requestAnimationFrame(frame); // you can use setInterval, but this will give a smoother animation
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment