2

EDIT: I KIND OF FIGURED IT OUT CODE HERE STILL SOME ISSUES (has to be 255 objects right now):

for (let i = 1; i <= 255; i++) {
  let arg = document.createElement("div");
  let red = 0;
  let green = 0;
  let blue = 0;
  if (color == 0) {
    red = 255;
    green = num * 3;
  } else if (color == 1) {
    red = 255 - num*3;
    green = 255;
    blue = num * 3;
  } else if (color == 2) {
    red = num * 3;
    green = 255-num*3;
    blue = 255; 
  }
  arg.style.backgroundColor = "#" + htd(red) + htd(green) + htd(blue);
  document.querySelector("body").appendChild(arg);
  if (num == 85) {
    num = 1;
    color++;
  } else {
    num++;
  }
}

OLD QUESTION

I am generating a number of HTML objects in JS using a for loop. I want these objects to progressively be colored from red to purple (rainbow order). How would I go about going from #FF0000 to #008080 and back again to #FF0000.

Here is my code so far (DOESN'T WORK WELL):

for (let i = 1; i < 255; i++) {
   let arg = document.createElement("div");
   let num = i;
   if (num > 255) {
      num = 255;
   }
   let red = 255;
   let blue = 0;
   if (num < 128) {
     let green = 0;
     arg.style.backgroundColor = "#" + htd(red - i) + htd(green + i * 2) + htd(blue + i);
   } else {
     let green = 256;
     arg.style.backgroundColor = "#" + htd(red - i * 2) + htd(green - i * 2) + htd(blue + i);
   }
   document.querySelector("body").appendChild(arg);
}

function htd(num) {
   let hexString = num.toString(16);
   if (hexString.length % 2) {
      hexString = '0' + hexString;
   }
   return hexString;
}

If you want to see why I need this go to https://codepen.io/navinate/pen/dwExxm

Thank You!

Trey Cluff
  • 21
  • 1
  • 3

1 Answers1

0

What I think you want is

  1. A gradient of hue values
  2. A conversion from HSL (hue, saturation, lightness) to RGB
  3. RGB to #hex notation, which you already have covered

A gradient of hues is a simple linear interpolation problem:

const length = 100;
const hueGradient = Array.from({length}, (v, k) => k/(length-1));

A sample conversion from HSL to RGB can be found in an answer to this question. Using that:

const saturation = 1.0;
const lightness = 0.5;
const rgbValues = hueGradient.map(hue => hslToRgb(hue, saturation, lightness));

The result is an array of [R, G, B] which you can express as #rgb values:

const htmlRgbValues = rgbValues.map(([r,g,b]) => `#${htd(r)}${htd(g)}${htd(b)}`);

There's a good chance that you don't want a lookup table, but instead want to interpolate on the fly, just use

const htmlRgbValue = hslToRgb(x / x_max, saturation, lightness);
Sami Hult
  • 3,052
  • 1
  • 12
  • 17