Skip to content

Instantly share code, notes, and snippets.

@robinhouston
Created December 14, 2012 11:52
Show Gist options
  • Save robinhouston/4284890 to your computer and use it in GitHub Desktop.
Save robinhouston/4284890 to your computer and use it in GitHub Desktop.
Simple color animation
function animateColor(element, property, start_hex, end_hex, duration) {
var start = parseHexColor(start_hex),
end = parseHexColor(end_hex);
var start_time = new Date().getTime();
var timer = setInterval(function() {
var elapsed_millis = new Date().getTime() - start_time;
if (elapsed_millis >= duration) {
clearInterval(timer);
element.css(property, end_hex);
return;
}
var t = elapsed_millis/duration;
var c = interpolateColor(start, end, t);
element.css(property, c);
}, 10);
}
function parseHexColor(hex_color) {
var a = hex_color.match(/^#(..)(..)(..)$/);
if (a == null)
throw "Failed to parse hex color: " + hex_color;
return [parseInt(a[1], 16), parseInt(a[2], 16), parseInt(a[3], 16)];
}
function toHexColor(color) {
var h = function(n) {
var x = Math.round(n).toString(16);
return (x.length == 1) ? "0" + x : x;
};
return "#" + h(color[0]) + h(color[1]) + h(color[2]);
}
function interpolateColor(start, end, t) {
var i = function(a, b) {
return (1-t)*a + t*b;
};
return toHexColor([
i(start[0], end[0]),
i(start[1], end[1]),
i(start[2], end[2])
]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment