'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
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
