3

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.

Caspar B
  • 499
  • 1
  • 6
  • 19

1 Answers1

0

Thank you, Lukas, for pointing me towards the original post with an answer that helped.

I've found a solution for all of you willing to use the P5.js library. First, define two RGB colors you'd like to transition between:

var startColor = color(
    floor(random(255)),
    floor(random(255)),
    floor(random(255))
);
var endColor = color(
    floor(random(255)),
    floor(random(255)),
    floor(random(255))
);

Next, define the color which transitions between the two:

var col = lerpColor(startColor, endColor, LEVEL);

LEVEL is a decimal ranging from 0 - 1, where 0 results in col = startColor and 1 results in col = endColor, and anything between transitions the two colours.

Apply col to a drawing through:

fill(col)
// draw rect, ellipse, etc...

And:

stroke(col)
// draw line

Read more on it here.

Caspar B
  • 499
  • 1
  • 6
  • 19