0

How do you calculate the div bg color from blue to lightblue to gray based on a percentage value? ex. if the value equals 100%, the div's bg color is #0000FF; if the value equals 50%, it's light blue; if the value equals 0, the bg color is gray.

Does there have a algorithm work on this?

Thanks for any help.

Richie Cotton
  • 118,240
  • 47
  • 247
  • 360
C.C.
  • 1,060
  • 3
  • 13
  • 25
  • You can check out this question, it uses math to determine the proper color of two RGB colors mixed together with a weighting factor: http://stackoverflow.com/a/1892036/420001 – Josh Mar 30 '12 at 03:34

2 Answers2

2

First, you'll want the hexadecimal value in RGB. For that, you can use this function:

function hexToRgb(hex) {
    return {
        r: parseInt(hex.substring(1, 3), 16),
        g: parseInt(hex.substring(3, 5), 16),
        b: parseInt(hex.substring(5, 7), 16)
    };
}

Then, just apply the weights to each component:

function blendColors(colorA, colorB, weight) {
    return {
        r: Math.floor(colorA.r * (1 - weight) + colorB.r * weight),
        g: Math.floor(colorA.g * (1 - weight) + colorB.g * weight),
        b: Math.floor(colorA.b * (1 - weight) + colorB.b * weight)
    };
}

Here's a demo.

Ry-
  • 218,210
  • 55
  • 464
  • 476
-2

You can make a json object and directly refer to it while changing the color

var colorMap = new Object();
colorMap["100%"] = "#0000FF";
colorMap["50%"] = "lightBlue";
colorMap["0%"] = "gray";

and then use this map whenevr you change the background color

var percentageValue = '100%'; //you can pass this value inside a function also
document.getElementById("obj").style.background-color=colorMap[percentageValue];
Tejasva Dhyani
  • 1,342
  • 1
  • 10
  • 19