Javascript color gradient calculator 1


Here is a color calculator I adapted from a friend’s PHP implementation:

Color = function() {
};

Color.hexdec = function(hex_string) {
    hex_string = (hex_string + '').replace(/[^a-f0-9]/gi, '');
    return parseInt(hex_string, 16);
}

Color.dechex = function(number) {
    if (number < 0) {
        number = 0xFFFFFFFF + number + 1;
    }
    return parseInt(number, 10).toString(16);
}

Color.pad = function(number, length) {
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
    return str;
}

Color.calcgrad = function(val, color1, color2) {
    
    if(!color1.match(/^#[0-9a-f]{6}/) || !color2.match(/^#[0-9a-f]{6}/)) return 'match err!';
    
    if (val > 1) {
        val = 1;
    }
    if (val < 0) {
        val = 0;
    }
    val = parseFloat(val);
    
    c1 = [Color.hexdec(color1.substr(1,2)), Color.hexdec(color1.substr(3,2)), Color.hexdec(color1.substr(5,2))]; //b
    c2 = [Color.hexdec(color2.substr(1,2)), Color.hexdec(color2.substr(3,2)), Color.hexdec(color2.substr(5,2))]; //r
    
    if (val < .5) {
        delta = [(c2[0] - c1[0]), (c2[1] - c1[1]), (c1[2] - c2[2])];
        arrColor = [c1[0] +1 * 2), c1[1] -2 * 2), c1[2] -3 * 2)];
    }
    return '#'+Color.pad(Color.dechex(arrColor[0]),2)+Color.pad(Color.dechex(arrColor[1]),2)+Color.pad(Color.dechex(arrColor[2]),2);
}

No related content found.

  1. delta[0] * val) * 2), c1[1] + ((delta[1] * val) * 2), c1[2] - ((delta[2] * val) * 2)]; } else { delta = [(c1[0] - c2[0]), (c1[1] - c2[1]), (c1[2] - c2[2])]; arrColor = [c1[0] - ((delta[0] * (val - .5 []
  2. delta[1] * (val - .5 []
  3. delta[2] * (val - .5 []

Leave a comment

One thought on “Javascript color gradient calculator