Reputation: 327
I have a background that I want to be a solid color, but the color changes as time progresses.
This one is easy to do because the only thing I have to change here is how much green to add.
But how can I do this with any 2 color?
Upvotes: 1
Views: 249
Reputation: 54026
This change is just a linear change.
So given two colours
var rgb1 = [100,200,10];
var rgb2 = [200,10,100];
The colour at a time t which is in the range 0 to 1
var colour = [
((rgb2[0] - rgb1[0]) * t + rgb1[0]) | 0, // the | 0 floors the value
((rgb2[1] - rgb1[1]) * t + rgb1[1]) | 0,
((rgb2[2] - rgb1[2]) * t + rgb1[2]) | 0,
]
If you have an absolute time in ms you can convert to normalised t (0-1) as follows
// do at start of time
startTime = performance.now();
endTime = performance.now() + 10000; // in ten seconds
// for each update
t = (performance.now() - startTime) / (endTime - startTime);
t = t > 1 ? 1 : t; // make sure you dont go past the end
// get the color
var colour = [
((rgb2[0] - rgb1[0]) * t + rgb1[0]) | 0, // the | 0 floors the value
((rgb2[1] - rgb1[1]) * t + rgb1[1]) | 0,
((rgb2[2] - rgb1[2]) * t + rgb1[2]) | 0,
]
// as a CSS colour
var cssColour = "rgb(" + colour[0] + "," + colour[1] + "," + colour[2] + ")";
Upvotes: 2