Skip to content

Instantly share code, notes, and snippets.

@cshireman
Forked from skypanther/anim.js
Created August 19, 2014 18:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cshireman/ad02a3859aafbd630621 to your computer and use it in GitHub Desktop.
Save cshireman/ad02a3859aafbd630621 to your computer and use it in GitHub Desktop.
function parseColor(color) {
// from http://www.bitstorm.org/jquery/color-animation/jquery.animate-colors.js
var match, triplet;
// Match #aabbcc
if (match = /#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/.exec(color)) {
triplet = [parseInt(match[1], 16), parseInt(match[2], 16), parseInt(match[3], 16), 1];
// Match #abc
} else if (match = /#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])/.exec(color)) {
triplet = [parseInt(match[1], 16) * 17, parseInt(match[2], 16) * 17, parseInt(match[3], 16) * 17, 1];
// Match rgb(n, n, n)
} else if (match = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color)) {
triplet = [parseInt(match[1]), parseInt(match[2]), parseInt(match[3]), 1];
} else if (match = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9\.]*)\s*\)/.exec(color)) {
triplet = [parseInt(match[1], 10), parseInt(match[2], 10), parseInt(match[3], 10),parseFloat(match[4])];
}
return triplet;
}
// next two from http://stackoverflow.com/a/5624139/292947
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function rgbToHex(r, g, b) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
var colorSteps = []
function calculateSteps(begin, end, numSteps) {
var startRGB = parseColor(begin),
endRGB = parseColor(end),
diffR = Math.ceil((endRGB[0] - startRGB[0])/numSteps),
diffG = Math.ceil((endRGB[1] - startRGB[1])/numSteps),
diffB = Math.ceil((endRGB[2] - startRGB[2])/numSteps);
for(var i=0;i<numSteps;i++) {
var r = Math.abs(startRGB[0] + diffR*i),
g = Math.abs(startRGB[1] + diffG*i),
b = Math.abs(startRGB[2] + diffB*i);
if(r<0) r = 0;
if(r>255) r = 255;
if(g<0) g = 0;
if(g>255) g = 255;
if(b<0) b = 0;
if(b>255) b = 255;
colorSteps.push([r, g, b]);
}
}
function doAnimate(obj) {
var step = 0;
var interval = setInterval(function() {
obj.color = rgbToHex(colorSteps[step][0], colorSteps[step][1], colorSteps[step][2]);
Ti.API.info('new color: ' + obj.color)
step++;
if(step == colorSteps.length) {
Ti.API.info('stopped')
clearInterval(interval)
}
}, 50);
}
// set your starting and ending colors here
// and the number of steps between them to take
calculateSteps('#ff0000', '#0000ff', 50);
// then call the function, passing your button object
doAnimate(yourButtonObject);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment