简体   繁体   中英

Blue to Gray CSS color calculate in javascript

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.

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.

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM