Coded snippet: Putting the question into context
Below, I have coded a little snippet using the p5.js library where a slider controls the number of bars that appear on a canvas. The colour of each bar is determined by multiplying the number of the bar that is being coloured by 255 / (the total number of bars - 1), so, regardless of the number of bars, the first will always be black and the last will always be slightly off-white (with greyscale in between).
Quick note: The last is off-white so I can see it against a white background.
Run the snippet here:
function setup() {
createCanvas(200,200);
}
function draw() {
background(255);
numberOfBars = document.getElementById("barSlider").value;
for (var i = 0; i < numberOfBars; i++) {
noStroke();
var spaceInterval = width / numberOfBars;
fill(i*(240/(numberOfBars-1)))
rect(i * spaceInterval, 0, spaceInterval, (i + 1) * spaceInterval);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.16/p5.js"></script>
<html>
<head>
</head>
<body>
<input type="range" min="2" max="100" value="10" id="barSlider">
</body>
</html>
The Question
So, this above snippet transitions from start-to-end between the RGB colour values of (0, 0, 0)
and (240, 240, 240)
- regardless of the number of bars that is displayed.
Now, if I have two randomly generated objects which hold the data for two RGB colours, as so:
startColor = {
r: floor(random(255)),
g: floor(random(255)),
b: floor(random(255))
}
endColor = {
r: floor(random(255)),
g: floor(random(255)),
b: floor(random(255))
}
How could I transition smoothly between these as the above snippet transitions between 0 and 240? I've been playing around and no code I run seems to produce a series of bars where the color of the first bar and the color of the end bar is even remotely similar to the true values of the startColor
and endColor
variables.
Thanks for reading. Please comment any questions below if this wasn't clear enough.