Reputation: 488
I am trying to dynamically calculate a range of colors for a pie chart in JavaScript. I need the colors to step gradually from the Start Blue to the End Blue, and given the fact that I don't know how many pie slices there will be, I need to calculate it based on the value of a variable: n
.
I found a great answer to this question in Java here: How to dynamically compute a list of colors?
But I'm not 100% sure how this translates into JavaScript. I also need them to be in order (lightest to darkest / darkest to lightest) in an array format.
var colorArray = [];
var startColor = #18AED5;`
var endColor = #1E1E26;`
// Calculate Colors...`
If anyone could help, I'd greatly appreciate it.
Upvotes: 6
Views: 2344
Reputation: 17626
Hello I created a little Demo
JS:
var div = document.getElementById('div');
var a = b = c = 0;
setInterval(function(){
div.style.backgroundColor = 'rgb('+a+','+b+','+c+')';
a+=1;
b+=2;
c+=3;
}, 50);
It's easier to handle the dynamic color change with rgb()
instead of the hex.
Update:
I was able to do as you wanted. To go from one color to another. Demo2
var div = document.getElementById('div');
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
var dynamicColorChange = function (start, end, target) {
var startRGB = hexToRgb(start),
endRGB = hexToRgb(end),
si = setInterval(function () {
if (startRGB.r < endRGB.r) {
startRGB.r += 1;
}else if(startRGB.r > endRGB.r){
startRGB.r -= 1;
}
if (startRGB.g < endRGB.g) {
startRGB.g += 1;
}else if(startRGB.g > endRGB.g){
startRGB.g -= 1;
}
if (startRGB.b < endRGB.b) {
startRGB.b += 1;
}else if(startRGB.b > endRGB.b){
startRGB.b -= 1;
}
target.style.backgroundColor = 'rgb(' + startRGB.r + ',' + startRGB.g + ',' + startRGB.b + ')';
if (startRGB.r == endRGB.r && startRGB.g == endRGB.g && startRGB.g == endRGB.g) {
clearInterval(si);
}
}, 50);
console.log(startRGB);
console.log(endRGB);
};
dynamicColorChange('#18AED5', '#1E1E26', div);
Upvotes: 2