13 May 2013

Color transition animation function for rgb or hex

Hi,
Following a previous post about turning 3 integers into the hexadecimal color format here is a function for smoothing one color into another.
Arguments are: the original color, the final color, a value from 0 to 1 proportional to how close to the final color you want to be.

function colorAnim(ori,dest,prog){
    var casergb;
    function toArr (s){
        if(s.charAt(0) !== 'r'){
            if(s.charAt(0)==='#') {
                s = s.slice(1);
            }
            if(s.length === 3) {
                s = ''.concat(s[0],s[0],s[1],s[1],s[2],s[2]);
            }
            var hex = parseInt(s,16);
            return [hex >> 16,hex >> 8 & 0xFF,hex & 0xFF];
        }else{
            casergb = s.slice(0,s.indexOf('('));
            return s.match(/[\d]+/g).map(function (n) {return parseInt(n,10);});
        }
    }
    var cori = toArr(ori);
    var cdest = toArr(dest);
    var cnow = []
    for(var i=0; i < 3; i++){
        cnow.push( (cori[i] + (cdest[i] - cori[i]) * prog) | 0);
    }
    if(casergb){
        if(casergb.length === 3){
            return casergb.concat('(',cnow[0],',',cnow[1],',',cnow[2], ')' );
        }else{
            return casergb.concat('(',cnow[0],',',cnow[1],',',cnow[2],',',cdest[3],')');
        }
    }else{
        return "#" + (0x1000000 | (cnow[0]<<16) | (cnow[1]<<8) | cnow[2]).toString(16).slice(1);
    }
}

You can use it for example in the progress option of a jQuery animation like

somejQElem.animate(
    { 
    « some properties to animate » 
    },{
    duration : 1234,
    progress:
            function (pa,progr,eta){
                somejQElem.css("color",colorAnim("#ABCDEF","rgb(1,2,3)",progr));
            }
    }
);

And you can check the jQuery animate API for detais.
Here is a small div animation example with color fading, click Result to see it:



If you are looking for a jQuery plugin there is this or any other so you can make use of the different smoothing function from jQuery. This locks you into a linear smoothing function (or change line 22 in colorAnim function e.g.).

No comments:

Post a Comment