Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to figure out all colors in a gradient? [duplicate]

Possible Duplicate:
Javascript color gradient

I have color one (let's say yellow) and color two (blue) - they make up a gradient.
Based on a value of 0 to 100, (0 being yellow and 100 being blue), I'd like to represent a mixture of color one and two.

I am trying to do this in a mobile browser (safari specifically).

Is there a way to do this in javascript?

like image 864
AngryHacker Avatar asked Nov 30 '22 06:11

AngryHacker


1 Answers

If what you're trying to do is to create a color that is some percentage (0-100) between two other colors, you can do that with this javascript:

function makeGradientColor(color1, color2, percent) {
    var newColor = {};

    function makeChannel(a, b) {
        return(a + Math.round((b-a)*(percent/100)));
    }

    function makeColorPiece(num) {
        num = Math.min(num, 255);   // not more than 255
        num = Math.max(num, 0);     // not less than 0
        var str = num.toString(16);
        if (str.length < 2) {
            str = "0" + str;
        }
        return(str);
    }

    newColor.r = makeChannel(color1.r, color2.r);
    newColor.g = makeChannel(color1.g, color2.g);
    newColor.b = makeChannel(color1.b, color2.b);
    newColor.cssColor = "#" + 
                        makeColorPiece(newColor.r) + 
                        makeColorPiece(newColor.g) + 
                        makeColorPiece(newColor.b);
    return(newColor);
}

This function assumes the gradient is made with linear interpolation between each r, g and b channel value of the two endpoint colors such that the 50% gradient value is the midpoint of each r,g,b value (halfway between the two colors presented). Once could make different types of gradients too (with different interpolation functions).

To assign this result to a background, you use the CSS color value I've added to the return result like this:

// sample usage
var yellow = {r:255, g:255, b:0};
var blue = {r:0, g:0, b:255};
var newColor = makeGradientColor(yellow, blue, 79);
element.style.backgroundColor = newColor.cssColor;
like image 187
jfriend00 Avatar answered Dec 04 '22 10:12

jfriend00