Justin
Justin

Reputation: 473

Get exact color from two colors with percentage in javascript

I have a percentage variable and two colors in javascript. Ex. One color is #D7F0FE & another color is #3DB6FC Percentage variable is 30 (%)

I need to get exact color from these three values. If percentage is zero then it should be #D7F0FE and if it's 100 then it should be #3DB6FC.

Need to find the best way to do that

Upvotes: 1

Views: 1127

Answers (2)

Didi Bear
Didi Bear

Reputation: 366

Here is a clean solution based on this comment here:

/** eg. gradient("#FF0000", "#0000FF", 0.5) => "#800080" */
function gradient(color1, color2, ratio) {
  const from = rgb(color1)
  const to = rgb(color2)

  const r = Math.ceil(from.r * ratio + to.r * (1 - ratio));
  const g = Math.ceil(from.g * ratio + to.g * (1 - ratio));
  const b = Math.ceil(from.b * ratio + to.b * (1 - ratio));

  return "#" + hex(r) + hex(g) + hex(b);
}

/** eg. rgb("#FF0080") => { r: 256, g: 0, b: 128 } */
function rgb(color) {
  const hex = color.replace("#", "")
  return {
    r: parseInt(hex.substring(0, 2), 16),
    g: parseInt(hex.substring(2, 4), 16),
    b: parseInt(hex.substring(4, 6), 16),
  }
}

/** eg. hex(123) => "7b" */
function hex(num) {
    num = num.toString(16);
    return (num.length == 1) ? '0' + num : num;
}

Upvotes: 1

Bin Rohan
Bin Rohan

Reputation: 352

I recommend to use RGB value as this value define with numbers. Such as

#D7F0FE -> rgb(215, 240, 254)

#3DB6FC -> rgb(61, 182, 252)

Now do some math to generate rgb value dynamically based on percentage.

Please check the following code, it generate rgb value depending on Input Percentage.

<html>
    <head> 
    </head>
    <body id="body">
        <input type="number" id="input-p">
        <button  onclick="changePercentage()">Percentage: </button>
        
        
        <script>
            var body = document.getElementById('body');
            var rgb1 = [215, 240, 254];
            var rgb2 = [61, 182, 252];
            var rgb = [];
            var p = 0;
            var r = (rgb2[0] - rgb1[0])/100;
            var g = (rgb2[1] - rgb1[1])/100;
            var b = (rgb2[2] - rgb1[2])/100;
            var color = 'rgb(215, 240, 254)';
            body.style.background = color;
            function newColor(){
                console.log(p * r);
                rgb = [
                    
                    Math.ceil(rgb1[0] + (p * r)),
                    Math.ceil(rgb1[1] + (p * g)),
                    Math.ceil(rgb1[2] + (p * b))
                ];
                color = 'rgb('+rgb[0]+','+rgb[1]+','+rgb[2]+')';
                body.style.background = color;
            }
            
            function changePercentage(){
                p = document.getElementById('input-p').value;
                newColor();
            }
            
        </script>
        
    </body>
</html>

not optimized

Upvotes: 2

Related Questions